id
stringlengths
40
40
text
stringlengths
29
2.03k
original_text
stringlengths
3
154k
subdomain
stringclasses
20 values
metadata
dict
85277f34f0575c5bc288fbb38547e2ff4d2b5a08
Stackoverflow Stackexchange Q: Cookies in Google Scripts Web App Is it possible to keep track of cookies (or any kind of session variables) in a GAS Web App? The script is running as myself, and anyone (even anonymous) can access the site. I need to be able to keep track of login information, so I should be able to see if the user is logged in between requests. Note: The user is not required to have a Gmail account. A: I didn't find the GAS solution for this even after almost 3 years since this question was asked. Looks like the only solution is to use javascript cookie handling (document.cookie) in each template file.
Q: Cookies in Google Scripts Web App Is it possible to keep track of cookies (or any kind of session variables) in a GAS Web App? The script is running as myself, and anyone (even anonymous) can access the site. I need to be able to keep track of login information, so I should be able to see if the user is logged in between requests. Note: The user is not required to have a Gmail account. A: I didn't find the GAS solution for this even after almost 3 years since this question was asked. Looks like the only solution is to use javascript cookie handling (document.cookie) in each template file.
stackoverflow
{ "language": "en", "length": 112, "provenance": "stackexchange_0000F.jsonl.gz:910758", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44685380" }
898f39038c2aa735a6b3727cdf8a809605ff5bca
Stackoverflow Stackexchange Q: Trying to know when a window closes in a macOS Document based application I'm trying to know when a window closes, I implemented this code: class ViewController: NSViewController, NSWindowDelegate { override func viewDidLoad() { super.viewDidLoad() let window: NSWindow? = view.window window?.delegate = self } func windowWillClose(_ aNotification: Notification) { print("windowWillClose") } } Unfortunately nothing happens, what could I made wrong? Documents: https://developer.apple.com/documentation/appkit/nswindow/1419400-willclosenotification PS I already read this question without to find a solution: Handle close event of the window in Swift A: The problem there is that the window property will always return nil inside viewDidLoadMethod. You need to set the delegate inside viewWillAppear method: class ViewController: NSViewController, NSWindowDelegate { override func viewWillAppear() { super.viewWillAppear() view.window?.delegate = self } func windowWillClose(_ aNotification: Notification) { print("windowWillClose") } }
Q: Trying to know when a window closes in a macOS Document based application I'm trying to know when a window closes, I implemented this code: class ViewController: NSViewController, NSWindowDelegate { override func viewDidLoad() { super.viewDidLoad() let window: NSWindow? = view.window window?.delegate = self } func windowWillClose(_ aNotification: Notification) { print("windowWillClose") } } Unfortunately nothing happens, what could I made wrong? Documents: https://developer.apple.com/documentation/appkit/nswindow/1419400-willclosenotification PS I already read this question without to find a solution: Handle close event of the window in Swift A: The problem there is that the window property will always return nil inside viewDidLoadMethod. You need to set the delegate inside viewWillAppear method: class ViewController: NSViewController, NSWindowDelegate { override func viewWillAppear() { super.viewWillAppear() view.window?.delegate = self } func windowWillClose(_ aNotification: Notification) { print("windowWillClose") } }
stackoverflow
{ "language": "en", "length": 128, "provenance": "stackexchange_0000F.jsonl.gz:910776", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44685445" }
76bc606cb1a54b88df68a5aa76a7f55b4fd74d93
Stackoverflow Stackexchange Q: How to call SQL View Dapper c# Is there any way to call a sql view by using Dapper c# ? I already know how to call stored procedures with that, but when it comes to views I have no idea how to do that. A: A view works like a table from the perspective of queries, including how filters and parameters work - so something like: string region = ... var data = connection.Query<SomeType>( "select * from SomeView where Region = @region", new { region }).AsList();
Q: How to call SQL View Dapper c# Is there any way to call a sql view by using Dapper c# ? I already know how to call stored procedures with that, but when it comes to views I have no idea how to do that. A: A view works like a table from the perspective of queries, including how filters and parameters work - so something like: string region = ... var data = connection.Query<SomeType>( "select * from SomeView where Region = @region", new { region }).AsList();
stackoverflow
{ "language": "en", "length": 88, "provenance": "stackexchange_0000F.jsonl.gz:910780", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44685451" }
52720390769dd3bcef002367bcf1990674406f65
Stackoverflow Stackexchange Q: "this" becomes undefined in ngOnInit "this" becomes undefined in ngOnInit I am trying to push the object that is returned on a callback into a globally defined array. but it gives error that "cannot read property of undefined" export class ItemsComponent implements OnInit { items: Item[]; devices: any[]; constructor(private itemService: ItemService) { this.devices = new Array(); } ngOnInit(): void { bluetooth.isBluetoothEnabled().then( enabled => console.log("Enabled ? " + enabled) ); bluetooth.startScanning({ serviceUUIDs: [], seconds: 4, onDiscovered: function(peripheral) { this.devices.push(peripheral); } }).then(function() { console.log("scanning complete"); }, function(err) { console.log("error while scanning: " + err); }); this.items = this.itemService.getItems(); }} i get this error at this.devices.push(peripheral); A: You should be using Arrow Function to get hold on correct this inside function. onDiscovered: function(peripheral) should be onDiscovered:(peripheral) => { }
Q: "this" becomes undefined in ngOnInit "this" becomes undefined in ngOnInit I am trying to push the object that is returned on a callback into a globally defined array. but it gives error that "cannot read property of undefined" export class ItemsComponent implements OnInit { items: Item[]; devices: any[]; constructor(private itemService: ItemService) { this.devices = new Array(); } ngOnInit(): void { bluetooth.isBluetoothEnabled().then( enabled => console.log("Enabled ? " + enabled) ); bluetooth.startScanning({ serviceUUIDs: [], seconds: 4, onDiscovered: function(peripheral) { this.devices.push(peripheral); } }).then(function() { console.log("scanning complete"); }, function(err) { console.log("error while scanning: " + err); }); this.items = this.itemService.getItems(); }} i get this error at this.devices.push(peripheral); A: You should be using Arrow Function to get hold on correct this inside function. onDiscovered: function(peripheral) should be onDiscovered:(peripheral) => { }
stackoverflow
{ "language": "en", "length": 127, "provenance": "stackexchange_0000F.jsonl.gz:910781", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44685453" }
a61d3c57ebfc464424815d44975cef13e1bb459e
Stackoverflow Stackexchange Q: React-Native displaying image from blob I'm pulling from an API that gives me back an image in a blob inside the response. I need to display this image somewhere. I tried using react-native-fetch-blob, but its clear that that's a complete mess. I'm guessing there has to be some way I can convert it to base64 so that the image can be displayed.
Q: React-Native displaying image from blob I'm pulling from an API that gives me back an image in a blob inside the response. I need to display this image somewhere. I tried using react-native-fetch-blob, but its clear that that's a complete mess. I'm guessing there has to be some way I can convert it to base64 so that the image can be displayed.
stackoverflow
{ "language": "en", "length": 63, "provenance": "stackexchange_0000F.jsonl.gz:910812", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44685555" }
b2a9d28f3c808a71ddd10b9943589625ac2a0874
Stackoverflow Stackexchange Q: Get posts with WP-REST without authentication I'm new to WP-REST API and Wordpress in general. I've tried to get the posts list using the endpoint wp-json/wp/v2/posts but I get the classic 403 error. I'd like to ask if there is a way to disable authentication for GET requests like posts, categories and so on since I want to create a web application in which a user can navigate and see them freely, with no need for authentication. Thank you all for the answers. A: You actually don't need to have authorization to merely GET posts or categories, so long as they aren't password protected. If someone has implemented a modifier to rest_authentication_errors, that might be your problem: https://developer.wordpress.org/rest-api/using-the-rest-api/frequently-asked-questions/#require-authentication-for-all-requests To see the available endpoints you have, visit yourwordpressurl.com/wp-json
Q: Get posts with WP-REST without authentication I'm new to WP-REST API and Wordpress in general. I've tried to get the posts list using the endpoint wp-json/wp/v2/posts but I get the classic 403 error. I'd like to ask if there is a way to disable authentication for GET requests like posts, categories and so on since I want to create a web application in which a user can navigate and see them freely, with no need for authentication. Thank you all for the answers. A: You actually don't need to have authorization to merely GET posts or categories, so long as they aren't password protected. If someone has implemented a modifier to rest_authentication_errors, that might be your problem: https://developer.wordpress.org/rest-api/using-the-rest-api/frequently-asked-questions/#require-authentication-for-all-requests To see the available endpoints you have, visit yourwordpressurl.com/wp-json
stackoverflow
{ "language": "en", "length": 128, "provenance": "stackexchange_0000F.jsonl.gz:910850", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44685674" }
90f307ba549d536ba1bf256b73fa316161f6c1eb
Stackoverflow Stackexchange Q: How to use Jest to test file download? I have some code as below: /* global document */ /* global window */ /* global Blob */ import FileSaver from 'file-saver'; export const createDownloadFromBlob = (blob, filename, extension) => { FileSaver.saveAs(blob, `${filename}.${extension}`); }; export const createDownload = (content, filename, extension) => { createDownloadFromBlob(new Blob([content], { type: 'application/octet-stream' }), filename, extension); }; I want to use Jest to unit-test these two methods, but I don't know where to start. Any help would be appreciated. A: I would mock out FileSaver with a spy: import FileSaver from 'file-saver'; jest.mock('file-saver', ()=>({saveAs: jest.fn()})) As you cant compare Blobs I would mock this as well: global.Blob = function (content, options){return ({content, options})} now you can run your test and use expect like this createDownload('content', 'filename', 'extension') expect(FileSaver.saveAs).toHaveBeenCalledWith( {content:'content', options: { type: 'application/octet-stream' }}, 'filename.extension' )
Q: How to use Jest to test file download? I have some code as below: /* global document */ /* global window */ /* global Blob */ import FileSaver from 'file-saver'; export const createDownloadFromBlob = (blob, filename, extension) => { FileSaver.saveAs(blob, `${filename}.${extension}`); }; export const createDownload = (content, filename, extension) => { createDownloadFromBlob(new Blob([content], { type: 'application/octet-stream' }), filename, extension); }; I want to use Jest to unit-test these two methods, but I don't know where to start. Any help would be appreciated. A: I would mock out FileSaver with a spy: import FileSaver from 'file-saver'; jest.mock('file-saver', ()=>({saveAs: jest.fn()})) As you cant compare Blobs I would mock this as well: global.Blob = function (content, options){return ({content, options})} now you can run your test and use expect like this createDownload('content', 'filename', 'extension') expect(FileSaver.saveAs).toHaveBeenCalledWith( {content:'content', options: { type: 'application/octet-stream' }}, 'filename.extension' ) A: In Typescript: If you create a Blob with a ArrayBuffer or binary data then you need handle that case separately than strings. import * as CRC32 from 'crc-32'; (window as any).global.Blob = function(content, options) { // for xlxs blob testing just return the CRC of the ArrayBuffer // and not the actual content of it. if (typeof content[0] !== 'string') { content = CRC32.buf(content); } return {content: JSON.stringify(content), options}; };
stackoverflow
{ "language": "en", "length": 211, "provenance": "stackexchange_0000F.jsonl.gz:910988", "question_score": "15", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44686077" }
c052c16c561316ec184c677fa045c1868e8ae35e
Stackoverflow Stackexchange Q: Vertically centre align a cropped image in a div I'm trying to create a CSS style that will take an image and scale it to best fit a letter box shaped div. The overflow will be cropped off. I'm close with this and it currently looks like this: The original image is I'd like to modify this so that the image is centered vertically in the div rather than top aligned. What am I missing here? My html is .crop { width: 670px; height: 200px; overflow: hidden; } .crop img { width: 670px; } <div class='crop'> <img src='http://cycle.travel/images/600/amsterdam_ccby_conor_luddy.jpg' /> </div> I can't assume the height of the image to be the same everywhere I use this. A: You can position the image relatively and then have the browser bump it upward 50% with top:-50%;: .crop { width: 670px; height: 200px; overflow: hidden; } .crop img { width: 670px; position:relative; top:-50%; } <div class='crop'> <img src='http://cycle.travel/images/600/amsterdam_ccby_conor_luddy.jpg' /> </div>
Q: Vertically centre align a cropped image in a div I'm trying to create a CSS style that will take an image and scale it to best fit a letter box shaped div. The overflow will be cropped off. I'm close with this and it currently looks like this: The original image is I'd like to modify this so that the image is centered vertically in the div rather than top aligned. What am I missing here? My html is .crop { width: 670px; height: 200px; overflow: hidden; } .crop img { width: 670px; } <div class='crop'> <img src='http://cycle.travel/images/600/amsterdam_ccby_conor_luddy.jpg' /> </div> I can't assume the height of the image to be the same everywhere I use this. A: You can position the image relatively and then have the browser bump it upward 50% with top:-50%;: .crop { width: 670px; height: 200px; overflow: hidden; } .crop img { width: 670px; position:relative; top:-50%; } <div class='crop'> <img src='http://cycle.travel/images/600/amsterdam_ccby_conor_luddy.jpg' /> </div> A: You could use the CSS background-position property. https://www.w3schools.com/cssref/pr_background-position.asp .crop { width: 100%; height: 200px; overflow: hidden; background-image: url('http://cycle.travel/images/600/amsterdam_ccby_conor_luddy.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-position: center; } <div class='crop'></div>
stackoverflow
{ "language": "en", "length": 186, "provenance": "stackexchange_0000F.jsonl.gz:911021", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44686186" }
a33a5aacb5ea74935cbea4a4dcda9bb55d19b624
Stackoverflow Stackexchange Q: Why is jQuery not working in my rails 5 app? I am trying to write my first js code in my new Rails5 app and cannot seem to get Jquery to work, guessing it's a config/environment issue but despite all my searching and confirg alterations I cannot seem to get it running. Can anyone see what it is that I'm doing wrong?: gemfile; # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~> 5' application.html.erb; <title>MyEngine</title> <!-- Gon::Base.render_data --> <%= Gon::Base.render_data %> <%= csrf_meta_tags %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> new.html.erb; <%= link_to 'Remove Employee', '#', id: 'hide-employee' %> quotes.coffee; $(document).on "page:change", -> $('#hide-employee').click -> alert "Clicked!" And no alert when clicked. No errors, server running and page rendering fine, just nothing in console. Thanks for the help. A: Try using turbolinks:load instead. $(document).on 'turbolinks:load', -> $('#hide-employee').click -> alert 'Clicked!'
Q: Why is jQuery not working in my rails 5 app? I am trying to write my first js code in my new Rails5 app and cannot seem to get Jquery to work, guessing it's a config/environment issue but despite all my searching and confirg alterations I cannot seem to get it running. Can anyone see what it is that I'm doing wrong?: gemfile; # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~> 5' application.html.erb; <title>MyEngine</title> <!-- Gon::Base.render_data --> <%= Gon::Base.render_data %> <%= csrf_meta_tags %> <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> new.html.erb; <%= link_to 'Remove Employee', '#', id: 'hide-employee' %> quotes.coffee; $(document).on "page:change", -> $('#hide-employee').click -> alert "Clicked!" And no alert when clicked. No errors, server running and page rendering fine, just nothing in console. Thanks for the help. A: Try using turbolinks:load instead. $(document).on 'turbolinks:load', -> $('#hide-employee').click -> alert 'Clicked!' A: For those coming here because they have Rails 5.1, jQuery is no longer a default dependency. From the release notes: jQuery was required by default in earlier versions of Rails to provide features like data-remote, data-confirm and other parts of Rails' Unobtrusive JavaScript offerings. It is no longer required, as the UJS has been rewritten to use plain, vanilla JavaScript. This code now ships inside of Action View as rails-ujs. You can still use jQuery if needed, but it is no longer required by default. To add it back in, add to the Gemfile: gem 'jquery-rails' # Use jquery as the JavaScript library and then $ bundle A: The page:change event is defined in turbolinks-classic. This version is now deprecated like you can see by yourself. Instead, you can use turbolinks:load or turbolinks:render or turbolinks:before-render. A: Make sure you're app/assets/javascripts/application.js contains: //= require jquery //= require jquery-ujs Note: If you're using Rails 5.1 you can omit //= require jquery_ujs in favor of //= require rails-ujs. Also, consider removing turbolinks entierly. Doing so has resolved more asset pipeline issue than I care to count. I have a feeling it's not providing you much value anyway. :-) Remove turbolinks with: * *Remove turbolinks from the Gemfile and $ bundle. *Remove //= require turbolinks from app/assets/javascripts/application.js *Remove both of the "data-turbolinks-track" => true hashes from app/views/layouts/application.html.erb.
stackoverflow
{ "language": "en", "length": 387, "provenance": "stackexchange_0000F.jsonl.gz:911030", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44686214" }
baf331a3bed48a597b0ea78d6c2c05ec6f12416f
Stackoverflow Stackexchange Q: How can I determine if a block is occupied in Linux through an ioctl call? In Linux, we can call the FIBMAP() ioctl to determine which blocks a file occupies within a file system. What I am curious about is- how can I determine if any random block is occupied with a file (or any data). Is there an ioctl to do this as well, or do I have to simply lseek to the block and see if there has been data written to it or not? If there's a simple ioctl call to determine if a block is occupied - that would be ideal.
Q: How can I determine if a block is occupied in Linux through an ioctl call? In Linux, we can call the FIBMAP() ioctl to determine which blocks a file occupies within a file system. What I am curious about is- how can I determine if any random block is occupied with a file (or any data). Is there an ioctl to do this as well, or do I have to simply lseek to the block and see if there has been data written to it or not? If there's a simple ioctl call to determine if a block is occupied - that would be ideal.
stackoverflow
{ "language": "en", "length": 106, "provenance": "stackexchange_0000F.jsonl.gz:911060", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44686299" }
07868a4d3d7da7f3c47120e4168985acb4c511ae
Stackoverflow Stackexchange Q: Trying to publish a .net core project, getting a "build has been canceled" message I have a .net core project I am trying to publish. It build just fine, but I can't publish it. In the output, I simply get "Build had been canceled". Setting build logging to verbose doesn't yield any more information.
Q: Trying to publish a .net core project, getting a "build has been canceled" message I have a .net core project I am trying to publish. It build just fine, but I can't publish it. In the output, I simply get "Build had been canceled". Setting build logging to verbose doesn't yield any more information.
stackoverflow
{ "language": "en", "length": 55, "provenance": "stackexchange_0000F.jsonl.gz:911062", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44686304" }
845bcf8181f93f79fcb6103e35126ac1923fc5ea
Stackoverflow Stackexchange Q: python matplotlib barh reduce gap between bars I have a barh bar chart with two bars only in the figure, but when plotting them, they are very far apart: import numpy as np import matplotlib.pyplot as plt labels = ('Out', 'In') bar_values = [5, 10] num_items = len(labels) width = 0.25 ind = np.arange(num_items) bar_width = 0.1 fig = plt.figure() ax = fig.add_subplot(111) barlist = ax.barh(ind, bar_values, bar_width, align='edge', color='green') barlist[0].set_color('mediumseagreen') barlist[1].set_color('orangered') ax.set_yticks(ind) ax.set_yticklabels(labels) ax.invert_yaxis() # labels read top-to-bottom ax.set_xlabel('Total') plt.show() Is there a way of putting the bars closer together? I have already tried to specify the size of the figure, but that only reduces the overall size and has no impact on the gap size... A: You could either just increase the width of the bars by setting bar_width = 0.6 or a similar value, or you could reduce the y range of the figure, for example: barlist = ax.barh([0.1, 0.3], bar_values, bar_width, align='edge', color='green') ax.set_yticks([0.1, 0.3]) ax.set_yticklabels(labels) Both should increase the width of the bars compared to the distance between the bars.
Q: python matplotlib barh reduce gap between bars I have a barh bar chart with two bars only in the figure, but when plotting them, they are very far apart: import numpy as np import matplotlib.pyplot as plt labels = ('Out', 'In') bar_values = [5, 10] num_items = len(labels) width = 0.25 ind = np.arange(num_items) bar_width = 0.1 fig = plt.figure() ax = fig.add_subplot(111) barlist = ax.barh(ind, bar_values, bar_width, align='edge', color='green') barlist[0].set_color('mediumseagreen') barlist[1].set_color('orangered') ax.set_yticks(ind) ax.set_yticklabels(labels) ax.invert_yaxis() # labels read top-to-bottom ax.set_xlabel('Total') plt.show() Is there a way of putting the bars closer together? I have already tried to specify the size of the figure, but that only reduces the overall size and has no impact on the gap size... A: You could either just increase the width of the bars by setting bar_width = 0.6 or a similar value, or you could reduce the y range of the figure, for example: barlist = ax.barh([0.1, 0.3], bar_values, bar_width, align='edge', color='green') ax.set_yticks([0.1, 0.3]) ax.set_yticklabels(labels) Both should increase the width of the bars compared to the distance between the bars.
stackoverflow
{ "language": "en", "length": 176, "provenance": "stackexchange_0000F.jsonl.gz:911065", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44686314" }
e9976cbb2fa8f13deee5af6b3fdd830fcccf651a
Stackoverflow Stackexchange Q: How many consumers are created to read records per direct stream? I'm using Spark Streaming to read data from Kafka (using the Kafka direct stream API). How many Kafka consumers are instantiated for a stream? Is the number of Kafka consumers equal to the number of executors? Does each executor instantiate one Kafka consumer (with the same group id)? A: With direct approach number of consumers will be exactly the same as the number of Kafka Partitions: The Spark Streaming integration for Kafka 0.10 is similar in design to the 0.8 Direct Stream approach. It provides simple parallelism, 1:1 correspondence between Kafka partitions and Spark partitions, and access to offsets and metadata and the separate consumer is initialized for each partition.
Q: How many consumers are created to read records per direct stream? I'm using Spark Streaming to read data from Kafka (using the Kafka direct stream API). How many Kafka consumers are instantiated for a stream? Is the number of Kafka consumers equal to the number of executors? Does each executor instantiate one Kafka consumer (with the same group id)? A: With direct approach number of consumers will be exactly the same as the number of Kafka Partitions: The Spark Streaming integration for Kafka 0.10 is similar in design to the 0.8 Direct Stream approach. It provides simple parallelism, 1:1 correspondence between Kafka partitions and Spark partitions, and access to offsets and metadata and the separate consumer is initialized for each partition.
stackoverflow
{ "language": "en", "length": 122, "provenance": "stackexchange_0000F.jsonl.gz:911078", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44686366" }
340a3b1b47823bae15799d2cc9ecd226b155e6fd
Stackoverflow Stackexchange Q: Libgdx sprite not drawing in browser This is the first time I'm trying to deploy a libgdx game to html but having some difficulties. On desktop everything works fine, but in browser two of my sprites are not showing up, the rest is fine. These two sprites should be backgrounds and scrolling why the character moves. I'm loading my textures in a GameScree class' show method like this: backgroundTexture = new Texture(Gdx.files.internal("background.png")); //setting wraping to repeat to achive scrolling background by one texture backgroundTexture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat); //and I render it like this (I create a Sprite of it) batch.draw(backgroundSprite.getTexture(),0,0, (int) position ,0, 1280, 720); By increasing position the background is scrolling which works fine on desktop. I got errors in chromes console: [.Offscreen-For-WebGL-00000000071AC350]RENDER WARNING: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering. Which I don't exactly understand why, how is it incompatible? And also, none of my texture are POT but they are still working. A: You should avoid using mipmaps when texture is not power of 2. backgroundTexture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); It's better to use texture is in power of 2 (pixel width and height are some 2n value)
Q: Libgdx sprite not drawing in browser This is the first time I'm trying to deploy a libgdx game to html but having some difficulties. On desktop everything works fine, but in browser two of my sprites are not showing up, the rest is fine. These two sprites should be backgrounds and scrolling why the character moves. I'm loading my textures in a GameScree class' show method like this: backgroundTexture = new Texture(Gdx.files.internal("background.png")); //setting wraping to repeat to achive scrolling background by one texture backgroundTexture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat); //and I render it like this (I create a Sprite of it) batch.draw(backgroundSprite.getTexture(),0,0, (int) position ,0, 1280, 720); By increasing position the background is scrolling which works fine on desktop. I got errors in chromes console: [.Offscreen-For-WebGL-00000000071AC350]RENDER WARNING: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering. Which I don't exactly understand why, how is it incompatible? And also, none of my texture are POT but they are still working. A: You should avoid using mipmaps when texture is not power of 2. backgroundTexture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); It's better to use texture is in power of 2 (pixel width and height are some 2n value)
stackoverflow
{ "language": "en", "length": 197, "provenance": "stackexchange_0000F.jsonl.gz:911101", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44686450" }
6caffe17e602bf8758b2a9eb721f67f97a792135
Stackoverflow Stackexchange Q: How to get environment variable from a core dump In UNIX environment(linux/solaris/AIX) my application crashing. Please help to me get environment variable from the core dump A: Running strings -a core should produce an obvious-looking block of strings like HOME=..., HOSTNAME=..., etc. You can also examine initial environment by looking at the 3rd argument to main, which is a envp[] -- a NULL-terminated array of pointers to the environment strings. Finally, current environment block is pointed at by __environ or similar variable.
Q: How to get environment variable from a core dump In UNIX environment(linux/solaris/AIX) my application crashing. Please help to me get environment variable from the core dump A: Running strings -a core should produce an obvious-looking block of strings like HOME=..., HOSTNAME=..., etc. You can also examine initial environment by looking at the 3rd argument to main, which is a envp[] -- a NULL-terminated array of pointers to the environment strings. Finally, current environment block is pointed at by __environ or similar variable.
stackoverflow
{ "language": "en", "length": 83, "provenance": "stackexchange_0000F.jsonl.gz:911109", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44686478" }
c457beced1fef992dd5f85ecd3b0a05ca8c61c7f
Stackoverflow Stackexchange Q: Tell when Job is Complete I'm looking for a way to tell (from within a script) when a Kubernetes Job has completed. I want to then get the logs out of the containers and perform cleanup. What would be a good way to do this? Would the best way be to run kubectl describe job <job_name> and grep for 1 Succeeded or something of the sort? A: You can use official Python kubernetes-client. https://github.com/kubernetes-client/python Create new Python virtualenv: virtualenv -p python3 kubernetes_venv activate it with source kubernetes_venv/bin/activate and install kubernetes client with: pip install kubernetes Create new Python script and run: from kubernetes import client, config config.load_kube_config() v1 = client.BatchV1Api() ret = v1.list_namespaced_job(namespace='<YOUR-JOB-NAMESPACE>', watch=False) for i in ret.items: print(i.status.succeeded) Remember to set up your specific kubeconfig in ~/.kube/config and valid value for your job namespace -> '<YOUR-JOB-NAMESPACE>'
Q: Tell when Job is Complete I'm looking for a way to tell (from within a script) when a Kubernetes Job has completed. I want to then get the logs out of the containers and perform cleanup. What would be a good way to do this? Would the best way be to run kubectl describe job <job_name> and grep for 1 Succeeded or something of the sort? A: You can use official Python kubernetes-client. https://github.com/kubernetes-client/python Create new Python virtualenv: virtualenv -p python3 kubernetes_venv activate it with source kubernetes_venv/bin/activate and install kubernetes client with: pip install kubernetes Create new Python script and run: from kubernetes import client, config config.load_kube_config() v1 = client.BatchV1Api() ret = v1.list_namespaced_job(namespace='<YOUR-JOB-NAMESPACE>', watch=False) for i in ret.items: print(i.status.succeeded) Remember to set up your specific kubeconfig in ~/.kube/config and valid value for your job namespace -> '<YOUR-JOB-NAMESPACE>' A: You can visually watch a job's status with this command: kubectl get jobs myjob -w The -w option watches for changes. You are looking for the SUCCESSFUL column to show 1. For waiting in a shell script, I'd use this command: until kubectl get jobs myjob -o jsonpath='{.status.conditions[? (@.type=="Complete")].status}' | grep True ; do sleep 1 ; done A: I would use -w or --watch: $ kubectl get jobs.batch --watch NAME COMPLETIONS DURATION AGE python 0/1 3m4s 3m4s A: Since version 1.11, you can do: kubectl wait --for=condition=complete job/myjob and you can also set a timeout: kubectl wait --for=condition=complete --timeout=30s job/myjob A: Adding the best answer, from a comment by @Coo, If you add a -f or --follow option when getting logs, it'll keep tailing the log and terminate when the job completes or fails. The $# status code is even non-zero when the job fails. kubectl logs -l job-name=myjob --follow One downside of this approach, that I'm aware of, is that there's no timeout option. Another downside is the logs call may fail while the pod is in Pending (while the containers are being started). You can fix this by waiting for the pod: # Wait for pod to be available; logs will fail if the pod is "Pending" while [[ "$(kubectl get pod -l job-name=myjob -o json | jq -rc '.items | .[].status.phase')" == 'Pending' ]]; do # Avoid flooding k8s with polls (seconds) sleep 0.25 done # Tail logs kubectl logs -l job-name=myjob --tail=400 -f A: It either one of these queries with kubectl kubectl get job test-job -o jsonpath='{.status.succeeded}' or kubectl get job test-job -o jsonpath='{.status.conditions[?(@.type=="Complete")].status}' A: Although kubectl wait --for=condition=complete job/myjob and kubectl wait --for=condition=complete job/myjob allow us to check whether the job completed but there is no way to check if the job just finished executing (irrespective of success or failure). If this is what you are looking for, a simple bash while loop with kubectl status check did the trick for me. #!/bin/bash while true; do status=$(kubectl get job jobname -o jsonpath='{.status.conditions[0].type}') echo "$status" | grep -qi 'Complete' && echo "0" && exit 0 echo "$status" | grep -qi 'Failed' && echo "1" && exit 1 done
stackoverflow
{ "language": "en", "length": 503, "provenance": "stackexchange_0000F.jsonl.gz:911134", "question_score": "112", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44686568" }
abd6281d065d5cb11afb8f2dfb283a1fb4c68438
Stackoverflow Stackexchange Q: depends in phpunit doesn't seem to be working Maybe it's just me but @depends doesn't seem to be working as I'd expect it to. My code: <?php use PHPUnit\Framework\TestCase; class MyTest extends TestCase { /* * @depends testFunc1 */ public function testFunc2() { exit('TEST FUNC 2 called'); } public function testFunc1() { exit('TEST FUNC 1 called'); } } When I do phpunit MyTest.php I'd expect to see TEST FUNC 1 called but instead I see TEST FUNC 2 called. As is it seems to just be running the tests in the order they appear in the script, regardless of the @depends attribute, which really begs the question: what does @depends actually do? I'm running PHPUnit 5.7.20. A: You need to use /** instead of /* to start a docblock.
Q: depends in phpunit doesn't seem to be working Maybe it's just me but @depends doesn't seem to be working as I'd expect it to. My code: <?php use PHPUnit\Framework\TestCase; class MyTest extends TestCase { /* * @depends testFunc1 */ public function testFunc2() { exit('TEST FUNC 2 called'); } public function testFunc1() { exit('TEST FUNC 1 called'); } } When I do phpunit MyTest.php I'd expect to see TEST FUNC 1 called but instead I see TEST FUNC 2 called. As is it seems to just be running the tests in the order they appear in the script, regardless of the @depends attribute, which really begs the question: what does @depends actually do? I'm running PHPUnit 5.7.20. A: You need to use /** instead of /* to start a docblock.
stackoverflow
{ "language": "en", "length": 130, "provenance": "stackexchange_0000F.jsonl.gz:911220", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44686855" }
38766a5fc030212d9673dc25e9dba6ff26e42a57
Stackoverflow Stackexchange Q: Bidirectional LSTM with Batch Normalization in Keras I was wondering how to implement biLSTM with Batch Normalization (BN) in Keras. I know that BN layer should be between linearity and nonlinearity, i.e., activation. This is easy to implement with CNN or Dense layers. But, how to do this with biLSTM? Thanks in advance. A: If you want to apply BatchNormalization over the linear outputs of an LSTM you can do it as from keras.models import Sequential from keras.layers.recurrent import LSTM from keras.layers.wrappers import Bidirectional from keras.layers.normalization import BatchNormalization model = Sequential() model.add(Bidirectional(LSTM(128, activation=None), input_shape=(256,10))) model.add(BatchNormalization()) Essentially, you are removing the non-linear activations of the LSTM (but not the gate activations), and then applying BatchNormalization to the outpus. If what you want is to apply BatchNormalization into one of the inside flows of the LSTM, such as recurrent flows, I'm afraid that feature has not been implemented in Keras.
Q: Bidirectional LSTM with Batch Normalization in Keras I was wondering how to implement biLSTM with Batch Normalization (BN) in Keras. I know that BN layer should be between linearity and nonlinearity, i.e., activation. This is easy to implement with CNN or Dense layers. But, how to do this with biLSTM? Thanks in advance. A: If you want to apply BatchNormalization over the linear outputs of an LSTM you can do it as from keras.models import Sequential from keras.layers.recurrent import LSTM from keras.layers.wrappers import Bidirectional from keras.layers.normalization import BatchNormalization model = Sequential() model.add(Bidirectional(LSTM(128, activation=None), input_shape=(256,10))) model.add(BatchNormalization()) Essentially, you are removing the non-linear activations of the LSTM (but not the gate activations), and then applying BatchNormalization to the outpus. If what you want is to apply BatchNormalization into one of the inside flows of the LSTM, such as recurrent flows, I'm afraid that feature has not been implemented in Keras.
stackoverflow
{ "language": "en", "length": 149, "provenance": "stackexchange_0000F.jsonl.gz:911249", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44686930" }
5a2f6c77f391f0ca29b95a4383b4de8e7528aae9
Stackoverflow Stackexchange Q: How to add characters to a string in C# Problem: I would like add characters to a phone. So instead of displaying ###-###-####, I would like to display (###) ###-####. I tried the following: string x = "Phone_Number"; string y = x.Remove(0,2);//removes the "1-" From here, I am not sure how I would add "()" around ### Any help would be appreciated. A: It's worth noting that strings are immutable in C#.. meaning that if you attempt to modify one you'll always be given a new string object. One route would be to convert to a number (as a sanity check) then format the string var result = String.Format("{0:(###) ###-####}", double.Parse("8005551234")) If you'd rather not do the double-conversion then you could do something like this: var result = String.Format("({0}) {1}-{2}", x.Substring(0 , 3), x.Substring(3, 3), x.Substring(6)); Or, if you already have the hyphen in place and really just want to jam in the parenthesis then you can do something like this: var result = x.Insert(3, ")").Insert(0, "(");
Q: How to add characters to a string in C# Problem: I would like add characters to a phone. So instead of displaying ###-###-####, I would like to display (###) ###-####. I tried the following: string x = "Phone_Number"; string y = x.Remove(0,2);//removes the "1-" From here, I am not sure how I would add "()" around ### Any help would be appreciated. A: It's worth noting that strings are immutable in C#.. meaning that if you attempt to modify one you'll always be given a new string object. One route would be to convert to a number (as a sanity check) then format the string var result = String.Format("{0:(###) ###-####}", double.Parse("8005551234")) If you'd rather not do the double-conversion then you could do something like this: var result = String.Format("({0}) {1}-{2}", x.Substring(0 , 3), x.Substring(3, 3), x.Substring(6)); Or, if you already have the hyphen in place and really just want to jam in the parenthesis then you can do something like this: var result = x.Insert(3, ")").Insert(0, "("); A: To insert string in particular position you can use Insert function. Here is an example: string phone = "111-222-8765"; phone = phone.Insert(0, "("); // (111-222-8765 phone = phone.Insert(3, ")"); // (111)-222-8765 A: You can use a regular expression to extract the digit groups (regardless of - or () and then output in your desired format: var digitGroups = Regex.Matches(x, @"(\d{3})-?(\d{3})-?(\d{4})")[0].Groups.Cast<Group>().Skip(1).Select(g => g.Value).ToArray(); var ans = $"({digitGroups[0]}) {digitGroups[1]}-{digitGroups[2]}"; A: I would do something like this: string FormatPhoneNumber(string phoneNumber) { if (string.IsNullOrEmpty(phoneNumber)) throw new ArgumentNullException(nameof(phoneNumber)); var phoneParts = phoneNumber.Split('-'); if (phoneParts.Length < 3) throw new ArgumentException("Something wrong with the input number format", nameof(phoneNumber)); var firstChar = phoneParts[0].First(); var lastChar = phoneParts[0].Last(); if (firstChar == '(' && lastChar == ')') return phoneNumber; else if (firstChar == '(') return $"{phoneParts[0]})-{phoneParts[1]}-{phoneParts[2]}"; else if (lastChar == ')') return $"({phoneParts[0]}-{phoneParts[1]}-{phoneParts[2]}"; return $"({phoneParts[0]})-{phoneParts[1]}-{phoneParts[2]}"; } You would use it like this: string n = "123-123-1234"; var formattedPhoneNumber = FormatPhoneNumber(n);
stackoverflow
{ "language": "en", "length": 319, "provenance": "stackexchange_0000F.jsonl.gz:911267", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44686985" }
668e654f0dd91727b0ed993276d1892fa597e4ea
Stackoverflow Stackexchange Q: Close modal dialog page and refresh the page Oracle APEX I am trying to close a modal dialog page after changes have been made and then refresh the edit form that was underneath the modal dialog in Oracle Apex. I tried using dynamic action to close the dialog, but it seems that the dynamic action proceeds the processing step, resulting in the data not being saved into the database after the modal dialog has closed. modal dialog = page edit form = page modal dialog is a pop out on the edit form Is there a way to close the dialog, while saving the data and also refresh the edit form? I think there is a way to also redirect to previous page but I do not know how to do that. A: Yes there are many ways to close the dialog box while saving the data. * *you can use the process for dialog close, process should be after your process which is saving data. *Javascript: please refer below link http://ashishtheapexian.blogspot.in/2017/06/refresh-region-of-base-page-when.html https://apex.oracle.com/pls/apex/f?p=1200008:15:132444785184935::NO:RP:P15_POST_ID:142 *Branching : You can create a branch after processing point. this will redirect and close the dialog after saving you data to the database.
Q: Close modal dialog page and refresh the page Oracle APEX I am trying to close a modal dialog page after changes have been made and then refresh the edit form that was underneath the modal dialog in Oracle Apex. I tried using dynamic action to close the dialog, but it seems that the dynamic action proceeds the processing step, resulting in the data not being saved into the database after the modal dialog has closed. modal dialog = page edit form = page modal dialog is a pop out on the edit form Is there a way to close the dialog, while saving the data and also refresh the edit form? I think there is a way to also redirect to previous page but I do not know how to do that. A: Yes there are many ways to close the dialog box while saving the data. * *you can use the process for dialog close, process should be after your process which is saving data. *Javascript: please refer below link http://ashishtheapexian.blogspot.in/2017/06/refresh-region-of-base-page-when.html https://apex.oracle.com/pls/apex/f?p=1200008:15:132444785184935::NO:RP:P15_POST_ID:142 *Branching : You can create a branch after processing point. this will redirect and close the dialog after saving you data to the database. A: Refresh Page when Dialog is closed. Click here this blog will give enough information about how to refresh the Page when model dialog closed (cross icon). We can trigger a dynamic action when user press cross icon in model dialog. This will archive by pasting the following code in Model dialog property-> Dialog -> attribute: close: function(event, ui) {apex.navigation.dialog.close(true,{dialogPageId:7});} And one more thing we need to keep in mind that "chained property" set to Yes for page to refresh. Here 7 is model dialog page number. Above given code will trigger dialog closed event.
stackoverflow
{ "language": "en", "length": 293, "provenance": "stackexchange_0000F.jsonl.gz:911282", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687041" }
e19abe783e679242f299a768678ecdfb1509f2c6
Stackoverflow Stackexchange Q: Keeping track of original indicies when sorting a list of lists by length You can sort a list of lists by length as follows: l1 = [1,2,3] l2 = [1,2,3] l3 = [1,2] lists = [l1, l2, l3] sorted_lists = sorted(lists, key=len) print sorted_lists #[[1,2], [1,2,3], [1,2,3]] I can't figure out how to keep track of the indicies to then match up the contents of sorted_lists with the original list names l1, l2 and l3. This gets close, but I'm not sure how the solution can be implemented when sorting by length. A: It is very possible. Just modify the key a bit to specify the right predicate on which len is to be applied. >>> lists = [l1, l2, l3] >>> lists = sorted(enumerate(lists), key=lambda x: len(x[1])) # enumerate is a tuple of (index, elem), sort by len(elem) [(2, [1, 2]), (0, [1, 2, 3]), (1, [1, 2, 3])]
Q: Keeping track of original indicies when sorting a list of lists by length You can sort a list of lists by length as follows: l1 = [1,2,3] l2 = [1,2,3] l3 = [1,2] lists = [l1, l2, l3] sorted_lists = sorted(lists, key=len) print sorted_lists #[[1,2], [1,2,3], [1,2,3]] I can't figure out how to keep track of the indicies to then match up the contents of sorted_lists with the original list names l1, l2 and l3. This gets close, but I'm not sure how the solution can be implemented when sorting by length. A: It is very possible. Just modify the key a bit to specify the right predicate on which len is to be applied. >>> lists = [l1, l2, l3] >>> lists = sorted(enumerate(lists), key=lambda x: len(x[1])) # enumerate is a tuple of (index, elem), sort by len(elem) [(2, [1, 2]), (0, [1, 2, 3]), (1, [1, 2, 3])] A: Using arg.sort() from numpy with list comprehension can be other way: import numpy new_list = [(index, lists[index])for index in numpy.argsort(lists)] print(new_list) Output: [(2, [1, 2]), (0, [1, 2, 3]), (1, [1, 2, 3])]
stackoverflow
{ "language": "en", "length": 185, "provenance": "stackexchange_0000F.jsonl.gz:911291", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687057" }
32123f4b461f90964029cb47cb96f05aa29a00db
Stackoverflow Stackexchange Q: How to use Chrome Developer Tools Performance or Memory tab when page freezes So I've got a page that after it is loaded the Javascript just keeps running and running until I bring up Chrome's Task Manager and kill the tab. I want to find the memory leak. When I use the Performance tab and stop a recording it'll say "Loading profile..." forever. So I'll kill the tab in Task Manager, but then the profile never loads. Same problem with taking a Heap Snapshot under the Memory Tab. Is there a way to use the Performance or Memory tabs when I have to kill the tab? Or do I just have to go "old school" and use console.log() everywhere?
Q: How to use Chrome Developer Tools Performance or Memory tab when page freezes So I've got a page that after it is loaded the Javascript just keeps running and running until I bring up Chrome's Task Manager and kill the tab. I want to find the memory leak. When I use the Performance tab and stop a recording it'll say "Loading profile..." forever. So I'll kill the tab in Task Manager, but then the profile never loads. Same problem with taking a Heap Snapshot under the Memory Tab. Is there a way to use the Performance or Memory tabs when I have to kill the tab? Or do I just have to go "old school" and use console.log() everywhere?
stackoverflow
{ "language": "en", "length": 120, "provenance": "stackexchange_0000F.jsonl.gz:911317", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687143" }
512b3b91c350b9655a87e7c68c44b51e0d587363
Stackoverflow Stackexchange Q: How to register custom hibernate type using spring boot? In hibernate documentation custom types are registered using a Configuration instance. How can I access this instance and register my type using spring boot? Using @TypeDef for entities works fine, but with a jpa native query i get a "javax.persistence.PersistenceException: org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111" It works with my own dialect and registering via registerHibernateType, but with only one custom type registered to column type Types.OTHER (JDBC type 1111). Any other custom type registration overwrites old one. The query is simple, only selects a constant value of the given custom type. Using hibernate 5.0.9 and spring boot 1.4.0. A: Same issue Postgresql driver 42.2.2 Hibernate 5.2.17 I have fixed the issue by adding a custom SQL Dialect. import java.sql.Types; import org.hibernate.dialect.PostgreSQL94Dialect; public class CustomPostgreSQLDialect extends PostgreSQL94Dialect { public ConnectedWellPostgreSQLDialect() { super(); registerHibernateType(Types.OTHER, "pg-uuid"); } } And configure configure hibrenate to use the new class: spring.jpa.properties.hibernate.dialect.config=com.mypackage.CustomPostgreSQLDialect
Q: How to register custom hibernate type using spring boot? In hibernate documentation custom types are registered using a Configuration instance. How can I access this instance and register my type using spring boot? Using @TypeDef for entities works fine, but with a jpa native query i get a "javax.persistence.PersistenceException: org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111" It works with my own dialect and registering via registerHibernateType, but with only one custom type registered to column type Types.OTHER (JDBC type 1111). Any other custom type registration overwrites old one. The query is simple, only selects a constant value of the given custom type. Using hibernate 5.0.9 and spring boot 1.4.0. A: Same issue Postgresql driver 42.2.2 Hibernate 5.2.17 I have fixed the issue by adding a custom SQL Dialect. import java.sql.Types; import org.hibernate.dialect.PostgreSQL94Dialect; public class CustomPostgreSQLDialect extends PostgreSQL94Dialect { public ConnectedWellPostgreSQLDialect() { super(); registerHibernateType(Types.OTHER, "pg-uuid"); } } And configure configure hibrenate to use the new class: spring.jpa.properties.hibernate.dialect.config=com.mypackage.CustomPostgreSQLDialect A: It seems there is no automatic mapping of the result to a custom type. For postgres, the returned jdbc PGObject contains the column type name (ex: 'tsvector'), but the hibernate custom types knows only the sql type (OTHER in this case), not the db type name, so it cannot do the match. The workaround is to unwrap the jpa native query and register the returned scalar type (custom hibernate type), ex: Query query = entityManager.createNativeQuery( "SELECT <SOMETHING> AS res" ); query.unwrap( SQLQuery.class ).addScalar( "res", CustomHibernateType.INSTANCE ); Note that this affects QueryDSL (4.1.4), as there is no mechanism to register the scalar as hibernate custom type, so the jpa native query fails (JPASQLQuery). The workaround in this case is to use a non-jpa native query with a AbstractType registered with QueryDSL, and the conversion will be done automatically.
stackoverflow
{ "language": "en", "length": 296, "provenance": "stackexchange_0000F.jsonl.gz:911320", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687149" }
5aaa8861aecc32bbd71762276152cc4e3a281283
Stackoverflow Stackexchange Q: How to create a free SMTP server I am not at all familiar with SMTP but I am working on sending emails through Python code. I have the code but I need to pass SMTP host name for it to actually work. Is there any service which provides a free SMTP service that I leverage for testing out my code? I looked around to create my own SMTP server but couldn't find something that provides a step by step guide to create a SMTP server. I want to create a free server(or if there is any free service) that will provide me with a host name(ip address) so that I can put that host name in my python code and execute it from any machine. If anyone can point me in the right direction it will be helpful. A: import smtplib username = 'user' password = 'pwd' from_addr = '[email protected]' to_addrs = '[email protected]' msg = "\r\n".join([ "From: [email protected]", "To: [email protected]", "Subject: subject", "", "message" ]) server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(username, password) server.sendmail(from_addr, to_addrs, msg) server.quit() You can use mutt linux command also here. See : https://docs.python.org/3/library/smtplib.html https://support.google.com/a/answer/176600?hl=en
Q: How to create a free SMTP server I am not at all familiar with SMTP but I am working on sending emails through Python code. I have the code but I need to pass SMTP host name for it to actually work. Is there any service which provides a free SMTP service that I leverage for testing out my code? I looked around to create my own SMTP server but couldn't find something that provides a step by step guide to create a SMTP server. I want to create a free server(or if there is any free service) that will provide me with a host name(ip address) so that I can put that host name in my python code and execute it from any machine. If anyone can point me in the right direction it will be helpful. A: import smtplib username = 'user' password = 'pwd' from_addr = '[email protected]' to_addrs = '[email protected]' msg = "\r\n".join([ "From: [email protected]", "To: [email protected]", "Subject: subject", "", "message" ]) server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(username, password) server.sendmail(from_addr, to_addrs, msg) server.quit() You can use mutt linux command also here. See : https://docs.python.org/3/library/smtplib.html https://support.google.com/a/answer/176600?hl=en A: You need service like https://mailtrap.io/. You'll get SMTP server address (eventually port number) that you point your application to. All e-mails produced by your application will be then intercepted by mailtrap (thus not delivered to the real To: address). They offer free variant that seems to be suitable for your needs.
stackoverflow
{ "language": "en", "length": 241, "provenance": "stackexchange_0000F.jsonl.gz:911326", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687159" }
43b8594ac221274d864f3f10b035a00572aac110
Stackoverflow Stackexchange Q: Typescript Error: Property 'append' does not exist on type 'HTMLElement' The Problem: I'm receiving a Typescript 2.2.1 compilation error when trying to append a compiled angular 1.5 template to an existing HTMLElement. Code: $document.find(scope.target)[0].append($compile(menu)(scope)[0]); Compile error: [ts] Property 'append' does not exist on type 'HTMLElement' I've searched through the type definitions and don't see a signature for append(). Any ideas as to which type or version of typescript I should be using? Thanks! A: Here there is nothing to do with TypeScript. The correct method to call is appendChild: https://developer.mozilla.org/en/docs/Web/API/Node/appendChild append is a jQuery method, and if you want to use that you could do: $document.find(scope.target).append($compile(menu)(scope)[0]); and it should work too. I hope it helps
Q: Typescript Error: Property 'append' does not exist on type 'HTMLElement' The Problem: I'm receiving a Typescript 2.2.1 compilation error when trying to append a compiled angular 1.5 template to an existing HTMLElement. Code: $document.find(scope.target)[0].append($compile(menu)(scope)[0]); Compile error: [ts] Property 'append' does not exist on type 'HTMLElement' I've searched through the type definitions and don't see a signature for append(). Any ideas as to which type or version of typescript I should be using? Thanks! A: Here there is nothing to do with TypeScript. The correct method to call is appendChild: https://developer.mozilla.org/en/docs/Web/API/Node/appendChild append is a jQuery method, and if you want to use that you could do: $document.find(scope.target).append($compile(menu)(scope)[0]); and it should work too. I hope it helps A: There is an append/prepend function on HTMLElement. The problem that it is currently still experimental. In order to use it without getting errors from TypeScript I used it as any Β―\_(ツ)_/Β― (<any>myElement).append(otherElement) A: Element.append() now exists (since 2016). If TypeScript is finding an error: * *Types: ensure that it's an Element and not just a Node *Config: ensure you're loading the DOM library *Config: ensure you're using a recent ES target/lib Example config: { "compilerOptions": { "target": "es2020", "lib": ["dom", "es2019", "es2020", "dom.iterable"] } }
stackoverflow
{ "language": "en", "length": 202, "provenance": "stackexchange_0000F.jsonl.gz:911330", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687176" }
36306259257f0d88982c7396081db67b4a9a9f1b
Stackoverflow Stackexchange Q: Why isn't 〉allowed as a Haskell infix operator? Why isn't 〉 allowed as an infix operator in Haskell? GHCi, version 8.0.2: http://www.haskell.org/ghc/ :? for help Prelude> :{ infixr 6 〉 (〉) :: Int -> (Int -> (Int)) a 〉 b = a + 2*b :} print (1 〉 2) According to this Haskell Report any Unicode symbol or punctuation and this question it should work. A: It's probably a bug. It doesn't seem to allow any characters marked as ClosePunctuation or OpenPunctuation by generalCategory. I suggest you open a ticket on the GHC Trac and see what they think. https://ghc.haskell.org/trac/ghc/ticket/2687 looks related and suggests that at least at some point OpenPunctuation and ClosePunctuation were considered graphic rather than symbol.
Q: Why isn't 〉allowed as a Haskell infix operator? Why isn't 〉 allowed as an infix operator in Haskell? GHCi, version 8.0.2: http://www.haskell.org/ghc/ :? for help Prelude> :{ infixr 6 〉 (〉) :: Int -> (Int -> (Int)) a 〉 b = a + 2*b :} print (1 〉 2) According to this Haskell Report any Unicode symbol or punctuation and this question it should work. A: It's probably a bug. It doesn't seem to allow any characters marked as ClosePunctuation or OpenPunctuation by generalCategory. I suggest you open a ticket on the GHC Trac and see what they think. https://ghc.haskell.org/trac/ghc/ticket/2687 looks related and suggests that at least at some point OpenPunctuation and ClosePunctuation were considered graphic rather than symbol.
stackoverflow
{ "language": "en", "length": 120, "provenance": "stackexchange_0000F.jsonl.gz:911378", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687319" }
f46bbec853db365f0cc492fa7352423660097b0e
Stackoverflow Stackexchange Q: Remove characters after the last occurrence of a specific character I have a string that looks like: exampleList <- c("rs40535:1745233:G:A_AGGG","rs41111:1733320:GAC:AAC_TTTTTTG", "exm2344379:1724237:A:T_A", "exm-rs234380:1890910:A:G_A", "rs423444419_T","psy_rs73453432_TCCC","22:1701234072:C:T_C","9:4534345:rs2342342_G","chr10_rs7287862_C","psy_rs7291672_A") I wish to remove everything after the last underscore ( _ ) so my result looks something like this: [1] "rs40535:1745233:G:A" "rs41111:1733320:GAC:AAC" "exm2344379:1724237:A:T" "exm-rs234380:1890910:A:G" "rs423444419" "psy_rs73453432" "22:1701234072:C:T" "9:4534345:rs2342342" "chr10_rs7287862" "psy_rs7291672" I've tried the following, but this removes everything after the first _. gsub("\\_.*$","",exampleList) I recognize there are similar posts but none I could find in R. A: Figured it out! outcome <- sub("_[^_]+$", "", exampleList)
Q: Remove characters after the last occurrence of a specific character I have a string that looks like: exampleList <- c("rs40535:1745233:G:A_AGGG","rs41111:1733320:GAC:AAC_TTTTTTG", "exm2344379:1724237:A:T_A", "exm-rs234380:1890910:A:G_A", "rs423444419_T","psy_rs73453432_TCCC","22:1701234072:C:T_C","9:4534345:rs2342342_G","chr10_rs7287862_C","psy_rs7291672_A") I wish to remove everything after the last underscore ( _ ) so my result looks something like this: [1] "rs40535:1745233:G:A" "rs41111:1733320:GAC:AAC" "exm2344379:1724237:A:T" "exm-rs234380:1890910:A:G" "rs423444419" "psy_rs73453432" "22:1701234072:C:T" "9:4534345:rs2342342" "chr10_rs7287862" "psy_rs7291672" I've tried the following, but this removes everything after the first _. gsub("\\_.*$","",exampleList) I recognize there are similar posts but none I could find in R. A: Figured it out! outcome <- sub("_[^_]+$", "", exampleList)
stackoverflow
{ "language": "en", "length": 89, "provenance": "stackexchange_0000F.jsonl.gz:911385", "question_score": "15", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687333" }
31a3351ddc5049667874abd8e4fe52ed2f8d5974
Stackoverflow Stackexchange Q: Bootstrap 3.3.7 "row" causing horizontal scroll bar Ok ok, I know. This question has been asked a lot. But, so far, I have not found a working solution. I boiled my page down to nothing but this: <div class="row"> <div class="col-sm-12"> stuff </div> </div> And there is still a horizontal scroll bar. In dev tools, I can find the row: .row { margin-right: -15px; margin-left: -15px; } And if I un-click margin-right: -15px; then the problem goes away. But, on my actual page (with all of the content) this creates another problem. The page needs to have zero margins, but it now was a 15px margin on the right. One of the answers here sad to wrap row with container-fluid. Another said to wrap it in container. Both of these did make the scroll bar go away, but they also give the page side margins, which I can't have. I've found threads discussing this as far back as 2013. Is this really not fixed yet? What do I need to do? Also: Fiddle https://jsfiddle.net/oLx4g8e3/1/ A: An easier way is to simply remove the margins on the offending row(s): .row { margin-left: 0px; margin-right: 0px; }
Q: Bootstrap 3.3.7 "row" causing horizontal scroll bar Ok ok, I know. This question has been asked a lot. But, so far, I have not found a working solution. I boiled my page down to nothing but this: <div class="row"> <div class="col-sm-12"> stuff </div> </div> And there is still a horizontal scroll bar. In dev tools, I can find the row: .row { margin-right: -15px; margin-left: -15px; } And if I un-click margin-right: -15px; then the problem goes away. But, on my actual page (with all of the content) this creates another problem. The page needs to have zero margins, but it now was a 15px margin on the right. One of the answers here sad to wrap row with container-fluid. Another said to wrap it in container. Both of these did make the scroll bar go away, but they also give the page side margins, which I can't have. I've found threads discussing this as far back as 2013. Is this really not fixed yet? What do I need to do? Also: Fiddle https://jsfiddle.net/oLx4g8e3/1/ A: An easier way is to simply remove the margins on the offending row(s): .row { margin-left: 0px; margin-right: 0px; } A: First of all you don't need row or col-*12 classes if your section is 100% wide look at this bootstrap example they have not taken any row or col-*12 neither with header nor jumbotron. If your section has column Just take row inside col-* classes for example <div class="col-sm-6"> <div class="row">stuff</div> </div> <div class="col-sm-6"> <div class="row">stuff</div> </div> Fiddle Or in case if you are using container-fluid <div class="container-fluid"> <div class="row"> <div class="col-sm-6"> <div class="row">stuff</div> </div> <div class="col-sm-6"> <div class="row">stuff</div> </div> </div> </div> Fiddle A: Are you talking about a scrollbar appearing on the bottom of the page when the container is supposed to be fluid? There might be an element in your page that is extending the width of the screen. I usually use this Chrome extension to see what CSS elements are extending farther than they should. Also, see if this Fiddle helps (code below). <div class="container-fluid"> <div class="row"> <div class="col-sm-12"> Lorem Ipsum is simply dummied text of the printing and typesetting industry. </div> </div> </div> A: I will just straight away jump to Bootstrap 5 since this is the latest version and everyone is using it currently. Last Updated on Dec 2022 Tested on Bootstrap 5.2 βœ” Tested on Bootstrap 5.1 βœ” Tested on Bootstrap 5.0 βœ” Bootstrap 5 If some of you using Bootstrap 5 you can use overflow-hidden to fix this issue. Thought it might help others. My situation is I had to use row inside container-fluid and the row is not touching the edge of my browser which is want I wanted. When I add px-0 i get the horizontal scroll bar. After going through the documentation I came across overflow-hidden. https://getbootstrap.com/docs/5.0/layout/gutters/#horizontal-gutters <div class="container-fluid px-0 overflow-hidden"> <div class="row"> <div class="col-12"> <!-- your text --> </div> </div> </div> A: If someone is facing this in Bootstrap v4. Just add m-0 to your div. <div class="row m-0"></div> A: Why dont you use a container-fluid and completely remove the margin ? <div class="container-fluid" style="margin: 0"> <div class="row"> <div class="col-md-6"> </div> <div class="col-md-6"> </div> </div> </div> Or make your own div around it with width: 100% A: In my particular case, I had to change .container from "width: 100%" to "width: initial". .container { width: initial; } If you need to keep width: 100%, you could perhaps also try box-sizing: border-box; .container { box-sizing: border-box; }
stackoverflow
{ "language": "en", "length": 584, "provenance": "stackexchange_0000F.jsonl.gz:911390", "question_score": "22", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687345" }
15fbc601c4b767a9a72d80dd1331ce8ab1727b1d
Stackoverflow Stackexchange Q: Android - PNG image has alpha channel, but when in imageview white background is shown. How can I fix? Problem: I have saved a png image into the @drawable folder in android studio. This image is confirmed to have an alpha channel. Image in android studio: When I add it to an image view in a relative layout the alpha channel is lost ImageView image: xml layout code: <ImageView android:layout_width="100dp" android:layout_height="100dp" app:srcCompat="@drawable/icon_main" android:id="@+id/main_icon_img" android:background="@android:color/transparent" android:scaleType="fitXY" android:adjustViewBounds="true" android:layout_marginLeft="31dp" android:layout_marginStart="31dp" android:layout_marginTop="113dp" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> I have tried setting the background to transparent. If I save it to a mipmap then the image will show the alpha channel, although this is not my preferred method. Is there a reason to why its appearing with a white background? A: For me the problem was <item name="android:background">@color/white</item> in the theme style. This made all the views to be drawn with a white BG. Even theTextViews.
Q: Android - PNG image has alpha channel, but when in imageview white background is shown. How can I fix? Problem: I have saved a png image into the @drawable folder in android studio. This image is confirmed to have an alpha channel. Image in android studio: When I add it to an image view in a relative layout the alpha channel is lost ImageView image: xml layout code: <ImageView android:layout_width="100dp" android:layout_height="100dp" app:srcCompat="@drawable/icon_main" android:id="@+id/main_icon_img" android:background="@android:color/transparent" android:scaleType="fitXY" android:adjustViewBounds="true" android:layout_marginLeft="31dp" android:layout_marginStart="31dp" android:layout_marginTop="113dp" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> I have tried setting the background to transparent. If I save it to a mipmap then the image will show the alpha channel, although this is not my preferred method. Is there a reason to why its appearing with a white background? A: For me the problem was <item name="android:background">@color/white</item> in the theme style. This made all the views to be drawn with a white BG. Even theTextViews. A: Please check the imageView if it has a background attribute and get rid of it as shown on this image I also found this site to be so helpful to enable you easily remove background from the image effectively making it PNG
stackoverflow
{ "language": "en", "length": 195, "provenance": "stackexchange_0000F.jsonl.gz:911396", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687364" }
bf08ef48368c51dbb0aa80552728b7ff696e368d
Stackoverflow Stackexchange Q: Shadow copy in mvc core In Asp.Net Shadow copying enables assemblies that are used in an application domain to be updated without unloading the application domain. Since Mvc Core not support AppDomain and can not load duplicate different version of assembly. I'm looking for a way to update the assemblies at runtime without unload or stop site. My goal is to update the site with a new version if available on remote server. A: You can find a workaround here: The site DLL seems to be intermittently locked when publishing. The trick consists of creating a subdirectory (eg. /PREVIOUS), move the 'old' files in that directory, change the web.config to point to the exe in that directory, publish the new site and change the web.config again. Of course, this should be scripted... If you have set 'Remove additional files at destination' you cannot work with a subdirectory, but you can put that directory elsewhere of course (as long as IIS has access to it).
Q: Shadow copy in mvc core In Asp.Net Shadow copying enables assemblies that are used in an application domain to be updated without unloading the application domain. Since Mvc Core not support AppDomain and can not load duplicate different version of assembly. I'm looking for a way to update the assemblies at runtime without unload or stop site. My goal is to update the site with a new version if available on remote server. A: You can find a workaround here: The site DLL seems to be intermittently locked when publishing. The trick consists of creating a subdirectory (eg. /PREVIOUS), move the 'old' files in that directory, change the web.config to point to the exe in that directory, publish the new site and change the web.config again. Of course, this should be scripted... If you have set 'Remove additional files at destination' you cannot work with a subdirectory, but you can put that directory elsewhere of course (as long as IIS has access to it). A: I too would like this. The current best workaround I’m aware of - when you want to overwrite assemblies that are in use, place a file in the folder called: app_offline.htm ...this will temporarily take the site offline allowing you to overwrite the files. Remove or rename the file when you’re done. If you script this it would have minimal impact. A: I have found the solution, which solves for me the problem of build errors in VS2017 due to locking of assemblies by dotnet.exe process, spawned by IIS Express. I've just added pre-build script to ASP.NET Core Web Application, touching applicationhost.config file, located in hidden .vs directory, which is used by IIS Express as config file. It looks in .csproj file like this: <Target Name="PreBuild" BeforeTargets="PreBuildEvent"> <Exec Command="IF EXIST &quot;$(SolutionDir)\.vs\config\applicationhost.config&quot; (pushd $(SolutionDir)\.vs\config\ &amp; copy /b applicationhost.config +,, &amp; popd)" /> </Target> Once file is touched by the script, IIS express terminates the dotnet.exe process, allowing build to proceed successfully. The new dotnet.exe process is spawned on the next request to web application. UPDATE For VS 2019 location of applicationhost.config file was changed so pre-build script event in .csproj file should look slightly different: <Target Name="PreBuild" BeforeTargets="PreBuildEvent" Condition="$(Configuration) == 'Debug'"> <Exec Command="IF EXIST &quot;$(SolutionDir)\.vs\<SolutionName>\config\applicationhost.config&quot; (pushd &quot;$(SolutionDir).vs\<SolutionName>\config\&quot; &amp; copy /b applicationhost.config +,, &amp; popd)" /> </Target> where <SolutionName> is solution file name without extension .sln. It is also required to remove the attribute hostingModel="InProcess" from the IIS Express configuration file $(SolutionDir)\.vs\<SolutionName>\config\applicationhost.config, which is automatically generated by VS on starting web application under IIS Express.
stackoverflow
{ "language": "en", "length": 419, "provenance": "stackexchange_0000F.jsonl.gz:911416", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687431" }
565eeba0aaf8283776129f7c1853331988e1843e
Stackoverflow Stackexchange Q: Python 2.7 exit a while loop with just one line if no match found Trying to implement Boyer Moore, bad character matching algorithm without looking at the answers. I want to exit this loop I wrote with just one line of "No match" if there was no pattern found, here is my code: T = 'ATGGGTATGGCTCGGCTCGG' p = 'ATCG' skip = 0 while skip + len(p) < len(T): string = T[skip:skip+len(p)] if string == p: print "offset at: ", skip break for i in range(len(string), 0, -1): if (string[i-1] != p[i-1]): if string[i-1] in p[:i-1]: skip += (i - p.find(string[i-1]) - 1) break elif not string[i-1] in p[:i-1]: skip += i break Any hits regarding how to modify the code. Thank you, xp edit: Scheme gave me the answer, as easy as that. I was so looping my head in the line string == p or string != p. Thank you for all your comments. A: I didn't quite get what you're trying to achieve here, but assuming you want to search for the substring within the base string, you can just use in as follows: if p in T: print "Match" else: print "No match"
Q: Python 2.7 exit a while loop with just one line if no match found Trying to implement Boyer Moore, bad character matching algorithm without looking at the answers. I want to exit this loop I wrote with just one line of "No match" if there was no pattern found, here is my code: T = 'ATGGGTATGGCTCGGCTCGG' p = 'ATCG' skip = 0 while skip + len(p) < len(T): string = T[skip:skip+len(p)] if string == p: print "offset at: ", skip break for i in range(len(string), 0, -1): if (string[i-1] != p[i-1]): if string[i-1] in p[:i-1]: skip += (i - p.find(string[i-1]) - 1) break elif not string[i-1] in p[:i-1]: skip += i break Any hits regarding how to modify the code. Thank you, xp edit: Scheme gave me the answer, as easy as that. I was so looping my head in the line string == p or string != p. Thank you for all your comments. A: I didn't quite get what you're trying to achieve here, but assuming you want to search for the substring within the base string, you can just use in as follows: if p in T: print "Match" else: print "No match" A: If i am understanding you correctly you would like to exit your while loop and print "no match" only once, if the string p is not contained in t. This looks like the all too common DNA exercise. Anyway a simple way to do what you want is to check for the substring p in t and break if it is not found. The answer here: How to determine whether a substring is in a different string would help with that. Basically: T = 'ATGGGTATGGCTCGGCTCGG' p = 'ATCG' skip = 0 while skip + len(p) < len(T): if not p in T: print "no match" break string = T[skip:skip+len(p)] if string == p: print "offset at: ", skip break for i in range(len(string), 0, -1): if (string[i-1] != p[i-1]): if string[i-1] in p[:i-1]: skip += (i - p.find(string[i-1]) - 1) break elif not string[i-1] in p[:i-1]: skip += i break The key here is the line if not p in T: Which is basically saying If the string p does not exist inside the string T then do something. else, carry on. On top of this you may want to consider looking at some good practices like variable naming, and using functions.
stackoverflow
{ "language": "en", "length": 400, "provenance": "stackexchange_0000F.jsonl.gz:911417", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687434" }
415cbb97c7fc0509e4e7fce1255fe6d940a2304e
Stackoverflow Stackexchange Q: Linter for consistent indentation in HTML files I'm looking for a CLI tool, npm package or gulp/grunt plugin to validate proper indentation in HTML files. All the options that I've tried don't report an error if the file is using the right spaces or tabs settings but the number of spaces expected is wrong. For example, the following indentation won't be reported as wrong: <button> <span class="someting">Lorem ipsum</span> <span>Lorem ipsum</span> <span>Consectetuer</span> </button> Ironically, the Stack Overflow editor detects wrong indentation, so I've been forced to use a snippet. I've tried htmllint, lintspaces and htmlhint.
Q: Linter for consistent indentation in HTML files I'm looking for a CLI tool, npm package or gulp/grunt plugin to validate proper indentation in HTML files. All the options that I've tried don't report an error if the file is using the right spaces or tabs settings but the number of spaces expected is wrong. For example, the following indentation won't be reported as wrong: <button> <span class="someting">Lorem ipsum</span> <span>Lorem ipsum</span> <span>Consectetuer</span> </button> Ironically, the Stack Overflow editor detects wrong indentation, so I've been forced to use a snippet. I've tried htmllint, lintspaces and htmlhint.
stackoverflow
{ "language": "en", "length": 95, "provenance": "stackexchange_0000F.jsonl.gz:911420", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687440" }
c5dc8c9ce92c9dbe0f6fff83c9b3816df5ddb059
Stackoverflow Stackexchange Q: How to visualize NodeJS .cpuprofile I use v8-profiler to profile my NodeJS app. It generates a .cpuprofile file. I used to be able to visualize the content of the file with Google Chrome built-in DevTools. However, Chrome recently changed the file format for profiling results and Chrome is no longer able to read .cpuprofile files. Note: My goal is to see the call tree and bottom-up. I do not care about flame chart. Thanks. A: I ended up downloading an old Chromium version. http://commondatastorage.googleapis.com/chromium-browser-continuous/index.html?prefix=Win_x64/381909/
Q: How to visualize NodeJS .cpuprofile I use v8-profiler to profile my NodeJS app. It generates a .cpuprofile file. I used to be able to visualize the content of the file with Google Chrome built-in DevTools. However, Chrome recently changed the file format for profiling results and Chrome is no longer able to read .cpuprofile files. Note: My goal is to see the call tree and bottom-up. I do not care about flame chart. Thanks. A: I ended up downloading an old Chromium version. http://commondatastorage.googleapis.com/chromium-browser-continuous/index.html?prefix=Win_x64/381909/ A: There is a vscode extension for viewing .cpuprofile: Flame Chart Visualizer for JavaScript Profiles https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-js-profile-flame A: Yes, it seems the format has changed. From NodeJS v9.11.1 I'm getting a tree-like JSON structure: { "typeId": "CPU", "uid": "1", "title": "Profile 1", "head": { "functionName": "(root)", "url": "", "lineNumber": 0, "callUID": 1319082045, "bailoutReason": "no reason", "id": 17, "hitCount": 0, "children": [ { "functionName": "(anonymous function)", "url": "...", "lineNumber": 726, "callUID": 3193325993, "bailoutReason": "no reason", "id": 16, "hitCount": 0, "children": [ { ... From Chromium 66.0.3359.117 I'm getting a flat structure: { "nodes": [ { "id": 1, "callFrame": { "functionName": "(root)", "scriptId": "0", "url": "", "lineNumber": -1, "columnNumber": -1 }, "hitCount": 0, "children": [ 2, 3 ] }, { ... What worked for me is the chrome2calltree tool, which takes the old format used by NodeJS and turns it into a .prof file that tools like KCacheGrind and QCacheGrind can open.
stackoverflow
{ "language": "en", "length": 234, "provenance": "stackexchange_0000F.jsonl.gz:911430", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687458" }
01d70d9c353b0e3d24cfbdf72eba41d896bdbcb8
Stackoverflow Stackexchange Q: Compare two dataframes for changes in variable value in R I'm trying to compare two dataframes with the exact same amount of rows and variables, for changes in variable value per unique ID (returning True if the value is the same, and false if it is different). Here's an example of how the data looks: df1 id col1 col2 1 abc 123 2 def 456 3 ghi 789 df2 col1 id col2 ghe 3 789 abc 1 123 def 2 455 And I guess I would have the result of the comparison be in df3 id col1 col2 1 true true 2 true false 3 false true Any help would be greatly appreciated! Hopefully I've made this somewhat clear. A: Try this: cbind.data.frame(id=df1$id, df1[-1]==df2[match(df1$id, df2$id), names(df1)[-1]]) # id col1 col2 #1 1 TRUE TRUE #2 2 TRUE FALSE #3 3 FALSE TRUE
Q: Compare two dataframes for changes in variable value in R I'm trying to compare two dataframes with the exact same amount of rows and variables, for changes in variable value per unique ID (returning True if the value is the same, and false if it is different). Here's an example of how the data looks: df1 id col1 col2 1 abc 123 2 def 456 3 ghi 789 df2 col1 id col2 ghe 3 789 abc 1 123 def 2 455 And I guess I would have the result of the comparison be in df3 id col1 col2 1 true true 2 true false 3 false true Any help would be greatly appreciated! Hopefully I've made this somewhat clear. A: Try this: cbind.data.frame(id=df1$id, df1[-1]==df2[match(df1$id, df2$id), names(df1)[-1]]) # id col1 col2 #1 1 TRUE TRUE #2 2 TRUE FALSE #3 3 FALSE TRUE
stackoverflow
{ "language": "en", "length": 143, "provenance": "stackexchange_0000F.jsonl.gz:911435", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687475" }
400ce25c187d270a40621647058356cf5a4ed92c
Stackoverflow Stackexchange Q: Cordova android emulator "cannot read property 'replace' of undefined" Have just installed the latest version of Apache Cordova (7.0.1) on Windows, the Android SDK, added the android platform, and when trying to run the android emulator it compiles everything ok but then shows a: Cannot read property 'replace' of undefined Without indication or anything else to trace the error. A: In the Ionic framework forum found the following answer that solved the problem: Tracked it down to file /platforms/android/cordova/lib/emulator.js line 202: var num = target.split('(API level ')1.replace(')', ''); Replace it with a regex search and extraction: var num = target.match(/\d+/)[0];
Q: Cordova android emulator "cannot read property 'replace' of undefined" Have just installed the latest version of Apache Cordova (7.0.1) on Windows, the Android SDK, added the android platform, and when trying to run the android emulator it compiles everything ok but then shows a: Cannot read property 'replace' of undefined Without indication or anything else to trace the error. A: In the Ionic framework forum found the following answer that solved the problem: Tracked it down to file /platforms/android/cordova/lib/emulator.js line 202: var num = target.split('(API level ')1.replace(')', ''); Replace it with a regex search and extraction: var num = target.match(/\d+/)[0]; A: Happened with me this week. Try to downgrade Android platform to 6.0.0 until ionic team resolve this issue. Commands: cordova platform rm Android cordova platform add [email protected] A: If you'd rather not modify emulator.js (Adrian's answer), I was able to work around this issue by manually starting an Android virtual device before running cordova emulate android. A: Device Info * *Windows 10 *Ionic 3 Command I ran the following command on Windows 10 using ionic and had the same issue: ionic cordova emulate android Error The following error was reported in the terminal: BUILD SUCCESSFUL Total time: 1.775 secs Built the following apk(s): C:/ionic/quoteapp/platforms/android/build/outputs/apk/android-debug.apk ANDROID_HOME=C:\Users\Arduino2\AppData\Local\Android\sdk JAVA_HOME=C:\Program Files\java\jdk1.8.0_144 Error: Cannot read property 'replace' of undefined Fix The replacement of: var num = target.split('(API level ')1.replace(')', ''); with var num = target.match(/\d+/)[0] as noted above worked. The file in an ionic project is found in your ionic app folder in the following directory: /platforms/android/cordova/lib/emulator.js I did not come up with this fix, just wanted to provide what command and error I got to help others.
stackoverflow
{ "language": "en", "length": 275, "provenance": "stackexchange_0000F.jsonl.gz:911436", "question_score": "24", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687476" }
c5b213ca799081312d762fc1286d1ab9958b1e5a
Stackoverflow Stackexchange Q: How to customize Place Autocomplete on android I'm using Place AutoComplete with the default UI : But I want to create my own like Uber and Waze does, I found tuns of tutorials, but most of them are deprecated, some codes doesn't work anymore... like this. Thanks!
Q: How to customize Place Autocomplete on android I'm using Place AutoComplete with the default UI : But I want to create my own like Uber and Waze does, I found tuns of tutorials, but most of them are deprecated, some codes doesn't work anymore... like this. Thanks!
stackoverflow
{ "language": "en", "length": 48, "provenance": "stackexchange_0000F.jsonl.gz:911458", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687547" }
2572b2179e0f252f69be58d4ff27ef1242b4af36
Stackoverflow Stackexchange Q: Secure AWS API Gateway with Lambda Integration I am creating a publicly available API using API Gateway which is backed with lambda functions to do some processing. I have secured it with a custom security header that implements hmac authentication with timestamp to protect against replay attacks. I understand that API Gateway protects against DDOS attacks through its high availability, but any invalid requests will still be passed to the lambda authentication function. So, I guess an attacker can submit invalid unauthenticated requests resulting in high costs. It will take a considerable number of requests to cause damage but it is still very doable. What is the best way to protect against that ? Thank you A: To prevent DDoS and higher rate of access, you can setup WAF. Have a look at this link, to get a deeper understanding how to setup WAF with API Gateway.
Q: Secure AWS API Gateway with Lambda Integration I am creating a publicly available API using API Gateway which is backed with lambda functions to do some processing. I have secured it with a custom security header that implements hmac authentication with timestamp to protect against replay attacks. I understand that API Gateway protects against DDOS attacks through its high availability, but any invalid requests will still be passed to the lambda authentication function. So, I guess an attacker can submit invalid unauthenticated requests resulting in high costs. It will take a considerable number of requests to cause damage but it is still very doable. What is the best way to protect against that ? Thank you A: To prevent DDoS and higher rate of access, you can setup WAF. Have a look at this link, to get a deeper understanding how to setup WAF with API Gateway. A: API Gateway will not charge you for unauthenticated requests, however you would be charged by Lambda for the invocation on the authorizer. API Gateway offers a semi-useful mitigation to this problem in the form of the 'identity validation expression' on the Authorizer, which is just a regex that is matched against the incoming identity source header. Besides that, you might want to just implement some kind of negative cache or validation yourself in the Authorizer function to minimize the billed milliseconds.
stackoverflow
{ "language": "en", "length": 230, "provenance": "stackexchange_0000F.jsonl.gz:911491", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687654" }
49bcdfffaf89a1053c4fe395c093a08a20c14272
Stackoverflow Stackexchange Q: getting permission denied in docker run I am trying using Docker using Dockerfile. My Dockerfile as follows, where I am using debian linux system. FROM debian:jessie ENV DEBIAN_FRONTEND noninteractive ARG AIRFLOW_VERSION=1.7.1.3 ENV AIRFLOW_HOME /usr/local/airflow .. .. COPY script/entrypoint.sh /entrypoint.sh COPY config/airflow.cfg ${AIRFLOW_HOME}/airflow.cfg .. .. USER airflow WORKDIR ${AIRFLOW_HOME} ENTRYPOINT ["/entrypoint.sh"] So when I run docker build -t test ., it build without problem. However, when I run docker run -p 8080:8080 test. It throws following error: container_linux.go:247: starting container process caused "exec: \"/entrypoint.sh\": permission denied" docker: Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "exec: \"/entrypoint.sh\": permission denied". What is I am doing wrong ? A: Since COPY copies files including their metadata, you can also simply change the permissions of the file in the host machine (the one building the Docker image): $ chmod +x entrypoint.sh Then, when running docker build -t test . the copied file will have the execution permission and docker run -p 8080:8080 test should work. Obs.: I'm not advocating this as best practice, but still, it works.
Q: getting permission denied in docker run I am trying using Docker using Dockerfile. My Dockerfile as follows, where I am using debian linux system. FROM debian:jessie ENV DEBIAN_FRONTEND noninteractive ARG AIRFLOW_VERSION=1.7.1.3 ENV AIRFLOW_HOME /usr/local/airflow .. .. COPY script/entrypoint.sh /entrypoint.sh COPY config/airflow.cfg ${AIRFLOW_HOME}/airflow.cfg .. .. USER airflow WORKDIR ${AIRFLOW_HOME} ENTRYPOINT ["/entrypoint.sh"] So when I run docker build -t test ., it build without problem. However, when I run docker run -p 8080:8080 test. It throws following error: container_linux.go:247: starting container process caused "exec: \"/entrypoint.sh\": permission denied" docker: Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "exec: \"/entrypoint.sh\": permission denied". What is I am doing wrong ? A: Since COPY copies files including their metadata, you can also simply change the permissions of the file in the host machine (the one building the Docker image): $ chmod +x entrypoint.sh Then, when running docker build -t test . the copied file will have the execution permission and docker run -p 8080:8080 test should work. Obs.: I'm not advocating this as best practice, but still, it works. A: You need to change the permission of the bash file by chmod +x entrypoint.sh before calling ENTRYPOINT. So change your code to the following: USER airflow WORKDIR ${AIRFLOW_HOME} RUN chmod +x entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] Rebuild the image and run the container, it should work. A: In your terminal, run "chmod +x entrypoint.sh" or if the entrypoint.sh file is in a folder, run "chmod +x folder_name/entrypoint.sh" A: I changed the location of the entrypoint in the dockerfolder and rebuild & it worked!
stackoverflow
{ "language": "en", "length": 260, "provenance": "stackexchange_0000F.jsonl.gz:911501", "question_score": "41", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687685" }
c6c63391621b9915b1817bbf9b1c982089c9b092
Stackoverflow Stackexchange Q: How to exclude blacklisted files from ls? I have a blacklist file: $ cat blacklist Iran Iraq Libya Somalia Sudan Syria Yemen How do I exclude the files listed in this blacklist file from the output of ls? I've read the man pages and the closest thing is the --ignore option which unfortunately doesn't read a file. I also thought of piping the output of ls to grep and using the --invert-match option to ignore all the files in the blacklist file but I don't know how to do so. A: If you have to use ls, you could do this: ls | grep -vFxf blacklist * *-v to invert selection *-F to treat lines from file blacklist as strings, not patterns *-x to match the whole line *-f to reads from blacklist for patterns / strings to match Note that the above solution works for all cases except where file names have newlines in them.
Q: How to exclude blacklisted files from ls? I have a blacklist file: $ cat blacklist Iran Iraq Libya Somalia Sudan Syria Yemen How do I exclude the files listed in this blacklist file from the output of ls? I've read the man pages and the closest thing is the --ignore option which unfortunately doesn't read a file. I also thought of piping the output of ls to grep and using the --invert-match option to ignore all the files in the blacklist file but I don't know how to do so. A: If you have to use ls, you could do this: ls | grep -vFxf blacklist * *-v to invert selection *-F to treat lines from file blacklist as strings, not patterns *-x to match the whole line *-f to reads from blacklist for patterns / strings to match Note that the above solution works for all cases except where file names have newlines in them.
stackoverflow
{ "language": "en", "length": 157, "provenance": "stackexchange_0000F.jsonl.gz:911560", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687850" }
ba9cb0d008e06fc1373edeb4ca82be74d7d89480
Stackoverflow Stackexchange Q: QueryDSL 4 select + where + exists Just started using queryDSL at my job. So far I think the syntax is very intuitive. I need to convert a very simple SQL query to queryDSL, but I don't know what do do with the EXISTS clause. SELECT * FROM XRDocument document WHERE status = 0 AND EXISTS ( select * FROM XEntity X WHERE X.pid in (11,22,33) ) AND NOT EXISTS ( select * FROM XEntity X WHERE X.pid in (44,55,66) ) I have all my Q classes ready. So far this is all I have (pseudo code): JPAQuery query = new JPAQuery(em); query.from(xDocument).where(xDocument.status.eq(0)) I read the documentation but there's no ".exists()" method. I also tried using the JDOExpressions class but I couldn't come up with a solution. Can anybody point me to the right direction? A: You could do something like JPAQuery query = new JPAQuery(em) .select(xDocument) .from(xDocument) .where(xDocument.status.eq(0) .and(JPAExpressions.selectOne() .from(xEntity) .where(xEntity.pid.in(11,22,33) .exists()) .and(JPAExpressions.selectOne() .from(xEntity) .where(xEntity.pid.in(44,55,66) .notExists()));
Q: QueryDSL 4 select + where + exists Just started using queryDSL at my job. So far I think the syntax is very intuitive. I need to convert a very simple SQL query to queryDSL, but I don't know what do do with the EXISTS clause. SELECT * FROM XRDocument document WHERE status = 0 AND EXISTS ( select * FROM XEntity X WHERE X.pid in (11,22,33) ) AND NOT EXISTS ( select * FROM XEntity X WHERE X.pid in (44,55,66) ) I have all my Q classes ready. So far this is all I have (pseudo code): JPAQuery query = new JPAQuery(em); query.from(xDocument).where(xDocument.status.eq(0)) I read the documentation but there's no ".exists()" method. I also tried using the JDOExpressions class but I couldn't come up with a solution. Can anybody point me to the right direction? A: You could do something like JPAQuery query = new JPAQuery(em) .select(xDocument) .from(xDocument) .where(xDocument.status.eq(0) .and(JPAExpressions.selectOne() .from(xEntity) .where(xEntity.pid.in(11,22,33) .exists()) .and(JPAExpressions.selectOne() .from(xEntity) .where(xEntity.pid.in(44,55,66) .notExists())); A: Just wanted to say that I solved my problem using the BooleanExpression class. BooleanExpression exists = JPAExpressions.selectFrom(xEntity).where(xEntity.pid.in(11,22,33)).exists(); After that you can use the expression inside a BooleanBuilder.
stackoverflow
{ "language": "en", "length": 186, "provenance": "stackexchange_0000F.jsonl.gz:911570", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687877" }
ce48f2e240391c7ceca1435252a191dedd3ce30c
Stackoverflow Stackexchange Q: Where should I place my middleware file for Rails 5.1? Previously I had my middleware under lib/middleware/my_middle_ware.rb However when doing this, config.middleware.use MyMiddleWare I receive a NameError: uninitialized constant Where is rails looking for the middleware? A: Create a folder app/middlewares and create your middleware file in this folder. But unfortunately The app/middlewares folder is not loading even if I added to the load paths in Rails v5.2.2 config.autoload_paths << "#{Rails.root}/app/middlewares" config.eager_load_paths << "#{Rails.root}/app/middlewares" So you can use require explicitly as follows, add this line in application.rb require_relative '../app/middlewares/my_middleware' and load middleware: config.middleware.use MyMiddleware and call rake middleware to see the middleware stack.
Q: Where should I place my middleware file for Rails 5.1? Previously I had my middleware under lib/middleware/my_middle_ware.rb However when doing this, config.middleware.use MyMiddleWare I receive a NameError: uninitialized constant Where is rails looking for the middleware? A: Create a folder app/middlewares and create your middleware file in this folder. But unfortunately The app/middlewares folder is not loading even if I added to the load paths in Rails v5.2.2 config.autoload_paths << "#{Rails.root}/app/middlewares" config.eager_load_paths << "#{Rails.root}/app/middlewares" So you can use require explicitly as follows, add this line in application.rb require_relative '../app/middlewares/my_middleware' and load middleware: config.middleware.use MyMiddleware and call rake middleware to see the middleware stack. A: Look like rails wasn't looking for it. I had to do the following for it to work. Dir["./lib/middleware/*.rb"].each do |file| require file end A: I believe you want to add your middleware to either your config/application.rb or your config/environments file. config.middleware.use MyMiddleWare This should work and append MyMiddleWare to the bottom of the middleware stack. A: Even before app/middleware contents are loaded if 'config.middleware.use' is called, I think you get the 'uninitialized Constant error'. The below should fix config.middleware.use "MyMiddleWare" If the above doesn't work, one of the below might be a no. Is MyMiddleWare in app/middleware/my_middle_ware.rb ? Is MyMiddleWare in lib/my_middle_ware.rb ? A: replacing middleware as a string in config/application.rb to config/environment/{environment} as a constant fixed the issue for me
stackoverflow
{ "language": "en", "length": 226, "provenance": "stackexchange_0000F.jsonl.gz:911611", "question_score": "18", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44687983" }
438e3cd9912819cf3cd67ff63eb163b3f2aa5a2c
Stackoverflow Stackexchange Q: Android Instant Apps - Cannot Find Symbol From Base Feature Asset I have a base feature module, and a feature module (you could call it the "child"). The base feature module has a strings.xml file asset containing: <resources> <string name="app_string">Test String</string> </resources> I attempt to reference this string resource in the "child" feature's activity, as below: int resId = R.string.app_string; Android Studio appears to respect this reference, and will even direct me to the app_string resource when I click it. However, during compilation, I am met with the following error message: Error:(13, 25) error: cannot find symbol variable app_string The build Gradle file for my "child" feature has the dependency too: dependencies { ... implementation project(':base') } I also tried compile project(':base'), but no success. Is there something blatant that I am missing? A: Your base and child modules have different package names - let's say they are com.example.base and com.example.child. Each contains its own set of resources, and their identifiers will be collected in separate R packages: * *com.example.base.R *com.example.child.R Because you're trying to access a resource defined in base module, you need to reference it with the fully qualified name of the variable, which is com.example.base.R.string.app_string.
Q: Android Instant Apps - Cannot Find Symbol From Base Feature Asset I have a base feature module, and a feature module (you could call it the "child"). The base feature module has a strings.xml file asset containing: <resources> <string name="app_string">Test String</string> </resources> I attempt to reference this string resource in the "child" feature's activity, as below: int resId = R.string.app_string; Android Studio appears to respect this reference, and will even direct me to the app_string resource when I click it. However, during compilation, I am met with the following error message: Error:(13, 25) error: cannot find symbol variable app_string The build Gradle file for my "child" feature has the dependency too: dependencies { ... implementation project(':base') } I also tried compile project(':base'), but no success. Is there something blatant that I am missing? A: Your base and child modules have different package names - let's say they are com.example.base and com.example.child. Each contains its own set of resources, and their identifiers will be collected in separate R packages: * *com.example.base.R *com.example.child.R Because you're trying to access a resource defined in base module, you need to reference it with the fully qualified name of the variable, which is com.example.base.R.string.app_string.
stackoverflow
{ "language": "en", "length": 199, "provenance": "stackexchange_0000F.jsonl.gz:911621", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688018" }
013613b22d0cdd31264ede780d93257b3d72a646
Stackoverflow Stackexchange Q: yticklabels Cut Off in Pandas plot I'm making a simple horizontal stacked bar plot: df = pd.DataFrame({'firstBox':firstL,'secondBox':secondL,'thirdBox':thirdL}) ax = df.plot.barh(stacked=True) ax.set_title("My Example Plot") ax.set_yticklabels(labels=['A label this long is cut off','this label is also cut off]) plt.show() but the values on my ytick labels are being cut off. If I increase the width of the returned plot window, I can see slightly more of them, but I need to stretch the window well past the width of my monitor to see the entire label. Is there a way to just push the plot to the right to include my long labels? Thanks! A: In case you are using savefig, bbox_inches='tight' is an option that automatically try to figure out the tight bbox of the figure.
Q: yticklabels Cut Off in Pandas plot I'm making a simple horizontal stacked bar plot: df = pd.DataFrame({'firstBox':firstL,'secondBox':secondL,'thirdBox':thirdL}) ax = df.plot.barh(stacked=True) ax.set_title("My Example Plot") ax.set_yticklabels(labels=['A label this long is cut off','this label is also cut off]) plt.show() but the values on my ytick labels are being cut off. If I increase the width of the returned plot window, I can see slightly more of them, but I need to stretch the window well past the width of my monitor to see the entire label. Is there a way to just push the plot to the right to include my long labels? Thanks! A: In case you are using savefig, bbox_inches='tight' is an option that automatically try to figure out the tight bbox of the figure. A: You can use ax.get_figure().tight_layout() or plt.gcf().tight_layout(). This will fix the figure layout. A: You should try this: from matplotlib import rcParams rcParams.update({'figure.autolayout': True}) A: Hi I've recently come across this as well. Here is some sample code that will expand the plot region to include all axis ticks. Note the bit that does the expanding of the plot area is bbox_inches='tight' import numpy as np import pandas as pd names = ['Name 1','Name 2','Name 3','Name 4','Name 5','Name 6'] y1 = [] y2 = [] for name in names: y1.append(np.random.rand()) y2.append(np.random.rand()) df = pd.DataFrame({'First ': y1, 'Second ': y2}, index=names) ax = df.plot.bar(rot=0) ax.set_xlabel("X Axis") ax.set_ylabel("Y Axis") ax.set_title("Sample Plot") ax.set_xticklabels(ax.get_xticklabels(), rotation=30, ha="right") fig = ax.get_figure() fig.savefig("Fig_Name", bbox_inches='tight')
stackoverflow
{ "language": "en", "length": 242, "provenance": "stackexchange_0000F.jsonl.gz:911622", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688019" }
34961925de548dea11c90cda504cd34d5e579a93
Stackoverflow Stackexchange Q: How are Code Aurora source archives organized? I hit up Code Aurora while trying to find the kernel sources for Qualcomm MSM devices. The listing at Code Aurora sources is overwhelming. I couldn't spot any documentation explaining what is what. What are all these projects? What's the naming convention followed? What are the grayed out items, e.g. quic/la? Do all these projects correspond to individual git repositories? Can anyone point to any source that explains me the archive structure? A: Now here's what I do know of the source structure. Under quic/la all the git projects that are used for running Android on MSMs are hosted. There are various versions of kernel git projects: * *https://source.codeaurora.org/quic/la/kernel/msm-3.10/ *https://source.codeaurora.org/quic/la/kernel/msm-3.14/ *https://source.codeaurora.org/quic/la/kernel/msm-3.18/ *https://source.codeaurora.org/quic/la/kernel/msm-4.4/ *https://source.codeaurora.org/quic/la/kernel/msm-4.9/ Now, as we all know form press that there are various snapdragons. Not all snapdragons may be supported on each kernel version. I would recommend listing the tags for each kernel and try and find if the chip of your interest is supported there, this is the tedious part. * *By looking at the device tree files you may be able to determine if your chip is in that kernel tree. *defconfig files you may find supported chips.
Q: How are Code Aurora source archives organized? I hit up Code Aurora while trying to find the kernel sources for Qualcomm MSM devices. The listing at Code Aurora sources is overwhelming. I couldn't spot any documentation explaining what is what. What are all these projects? What's the naming convention followed? What are the grayed out items, e.g. quic/la? Do all these projects correspond to individual git repositories? Can anyone point to any source that explains me the archive structure? A: Now here's what I do know of the source structure. Under quic/la all the git projects that are used for running Android on MSMs are hosted. There are various versions of kernel git projects: * *https://source.codeaurora.org/quic/la/kernel/msm-3.10/ *https://source.codeaurora.org/quic/la/kernel/msm-3.14/ *https://source.codeaurora.org/quic/la/kernel/msm-3.18/ *https://source.codeaurora.org/quic/la/kernel/msm-4.4/ *https://source.codeaurora.org/quic/la/kernel/msm-4.9/ Now, as we all know form press that there are various snapdragons. Not all snapdragons may be supported on each kernel version. I would recommend listing the tags for each kernel and try and find if the chip of your interest is supported there, this is the tedious part. * *By looking at the device tree files you may be able to determine if your chip is in that kernel tree. *defconfig files you may find supported chips. A: la is for android, le for embedded and I believe lc is for chromium.
stackoverflow
{ "language": "en", "length": 214, "provenance": "stackexchange_0000F.jsonl.gz:911631", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688044" }
4d180c0983b977a2a7137472821eb7b3633cf75c
Stackoverflow Stackexchange Q: Serilog Seq Output Template I am new to Serilog and to Seq. Sorry for the beginner question. I want to have an output template that seems to be available in Serilog for the Console, but I can't seem to configure it in the WriteTo.Seq parameters. Am I missing something or is this not available or is there another way to do this? I was hoping to create a template constant and keep the format all in one place. TIA A: Seq uses signals with tagged properties for this. * *Pick an event that has a property you want to show beside the message, *click the green "tick" to "Show as tag", and then *save the resulting signal so that you can apply it when you want to show the property inline. The signal can be set as a default for your user account in (your username) > Preferences.
Q: Serilog Seq Output Template I am new to Serilog and to Seq. Sorry for the beginner question. I want to have an output template that seems to be available in Serilog for the Console, but I can't seem to configure it in the WriteTo.Seq parameters. Am I missing something or is this not available or is there another way to do this? I was hoping to create a template constant and keep the format all in one place. TIA A: Seq uses signals with tagged properties for this. * *Pick an event that has a property you want to show beside the message, *click the green "tick" to "Show as tag", and then *save the resulting signal so that you can apply it when you want to show the property inline. The signal can be set as a default for your user account in (your username) > Preferences.
stackoverflow
{ "language": "en", "length": 149, "provenance": "stackexchange_0000F.jsonl.gz:911637", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688061" }
92ef2e3d146b86324a5b00e5ec7fea995612fe3a
Stackoverflow Stackexchange Q: Why is nil returned by Clojure functions that don't return a value? I'm a new student of Clojure and don't get why "nil" is returned in REPL when I call functions that do not return values. Above an example: (println "Hello Nil") nil What type of evaluation process are made to reach "nil"? A: It is a convention of functional languages like Clojure that every function needs to return exactly one value. For functions like println that are intended to perform side effects (like printing to the screen), it is not always clear what the return value could or should be. In these cases, nil is a placeholder value that means "nothing" or "not applicable".
Q: Why is nil returned by Clojure functions that don't return a value? I'm a new student of Clojure and don't get why "nil" is returned in REPL when I call functions that do not return values. Above an example: (println "Hello Nil") nil What type of evaluation process are made to reach "nil"? A: It is a convention of functional languages like Clojure that every function needs to return exactly one value. For functions like println that are intended to perform side effects (like printing to the screen), it is not always clear what the return value could or should be. In these cases, nil is a placeholder value that means "nothing" or "not applicable".
stackoverflow
{ "language": "en", "length": 116, "provenance": "stackexchange_0000F.jsonl.gz:911642", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688076" }
1d1840937d2caa99f31e67d2016d0bbaf6c94fc8
Stackoverflow Stackexchange Q: How do I set a timezone in Selenium Chromedriver? I can't figure out how to set a timezone when using Chromedriver. Is there some ChromeOptions argument or something? The issue is that when I go to some sites (for example, https://whoer.net), it shows the system time that is equal to the time set on Windows. And I want to be able to change the Chromedriver's timezone somehow to perform timezone dependent testing. I tried to set some chrome options: Map<String, Object> chromeOptions = new HashMap<String, Object>(); chromeOptions.put("args", Arrays.asList("--disable-system-timezone-automatic-detection", "--local-timezone")); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); It doesn't work. Tried to do some weird thing using Javascript: ((JavascriptExecutor) driver).executeScript("Date.prototype.getTime = function() { return 1 };"); It didn't help either. EDIT: Found this https://sqa.stackexchange.com/questions/8838/faking-system-time-date-with-selenium-webdriver Tried to execute javascript on page with the code copied from TimeShift.js like this: ((JavascriptExecutor) driver).executeScript("/*code from TimeShift.js here*/ TimeShift.setTimezoneOffset(-60);"); System time at https://whoer.net didn't change. What am I doing wrong? A: You can do it by using Chrome DevTools Protocol, and here is the python code: driver = webdriver.Chrome() tz_params = {'timezoneId': 'America/New_York'} driver.execute_cdp_cmd('Emulation.setTimezoneOverride', tz_params)
Q: How do I set a timezone in Selenium Chromedriver? I can't figure out how to set a timezone when using Chromedriver. Is there some ChromeOptions argument or something? The issue is that when I go to some sites (for example, https://whoer.net), it shows the system time that is equal to the time set on Windows. And I want to be able to change the Chromedriver's timezone somehow to perform timezone dependent testing. I tried to set some chrome options: Map<String, Object> chromeOptions = new HashMap<String, Object>(); chromeOptions.put("args", Arrays.asList("--disable-system-timezone-automatic-detection", "--local-timezone")); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions); It doesn't work. Tried to do some weird thing using Javascript: ((JavascriptExecutor) driver).executeScript("Date.prototype.getTime = function() { return 1 };"); It didn't help either. EDIT: Found this https://sqa.stackexchange.com/questions/8838/faking-system-time-date-with-selenium-webdriver Tried to execute javascript on page with the code copied from TimeShift.js like this: ((JavascriptExecutor) driver).executeScript("/*code from TimeShift.js here*/ TimeShift.setTimezoneOffset(-60);"); System time at https://whoer.net didn't change. What am I doing wrong? A: You can do it by using Chrome DevTools Protocol, and here is the python code: driver = webdriver.Chrome() tz_params = {'timezoneId': 'America/New_York'} driver.execute_cdp_cmd('Emulation.setTimezoneOverride', tz_params) A: As far as I know you can only do this with TZ variable or with Decker Selenium. Were you able to find a viable solution to this however? I am trying to do the same exact thing and have found very little in the way of solutions. I'm trying to do it with Python. The Tz variable solution is limited to Firefox in windows and decker selenium is a nightmare to install on windows. UPDATED PYTHON SOLUTION VIABLE (below) os.environ["DEBUSSY"] = "1" SEE: How to set environment variables in Python I am not sure if there is a Java equivalent but this Python equivalent worked for me in windows but only in Firefox. If you find a Java equivalent then that's awesome but if this issue is important to you Python is the way to go! :). I believe you are limited to three letters in windows but full customisation in Linux operating systems. E.g UTC, GMT etc, etc,. Hope this was helpful to you. I spent ages looking for this but turns out I was overthinking it. Good luck!! A: with new selenium 4, it can be done natively with CDP WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); DevTools devTools = ((ChromeDriver) driver).getDevTools(); devTools.createSession(); devTools.send(Emulation.setTimezoneOverride("Antarctica/Casey")); download the following maven dependency: <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.0.0-alpha-6</version> </dependency> list of time zones can be found here
stackoverflow
{ "language": "en", "length": 403, "provenance": "stackexchange_0000F.jsonl.gz:911644", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688079" }
2a27b243af00d4e0306fb4102170840cb50af40b
Stackoverflow Stackexchange Q: Why does my mongoid server description change from primary to primary all the time? I see these a lot, a lot: MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. Is there a particular misconfiguration that's causing this, or is this a part of normal operation? my /etc/mongodb.conf: storage: dbPath: /var/lib/mongodb journal: enabled: true systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log net: port: 27017 bindIp: 127.0.0.1 replication: replSetName: something
Q: Why does my mongoid server description change from primary to primary all the time? I see these a lot, a lot: MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. MONGODB | Server description for localhost:27017 changed from 'primary' to 'primary'. Is there a particular misconfiguration that's causing this, or is this a part of normal operation? my /etc/mongodb.conf: storage: dbPath: /var/lib/mongodb journal: enabled: true systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log net: port: 27017 bindIp: 127.0.0.1 replication: replSetName: something
stackoverflow
{ "language": "en", "length": 182, "provenance": "stackexchange_0000F.jsonl.gz:911647", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688089" }
07d72555e2e71de4a57f20b5f3e8ab5035c074d0
Stackoverflow Stackexchange Q: How do I stop Paw from converting my text input into dynamic values? I paste something with :blah and :blah is converted to a dynamic value blah. How do I stop this?
Q: How do I stop Paw from converting my text input into dynamic values? I paste something with :blah and :blah is converted to a dynamic value blah. How do I stop this?
stackoverflow
{ "language": "en", "length": 33, "provenance": "stackexchange_0000F.jsonl.gz:911654", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688106" }
11ccb8eca20a671ca31435b56b5520d910dc2942
Stackoverflow Stackexchange Q: How many requests can be processed simultaneously by R OpenCPU I am new to OpenCPU, I look at the documents at https://www.opencpu.org/, It looks that OpenCPU can process http requests concurrently? I ask so because R itself only has single-thread mode, and how many requests can it process concurrently? Thanks. A: If you run the Apache based opencpu-server there is no limit to the number of concurrent requests. You can tweak the number of workers in the prefork settings. The local single-user server in R on the other hand only uses a single R process. You can still make concurrent requests, but they will automatically be queued and processed one after the other. One way or another, you shouldn't worry about it in the client.
Q: How many requests can be processed simultaneously by R OpenCPU I am new to OpenCPU, I look at the documents at https://www.opencpu.org/, It looks that OpenCPU can process http requests concurrently? I ask so because R itself only has single-thread mode, and how many requests can it process concurrently? Thanks. A: If you run the Apache based opencpu-server there is no limit to the number of concurrent requests. You can tweak the number of workers in the prefork settings. The local single-user server in R on the other hand only uses a single R process. You can still make concurrent requests, but they will automatically be queued and processed one after the other. One way or another, you shouldn't worry about it in the client.
stackoverflow
{ "language": "en", "length": 126, "provenance": "stackexchange_0000F.jsonl.gz:911669", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688149" }
1e18c836828cec6bce3ae9e010a4e5211fc5a6aa
Stackoverflow Stackexchange Q: How to install a minimal cuda driver file into Alpine linux I'm wanting to install the minimal cuda runtime files into alpine linux and create a much smaller docker base with cuda than that provided by nvidia themselves. The nvidia official ones are enormous as usual. How do I obtain these runtime files without pulling the entire cuda 8 toolkit during docker build? A: I can't speak as to what other files might be needed. However, Nvidia drivers are compiled with glibc, and alpine uses musl to maintain its small footprint. You would likely need the nvidia driver's source code so you could recompile it with musl, or an alpine baseimage that implements glibc such as this one. I haven't tried using this yet, but I was able to sucessfully compile libcudacore with musl and gcc/make on an alpine 3.8 container. I have not yet been able to compile the entire Nvidia/Cuda toolkit yet. I will attempt to test this more when I have more time.
Q: How to install a minimal cuda driver file into Alpine linux I'm wanting to install the minimal cuda runtime files into alpine linux and create a much smaller docker base with cuda than that provided by nvidia themselves. The nvidia official ones are enormous as usual. How do I obtain these runtime files without pulling the entire cuda 8 toolkit during docker build? A: I can't speak as to what other files might be needed. However, Nvidia drivers are compiled with glibc, and alpine uses musl to maintain its small footprint. You would likely need the nvidia driver's source code so you could recompile it with musl, or an alpine baseimage that implements glibc such as this one. I haven't tried using this yet, but I was able to sucessfully compile libcudacore with musl and gcc/make on an alpine 3.8 container. I have not yet been able to compile the entire Nvidia/Cuda toolkit yet. I will attempt to test this more when I have more time. A: The reality is that Nvidia/CUDA is not supported in any way with Alpine Linux Musl or its libc port, and you will end up with a flaky image nevertheless even if you succeed with your alchemist venture. Nvidia drivers and CUDA Toolkits are incredibly complex systems that honestly I can't see the point to compile it yourself for an unsupported system library or an unsupported port for libc, with all the unexpected to happen even in the case it compiles. Use Debian's slim images or Ubuntu minimal and install official supported files manually, as this is the smallest you can go. Or even better use the "huge" Nvidia DockerHub images (ubuntu LTS based). Anyway, beyond this question, the Nvidia DockerHub ones are the best way to go, they are supported by the creators of CUDA Toolkit itself and they are no brainers. If you want to be picky go to their Gitlab's repository for dockers, you can build up Debian/Ubuntu by hand pretty easily and quick. Yes they Nvidia DockerHub images are 1-2 gig's large, but normally you only have to download them once, as you use the image as a base, if you add your code to it only those layers of your code which are normally small to dozens of Mbi are to be recurrently pulled/pushed, not the entire image, so honestly I can't see a reason why people is so much concerned about image sizes, small is better no doubt but up to a point, spending your valuable time in your actual needs is far better. A: somebody's solution for alpine-cuda: https://arto.s3.amazonaws.com/notes/cuda Drivers https://developer.nvidia.com/vulkan-driver $ lsmod | fgrep nvidia $ nvidia-smi Driver Installation https://us.download.nvidia.com/XFree86/Linux-x86_64/390.77/README/ https://github.com/NVIDIA/nvidia-installer Driver Installation on Alpine Linux https://github.com/sgerrand/alpine-pkg-glibc https://github.com/sgerrand/alpine-pkg-glibc/releases https://wiki.alpinelinux.org/wiki/Running_glibc_programs $ apk add sudo bash ca-certificates wget xz make gcc linux-headers $ wget -q -O /etc/apk/keys/sgerrand.rsa.pub https://raw.githubusercontent.com/sgerrand/alpine-pkg-glibc/master/sgerrand.rsa.pub $ wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.27-r0/glibc-2.27-r0.apk $ wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.27-r0/glibc-bin-2.27-r0.apk $ wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.27-r0/glibc-dev-2.27-r0.apk $ wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.27-r0/glibc-i18n-2.27-r0.apk $ apk add glibc-2.27-r0.apk glibc-bin-2.27-r0.apk glibc-dev-2.27-r0.apk glibc-i18n-2.27-r0.apk $ /usr/glibc-compat/bin/localedef -i en_US -f UTF-8 en_US.UTF-8 $ bash NVIDIA-Linux-x86_64-390.77.run --check $ bash NVIDIA-Linux-x86_64-390.77.run --extract-only $ cd NVIDIA-Linux-x86_64-390.77 && ./nvidia-installer Driver Uninstallation $ nvidia-uninstall Driver Troubleshooting Uncompressing NVIDIA Accelerated Graphics Driver for Linux-x86_64 390.77NVIDIA-Linux-x86_64-390.77.run: line 998: /tmp/makeself.XXX/xz: No such file or directory\nExtraction failed. $ apk add xz # Alpine Linux bash: ./nvidia-installer: No such file or directory Install the glibc compatibility layer package for Alpine Linux. ERROR: You do not appear to have libc header files installed on your system. Please install your distribution's libc development package. $ apk add musl-dev # Alpine Linux ERROR: Unable to find the kernel source tree for the currently running kernel. Please make sure you have installed the kernel source files for your kernel and that they are properly configured $ apk add linux-vanilla-dev # Alpine Linux ERROR: Failed to execute `/sbin/ldconfig`: The installer has encountered the following error during installation: 'Failed to execute `/sbin/ldconfig`'. Would you like to continue installation anyway? Continue installation. Toolkit https://developer.nvidia.com/cuda-toolkit https://docs.nvidia.com/cuda/cuda-toolkit-release-notes/ Toolkit Download https://developer.nvidia.com/cuda-downloads?target_os=Linux&target_arch=x86_64&target_distro=Ubuntu&target_version=1604&target_type=runfilelocal $ wget -c https://developer.nvidia.com/compute/cuda/9.2/Prod2/local_installers/cuda_9.2.148_396.37_linux Toolkit Installation https://docs.nvidia.com/cuda/cuda-installation-guide-linux/ Toolkit Installation on Alpine Linux $ apk add sudo bash $ sudo bash cuda_9.2.148_396.37_linux # You are attempting to install on an unsupported configuration. Do you wish to continue? y # Install NVIDIA Accelerated Graphics Driver for Linux-x86_64 396.37? y # Do you want to install the OpenGL libraries? y # Do you want to run nvidia-xconfig? n # Install the CUDA 9.2 Toolkit? y # Enter Toolkit Location: /opt/cuda-9.2 # Do you want to install a symbolic link at /usr/local/cuda? y # Install the CUDA 9.2 Samples? y # Enter CUDA Samples Location: /opt/cuda-9.2/samples $ sudo ln -s cuda-9.2 /opt/cuda $ export PATH="/opt/cuda/bin:$PATH" Toolkit Uninstallation $ sudo /opt/cuda-9.2/bin/uninstall_cuda_9.2.pl Toolkit Troubleshooting Cannot find termcap: Can't find a valid termcap file at /usr/share/perl5/core_perl/Term/ReadLine.pm line 377. $ export PERL_RL="Perl o=0" gcc: error trying to exec 'cc1plus': execvp: No such file or directory $ apk add g++ # Alpine Linux cicc: Relink `/usr/lib/libgcc_s.so.1' with `/usr/glibc-compat/lib/libc.so.6' for IFUNC symbol `memset' https://github.com/sgerrand/alpine-pkg-glibc/issues/58 $ scp /lib/x86_64-linux-gnu/libgcc_s.so.1 root@alpine:/usr/glibc-compat/lib/libgcc_s.so.1 $ sudo /usr/glibc-compat/sbin/ldconfig /usr/glibc-compat/lib /lib /usr/lib Compiler https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/ $ nvcc -V A: Please define what you actually mean by "into Alpine Linux". Regardless whether you're running the workloads directly on the host or in a container or chroot - you need to install the whole NVidia driver stack (including Cuda libs, kernel drivers, etc) on the host. Also kernel and userland drivers are two sides of the same product, both have to have the same version. This means: whatever the host OS actually is, it has to be exactly one of those directly supported by NVidia. You have to use exactly the kernel versions (and configurations) that Nvidia built their proprietary/binary-only drivers for. Using a different kernel version or recompiling it with different configuration MIGHT POSSIBLY work, but it's DANGEROUS. Even with exactly the officially supported distros, it's still gambling, and depending on moon phase or whether some Chinese rice bag fallen over. It often works, but when it doesn't anymore, you're most likely out of luck. Now when you're putting your workloads into some separate OS image, e.g. chroot or container, you also have to have the same driver package version in that image, too. One of the primary reasons for using containers or chroots - isolating and decoupling applications from host OS (so you don't need to fit them in anymore and do upgrades independently, even have container images independent from the host OS) - is now immediately voided. Host and workload need to fit together exactly. In short: if you wanna have a CUDA workload, both host OS as well as workload image (container, chroot, etc) need to be supported by that, and they both need to have the same driver version installed. Anything else is just russian roulette. Since somebody mentioned "nvidia-docker". This breaks the security isolation that docker is originally meant for. (just look at the source, which actually is available somewhere on github). It's nothing but a better chroot. And still, host and docker image need to have the same driver stack version installed. Finally, I'd like to ask the question, what your actual use case is here. Be warned: this all might be okay for playing games on an totally unimportant home computer, but really not suited for anything professional, where stability and security matter. If you're bound to certain data security / privacy regulations like GDPO, keep far away from this - you just cannot comply to these regulations with those proprietary drivers. Legally dangerous. --mtx Addendum: why do proprietary kernel drivers never work reliably ? Express answer: the Linux kernel was never ever made for that, this just isn't supported. Longer answer: kernel modules are NOT external programs, that are executed in some isolated environment (like eg. done with userland programs) - they are (by definition) integral pieces of the kernel that just happen to be lazily loaded when needed. (they are not even like shared libraries / DLLs). This means that they have to fit - on binary level - exactly to the actual build of the kernel you're running. When compiling the kernel, there're lots of config options that influence the actual internal binary layout in subtle ways, e.g. enabling/disabling some features can change the layout of certain data structures, cpu specific optimizations can change datastructures, calling conventions, locking mechanisms, and much much more. And those things also change from kernel version to another. We're e.g. doing lots of internal refactorings (e.g. in data structures, macros and inline functions) after which the same piece source code generates very different binary code. Therefore, any kernel modules always need to be compiled exactly for a specific kernel image (with the same config options, against the same includes, with the same compiler flags), or you risks horrible failures that could lead to lockups, security flaws, data corruptions or even total data loss. You have been warned. A: To clarify, this is just the driver. Not cuda. That's another story. In fact this turns out to be much easier than expected. I just didn't quite /understand how far nvidia-docker project had come and quite how it worked. Basically, download and install the latest nvidia-docker. From the nvidia-docker project. https://github.com/NVIDIA/nvidia-docker/releases Then create an alpine linux Dockerfile. FROM alpine:3.5 LABEL com.nvidia.volumes.needed="nvidia_driver" ENV PATH /usr/local/nvidia/bin:/usr/local/cuda/bin:${PATH} ENV LD_LIBRARY_PATH /usr/local/nvidia/lib:/usr/local/nvidia/lib64 RUN /bin/sh Build it. docker build -t alpine-nvidia Run nvidia-docker run -ti --rm alpine-nvidia Note the use of the nvidia-docker cli instead of the normal docker cli. nvidia-docker calls docker cli with extra parameters.
stackoverflow
{ "language": "en", "length": 1570, "provenance": "stackexchange_0000F.jsonl.gz:911688", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688200" }
b71eaf453fb613e79e513e228d25592800e7f7c8
Stackoverflow Stackexchange Q: Array destructuring in parameters list, with TypeScript Using TypeScript, I am trying to figure out how to do array destructuring in the arguments list. We can use object destructuring like so: let foo = function({firstname, lastname}){...} foo({ firstname: 'ralph', lastname: 'lauren' }); I am wondering if we can do the same thing with array destructuring, it would be very useful for me, something like: let bar = function([desc, opts, fn]){...} bar([ 'yes', {}, function(){} ]); is it possible to do this with an array with TypeScript? A: An array of fixed length and types is also called a tuple in TS. We can destructure a tuple argument like: let bar = function ([desc, opts, fn]: [string, {}, Function]) { } bar([ 'yes', {}, function () { } ]);
Q: Array destructuring in parameters list, with TypeScript Using TypeScript, I am trying to figure out how to do array destructuring in the arguments list. We can use object destructuring like so: let foo = function({firstname, lastname}){...} foo({ firstname: 'ralph', lastname: 'lauren' }); I am wondering if we can do the same thing with array destructuring, it would be very useful for me, something like: let bar = function([desc, opts, fn]){...} bar([ 'yes', {}, function(){} ]); is it possible to do this with an array with TypeScript? A: An array of fixed length and types is also called a tuple in TS. We can destructure a tuple argument like: let bar = function ([desc, opts, fn]: [string, {}, Function]) { } bar([ 'yes', {}, function () { } ]);
stackoverflow
{ "language": "en", "length": 129, "provenance": "stackexchange_0000F.jsonl.gz:911726", "question_score": "20", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688316" }
beb2307def1a5fe09818f1cd20e90deb4c9e3a43
Stackoverflow Stackexchange Q: Differences between conan and conda package managers For C/C++ packages, what are the practical differences, i.e. from the point of view of a developer, between conan and conda?
Q: Differences between conan and conda package managers For C/C++ packages, what are the practical differences, i.e. from the point of view of a developer, between conan and conda?
stackoverflow
{ "language": "en", "length": 29, "provenance": "stackexchange_0000F.jsonl.gz:911807", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688532" }
28a6864766dc9debdee7ce31e910b00741f436ae
Stackoverflow Stackexchange Q: ios Vision VNImageRequestHandler orientation issue I am trying to detect faces via camera using VNImageRequestHandler (iOS Vision). When I point on the photo by the camera in landscape mode it detects faces but with opposite orientation mode. let detectFaceRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]) A: Have you tried to play with the VNImageRequestHandler orientation property? let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .right, options: [:]) I had to set it to .right while reading video input from back camera in portrait mode.
Q: ios Vision VNImageRequestHandler orientation issue I am trying to detect faces via camera using VNImageRequestHandler (iOS Vision). When I point on the photo by the camera in landscape mode it detects faces but with opposite orientation mode. let detectFaceRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]) A: Have you tried to play with the VNImageRequestHandler orientation property? let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .right, options: [:]) I had to set it to .right while reading video input from back camera in portrait mode. A: Convert the image to CIImage and apply the orientation property like below and pass it to the imagerequest handler let orientation = CGImagePropertyOrientation(uiImage.imageOrientation) let imageElement = ciImage.applyingOrientation(Int32(orientation.rawValue)) // Show the image in the UI. originalImage.image = uiImage also check https://github.com/gunapandianraj/iOS-Vision code for converting Vision rect to UIKit rect A: I always got flipped points (bounding boxes) vertically. I fixed this totally with helper method: private static func translateVisionToNormalBoundingBox(bb: CGRect, imageFullRect: CGRect) -> CGRect { let renormalized = VNImageRectForNormalizedRect(bb, Int(imageFullRect.width), Int(imageFullRect.height)) // Vertically translate origin !!! // Vertically translate origin !!! // Vertically translate origin !!! return CGRect( origin: CGPoint( x: renormalized.origin.x, y: imageFullRect.maxY - renormalized.origin.y - renormalized.size.height ), size: renormalized.size ) } For cgImage orientation I use this StackOverflow's extension: extension UIImage { var cgImagePropertyOrientation: CGImagePropertyOrientation { switch imageOrientation { case .down: return .down case .left: return .left case .right: return .right case .up: return .up case .downMirrored: return .downMirrored case .leftMirrored: return .leftMirrored case .rightMirrored: return .rightMirrored case .upMirrored: return .upMirrored // TWEAK FOR NEW CASES !!! // TWEAK FOR NEW CASES !!! // TWEAK FOR NEW CASES !!! @unknown default: return .down } } }
stackoverflow
{ "language": "en", "length": 270, "provenance": "stackexchange_0000F.jsonl.gz:911817", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688552" }
77546677994ff41814222e7aa6e157b82f4c8f05
Stackoverflow Stackexchange Q: How to properly use selectors in swift 4 I have read many tutorials and even the official Apple documentation and must not understand what is wrong with this code. var dueDatePicker = UIDatePicker() @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() textField.inputView = dueDatePicker dueDatePicker.addTarget(self, action: #selector(datePickerValueChanged(_:)), for: UIControlEvents.valueChanged) } func datePickerValueChanged(_ sender: UIDatePicker){ //Do Stuff } At runtime, I click on the textField and the UIDatePicker appears. The function that the selector points to is executed. As soon as I click a UI object outside of the UIDatePicker, the app crashes with this error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[YourApp.PromiseViewController dueDateChanged:]: unrecognized selector sent to instance 0x100b12ae0' What I don't understand is that the "selector" or pointer to the desired function is recognized initially. However, when I trigger another event from another UI Object this exception is thrown. Why is this happening? Shouldn't this exception be triggered when datePickerValueChanged() is called initially? A: Just add @objc in front of your function @objc func datePickerValueChanged(_ sender: UIDatePicker){ //Do Stuff }
Q: How to properly use selectors in swift 4 I have read many tutorials and even the official Apple documentation and must not understand what is wrong with this code. var dueDatePicker = UIDatePicker() @IBOutlet weak var textField: UITextField! override func viewDidLoad() { super.viewDidLoad() textField.inputView = dueDatePicker dueDatePicker.addTarget(self, action: #selector(datePickerValueChanged(_:)), for: UIControlEvents.valueChanged) } func datePickerValueChanged(_ sender: UIDatePicker){ //Do Stuff } At runtime, I click on the textField and the UIDatePicker appears. The function that the selector points to is executed. As soon as I click a UI object outside of the UIDatePicker, the app crashes with this error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[YourApp.PromiseViewController dueDateChanged:]: unrecognized selector sent to instance 0x100b12ae0' What I don't understand is that the "selector" or pointer to the desired function is recognized initially. However, when I trigger another event from another UI Object this exception is thrown. Why is this happening? Shouldn't this exception be triggered when datePickerValueChanged() is called initially? A: Just add @objc in front of your function @objc func datePickerValueChanged(_ sender: UIDatePicker){ //Do Stuff } A: The error is telling you that an action with the selector dueDateChanged(_:) has been added as a target action. More than one target action can be added to a control. Somewhere, maybe in your storyboard or xib, you have another action added to dueDatePicker.
stackoverflow
{ "language": "en", "length": 221, "provenance": "stackexchange_0000F.jsonl.gz:911882", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688764" }
3df9d636fa3523e86cbd60bd5067dd4d61ebfbef
Stackoverflow Stackexchange Q: In shell, how to extract substring from a complete file path If I have the variables like: baseFolder="/a/b/c/" completeFilePath="a/b/c/x/y/z.txt" How to extract the substring from completeFilePath and get the output as: x/y/z.txt baseFolder directory depth may be more or less A: You can use bash parameter expansion: baseFolder="/a/b/c/" completeFilePath="/a/b/c/x/y/z.txt" echo "${completeFilePath#$baseFilePath}" Refer: http://wiki.bash-hackers.org/syntax/pe#substring_removal
Q: In shell, how to extract substring from a complete file path If I have the variables like: baseFolder="/a/b/c/" completeFilePath="a/b/c/x/y/z.txt" How to extract the substring from completeFilePath and get the output as: x/y/z.txt baseFolder directory depth may be more or less A: You can use bash parameter expansion: baseFolder="/a/b/c/" completeFilePath="/a/b/c/x/y/z.txt" echo "${completeFilePath#$baseFilePath}" Refer: http://wiki.bash-hackers.org/syntax/pe#substring_removal A: Try to solve this with awk $ baseFolder="/a/b/c/" $ completeFilePath="a/b/c/x/y/z.txt" $ echo $completeFilePath| awk -v a=$baseFolder '{len=length(a)}{print substr($0,len)}' x/y/z.txt Brief explanation: * *len=length(a): get the length of $baseFolder *substr($0,len): print the substring of $completeFilePath starting from position len A: Here's a simple way using bash parameter expansion: b="a/b/c/d/" p="a/b/c/d/x/y/z.txt" echo "${p/${b}/}" The substitution takes the base folder as the pattern and replaces it with nothing (removing it).
stackoverflow
{ "language": "en", "length": 122, "provenance": "stackexchange_0000F.jsonl.gz:911903", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688849" }
e0c0f4be3ea11cfbff77d04ff2f9c53cf1b49896
Stackoverflow Stackexchange Q: How to extract uppercased attributes with Cheerio I have a log entry as below: <Event Timestamp="2017-06-14T10:17:09.313991+10:00" Level="INFO" Identity=""><Message>Accessed Page: </Message></Event> I'd like to extract the attribute like Timestamp, Level with Cheerio. What I did is like this: const $ = cheerio.load(line) console.log($("Event").attr('Timestamp')) However, I just get undefined in the console. Could you please advise where is the problem? A: .attr() is the correct Cheerio method call, but the HTML (or whatever it is) is odd. In HTML, attributes are lowercased, so you should get the right result if you use "timestamp" with a lowercase "t": const cheerio = require("cheerio"); // 1.0.0-rc.12 const html = ` <Event Timestamp="2017-06-14T10:17:09.313991+10:00" Level="INFO" Identity=""><Message>Accessed Page: </Message></Event> `; const $ = cheerio.load(html); console.log($("Event").attr("timestamp")); // => 2017-06-14T10:17:09.313991+10:00
Q: How to extract uppercased attributes with Cheerio I have a log entry as below: <Event Timestamp="2017-06-14T10:17:09.313991+10:00" Level="INFO" Identity=""><Message>Accessed Page: </Message></Event> I'd like to extract the attribute like Timestamp, Level with Cheerio. What I did is like this: const $ = cheerio.load(line) console.log($("Event").attr('Timestamp')) However, I just get undefined in the console. Could you please advise where is the problem? A: .attr() is the correct Cheerio method call, but the HTML (or whatever it is) is odd. In HTML, attributes are lowercased, so you should get the right result if you use "timestamp" with a lowercase "t": const cheerio = require("cheerio"); // 1.0.0-rc.12 const html = ` <Event Timestamp="2017-06-14T10:17:09.313991+10:00" Level="INFO" Identity=""><Message>Accessed Page: </Message></Event> `; const $ = cheerio.load(html); console.log($("Event").attr("timestamp")); // => 2017-06-14T10:17:09.313991+10:00
stackoverflow
{ "language": "en", "length": 121, "provenance": "stackexchange_0000F.jsonl.gz:911904", "question_score": "8", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688853" }
e7f975aeabe9b55c7567c1d0a502b3687cb27ad9
Stackoverflow Stackexchange Q: Swift: Get 30 days before 'Specific Date' I have a problem about showing specific date. Here the case, I have a random date from my API (06/16/2015) that always change. I put it into variable name toDate with Date type. I need to get 30 days before the toDate for my fromDate variable. I read this but it's still not working. Note: I don't have any DatePicker in this controller. A: Here you go: let toDate = `your date object` let fromDate = Calendar.current.date(byAdding: .month, value: -1, to: toDate) or, // If you want to have exactly 30 days before let fromDate = Calendar.current.date(byAdding: .day, value: -30, to: toDate)
Q: Swift: Get 30 days before 'Specific Date' I have a problem about showing specific date. Here the case, I have a random date from my API (06/16/2015) that always change. I put it into variable name toDate with Date type. I need to get 30 days before the toDate for my fromDate variable. I read this but it's still not working. Note: I don't have any DatePicker in this controller. A: Here you go: let toDate = `your date object` let fromDate = Calendar.current.date(byAdding: .month, value: -1, to: toDate) or, // If you want to have exactly 30 days before let fromDate = Calendar.current.date(byAdding: .day, value: -30, to: toDate) A: You can use the following code: let today = Date() //Jun 21, 2017, 7:18 PM let thirtyDaysBeforeToday = Calendar.current.date(byAdding: .day, value: -30, to: today)! //May 22, 2017, 7:18 PM I hope this helps.
stackoverflow
{ "language": "en", "length": 144, "provenance": "stackexchange_0000F.jsonl.gz:911948", "question_score": "17", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44688978" }
4cac7a1f78d8e9bab9211cde54bfe46ee77e08b9
Stackoverflow Stackexchange Q: md-datepicker timezone issue I'm having a timezone issue with md-datepicker. I have this element: HTML: <md-datepicker name="indate" md-placeholder="In Date" ng-model="fechain" ng-model-options="{ timezone: timezone }" md-min-date="fechain" md-max-date="fechain" required></md-datepicker> And this is a piece of the controller related to the view: $scope.fechain = $scope.fechaminin = moment().toDate(); //Wed Jun 21 2017 21:10:59 GMT-0500 (-05) $scope.timezone = moment().format('ZZ'); // "-0500" But the datepicker shows june 22nd. I've been searching on Google but couldn't find any solution. Any ideas?
Q: md-datepicker timezone issue I'm having a timezone issue with md-datepicker. I have this element: HTML: <md-datepicker name="indate" md-placeholder="In Date" ng-model="fechain" ng-model-options="{ timezone: timezone }" md-min-date="fechain" md-max-date="fechain" required></md-datepicker> And this is a piece of the controller related to the view: $scope.fechain = $scope.fechaminin = moment().toDate(); //Wed Jun 21 2017 21:10:59 GMT-0500 (-05) $scope.timezone = moment().format('ZZ'); // "-0500" But the datepicker shows june 22nd. I've been searching on Google but couldn't find any solution. Any ideas?
stackoverflow
{ "language": "en", "length": 75, "provenance": "stackexchange_0000F.jsonl.gz:911956", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689010" }
dc05e2abd8a9c9dc2af1ffbece4b83675283079c
Stackoverflow Stackexchange Q: How can we configure the Header of ant design table component? We have requirement where we need to show 'Hide/Show' columns feature on the header of table and also we want to provide different color to the header of table in ant design. Can anyone help me how can we do this? I did not find any control to do it as header rendering is completely internal to component. A: You can use the <Table.Column title={<...any react node...>}> attribute in combination with ordinary CSS.
Q: How can we configure the Header of ant design table component? We have requirement where we need to show 'Hide/Show' columns feature on the header of table and also we want to provide different color to the header of table in ant design. Can anyone help me how can we do this? I did not find any control to do it as header rendering is completely internal to component. A: You can use the <Table.Column title={<...any react node...>}> attribute in combination with ordinary CSS. A: The solution offered by kalpana did not work for me. What did work (Ant V4.10.x) was this: thead > tr > th { background-color: yellow; } Note that the !important setting is not required to make this work. Similarly, if you want to target the cells of the table, you can use: tbody > tr > td { background-color: yellow; } A: What I tried to resolve the background colour issue of header is overwrite the ant style class as below thead[class*="ant-table-thead"] th{ background-color: yellow !important; } I am not sure if this is the correct way of doing or not. antd should provide the property on Table to configure the header style. Is there any other better way to do it?
stackoverflow
{ "language": "en", "length": 208, "provenance": "stackexchange_0000F.jsonl.gz:911996", "question_score": "11", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689128" }
e6affdf8775727ae031e353c9191da3875159000
Stackoverflow Stackexchange Q: Firebase retrieve data below auto ID In Swift I'm in trouble in retrieving data from Firebase. I'd like to read all contactName data in JSON under auto ID , then append to UIPickerView. Here is my JSON tree (used childByAutoId()) And Here is my Swift Code dbRef = Database.database().reference() dbRef.child("user").child("contacts").queryOrdered(byChild: "contactName").observeSingleEvent(of: .value, with: {(snapshot) in for snap in snapshot.children { let userSnap = snap as! DataSnapshot let contactName = userSnap.value as? String self.pickOption.append("\(contactName)") } }) But the result shows me all nil data... looks like this. How Can I fix it..? A: I solved myself! But first of all, I decided not to use UIPickerView. And what I wanna do is to add data below auto ID. I'm not sure this is good algorithm for solving this problem, But Anyway, I made it :) dbRef.child("user/contacts/").observe(.value, with: {(snapshot) in if let result = snapshot.children.allObjects as? [DataSnapshot] { for child in result { let orderID = child.key as String //get autoID self.dbRef.child("user/contacts/\(orderID)/contactName").observe(.value, with: { (snapshot) in if let nameDB = snapshot.value as? String { if self.debtorName == nameDB { self.dbRef.child("user/contacts/\(orderID)").updateChildValues(data) } } }) } } })
Q: Firebase retrieve data below auto ID In Swift I'm in trouble in retrieving data from Firebase. I'd like to read all contactName data in JSON under auto ID , then append to UIPickerView. Here is my JSON tree (used childByAutoId()) And Here is my Swift Code dbRef = Database.database().reference() dbRef.child("user").child("contacts").queryOrdered(byChild: "contactName").observeSingleEvent(of: .value, with: {(snapshot) in for snap in snapshot.children { let userSnap = snap as! DataSnapshot let contactName = userSnap.value as? String self.pickOption.append("\(contactName)") } }) But the result shows me all nil data... looks like this. How Can I fix it..? A: I solved myself! But first of all, I decided not to use UIPickerView. And what I wanna do is to add data below auto ID. I'm not sure this is good algorithm for solving this problem, But Anyway, I made it :) dbRef.child("user/contacts/").observe(.value, with: {(snapshot) in if let result = snapshot.children.allObjects as? [DataSnapshot] { for child in result { let orderID = child.key as String //get autoID self.dbRef.child("user/contacts/\(orderID)/contactName").observe(.value, with: { (snapshot) in if let nameDB = snapshot.value as? String { if self.debtorName == nameDB { self.dbRef.child("user/contacts/\(orderID)").updateChildValues(data) } } }) } } })
stackoverflow
{ "language": "en", "length": 185, "provenance": "stackexchange_0000F.jsonl.gz:912053", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689303" }
c1901ba7fac03b8fd7cc0cfcf474d8ae6b7d7284
Stackoverflow Stackexchange Q: Insert row into psql db using psycopg2 Could you please help me figure out what I am doing wrong? I am trying to insert a new player into the players table. this is the python code: def registerPlayer(name): code for connecting to db and cursor c.execute("INSERT INTO players(player_name) VALUES({name});".format(name=name)) code for committing to db and closing the connection here is my table schema: CREATE TABLE players( player_id serial PRIMARY KEY, player_name varchar(50) NOT NULL ); below is error: psycopg2.ProgrammingError: syntax error at or near "Nalaar" LINE 1: INSERT INTO players(player_name) VALUES(Chandra Nalaar); A: You should never use string formatting for placing values into sql query. Instead, you should use %s and pass the name in the vars parameter. The reason behind doing it this way is because it helps you convert the parameters into the appropriate data types. Btw, having a ; at the end in the sql string is redundant when called by cursor.execute, since it does it for you automatically. c.execute("INSERT INTO players(player_name) VALUES(%(name)s)", {"name":name}) See this page for further details: http://initd.org/psycopg/docs/usage.html#query-parameters
Q: Insert row into psql db using psycopg2 Could you please help me figure out what I am doing wrong? I am trying to insert a new player into the players table. this is the python code: def registerPlayer(name): code for connecting to db and cursor c.execute("INSERT INTO players(player_name) VALUES({name});".format(name=name)) code for committing to db and closing the connection here is my table schema: CREATE TABLE players( player_id serial PRIMARY KEY, player_name varchar(50) NOT NULL ); below is error: psycopg2.ProgrammingError: syntax error at or near "Nalaar" LINE 1: INSERT INTO players(player_name) VALUES(Chandra Nalaar); A: You should never use string formatting for placing values into sql query. Instead, you should use %s and pass the name in the vars parameter. The reason behind doing it this way is because it helps you convert the parameters into the appropriate data types. Btw, having a ; at the end in the sql string is redundant when called by cursor.execute, since it does it for you automatically. c.execute("INSERT INTO players(player_name) VALUES(%(name)s)", {"name":name}) See this page for further details: http://initd.org/psycopg/docs/usage.html#query-parameters
stackoverflow
{ "language": "en", "length": 175, "provenance": "stackexchange_0000F.jsonl.gz:912068", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689359" }
8cae04f323e32b8e80c586a60d88c33ce137b983
Stackoverflow Stackexchange Q: Curl showing gzip but chrome showing no gzip header curl -I -H 'Accept-Encoding: gzip,deflate' https://example.com/a.min.js HTTP/1.1 200 OK Server: nginx Date: Thu, 22 Jun 2017 02:45:49 GMT Content-Type: application/javascript; charset=utf-8 Content-Length: 5430 Connection: keep-alive X-Accel-Version: 0.01 Last-Modified: Sat, 14 Jan 2017 12:50:18 GMT Accept-Ranges: bytes Vary: Accept-Encoding,User-Agent Content-Encoding: gzip X-Powered-By: PleskLin Cache-Control: max-age=2628000, private Here it is very clear that file is gzipped but in case of chrome, pagespeed and gtmetrix they are mentioning this file is not compressed. There is no content encoding in header when i view in chrome. Also my homepage is being compressed with gzipp. when using varvy service they are saying your local files are not compressed. I have enabled compression in nginx and apache both. also in .htaccess. but this is very weired. A: I just faced similar problem and found it was the antivirus extracting the gzipped assets. I had to completely disable the antivirus and restart the browser. See as well X-Content-Encoding-Over-Network in Response Header but not Content-Encoding
Q: Curl showing gzip but chrome showing no gzip header curl -I -H 'Accept-Encoding: gzip,deflate' https://example.com/a.min.js HTTP/1.1 200 OK Server: nginx Date: Thu, 22 Jun 2017 02:45:49 GMT Content-Type: application/javascript; charset=utf-8 Content-Length: 5430 Connection: keep-alive X-Accel-Version: 0.01 Last-Modified: Sat, 14 Jan 2017 12:50:18 GMT Accept-Ranges: bytes Vary: Accept-Encoding,User-Agent Content-Encoding: gzip X-Powered-By: PleskLin Cache-Control: max-age=2628000, private Here it is very clear that file is gzipped but in case of chrome, pagespeed and gtmetrix they are mentioning this file is not compressed. There is no content encoding in header when i view in chrome. Also my homepage is being compressed with gzipp. when using varvy service they are saying your local files are not compressed. I have enabled compression in nginx and apache both. also in .htaccess. but this is very weired. A: I just faced similar problem and found it was the antivirus extracting the gzipped assets. I had to completely disable the antivirus and restart the browser. See as well X-Content-Encoding-Over-Network in Response Header but not Content-Encoding A: I think it has something to do with caching. If I had to guess, I'd say each curl request grabs a fresh response from the server with gzip encoding. Chrome on the other hand, utilizes caching which seems to store the file after decompressing it. Chrome then serves you the decompressed file (no gzip encoding) from cache. I ran into a similar problem with chrome dev tools, and noticed that the content-encoding header was included only when I disabled caching (or hard refreshed) This forum goes a little more in-depth about it
stackoverflow
{ "language": "en", "length": 260, "provenance": "stackexchange_0000F.jsonl.gz:912103", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689471" }
fe3f2ea40e967725aa42e12a52a6c15252d7e015
Stackoverflow Stackexchange Q: ERROR TypeError: Cannot read property 'length' of undefined There is an error in this part of my code <img src="../../../assets/gms-logo.png" alt="logo" routerLink="/overview" alt="website icon"> But when I checked the assets folder, gms-logo.png is still there and in angular-cli.json, assets is also there. The path is also correct. Recently though, I've been working on Search function. So my hypothesis is, Has the program started searching even if the user is still not focused on the input type? How do I fix this? Below is my html for Search and the showing of its suggestion segment <input type="text" placeholder="Search" (keyup)="onSearch($event.target.value)"> <div class="suggestion" *ngIf="results.length > 0"> <div *ngFor="let result of results "> <a href="" target="_blank"> {{ result.name }} </a> </div> </div> Below is my component results: Object; onSearch(name) { this.search .searchEmployee(name) .subscribe( name => this.results = name,//alert(searchName),this.route.navigate(['/information/employees/']), error => alert(error), ); } A: Initializing the variable to empty solved my issue. DoctorList: any[] = [];
Q: ERROR TypeError: Cannot read property 'length' of undefined There is an error in this part of my code <img src="../../../assets/gms-logo.png" alt="logo" routerLink="/overview" alt="website icon"> But when I checked the assets folder, gms-logo.png is still there and in angular-cli.json, assets is also there. The path is also correct. Recently though, I've been working on Search function. So my hypothesis is, Has the program started searching even if the user is still not focused on the input type? How do I fix this? Below is my html for Search and the showing of its suggestion segment <input type="text" placeholder="Search" (keyup)="onSearch($event.target.value)"> <div class="suggestion" *ngIf="results.length > 0"> <div *ngFor="let result of results "> <a href="" target="_blank"> {{ result.name }} </a> </div> </div> Below is my component results: Object; onSearch(name) { this.search .searchEmployee(name) .subscribe( name => this.results = name,//alert(searchName),this.route.navigate(['/information/employees/']), error => alert(error), ); } A: Initializing the variable to empty solved my issue. DoctorList: any[] = []; A: I got stuck in a similar situation where even after assigning results as an array ( as shown below ), the error persisted. results: Array<any>; Using '?' ( Safe Navigation Operator ) worked out well for me. *ngIf="results?.length" The Safe Navigation Operator (?) can be used to prevent Angular from throwing errors while trying to access the properties of an object that doesn't exist. This example will evaluate the length only when a value of results is not Null or Undefined. A: You need to initialize your results variable as an array. In your component, add: results = []; Another option is to change your suggestion div's *ngIf statement to check if results is defined: <div class="suggestion" *ngIf="results"> <div *ngFor="let result of results "> <a href="" target="_blank"> {{ result.name }} </a> </div> </div> A: The safe navigation operator ( ?. ) and null property paths The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null. So in your example you can also use The safe navigation operator ( ?. ): <div class="suggestion" *ngIf="results?.length > 0"> <div *ngFor="let result of results "> <a href="" target="_blank"> {{ result.name }} </a> </div> </div> A: I got same issue. I found 2 ways to fix it * *Assign result as an Array result = [] in html *ngIf="results.length" *Use ? *ngIf="results?.length" A: you can just initialise your array in declaration : result: Array<any>; if the probleme style persiste you should check of null in your method lik this : onSearch(name) { this.search .searchEmployee(name) .subscribe( name => if(name!=null){ this.results = name,//alert(searchName),this.route.navigate(['/information/employees/']), } error => alert(error), ); }
stackoverflow
{ "language": "en", "length": 442, "provenance": "stackexchange_0000F.jsonl.gz:912104", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689474" }
31c23806fce84c4256e35f835f37dcd684a488af
Stackoverflow Stackexchange Q: Is it possible to refer to postman call name within the tests body App Details: Postman for Chrome Version 5.0.1 win / x86-64 Chrome 58.0.3029.110 In my collection, I have various requests within folders. e.g. Collection>CollectionFolder1>Request1, Request2 ... Is it possible to get a reference of the request names within the tests so that I could write something like: try { ... } catch (e) { tests[Test failed with exception ${e} for call request ${SOME_VARIABLE_THAT_STORES_REQUEST_NAME}] = false } This would allow me to duplicate this skeleton in all my requests without having to bother about maintaining it. Is there any postman variable or structure that would store any such info. A: In https://www.getpostman.com/docs/postman/scripts/postman_sandbox - paragraph Request/response related properties you can use the 'request' object. request.name: gives you the current test case name Obsolete use pm.info.requestName request.method: gives you the method used (PUT, GET, etc.) request.url: gives you the target url In order to see all the available data you may use, I suggest you to open the console (View/Show postman console or Alt+Ctrl+C) and see the data returned by this: console.log(request)
Q: Is it possible to refer to postman call name within the tests body App Details: Postman for Chrome Version 5.0.1 win / x86-64 Chrome 58.0.3029.110 In my collection, I have various requests within folders. e.g. Collection>CollectionFolder1>Request1, Request2 ... Is it possible to get a reference of the request names within the tests so that I could write something like: try { ... } catch (e) { tests[Test failed with exception ${e} for call request ${SOME_VARIABLE_THAT_STORES_REQUEST_NAME}] = false } This would allow me to duplicate this skeleton in all my requests without having to bother about maintaining it. Is there any postman variable or structure that would store any such info. A: In https://www.getpostman.com/docs/postman/scripts/postman_sandbox - paragraph Request/response related properties you can use the 'request' object. request.name: gives you the current test case name Obsolete use pm.info.requestName request.method: gives you the method used (PUT, GET, etc.) request.url: gives you the target url In order to see all the available data you may use, I suggest you to open the console (View/Show postman console or Alt+Ctrl+C) and see the data returned by this: console.log(request) A: Postman v6.5.2 and up uses pm.info.requestName console.log("Running: "+ pm.info.requestName); Look at pm.info object: https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/#scripting-with-request-info
stackoverflow
{ "language": "en", "length": 197, "provenance": "stackexchange_0000F.jsonl.gz:912122", "question_score": "15", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689530" }
1585124f84e9604d84bcf41dd16f3f3eb0d11153
Stackoverflow Stackexchange Q: Add SSL to Node.js Koa Server? I'd like to encrypt my Koa server with SSL. It seems simple enough with a regular httpServer, but I'm not how to do it with Koa. Could anyone help? A: Looks like there's no clear cut way to do this, but running Nginx on top of my server was an easy workaround.
Q: Add SSL to Node.js Koa Server? I'd like to encrypt my Koa server with SSL. It seems simple enough with a regular httpServer, but I'm not how to do it with Koa. Could anyone help? A: Looks like there's no clear cut way to do this, but running Nginx on top of my server was an easy workaround. A: I stumbled upon this. Launching an https server with the node package and passing it the Koa server instance .callback() does the trick. Koa's doc var fs = require('fs'); var path = require('path'); var http = require('http'); var https = require('https'); var Koa = require('koa'); var server = new Koa(); // add main routes // the following routes are for the authorisation challenges // ... we'll come back to this shortly var acmeRouter = require('./acme-router.js'); server .use(acmeRouter.routes()) .use(acmeRouter.allowedMethods()); var config = { domain: 'example.com', http: { port: 8989, }, https: { port: 7979, options: { key: fs.readFileSync(path.resolve(process.cwd(), 'certs/privkey.pem'), 'utf8').toString(), cert: fs.readFileSync(path.resolve(process.cwd(), 'certs/fullchain.pem'), 'utf8').toString(), }, }, }; let serverCallback = server.callback(); try { var httpServer = http.createServer(serverCallback); httpServer .listen(config.http.port, function(err) { if (!!err) { console.error('HTTP server FAIL: ', err, (err && err.stack)); } else { console.log(`HTTP server OK: http://${config.domain}:${config.http.port}`); } }); } catch (ex) { console.error('Failed to start HTTP server\n', ex, (ex && ex.stack)); } try { var httpsServer = https.createServer(config.https.options, serverCallback); httpsServer .listen(config.https.port, function(err) { if (!!err) { console.error('HTTPS server FAIL: ', err, (err && err.stack)); } else { console.log(`HTTPS server OK: http://${config.domain}:${config.https.port}`); } }); } catch (ex) { console.error('Failed to start HTTPS server\n', ex, (ex && ex.stack)); } module.exports = server;
stackoverflow
{ "language": "en", "length": 262, "provenance": "stackexchange_0000F.jsonl.gz:912128", "question_score": "12", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689542" }
4324a2e1869dfc9d68c5a028fb8c49b8ccc83290
Stackoverflow Stackexchange Q: How to print out a dictionary nicely in Python? I've just started to learn python and I'm building a text game. I want an inventory system, but I can't seem to print out the dictionary without it looking ugly. This is what I have so far: def inventory(): for numberofitems in len(inventory_content.keys()): inventory_things = list(inventory_content.keys()) inventory_amounts = list(inventory_content.values()) print(inventory_things[numberofitems]) A: My favorite way: import json print(json.dumps(dictionary, indent=4, sort_keys=True))
Q: How to print out a dictionary nicely in Python? I've just started to learn python and I'm building a text game. I want an inventory system, but I can't seem to print out the dictionary without it looking ugly. This is what I have so far: def inventory(): for numberofitems in len(inventory_content.keys()): inventory_things = list(inventory_content.keys()) inventory_amounts = list(inventory_content.values()) print(inventory_things[numberofitems]) A: My favorite way: import json print(json.dumps(dictionary, indent=4, sort_keys=True)) A: I would suggest to use beeprint instead of pprint. Examples: pprint {'entities': {'hashtags': [], 'urls': [{'display_url': 'github.com/panyanyany/beeprint', 'indices': [107, 126], 'url': 'https://github.com/panyanyany/beeprint'}], 'user_mentions': []}} beeprint { 'entities': { 'hashtags': [], 'urls': [ { 'display_url': 'github.com/panyanyany/beeprint', 'indices': [107, 126], 'url': 'https://github.com/panyanyany/beeprint'}], }, ], 'user_mentions': [], }, } A: Yaml is typically much more readable, especially if you have complicated nested objects, hierarchies, nested dictionaries etc: First make sure you have pyyaml module: pip install pyyaml Then, import yaml print(yaml.dump(my_dict)) A: Here's the one-liner I'd use. (Edit: works for things that aren't JSON-serializable too) print("\n".join("{}\t{}".format(k, v) for k, v in dictionary.items())) Explanation: This iterates through the keys and values of the dictionary, creating a formatted string like key + tab + value for each. And "\n".join(... puts newlines between all those strings, forming a new string. Example: >>> dictionary = {1: 2, 4: 5, "foo": "bar"} >>> print("\n".join("{}\t{}".format(k, v) for k, v in dictionary.items())) 1 2 4 5 foo bar >>> Edit 2: Here's a sorted version. "\n".join("{}\t{}".format(k, v) for k, v in sorted(dictionary.items(), key=lambda t: str(t[0]))) A: I like the pprint module (Pretty Print) included in Python. It can be used to either print the object, or format a nice string version of it. import pprint # Prints the nicely formatted dictionary pprint.pprint(dictionary) # Sets 'pretty_dict_str' to the formatted string value pretty_dict_str = pprint.pformat(dictionary) But it sounds like you are printing out an inventory, which users will likely want shown as something more like the following: def print_inventory(dct): print("Items held:") for item, amount in dct.items(): # dct.iteritems() in Python 2 print("{} ({})".format(item, amount)) inventory = { "shovels": 3, "sticks": 2, "dogs": 1, } print_inventory(inventory) which prints: Items held: shovels (3) sticks (2) dogs (1) A: Agree, "nicely" is very subjective. See if this helps, which I have been using to debug dict for i in inventory_things.keys(): logger.info('Key_Name:"{kn}", Key_Value:"{kv}"'.format(kn=i, kv=inventory_things[i])) A: I wrote this function to print simple dictionaries: def dictToString(dict): return str(dict).replace(', ','\r\n').replace("u'","").replace("'","")[1:-1] A: I did create function (in Python 3): def print_dict(dict): print( str(dict) .replace(', ', '\n') .replace(': ', ':\t') .replace('{', '') .replace('}', '') ) A: Maybe it doesn't fit all the needs but I just tried this and it got a nice formatted output So just convert the dictionary to Dataframe and that's pretty much all pd.DataFrame(your_dic.items()) You can also define columns to assist even more the readability pd.DataFrame(your_dic.items(),columns={'Value','key'}) So just give a try : print(pd.DataFrame(your_dic.items(),columns={'Value','key'}))
stackoverflow
{ "language": "en", "length": 467, "provenance": "stackexchange_0000F.jsonl.gz:912129", "question_score": "132", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689546" }
10809bc9d4cfdad53bffbcc30b5b86aa6e74aa94
Stackoverflow Stackexchange Q: GMSCameraPosition not accurate I am using GMS to show map locations in my iOS app using the following code. The position of the camera is not centered at marker position but it is slightly north(around 5 miles) of it. How can I center camera position to center on marker? let marker = GMSMarker() marker.position = CLLocationCoordinate2D(latitude: latitude!, longitude:longitude!) let camera = GMSCameraPosition.camera(withTarget: marker.position, zoom: 10.0) let mapView = GMSMapView.map(withFrame: view.bounds, camera: camera) marker.map = mapView cell.mapView.addSubview(mapView) Above is the initial location of the map. The marker is south of the initial view. A: The view in withFrame: view.bounds is not the correct mapView. Changing that to mapView fixed the problem.
Q: GMSCameraPosition not accurate I am using GMS to show map locations in my iOS app using the following code. The position of the camera is not centered at marker position but it is slightly north(around 5 miles) of it. How can I center camera position to center on marker? let marker = GMSMarker() marker.position = CLLocationCoordinate2D(latitude: latitude!, longitude:longitude!) let camera = GMSCameraPosition.camera(withTarget: marker.position, zoom: 10.0) let mapView = GMSMapView.map(withFrame: view.bounds, camera: camera) marker.map = mapView cell.mapView.addSubview(mapView) Above is the initial location of the map. The marker is south of the initial view. A: The view in withFrame: view.bounds is not the correct mapView. Changing that to mapView fixed the problem.
stackoverflow
{ "language": "en", "length": 111, "provenance": "stackexchange_0000F.jsonl.gz:912139", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689573" }
9f16aa51043179c62eb7905e861f034317001906
Stackoverflow Stackexchange Q: I am using ngx-tooltip within angular-material, but the tooltip is being cut off, any way to adjust z-index? I am using ngx-tooltip (https://www.npmjs.com/package/ngx-tooltip) with angular.material.io tabs and am running into an issue where the tooltip appears to get cut off on the left side when inside of the md-tab container. How do I make it such that the tooltip floats above everything? Is there some way I can adjust the z-index of the tooltip or is there some other way? Code: <md-tab-group> <md-tab label="Tab 1"> <!-- tooltip with dynamic html content --> <div> <tooltip-content #myTooltip> <b>Very</b> <span style="color: #C21F39">Dynamic</span> <span style="color: #00b3ee">Reusable</span> <b><i><span style="color: #ffc520">Tooltip With</span></i></b> <small>Html support</small>. </tooltip-content> <button [tooltip]="myTooltip">hover this button to see a tooltip</button> </div> </md-tab> </md-tab-group> A: I reproduced your problem in this plunker. In order to make the tooltip visible outside of the md-tab container, I had to do the following (see this corrected plunker): * *In the Component decorator, I set the encapsulation to ViewEncapsulation.None: import {ViewEncapsulation} from '@angular/core'; @Component({ ... styleUrls: ["./tabs-overview-example.css"], encapsulation: ViewEncapsulation.None }) *In the CSS file, I set the overflow attribute as follows: md-tab-group, md-tab-body, .mat-tab-body-wrapper, .mat-tab-body-content { overflow: visible !important; }
Q: I am using ngx-tooltip within angular-material, but the tooltip is being cut off, any way to adjust z-index? I am using ngx-tooltip (https://www.npmjs.com/package/ngx-tooltip) with angular.material.io tabs and am running into an issue where the tooltip appears to get cut off on the left side when inside of the md-tab container. How do I make it such that the tooltip floats above everything? Is there some way I can adjust the z-index of the tooltip or is there some other way? Code: <md-tab-group> <md-tab label="Tab 1"> <!-- tooltip with dynamic html content --> <div> <tooltip-content #myTooltip> <b>Very</b> <span style="color: #C21F39">Dynamic</span> <span style="color: #00b3ee">Reusable</span> <b><i><span style="color: #ffc520">Tooltip With</span></i></b> <small>Html support</small>. </tooltip-content> <button [tooltip]="myTooltip">hover this button to see a tooltip</button> </div> </md-tab> </md-tab-group> A: I reproduced your problem in this plunker. In order to make the tooltip visible outside of the md-tab container, I had to do the following (see this corrected plunker): * *In the Component decorator, I set the encapsulation to ViewEncapsulation.None: import {ViewEncapsulation} from '@angular/core'; @Component({ ... styleUrls: ["./tabs-overview-example.css"], encapsulation: ViewEncapsulation.None }) *In the CSS file, I set the overflow attribute as follows: md-tab-group, md-tab-body, .mat-tab-body-wrapper, .mat-tab-body-content { overflow: visible !important; } A: Assuming that #myTooltip is the reference to your tooltip, in your component import {Input, ElementRef, AfterViewInit, Component } from '@angular/core'; @Component(...) export class MyComponent implements AfterViewInit { @Input() myTooltip: ElementRef; ngAfterViewInit() { this.myTooltip.nativeElement.style.zIndex = '9999 !important'; } } A: I also had to add ".mat-tab-body" for it to work: md-tab-group, md-tab-body, .mat-tab-body-wrapper, .mat-tab-body-content, .mat-tab-body { overflow: visible !important; }
stackoverflow
{ "language": "en", "length": 253, "provenance": "stackexchange_0000F.jsonl.gz:912151", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689595" }
8aef361bf09a19440237d7ee618ad0906de487ad
Stackoverflow Stackexchange Q: How can I pass an html string to my child component? I need to pass an html string to a component in angular 4, but I can't find a way to mark the passed string as safe. I'm creating the passed html in parent component, it's not something I get from user or retrieve from server, it's also dynamic (created depending on the situation / alert type) My code looks like this: <app-alert message = "Please complete your <span class=u>Profile</span>" alertType = "alert-info" icon = "glyphicon glyphicon-info-sign" closeBtn = "true"> </app-alert> I searched a lot, but I couldn't find something suitable, the closest I could find is this question, but it only deals with "normal" strings, not strings that contains html in it How can I pass an html string to my child component? A: you could pass the html string as a component input. then within your child component's html use the innerHTML directive (https://www.dev6.com/Angular-2-HTML-binding) <span [innerHTML]="componentInput"></span>
Q: How can I pass an html string to my child component? I need to pass an html string to a component in angular 4, but I can't find a way to mark the passed string as safe. I'm creating the passed html in parent component, it's not something I get from user or retrieve from server, it's also dynamic (created depending on the situation / alert type) My code looks like this: <app-alert message = "Please complete your <span class=u>Profile</span>" alertType = "alert-info" icon = "glyphicon glyphicon-info-sign" closeBtn = "true"> </app-alert> I searched a lot, but I couldn't find something suitable, the closest I could find is this question, but it only deals with "normal" strings, not strings that contains html in it How can I pass an html string to my child component? A: you could pass the html string as a component input. then within your child component's html use the innerHTML directive (https://www.dev6.com/Angular-2-HTML-binding) <span [innerHTML]="componentInput"></span>
stackoverflow
{ "language": "en", "length": 159, "provenance": "stackexchange_0000F.jsonl.gz:912159", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689623" }
3d8060ffc5b13ccfebe8d16201077bffd0172065
Stackoverflow Stackexchange Q: Using str_extract_all to extract only first two words in R? I am stuck with a problem which should be simple. Likely a regex issue. I am a newbie. Please consider a string vector such as the one: species_location<-c('Homo_sapiens_Lausanne_Switzerland', 'Solenopsis_invicta_California_US', 'Rattus_novaborensis_Copenhagen_Denmark', 'Candida_albicans_Crotch_Home') I wanted to end up with a new vector for species that looks like: c(Homo_sapiens, Solenopsis_invicta, Rattus_novaborensis, Candida_albicans) Currently I am using the following function: str_extract_all(species_location,'^(\\S+?)_(\\S+?)_') However it returns the first 3 words instead of what I designed it for. I cannot figure out why. Please could anyone help and explain? Thanks UPDATE: For anyone passing by, the code entered above works as it should, excepting on my R Console for Mac OS 3.0.0, R.app 1.60. I still do not know what is the issue there but it might be interest someone else to check. Will try and add a picture here. A: We can use str_extract str_extract(species_location, "[^_]+_[^_]+")
Q: Using str_extract_all to extract only first two words in R? I am stuck with a problem which should be simple. Likely a regex issue. I am a newbie. Please consider a string vector such as the one: species_location<-c('Homo_sapiens_Lausanne_Switzerland', 'Solenopsis_invicta_California_US', 'Rattus_novaborensis_Copenhagen_Denmark', 'Candida_albicans_Crotch_Home') I wanted to end up with a new vector for species that looks like: c(Homo_sapiens, Solenopsis_invicta, Rattus_novaborensis, Candida_albicans) Currently I am using the following function: str_extract_all(species_location,'^(\\S+?)_(\\S+?)_') However it returns the first 3 words instead of what I designed it for. I cannot figure out why. Please could anyone help and explain? Thanks UPDATE: For anyone passing by, the code entered above works as it should, excepting on my R Console for Mac OS 3.0.0, R.app 1.60. I still do not know what is the issue there but it might be interest someone else to check. Will try and add a picture here. A: We can use str_extract str_extract(species_location, "[^_]+_[^_]+") A: Just relying on the stringr package. library(stringr) species_location<-c('Homo_sapiens_Lausanne_Switzerland', 'Solenopsis_invicta_California_US', 'Rattus_novaborensis_Copenhagen_Denmark', 'Candida_albicans_Crotch_Home') word(species_location, 1,2, sep="_")
stackoverflow
{ "language": "en", "length": 166, "provenance": "stackexchange_0000F.jsonl.gz:912166", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689640" }
717bfe9da95ce8d4849f68fcdb35d7cb932f87af
Stackoverflow Stackexchange Q: Alternative of HttpPostedFileBase in asp.net core and name of namespace I want to design a class that have HttpPostedFileBase based property like, public HttpPostedFileBase picture; I am using IFormFile and using Microsoft.AspNet.Http; the Code looks like this: using Microsoft.AspNet.Http; namespace design.Model { public class gallery { public IFormFile picture; } } and it gives an error at using Microsoft.AspNet.Http line. How can this be solved? A: Instead of HttpFileBase, you've to use IFormFile from Microsoft.AspNetCore.Http (install NuGet package if you haven't.)
Q: Alternative of HttpPostedFileBase in asp.net core and name of namespace I want to design a class that have HttpPostedFileBase based property like, public HttpPostedFileBase picture; I am using IFormFile and using Microsoft.AspNet.Http; the Code looks like this: using Microsoft.AspNet.Http; namespace design.Model { public class gallery { public IFormFile picture; } } and it gives an error at using Microsoft.AspNet.Http line. How can this be solved? A: Instead of HttpFileBase, you've to use IFormFile from Microsoft.AspNetCore.Http (install NuGet package if you haven't.) A: Install Microsoft.AspNetCore.Http from NuGet Package Manager.
stackoverflow
{ "language": "en", "length": 89, "provenance": "stackexchange_0000F.jsonl.gz:912169", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689652" }
0bac1b6ca7629455f29cdb921e3c6b13f6bb950c
Stackoverflow Stackexchange Q: Sugar ORM cannot query column with boolean values I'm using Sugar ORM to query a list of apps. I have a boolean column for tagging fields in this using: @Setter @Getter public boolean isNew = false; Now after API call I will update and save the record to tag all new apps and then for display I will just query it using: List<AppsModel> app_list = AppsModel.find(AppsModel.class, "is_new = ?", "true"); Problem is that it returns 0 entry where it to have 3 on my end. To check I get all the list and check the column one by one to check its values: List<AppsModel> test = AppsModel.listAll(AppsModel.class); for(int i=0;i<test.size();i++){ Log.e("Test app size", String.valueOf(test.get(i).isNew())); } And it returns 3 as expected with true values. I can make use of this loop for list but I don't want to as I want to keep my code clean as possible. Am I missing something here? A: Okay I found the answer here from satyan himself So basically, using "true" will match it as String. So instead use: List<AppsModel> app_list = AppsModel.find(AppsModel.class, "is_new = ?", "1"); As SQlite store boolean values as 0 and 1.
Q: Sugar ORM cannot query column with boolean values I'm using Sugar ORM to query a list of apps. I have a boolean column for tagging fields in this using: @Setter @Getter public boolean isNew = false; Now after API call I will update and save the record to tag all new apps and then for display I will just query it using: List<AppsModel> app_list = AppsModel.find(AppsModel.class, "is_new = ?", "true"); Problem is that it returns 0 entry where it to have 3 on my end. To check I get all the list and check the column one by one to check its values: List<AppsModel> test = AppsModel.listAll(AppsModel.class); for(int i=0;i<test.size();i++){ Log.e("Test app size", String.valueOf(test.get(i).isNew())); } And it returns 3 as expected with true values. I can make use of this loop for list but I don't want to as I want to keep my code clean as possible. Am I missing something here? A: Okay I found the answer here from satyan himself So basically, using "true" will match it as String. So instead use: List<AppsModel> app_list = AppsModel.find(AppsModel.class, "is_new = ?", "1"); As SQlite store boolean values as 0 and 1.
stackoverflow
{ "language": "en", "length": 192, "provenance": "stackexchange_0000F.jsonl.gz:912176", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689676" }
a5522cb2bec9bbfba03d6128f8466417c2fe18d0
Stackoverflow Stackexchange Q: Google Maps Autocomplete InvalidValueError: not an instance of HTMLInputElement I've read through a few different S.O. questions on this one and haven't been able to find anything indicating what I might be missing here. I'm very new to Ember, so it's possible that I've got this code in the wrong place. Regardless, here's what I've got: ../components/auto-complete.js import Ember from 'ember'; export default Ember.Component.extend({ didRender: function(){ var defaultBounds = new google.maps.LatLngBounds( new google.maps.LatLng(-90, -180), new google.maps.LatLng(90, 180) ); var options = { bounds: defaultBounds } var i = Ember.$('input'); var autocomplete = new google.maps.places.Autocomplete(i, options); } }); ../components/auto-complete.hbs <input id="input-user" class="controls" type="text" placeholder="Location" onfocus="autocomplete"> My console output I've looked at the tutorial, docs, etc. and there doesn't seem to be that much room for error here. I've also tried without the onfocus="autocomplete" Any and all advice would be appreciated. A: Ember.$('input') returns a DOM element; but google's autocomplete seems to be requiring HTMLInputElement you can try the following Ember.$('input')[0] and it should work.
Q: Google Maps Autocomplete InvalidValueError: not an instance of HTMLInputElement I've read through a few different S.O. questions on this one and haven't been able to find anything indicating what I might be missing here. I'm very new to Ember, so it's possible that I've got this code in the wrong place. Regardless, here's what I've got: ../components/auto-complete.js import Ember from 'ember'; export default Ember.Component.extend({ didRender: function(){ var defaultBounds = new google.maps.LatLngBounds( new google.maps.LatLng(-90, -180), new google.maps.LatLng(90, 180) ); var options = { bounds: defaultBounds } var i = Ember.$('input'); var autocomplete = new google.maps.places.Autocomplete(i, options); } }); ../components/auto-complete.hbs <input id="input-user" class="controls" type="text" placeholder="Location" onfocus="autocomplete"> My console output I've looked at the tutorial, docs, etc. and there doesn't seem to be that much room for error here. I've also tried without the onfocus="autocomplete" Any and all advice would be appreciated. A: Ember.$('input') returns a DOM element; but google's autocomplete seems to be requiring HTMLInputElement you can try the following Ember.$('input')[0] and it should work.
stackoverflow
{ "language": "en", "length": 164, "provenance": "stackexchange_0000F.jsonl.gz:912181", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689696" }
4e7de87f1f614a2e807589b00532ad8f8c76e58e
Stackoverflow Stackexchange Q: vscode - swapping selected texts in vscode I recently started using VSCode and I am really loving it. I Googled my question and dint find any answers related to VSCode. Consider I am having the following code: if (a === 'some condition') return true else return false If I want swap or switch the return, i.e., I select true and false and is there any keyboard shortcuts or key binding to swap my selections. Any help would be greatly appreciated. A: Not that I know of. I also came across the same issue some time back. You can use this Transpose plugin for VSCode Hope this helps :) PS - This is the issue thread from which I got to know about this plugin: https://github.com/Microsoft/vscode/issues/12435
Q: vscode - swapping selected texts in vscode I recently started using VSCode and I am really loving it. I Googled my question and dint find any answers related to VSCode. Consider I am having the following code: if (a === 'some condition') return true else return false If I want swap or switch the return, i.e., I select true and false and is there any keyboard shortcuts or key binding to swap my selections. Any help would be greatly appreciated. A: Not that I know of. I also came across the same issue some time back. You can use this Transpose plugin for VSCode Hope this helps :) PS - This is the issue thread from which I got to know about this plugin: https://github.com/Microsoft/vscode/issues/12435 A: Use Any Swap (the most installed) plugin for swapping text in Visual Studio code A: The Swap extension should work as you intended. Keyboard Shortcut: * *Windows: CTRL+ALT+8 *Mac: CMD+OPTION+8
stackoverflow
{ "language": "en", "length": 157, "provenance": "stackexchange_0000F.jsonl.gz:912188", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689723" }
f6339565ae0d592053fb14269896c4e84b390db3
Stackoverflow Stackexchange Q: Why converting new.Date() .toISOString() changes the time? I'm inserting a date in a database in two different format. this is inserting as Datetime var mydate; mydate = new Date(); document.getElementById('clockinhour').value = mydate.toISOString().slice(0, 19).replace('T', ' '); Output A 2017-06-21 20:14:31 this is inserting as varchar : document.getElementById('clocked_in_time').value = Date(); Output B Wed Jun 21 2017 16:14:31 GMT-0400 (Eastern Standard Time) Output B is the correct time but I need to display output A. What causes the time to change when converted toISOString? How can I fix this? A: ISO time is time zone free. You'll notice with b you have time zone GMT-04:00 if you add those four hours to the 16 hours in the Date, you get 20
Q: Why converting new.Date() .toISOString() changes the time? I'm inserting a date in a database in two different format. this is inserting as Datetime var mydate; mydate = new Date(); document.getElementById('clockinhour').value = mydate.toISOString().slice(0, 19).replace('T', ' '); Output A 2017-06-21 20:14:31 this is inserting as varchar : document.getElementById('clocked_in_time').value = Date(); Output B Wed Jun 21 2017 16:14:31 GMT-0400 (Eastern Standard Time) Output B is the correct time but I need to display output A. What causes the time to change when converted toISOString? How can I fix this? A: ISO time is time zone free. You'll notice with b you have time zone GMT-04:00 if you add those four hours to the 16 hours in the Date, you get 20 A: In your this is inserting as Datetime block your slice are stripping of the timezone part (the Z at the end of toISOString output): document.getElementById('clockinhour').value = mydate.toISOString().slice(0, 19).replace('T', ' '); As pointed out by @RobG in the comments section, toISOString should always return the date in UTC (Z or +00:00). RTFM: "The time zone [offset] is always UTC, denoted by the suffix Z", The time "changes" because it is converted to UTC when you calls toISOString. If you want to get ISO date in your timezone, you should take a look in these two questions: How to ISO 8601 format a Date with Timezone Offset in JavaScript? and How to format a JavaScript date
stackoverflow
{ "language": "en", "length": 234, "provenance": "stackexchange_0000F.jsonl.gz:912200", "question_score": "22", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689770" }
089365034d0acc3475a912b2391b745f1d183cb0
Stackoverflow Stackexchange Q: Getting COUNT from sqlalchemy I have: res = db.engine.execute('select count(id) from sometable') The returned object is sqlalchemy.engine.result.ResultProxy. How do I get count value from res? Res is not accessed by index but I have figured this out as: count=None for i in res: count = res[0] break There must be an easier way right? What is it? I didn't discover it yet. Note: The db is a postgres db. A: what you are asking for called unpacking, ResultProxy is an iterable, so we can do # there will be single record record, = db.engine.execute('select count(id) from sometable') # this record consist of single value count, = record
Q: Getting COUNT from sqlalchemy I have: res = db.engine.execute('select count(id) from sometable') The returned object is sqlalchemy.engine.result.ResultProxy. How do I get count value from res? Res is not accessed by index but I have figured this out as: count=None for i in res: count = res[0] break There must be an easier way right? What is it? I didn't discover it yet. Note: The db is a postgres db. A: what you are asking for called unpacking, ResultProxy is an iterable, so we can do # there will be single record record, = db.engine.execute('select count(id) from sometable') # this record consist of single value count, = record A: The ResultProxy in SQLAlchemy (as documented here http://docs.sqlalchemy.org/en/latest/core/connections.html?highlight=execute#sqlalchemy.engine.ResultProxy) is an iterable of the columns returned from the database. For a count() query, simply access the first element to get the column, and then another index to get the first element (and only) element of that column. result = db.engine.execute('select count(id) from sometable') count = result[0][0] If you happened to be using the ORM of SQLAlchemy, I would suggest using the Query.count() method on the appropriate model as shown here: http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=count#sqlalchemy.orm.query.Query.count A: While the other answers work, SQLAlchemy provides a shortcut for scalar queries as ResultProxy.scalar(): count = db.engine.execute('select count(id) from sometable').scalar() scalar() fetches the first column of the first row and closes the result set, or returns None if no row is present. There's also Query.scalar(), if using the Query API.
stackoverflow
{ "language": "en", "length": 240, "provenance": "stackexchange_0000F.jsonl.gz:912208", "question_score": "10", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689793" }
fcc7e4703142d1ba963f14886d7d0555a7807593
Stackoverflow Stackexchange Q: You want your type to be able to be converted from string. Which interface should you implement? The answer in Exam Ref 70-483 (Wouter de Kort) is "IFormattable". Explanation in the book is "IFormattable provides the functionality to format the value of an object into a string representation(I'm agree with this part). It is also used by the Convert class to do the opposite." How Convert can create an object from a string? It doesn't have FromString (it has ChangeType but still). More interesting, how could IFormattable facilitate in conversation FROM string? I sincerely think that the question is not valid but want to be sure.
Q: You want your type to be able to be converted from string. Which interface should you implement? The answer in Exam Ref 70-483 (Wouter de Kort) is "IFormattable". Explanation in the book is "IFormattable provides the functionality to format the value of an object into a string representation(I'm agree with this part). It is also used by the Convert class to do the opposite." How Convert can create an object from a string? It doesn't have FromString (it has ChangeType but still). More interesting, how could IFormattable facilitate in conversation FROM string? I sincerely think that the question is not valid but want to be sure.
stackoverflow
{ "language": "en", "length": 107, "provenance": "stackexchange_0000F.jsonl.gz:912232", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689857" }
0b00e42c8c1dccbaba8abc8453b41b94f692015d
Stackoverflow Stackexchange Q: how to debug tensorflow internal c++ code efficiently with IDE(intelJ or Xcode) on mac? I want to debug the c++ source code of tensorflow, e.g tensorflow/c/c_api.cc . I've found some answers about how to debug the c++ code with gdb,but I want to know if it's possible to debug it with ide like Xcode, which can be very comfortable for editing and debug.Thanks . A: After much search and dig, I finally succeed to debug the tensorflow c++ source code in an acceptable way.I used bazel+vscode+lldb on mac. bazel: build the target(Also can be done by vscode). visual studio code: debug and read code lldb : debug backend my vscode lanch.json is : { "version": "0.2.0", "configurations": [ { "name": "(lldb) Launch", "type": "cppdbg", "request": "launch", "program": "${workspaceRoot}/bazel-out/darwin_x86_64-dbg/bin/tensorflow/cc/example/example", "args": [], "stopAtEntry": false, "cwd": "${workspaceRoot}", "environment": [], "externalConsole": true, "MIMode": "lldb" } ] }
Q: how to debug tensorflow internal c++ code efficiently with IDE(intelJ or Xcode) on mac? I want to debug the c++ source code of tensorflow, e.g tensorflow/c/c_api.cc . I've found some answers about how to debug the c++ code with gdb,but I want to know if it's possible to debug it with ide like Xcode, which can be very comfortable for editing and debug.Thanks . A: After much search and dig, I finally succeed to debug the tensorflow c++ source code in an acceptable way.I used bazel+vscode+lldb on mac. bazel: build the target(Also can be done by vscode). visual studio code: debug and read code lldb : debug backend my vscode lanch.json is : { "version": "0.2.0", "configurations": [ { "name": "(lldb) Launch", "type": "cppdbg", "request": "launch", "program": "${workspaceRoot}/bazel-out/darwin_x86_64-dbg/bin/tensorflow/cc/example/example", "args": [], "stopAtEntry": false, "cwd": "${workspaceRoot}", "environment": [], "externalConsole": true, "MIMode": "lldb" } ] }
stackoverflow
{ "language": "en", "length": 144, "provenance": "stackexchange_0000F.jsonl.gz:912234", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689863" }
d175b6b55f5bb45cbcaa63aaf091e2c8b5c092cc
Stackoverflow Stackexchange Q: Configure Nginx for aws s3 static and media files I am using aws s3 for static and media files for my django app. Gunicorn and Nginx are being used for application and proxy server. Nginx setup: server { listen 80; server_name sitename.com; location / { include proxy_params; proxy_pass http://unix:/home/SiteNameDjango/myproject/myproject.sock; } } Since I am using aws s3 for my static and media files, how should I configure Nginx for my static location? Or there's no need to configure for the static and media files? If it helps, here is the Django project settings for aws s3: STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' STATICFILES_STORAGE = 'myproject.custom_storages.StaticStorage' DEFAULT_FILE_STORAGE = 'myproject.custom_storages.MediaStorage' AWS_STORAGE_BUCKET_NAME = "django-bucket" AWS_S3_CUSTOM_DOMAIN = AWS_STORAGE_BUCKET_NAME + ".s3.amazonaws.com" STATIC_URL = "https://" + AWS_STORAGE_BUCKET_NAME + ".s3.amazonaws.com/" MEDIA_URL = STATIC_URL + "media/" ADMIN_MEDIA_PREFIX = STATIC_URL + "admin/" Eg url: https://django-bucket.s3.amazonaws.com/media/user_image/1497598249_49.jpeg A: In case of S3, nginx is not responsible for serving static and media files and you no need to configure anything.
Q: Configure Nginx for aws s3 static and media files I am using aws s3 for static and media files for my django app. Gunicorn and Nginx are being used for application and proxy server. Nginx setup: server { listen 80; server_name sitename.com; location / { include proxy_params; proxy_pass http://unix:/home/SiteNameDjango/myproject/myproject.sock; } } Since I am using aws s3 for my static and media files, how should I configure Nginx for my static location? Or there's no need to configure for the static and media files? If it helps, here is the Django project settings for aws s3: STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' STATICFILES_STORAGE = 'myproject.custom_storages.StaticStorage' DEFAULT_FILE_STORAGE = 'myproject.custom_storages.MediaStorage' AWS_STORAGE_BUCKET_NAME = "django-bucket" AWS_S3_CUSTOM_DOMAIN = AWS_STORAGE_BUCKET_NAME + ".s3.amazonaws.com" STATIC_URL = "https://" + AWS_STORAGE_BUCKET_NAME + ".s3.amazonaws.com/" MEDIA_URL = STATIC_URL + "media/" ADMIN_MEDIA_PREFIX = STATIC_URL + "admin/" Eg url: https://django-bucket.s3.amazonaws.com/media/user_image/1497598249_49.jpeg A: In case of S3, nginx is not responsible for serving static and media files and you no need to configure anything. A: In Nginx try with: location /static { alias /path/to/your/static; } In Djando settings.py use: STATIC_ROOT = '/path/to/your/static' STATIC_URL = '/static/' After this you need to collect statics in the folder, run the following command: python manange.py collectstatic Django will save all static files in the path specified, now Nginx will load the static files without the URL A: In case you are using app server to serve the static files,then you need to configure nginx the way mattia has mentioned. However you don't really need the same if you are using s3 path. Based on your configuration when your run collectstatic it should automatically sync your files on s3. In you views you use the s3 , to have performance boost you can put your s3 behind Cloudfront and server content from there.
stackoverflow
{ "language": "en", "length": 293, "provenance": "stackexchange_0000F.jsonl.gz:912242", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689882" }
5525c238c4704c0679e7654eb6ba7d285b0d9ab5
Stackoverflow Stackexchange Q: How to unwrap a discriminated union without pattern matching? I have a discriminated union like this: Type Result = | Good of bool | Bad of bool In many cases I know that result is Good. To unwrap the Result, I have to use pattern matching for just the Good option. As a result I get a warning (not an error) that says "Incomplete pattern match on this expression..". Is there a way to unwrap is without having to use pattern matching? A: You can add methods to unions just like any other type, like this: type Result = | Good of bool | Bad of bool with member x.GoodValue = match x with | Good b -> b | Bad _ -> failwith "Not a good value" [<EntryPoint>] let main argv = let r = Good true let s = Bad true printfn "%A" r.GoodValue printfn "%A" s.GoodValue // You know what happens..! 0
Q: How to unwrap a discriminated union without pattern matching? I have a discriminated union like this: Type Result = | Good of bool | Bad of bool In many cases I know that result is Good. To unwrap the Result, I have to use pattern matching for just the Good option. As a result I get a warning (not an error) that says "Incomplete pattern match on this expression..". Is there a way to unwrap is without having to use pattern matching? A: You can add methods to unions just like any other type, like this: type Result = | Good of bool | Bad of bool with member x.GoodValue = match x with | Good b -> b | Bad _ -> failwith "Not a good value" [<EntryPoint>] let main argv = let r = Good true let s = Bad true printfn "%A" r.GoodValue printfn "%A" s.GoodValue // You know what happens..! 0 A: You can just use let, e.g. type Result = | Good of bool | Bad of bool let example = Good true let (Good unwrappedBool) = example Note that this will still result in a compiler warning that the match cases might be incomplete. Technically, however, this is still using pattern matching, just doing so without a match expression.
stackoverflow
{ "language": "en", "length": 216, "provenance": "stackexchange_0000F.jsonl.gz:912266", "question_score": "6", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44689940" }
2dbade318c52de46187a7054d5c9ae6720a341d1
Stackoverflow Stackexchange Q: Cheerio how to ignore elements of a certain tag I am scraping the body of the webpage: axios.get(url) .then(function(response){ var $ = cheerio.load(response.data); var body = $('body').text(); }); The problem is, I want to exclude contents from the <footer> tag. How do I do that? A: cheerio creates a pseudo-DOM when it parses the HTML. You can manipulate that DOM similar to how you would manipulate the DOM in a browser. In your specific case, you could remove items from the DOM using any number of methods such as .remove() .replaceWith() .empty() .html() So, the basic idea is that you would use a selector to find the footer element and then remove it as in: $('footer').remove(); Then, fetch the text after you've removed those elements: var body = $('body').text();
Q: Cheerio how to ignore elements of a certain tag I am scraping the body of the webpage: axios.get(url) .then(function(response){ var $ = cheerio.load(response.data); var body = $('body').text(); }); The problem is, I want to exclude contents from the <footer> tag. How do I do that? A: cheerio creates a pseudo-DOM when it parses the HTML. You can manipulate that DOM similar to how you would manipulate the DOM in a browser. In your specific case, you could remove items from the DOM using any number of methods such as .remove() .replaceWith() .empty() .html() So, the basic idea is that you would use a selector to find the footer element and then remove it as in: $('footer').remove(); Then, fetch the text after you've removed those elements: var body = $('body').text();
stackoverflow
{ "language": "en", "length": 130, "provenance": "stackexchange_0000F.jsonl.gz:912291", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690023" }
558de307d62fa799027ee474eaaf47d4c66c0df8
Stackoverflow Stackexchange Q: Spark: Convert column of string to an array How to convert a column that has been read as a string into a column of arrays? i.e. convert from below schema scala> test.printSchema root |-- a: long (nullable = true) |-- b: string (nullable = true) +---+---+ | a| b| +---+---+ | 1|2,3| +---+---+ | 2|4,5| +---+---+ To: scala> test1.printSchema root |-- a: long (nullable = true) |-- b: array (nullable = true) | |-- element: long (containsNull = true) +---+-----+ | a| b | +---+-----+ | 1|[2,3]| +---+-----+ | 2|[4,5]| +---+-----+ Please share both scala and python implementation if possible. On a related note, how do I take care of it while reading from the file itself? I have data with ~450 columns and few of them I want to specify in this format. Currently I am reading in pyspark as below: df = spark.read.format('com.databricks.spark.csv').options( header='true', inferschema='true', delimiter='|').load(input_file) Thanks. A: In python (pyspark) it would be: from pyspark.sql.types import * from pyspark.sql.functions import col, split test = test.withColumn( "b", split(col("b"), ",\s*").cast("array<int>").alias("ev") )
Q: Spark: Convert column of string to an array How to convert a column that has been read as a string into a column of arrays? i.e. convert from below schema scala> test.printSchema root |-- a: long (nullable = true) |-- b: string (nullable = true) +---+---+ | a| b| +---+---+ | 1|2,3| +---+---+ | 2|4,5| +---+---+ To: scala> test1.printSchema root |-- a: long (nullable = true) |-- b: array (nullable = true) | |-- element: long (containsNull = true) +---+-----+ | a| b | +---+-----+ | 1|[2,3]| +---+-----+ | 2|[4,5]| +---+-----+ Please share both scala and python implementation if possible. On a related note, how do I take care of it while reading from the file itself? I have data with ~450 columns and few of them I want to specify in this format. Currently I am reading in pyspark as below: df = spark.read.format('com.databricks.spark.csv').options( header='true', inferschema='true', delimiter='|').load(input_file) Thanks. A: In python (pyspark) it would be: from pyspark.sql.types import * from pyspark.sql.functions import col, split test = test.withColumn( "b", split(col("b"), ",\s*").cast("array<int>").alias("ev") ) A: There are various method, The best way to do is using split function and cast to array<long> data.withColumn("b", split(col("b"), ",").cast("array<long>")) You can also create simple udf to convert the values val tolong = udf((value : String) => value.split(",").map(_.toLong)) data.withColumn("newB", tolong(data("b"))).show Hope this helps! A: Using a UDF would give you exact required schema. Like this: val toArray = udf((b: String) => b.split(",").map(_.toLong)) val test1 = test.withColumn("b", toArray(col("b"))) It would give you schema as follows: scala> test1.printSchema root |-- a: long (nullable = true) |-- b: array (nullable = true) | |-- element: long (containsNull = true) +---+-----+ | a| b | +---+-----+ | 1|[2,3]| +---+-----+ | 2|[4,5]| +---+-----+ As far as applying schema on file read itself is concerned, I think that is a tough task. So, for now you can apply transformation after creating DataFrameReader of test. I hope this helps!
stackoverflow
{ "language": "en", "length": 316, "provenance": "stackexchange_0000F.jsonl.gz:912334", "question_score": "23", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690174" }
495a25c4eed8ec99a4a8efbc8836af9545ce35bb
Stackoverflow Stackexchange Q: Woocommerce - Cart page not displaying After ADD TO CART option i can see the items are getting updated to CART but when moving to cart page it is redirecting back to homepage. The cart page shortcode is also provided. Please help out!I'm new to woocommerce. A: So I fixed mine, here is how I did it, seems woocommerce does not create all the pages in the newest version, you are missing the 'cart page'.. create a page name it 'cart' then place this short code on the page.. [woocommerce_cart] save..Tada.. ;o) Shop – No content required. Cart – Contains [woocommerce_cart] shortcode and shows the cart contents Checkout – Contains [woocommerce_checkout] shortcode and shows information such as shipping and payment options My Account – Contains [woocommerce_my_account] shortcode and shows each customer information related to their account, orders, etc.
Q: Woocommerce - Cart page not displaying After ADD TO CART option i can see the items are getting updated to CART but when moving to cart page it is redirecting back to homepage. The cart page shortcode is also provided. Please help out!I'm new to woocommerce. A: So I fixed mine, here is how I did it, seems woocommerce does not create all the pages in the newest version, you are missing the 'cart page'.. create a page name it 'cart' then place this short code on the page.. [woocommerce_cart] save..Tada.. ;o) Shop – No content required. Cart – Contains [woocommerce_cart] shortcode and shows the cart contents Checkout – Contains [woocommerce_checkout] shortcode and shows information such as shipping and payment options My Account – Contains [woocommerce_my_account] shortcode and shows each customer information related to their account, orders, etc. A: In wordpress 5.4.x it is here like in this image: A: Dear go to woo commerce setting page and click to checkout tab then select the cart page for add to cart. you should also need to reset your permalinks first default and then post name. A: This question is from years ago but since I had the same problem and finally could find the culprit by try and error, I post this answer in case someone has the same struggle. Go to woocomerce setting and then advance and set the checkout and cart pages If the woocommerce doesn't create checkout and cart pages when you install it, you need to create them by yourself using these pieces of codes: [woocommerce_cart] [woocommerce_checkout] You can find other codes from here: https://docs.woocommerce.com/document/pages-not-displaying/# A: Be sure you have page.php setup in your theme to get the content. Something like: <?php while (have_posts()) : the_post(); ?> <?php the_content(); ?> <?php endwhile; ?>
stackoverflow
{ "language": "en", "length": 298, "provenance": "stackexchange_0000F.jsonl.gz:912360", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690261" }
db55e04c19e3e844694eb8b5c0b1d19355b1eef9
Stackoverflow Stackexchange Q: How do i change keybinding in sublime text 3 I want to know how to change the run key binding from ctrl+shift+b to f9 but I can't find whats the command name for it. A: preferences->key bindings - user [ { "keys": ["f9"], "command": "build" } ]
Q: How do i change keybinding in sublime text 3 I want to know how to change the run key binding from ctrl+shift+b to f9 but I can't find whats the command name for it. A: preferences->key bindings - user [ { "keys": ["f9"], "command": "build" } ] A: The answers are correct, you just need to confirm your binding by actually executing the new binding you've made. At least that's what's worked for me so: * *Go to "Preferences" -> "Key Bindings" *Type in the following in the right hand window. [ { "keys": ["f9"], "command": "build" } ] *Press F9 on your keyboard to confirm. It seems that the left side window is like it's own little console that needs to "build" the new key binding. I guess the execution adds the new key binding to the key bindings dictionary just like when you run a normal command in python. After the "script" is executed, the variable is added and can be used from now on. A: On the menu, go to "Preferences" -> "Run key bindings" A new window opens with the standard settings on the left and a custom setting on the right. Give your new entry to override default settings. A: Try this: { "keys": ["f9"], "command": "build", "args": {"variant": "Run"} }, A: Use this: { "keys": ["ctrl+enter"], "command": "build", "args": {"select": true} }, Thanks!
stackoverflow
{ "language": "en", "length": 230, "provenance": "stackexchange_0000F.jsonl.gz:912368", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690300" }
85689bf1cf61995dc9b3ee8fe582e5b0d45cdb1d
Stackoverflow Stackexchange Q: How do I print an integer in binary with leading zeros? I'm doing some bit twiddling and I'd like to print all the bits in my u16. let flags = 0b0000000000101100u16; println!("flags: {:#b}", flags); This prints flags: 0b101100. How do I make it print flags: 0b0000000000101100? A: let flags = 0b0000000000101100u16; println!("flags: {:#018b}", flags); The 018 pads with zeros to a width of 18. That width includes 0b (length=2) plus a u16 (length=16) so 18 = 2 + 16. It must come between # and b. Rust's fmt docs explain both leading zeros and radix formatting, but don't show how to combine them. Here are u8, u16, and u32: // Width 0 8 16 24 32 // | | | | | println!("{:#010b}", 1i8); // 0b00000001 println!("{:#018b}", 1i16); // 0b0000000000000001 println!("{:#034b}", 1i32); // 0b00000000000000000000000000000001
Q: How do I print an integer in binary with leading zeros? I'm doing some bit twiddling and I'd like to print all the bits in my u16. let flags = 0b0000000000101100u16; println!("flags: {:#b}", flags); This prints flags: 0b101100. How do I make it print flags: 0b0000000000101100? A: let flags = 0b0000000000101100u16; println!("flags: {:#018b}", flags); The 018 pads with zeros to a width of 18. That width includes 0b (length=2) plus a u16 (length=16) so 18 = 2 + 16. It must come between # and b. Rust's fmt docs explain both leading zeros and radix formatting, but don't show how to combine them. Here are u8, u16, and u32: // Width 0 8 16 24 32 // | | | | | println!("{:#010b}", 1i8); // 0b00000001 println!("{:#018b}", 1i16); // 0b0000000000000001 println!("{:#034b}", 1i32); // 0b00000000000000000000000000000001
stackoverflow
{ "language": "en", "length": 135, "provenance": "stackexchange_0000F.jsonl.gz:912411", "question_score": "35", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690439" }
4d71ae074582025d2e96ac7e74bd1339003b8aca
Stackoverflow Stackexchange Q: What does "-spec" do in Erlang syntax? What is the diffrence if a function is created with or without -spec I am new to erlang programming. I have many doubts. One of them is use of -spec. What does "-spec" do in Erlang syntax? What is the difference if a function is created with or without -spec function without -spec add(A, B) -> A + B. function with -spec -spec add(Number, Number). add(A, B) -> A + B. I searched on the google but unable to understand the exact use of the -spec. Can anyone please explain? A: spec adds up information about the code. It indicates the arity of the function and combined with -type declarations, are helpful for documentation and bug detection tools. Tools like Edoc use these type specifications for building documentation. Tools like Dialyzer use it for static analysis of the code. So it is not used directly by the running code but many tools use it for better "understanding" the code.
Q: What does "-spec" do in Erlang syntax? What is the diffrence if a function is created with or without -spec I am new to erlang programming. I have many doubts. One of them is use of -spec. What does "-spec" do in Erlang syntax? What is the difference if a function is created with or without -spec function without -spec add(A, B) -> A + B. function with -spec -spec add(Number, Number). add(A, B) -> A + B. I searched on the google but unable to understand the exact use of the -spec. Can anyone please explain? A: spec adds up information about the code. It indicates the arity of the function and combined with -type declarations, are helpful for documentation and bug detection tools. Tools like Edoc use these type specifications for building documentation. Tools like Dialyzer use it for static analysis of the code. So it is not used directly by the running code but many tools use it for better "understanding" the code.
stackoverflow
{ "language": "en", "length": 167, "provenance": "stackexchange_0000F.jsonl.gz:912421", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690467" }
031c5f433404f9f6cf4b7a573d688dffc5b2d28e
Stackoverflow Stackexchange Q: Android Cannot recover key I'm having an error recovering my key in Android Studio. I know the key alias and I have the correct password for both. I know this because I am able to run: keytool -list -v -keystore mykeystore.jks -alias myKey -storepass myPass -keypass myPass in cmd and get my certs. My storepass and keypass are the same and I copied and pasted all of the values from cmd to android studio, but I still get this error. I've also tried restarting android studio and manually retyping my passwords and alias multiple times to no avail.
Q: Android Cannot recover key I'm having an error recovering my key in Android Studio. I know the key alias and I have the correct password for both. I know this because I am able to run: keytool -list -v -keystore mykeystore.jks -alias myKey -storepass myPass -keypass myPass in cmd and get my certs. My storepass and keypass are the same and I copied and pasted all of the values from cmd to android studio, but I still get this error. I've also tried restarting android studio and manually retyping my passwords and alias multiple times to no avail.
stackoverflow
{ "language": "en", "length": 99, "provenance": "stackexchange_0000F.jsonl.gz:912437", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690499" }
9ec758e249bf9361bbfa2e87a5333f363fe13739
Stackoverflow Stackexchange Q: How to find record id in aftersave hooks logic-SuiteCRM I am doing some API calls in aftersave hooks logic.One thing i need to get the Id of saved record from DB to redirect user to edit view if any error occurs in hooks class. This my error code to redirect user but i need the record id: function ShowError($errorMsg,$beanID){ try{ self::$already_ran = false; SugarApplication::appendErrorMessage($errorMsg); $params = array( 'module'=> 'ad123_Ads', 'return_module'=> 'ad123_Ads', 'action'=>'EditView', 'record' => $beanID ); SugarApplication::redirect('index.php?' . http_build_query($params)); } catch (Exception $e) { echo 'Caught exception: ', $e, "\n"; } } A: The first argument for a hook is the bean that the hook is being run on, in an aftersave hook you can simply grab the id from the bean: function myLogicHook(SugarBean $bean, $event, $arguments){ echo "Bean id is ".$bean->id; }
Q: How to find record id in aftersave hooks logic-SuiteCRM I am doing some API calls in aftersave hooks logic.One thing i need to get the Id of saved record from DB to redirect user to edit view if any error occurs in hooks class. This my error code to redirect user but i need the record id: function ShowError($errorMsg,$beanID){ try{ self::$already_ran = false; SugarApplication::appendErrorMessage($errorMsg); $params = array( 'module'=> 'ad123_Ads', 'return_module'=> 'ad123_Ads', 'action'=>'EditView', 'record' => $beanID ); SugarApplication::redirect('index.php?' . http_build_query($params)); } catch (Exception $e) { echo 'Caught exception: ', $e, "\n"; } } A: The first argument for a hook is the bean that the hook is being run on, in an aftersave hook you can simply grab the id from the bean: function myLogicHook(SugarBean $bean, $event, $arguments){ echo "Bean id is ".$bean->id; }
stackoverflow
{ "language": "en", "length": 134, "provenance": "stackexchange_0000F.jsonl.gz:912477", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690599" }
676fb36c60faadf232d9081ef7946d7abda1e61f
Stackoverflow Stackexchange Q: 360 panorama image with Ionic/Cordova I want to capture 360 view image from device camera. Is there any plugin or setting for camera available in Ionic/Cordova that can facilitate me starting device camera with appropriate settings/options of 360 panorama mode?
Q: 360 panorama image with Ionic/Cordova I want to capture 360 view image from device camera. Is there any plugin or setting for camera available in Ionic/Cordova that can facilitate me starting device camera with appropriate settings/options of 360 panorama mode?
stackoverflow
{ "language": "en", "length": 41, "provenance": "stackexchange_0000F.jsonl.gz:912509", "question_score": "9", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690698" }
69374d3c24ce0903c36cc1075b662ab9ffba511a
Stackoverflow Stackexchange Q: How to map EnumOrdinalTypeHandler for mybatis-spring-boot? I am now using Mybatis with spring-boot. I didn't add mybatis-config.xml. I make all configurations for datasource and mybatis via application.properties from instructions of mybatis-spring-boot-autoconfigure as below ### Database Configuration spring.datasource.url=jdbc:sqlserver://localhost;databaseName=mywebsite;catalogName=mywebsite spring.datasource.username=sa spring.datasource.password=root spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver ### Mybatis Configurations ### mybatis.type-aliases-package=com.mycom.myproducts.mywebsite.config.bean mybatis.type-handlers-package=org.apache.ibatis.type.EnumOrdinalTypeHandler mybatis.mapperLocations=classpath:mybatis/mapper/**/*.xml mybatis.configuration.default-fetch-size=100 mybatis.configuration.default-statement-timeout=30 The problem is mybatis can't map for my enum types and the error show Caused by: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'gender' from result set. Cause: java.lang.IllegalArgumentException: No enum constant com.mycom.myproducts.mywebsite.config.bean.config.UserBean.Gender.0 This can be fixed by mybatis-config.xml with <typeHandlers> <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="com.mycom.myproducts.mywebsite.config.bean.config.UserBean$Gender"/> </typeHandlers> but I don't know how can this be done by application.properties file ? A: Try this package com.example.typehandler; @MappedTypes({Gender.class}) public class GenderTypeHandler extends EnumOrdinalTypeHandler {} mybatis.type-handlers-package=com.example.typehandler @Select(...) @Results(value = { @Result(property="gender", column="gender", typeHandler="com.example.typehandler.Gender"), ... The typeHandler in the @Result may be unnecessary if you use @MappedTypes.
Q: How to map EnumOrdinalTypeHandler for mybatis-spring-boot? I am now using Mybatis with spring-boot. I didn't add mybatis-config.xml. I make all configurations for datasource and mybatis via application.properties from instructions of mybatis-spring-boot-autoconfigure as below ### Database Configuration spring.datasource.url=jdbc:sqlserver://localhost;databaseName=mywebsite;catalogName=mywebsite spring.datasource.username=sa spring.datasource.password=root spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver ### Mybatis Configurations ### mybatis.type-aliases-package=com.mycom.myproducts.mywebsite.config.bean mybatis.type-handlers-package=org.apache.ibatis.type.EnumOrdinalTypeHandler mybatis.mapperLocations=classpath:mybatis/mapper/**/*.xml mybatis.configuration.default-fetch-size=100 mybatis.configuration.default-statement-timeout=30 The problem is mybatis can't map for my enum types and the error show Caused by: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'gender' from result set. Cause: java.lang.IllegalArgumentException: No enum constant com.mycom.myproducts.mywebsite.config.bean.config.UserBean.Gender.0 This can be fixed by mybatis-config.xml with <typeHandlers> <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="com.mycom.myproducts.mywebsite.config.bean.config.UserBean$Gender"/> </typeHandlers> but I don't know how can this be done by application.properties file ? A: Try this package com.example.typehandler; @MappedTypes({Gender.class}) public class GenderTypeHandler extends EnumOrdinalTypeHandler {} mybatis.type-handlers-package=com.example.typehandler @Select(...) @Results(value = { @Result(property="gender", column="gender", typeHandler="com.example.typehandler.Gender"), ... The typeHandler in the @Result may be unnecessary if you use @MappedTypes. A: You need to specify a package instead of the TypeHandler class directly. So you could use it as next: mybatis.type-handlers-package=org.apache.ibatis.type The manual page says type-handlers-package get package to search for type aliases. type-handlers-package Packages to search for type handlers. (Package delimiters are ",; \t\n")
stackoverflow
{ "language": "en", "length": 185, "provenance": "stackexchange_0000F.jsonl.gz:912537", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690789" }
66a040a8cf9a716b67e0e3be196ca149824e5c8a
Stackoverflow Stackexchange Q: How to hide EA properties dialog? I am using EA Api's "EA_OnPostNewElement" to modify the dropped element from the Toolbox. As soon I drop the element from the toolbox to the diagram, EA properties diaglog is popped up. Even after using Repository.SuppressEADialogs = true; How to suppress the EA diaglog if any Element is dropped from the toolbox ? A: The documentation says indeed to use Repository.SuppressEADialogs = true; to disable the standard properties dialog to show up. If that doesn't work you should probably send in a bug report. But you can also disable that from the general options by disabling the option Objects | Edit Object on New Then use the event EA_OnContextItemDoubleClicked to show your own properties dialog and return true to let EA know that you have handled the double-click event so it doesn't show the default properties dialog anyway.
Q: How to hide EA properties dialog? I am using EA Api's "EA_OnPostNewElement" to modify the dropped element from the Toolbox. As soon I drop the element from the toolbox to the diagram, EA properties diaglog is popped up. Even after using Repository.SuppressEADialogs = true; How to suppress the EA diaglog if any Element is dropped from the toolbox ? A: The documentation says indeed to use Repository.SuppressEADialogs = true; to disable the standard properties dialog to show up. If that doesn't work you should probably send in a bug report. But you can also disable that from the general options by disabling the option Objects | Edit Object on New Then use the event EA_OnContextItemDoubleClicked to show your own properties dialog and return true to let EA know that you have handled the double-click event so it doesn't show the default properties dialog anyway.
stackoverflow
{ "language": "en", "length": 145, "provenance": "stackexchange_0000F.jsonl.gz:912552", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690833" }
a93f900deec2699e6a05008972b502f1b5eff533
Stackoverflow Stackexchange Q: How to solve MySQL error which occurs while loading image When I am opening a local connection in MySQL, an error occurring while loading image search_sidebar.png.How can I solve this problem in MySQL? I have attached a screenshot of error showing I am using MySQL Server 5.7 and MySQL Workbench 6.3 version 6.3.8 A: Fixed by reinstalling and choosing Repair option. Background Previously, i upgraded MySQL Workbench from earlier edition to latest version 6.3.10. It worked fine for many days but one fine day after Windows restart it started showing Error while loading image popup. I tried several times closing and starting MySQL Workbench but same popup appears each time. Solution I downloaded fresh copy of MySQL Workbench from https://dev.mysql.com/downloads/file/?id=474210 and chose Repair option during installation. My databases and everything else is intact and working as before. Additionally, it resolved popup issue. Note There is no need to remove MySQL Workbench, just choosing Repair option during install worked for me.
Q: How to solve MySQL error which occurs while loading image When I am opening a local connection in MySQL, an error occurring while loading image search_sidebar.png.How can I solve this problem in MySQL? I have attached a screenshot of error showing I am using MySQL Server 5.7 and MySQL Workbench 6.3 version 6.3.8 A: Fixed by reinstalling and choosing Repair option. Background Previously, i upgraded MySQL Workbench from earlier edition to latest version 6.3.10. It worked fine for many days but one fine day after Windows restart it started showing Error while loading image popup. I tried several times closing and starting MySQL Workbench but same popup appears each time. Solution I downloaded fresh copy of MySQL Workbench from https://dev.mysql.com/downloads/file/?id=474210 and chose Repair option during installation. My databases and everything else is intact and working as before. Additionally, it resolved popup issue. Note There is no need to remove MySQL Workbench, just choosing Repair option during install worked for me. A: To repair without completely re-installing MySQL: ON Windows 10 * *Go to Control Panel *Uninstall a Program *Find MySQL (In My Case MySQL Workbench 8.0 CE) *Right Click and select "Repair" Once installation is complete, please restart MySQL Workbench 8.0 CE Hopefully this resolves the issue for you. A: I have removed Workbench from MySql Installer and Reinstall version 6.3.7 Now working...
stackoverflow
{ "language": "en", "length": 224, "provenance": "stackexchange_0000F.jsonl.gz:912553", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690836" }
168c90f3f7f89c1fc7fffb3275d908695c67a6cb
Stackoverflow Stackexchange Q: "Can't bind multiple parameter to the request's content." in web api and angularJs When Multiple parameters pass in WebApi it results as an exception "Can't bind multiple parameter to the request's content.".Have any solution for following code public class A1 { public int id {get;set;} public string name {get;set;} } public class A2 { public int id2 {get;set;} public string name2 {get;set;} } [Route("Save")] [HttpPost] public string Save([FromBody]A1 Emp, [FromBody]List<A2> EmpMarks) { } JS file $http({ method: "post", url: "/api/Employee/Save", data: JSON.stringify({ Emp: $scope.Emp, EmpMarks: $scope.EmpMarks }) }).then(function (response) { }, function () { alert("Error Occur"); }) A: You might want to use a model which contains your data: public class A1 { public int id { get; set; } public string name { get; set; } } public class A2 { public int id2 { get; set; } public string name2 { get; set; } } public class AModel { public A1 Emp { get; set; } public A2 EmpMarks { get; set; } } [Route("Save")] [HttpPost] public string Save(AModel aData) { // ... your logic here }
Q: "Can't bind multiple parameter to the request's content." in web api and angularJs When Multiple parameters pass in WebApi it results as an exception "Can't bind multiple parameter to the request's content.".Have any solution for following code public class A1 { public int id {get;set;} public string name {get;set;} } public class A2 { public int id2 {get;set;} public string name2 {get;set;} } [Route("Save")] [HttpPost] public string Save([FromBody]A1 Emp, [FromBody]List<A2> EmpMarks) { } JS file $http({ method: "post", url: "/api/Employee/Save", data: JSON.stringify({ Emp: $scope.Emp, EmpMarks: $scope.EmpMarks }) }).then(function (response) { }, function () { alert("Error Occur"); }) A: You might want to use a model which contains your data: public class A1 { public int id { get; set; } public string name { get; set; } } public class A2 { public int id2 { get; set; } public string name2 { get; set; } } public class AModel { public A1 Emp { get; set; } public A2 EmpMarks { get; set; } } [Route("Save")] [HttpPost] public string Save(AModel aData) { // ... your logic here } A: The issue occours because you are declaring the [FromBody] attribute twice. As per design, http POST does only have one body and the [FromBody] will try to read all content in the body and parse it to your specified object. To solve this issue you need to create an object which matches your client object which is being attach to the request body. public class RequestModel { public A1 Emp {get;set;} public List<A2> EmpMarks {get;set;} } Then fetch that from the request body in your post method [Route("Save")] [HttpPost] public string Save([FromBody]RequestModel Emps) A: [Route("Save")] [HttpPost] public string Save(JObject EmpData) { dynamic json = EmpData; A1 Emp=json.Emp.ToObject<A1>(); List<A2> EmpMarks=json.ToObject<List<A2>>(); } It is an another option.It is work for me A: If you want to pass multiple parameters to a POST call, you can simply do as below and add as many to match the service. var data = new FormData(); data.append('Emp', $scope.Emp); data.append('EmpMarks', $scope.EmpMarks); $http.post('/api/Employee/Save', **data**, { withCredentials : false, transformRequest : angular.identity, headers : { 'Content-Type' : undefined } }).success(function(resp) { });
stackoverflow
{ "language": "en", "length": 354, "provenance": "stackexchange_0000F.jsonl.gz:912580", "question_score": "7", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690905" }
aab5c2894584ceb747384f31556379e13cb6bb8e
Stackoverflow Stackexchange Q: Round-up and round-down R It might seem silly but I have not been successful in trying to round my data as I wanted. This is an example of my array: a<-c(-0.5:30,by=5) What I want is: for min(a) to round-down to the next number to multiples of 10 but the max(a) to round-up. This case: min(a)=-0.5 and I want it round down to -10 max(a)=29.5 and I want to round up (to 30 or 40). I have spent time to think and search for it but have not found anything. Any help would be highly appreciated. Regards, Phuong A: a<- seq(from = -0.5, to = 30, by = 5) For rounding up max: roundUp <- function(x,to=10) { to*(x%/%to + as.logical(x%%to)) } roundUp(max(a)) For rounding down min: roundDw <- function(x,to=-10) { to*(x%/%to + as.logical(x%%to)) } roundDw(min(a))
Q: Round-up and round-down R It might seem silly but I have not been successful in trying to round my data as I wanted. This is an example of my array: a<-c(-0.5:30,by=5) What I want is: for min(a) to round-down to the next number to multiples of 10 but the max(a) to round-up. This case: min(a)=-0.5 and I want it round down to -10 max(a)=29.5 and I want to round up (to 30 or 40). I have spent time to think and search for it but have not found anything. Any help would be highly appreciated. Regards, Phuong A: a<- seq(from = -0.5, to = 30, by = 5) For rounding up max: roundUp <- function(x,to=10) { to*(x%/%to + as.logical(x%%to)) } roundUp(max(a)) For rounding down min: roundDw <- function(x,to=-10) { to*(x%/%to + as.logical(x%%to)) } roundDw(min(a)) A: You can use round_any from plyr. library(plyr) a <- seq(-0.5, 30, by = 5) round_any(min(a), 10, f = floor) ## -10 round_any(max(a), 10, f = ceiling) ## 30
stackoverflow
{ "language": "en", "length": 164, "provenance": "stackexchange_0000F.jsonl.gz:912594", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690949" }
21b03ecffd8f31528d7c28dc99752b8069ce7b81
Stackoverflow Stackexchange Q: C++: is std::unordered_map guaranteed to be node-based? What is the typical layout of std::unordered_map<K, V>? Are the K and V objects stored in the buckets themselves, or do the buckets store pointers to nodes containing the keys and values? I'm trying to figure out the performance implications of using std::unordered_map<K, V> versus std::unordered_map<K, V*>. Assuming I only ever emplace and look up values, is there any reason to prefer the latter, even if the values are quite large? The only reason I can imagine is if the values are stored in-line in buckets, and need to be re-allocated each time the container is rehashed. Is there anything in the standard that guarantees this won't happen? A: [unord.req]/8: Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. The fact that pointers and references to elements are not invalidated by rehashing (or insertion/deletion, see /13) pretty much means that they have to be node based. C++17 even exposes node handles so that you can transfer nodes between two unordered_maps.
Q: C++: is std::unordered_map guaranteed to be node-based? What is the typical layout of std::unordered_map<K, V>? Are the K and V objects stored in the buckets themselves, or do the buckets store pointers to nodes containing the keys and values? I'm trying to figure out the performance implications of using std::unordered_map<K, V> versus std::unordered_map<K, V*>. Assuming I only ever emplace and look up values, is there any reason to prefer the latter, even if the values are quite large? The only reason I can imagine is if the values are stored in-line in buckets, and need to be re-allocated each time the container is rehashed. Is there anything in the standard that guarantees this won't happen? A: [unord.req]/8: Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. The fact that pointers and references to elements are not invalidated by rehashing (or insertion/deletion, see /13) pretty much means that they have to be node based. C++17 even exposes node handles so that you can transfer nodes between two unordered_maps.
stackoverflow
{ "language": "en", "length": 182, "provenance": "stackexchange_0000F.jsonl.gz:912606", "question_score": "5", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44690986" }
7c82b34525fb7cf26fc4b533fb3873a6d9c07ee9
Stackoverflow Stackexchange Q: Can not use PrivateKey after extracting it from AndroidKeyStore When we generate a key pair and use a private key from it in the cipher, it works as intended without any exceptions: KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC"); kpg.initialize(1024, new SecureRandom()); KeyPair kp = kpg.generateKeyPair(); PrivateKey privateKey = kp.getPrivate(); byte[] encryptedBytes = "SAMPLE".getBytes(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); But after saving of the generated PrivateKey into the AndroidKeyStore and extraction from it: KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); ks.load(null); KeyStore.Entry entry = ks.getEntry("alias", null); PrivateKey privateKey = ((KeyStore.PrivateKeyEntry) entry).getPrivateKey(); the privateKey is not null, but the same code in the first block above (for decryption) throws an exception with message "unknown key type passed to RSA" on the line: cipher.init(Cipher.DECRYPT_MODE, privateKey); I know that AndroidKeyStore was not purposed to extract the data about keys saved in it, but I expect it to return a correct Private Key to work with Android's Cipher class correctly at least.
Q: Can not use PrivateKey after extracting it from AndroidKeyStore When we generate a key pair and use a private key from it in the cipher, it works as intended without any exceptions: KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC"); kpg.initialize(1024, new SecureRandom()); KeyPair kp = kpg.generateKeyPair(); PrivateKey privateKey = kp.getPrivate(); byte[] encryptedBytes = "SAMPLE".getBytes(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); But after saving of the generated PrivateKey into the AndroidKeyStore and extraction from it: KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); ks.load(null); KeyStore.Entry entry = ks.getEntry("alias", null); PrivateKey privateKey = ((KeyStore.PrivateKeyEntry) entry).getPrivateKey(); the privateKey is not null, but the same code in the first block above (for decryption) throws an exception with message "unknown key type passed to RSA" on the line: cipher.init(Cipher.DECRYPT_MODE, privateKey); I know that AndroidKeyStore was not purposed to extract the data about keys saved in it, but I expect it to return a correct Private Key to work with Android's Cipher class correctly at least.
stackoverflow
{ "language": "en", "length": 159, "provenance": "stackexchange_0000F.jsonl.gz:912616", "question_score": "4", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44691029" }
0b6e75b0b3ab57aecd9ab2475ad42a1611835d88
Stackoverflow Stackexchange Q: In CMake how to create targets with identical names? I have a question regarding CMake and I need help to solve the following error I'm getting: CMake Error at :::: (add_custom_target): add_custom_target cannot create target "generate" because another target with the same name already exists. The existing target is a custom target created in source directory :::::. Here the target names of the two same level CMakeLists.txt are the same and I want to keep them identical, without any conflict. Can anyone help me out? A: This could be a good help: OUTPUT_NAME sets the real name of a target when it is built and can be used to help create two targets of the same name even though CMake requires unique logical target names. https://cmake.org/cmake/help/v3.0/command/set_target_properties.html
Q: In CMake how to create targets with identical names? I have a question regarding CMake and I need help to solve the following error I'm getting: CMake Error at :::: (add_custom_target): add_custom_target cannot create target "generate" because another target with the same name already exists. The existing target is a custom target created in source directory :::::. Here the target names of the two same level CMakeLists.txt are the same and I want to keep them identical, without any conflict. Can anyone help me out? A: This could be a good help: OUTPUT_NAME sets the real name of a target when it is built and can be used to help create two targets of the same name even though CMake requires unique logical target names. https://cmake.org/cmake/help/v3.0/command/set_target_properties.html A: According with CMake policy CMP0002 (introduced by CMake 2.6, emphasis mine): Targets names created with add_executable, add_library, or add_custom_target are logical build target names. Logical target names must be globally unique [...] The following note deserves a mention and could probably help you anyway: Custom targets must simply have globally unique names (unless one uses the global property ALLOW_DUPLICATE_CUSTOM_TARGETS with a Makefiles generator). It means that there exists a global property named ALLOW_DUPLICATE_CUSTOM_TARGETS that is probably what you are looking for. It has a limited use and you should read carefully the documentation, but it's worth a try. The most relevant part follows: Makefile generators are capable of supporting duplicate custom target names. [...] However, setting this property will cause non-Makefile generators to produce an error and refuse to generate the project. To be able to use duplicate custom targets put the following line in your CMakeLists.txt: set(ALLOW_DUPLICATE_CUSTOM_TARGETS TRUE) If it solves your issue mainly depends on the actual problem, so I cannot say.
stackoverflow
{ "language": "en", "length": 292, "provenance": "stackexchange_0000F.jsonl.gz:912631", "question_score": "13", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44691109" }
a0dcef682b72c996b4e5d0fec2b66c15c98818d5
Stackoverflow Stackexchange Q: How to obtain username from UserID in Telegram? I am using Python-Telegram-Bot API to create a bot. I get people's userID and username when they start the bot. The userID doesn't change ever but the username can be changed by the user any time. So I have usernames and UserIDs, and I receive another username - I wish to figure out whether that username is of someone already in the existing list or not. Basically need to find out username from userID or if there's any other way I'm open to it. A: thats why you always process messages using the users' IDs but to answer your question, you can either get the user's username directly using the user object, for example update.message.from_user.username or update.effective_user.username or use bot.getchat(chat_id) to get an user object of a certain chat (which could be an user's private chat
Q: How to obtain username from UserID in Telegram? I am using Python-Telegram-Bot API to create a bot. I get people's userID and username when they start the bot. The userID doesn't change ever but the username can be changed by the user any time. So I have usernames and UserIDs, and I receive another username - I wish to figure out whether that username is of someone already in the existing list or not. Basically need to find out username from userID or if there's any other way I'm open to it. A: thats why you always process messages using the users' IDs but to answer your question, you can either get the user's username directly using the user object, for example update.message.from_user.username or update.effective_user.username or use bot.getchat(chat_id) to get an user object of a certain chat (which could be an user's private chat
stackoverflow
{ "language": "en", "length": 145, "provenance": "stackexchange_0000F.jsonl.gz:912667", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44691233" }
755c7d2fc5a120dce57a5936b98b167a82cf6689
Stackoverflow Stackexchange Q: logging to stackdriver from winston I am using the library here to log to Stackdriver from Node.js. However, the logs aren't showing up - I think because I'm not specifying a metadata resource, such as 'global'. How do I do that? var winston = require('winston'); var transport = require('@google-cloud/logging-winston'); winston.add(transport, { projectId: 'myproject', keyFilename: 'google_key.json', level: 'warn' // log at 'warn' and above }); winston.error('warp nacelles offline'); A: The solution is to add a 'label' field to the configuration, like so: winston.add(transport, { projectId: 'myproject', keyFilename: 'google_key.json', level: 'warn', // log at 'warn' and above, label: 'Global' });
Q: logging to stackdriver from winston I am using the library here to log to Stackdriver from Node.js. However, the logs aren't showing up - I think because I'm not specifying a metadata resource, such as 'global'. How do I do that? var winston = require('winston'); var transport = require('@google-cloud/logging-winston'); winston.add(transport, { projectId: 'myproject', keyFilename: 'google_key.json', level: 'warn' // log at 'warn' and above }); winston.error('warp nacelles offline'); A: The solution is to add a 'label' field to the configuration, like so: winston.add(transport, { projectId: 'myproject', keyFilename: 'google_key.json', level: 'warn', // log at 'warn' and above, label: 'Global' });
stackoverflow
{ "language": "en", "length": 99, "provenance": "stackexchange_0000F.jsonl.gz:912669", "question_score": "3", "source": "stackexchange", "timestamp": "2023-03-29T00:00:00", "url": "https://stackoverflow.com/questions/44691241" }