text
stringlengths
15
59.8k
meta
dict
Q: Unable to perform successful Paypal webhook validation I am working to validate Paypal webhook data but I'm running into an issue where it's always returning a FAILURE for the validation status. I'm wondering if it's because this is all happening in a sandbox environment and Paypal doesn't allow verification for sandbox webhook events? I followed this API doc to implement the call: https://developer.paypal.com/docs/api/webhooks/v1/#verify-webhook-signature Relevant code (from separate elixir modules): def call(conn, _opts) do conn |> extract_webhook_signature(conn.params) |> webhook_signature_valid?() |> # handle the result end defp extract_webhook_signature(conn, params) do %{ auth_algo: get_req_header(conn, "paypal-auth-algo") |> Enum.at(0, ""), cert_url: get_req_header(conn, "paypal-cert-url") |> Enum.at(0, ""), transmission_id: get_req_header(conn, "paypal-transmission-id") |> Enum.at(0, ""), transmission_sig: get_req_header(conn, "paypal-transmission-sig") |> Enum.at(0, ""), transmission_time: get_req_header(conn, "paypal-transmission-time") |> Enum.at(0, ""), webhook_id: get_webhook_id(), webhook_event: params } end def webhook_signature_valid?(signature) do body = Jason.encode!(signature) case Request.post("/v1/notifications/verify-webhook-signature", body) do {:ok, %{verification_status: "SUCCESS"}} -> true _ -> false end end I get back a 200 from Paypal, which means that Paypal got my request and was able to properly parse it and run it though its validation, but it's always returning a FAILURE for the validation status, meaning that the authenticity of the request couldn't be verified. I looked at the data I was posting to their endpoint and it all looks correct, but for some reason it isn't validating. I put the JSON that I posted to the API (from extract_webhook_signature) into a Pastebin here cause it's pretty large: https://pastebin.com/SYBT7muv If anyone has experience with this and knows why it could be failing, I'd love to hear. A: I solved my own problem. Paypal does not canonicalize their webhook validation requests. When you receive the POST from Paypal, do NOT parse the request body before you go to send it back to them in the verification call. If your webhook_event is any different (even if the fields are in a different order), the event will be considered invalid and you will receive back a FAILURE. You must read the raw POST body and post that exact data back to Paypal in your webhook_event. Example: if you receive {"a":1,"b":2} and you post back {..., "webhook_event":{"b":2,"a":1}, ...} (notice the difference in order of the json fields from what we recieved and what we posted back) you will recieve a FAILURE. Your post needs to be {..., "webhook_event":{"a":1,"b":2}, ...} A: For those who are struggling with this, I'd like to give you my solution which includes the accepted answer. Before you start, make sure to store the raw_body in your conn, as described in Verifying the webhook - the client side @verification_url "https://api-m.sandbox.paypal.com/v1/notifications/verify-webhook-signature" @auth_token_url "https://api-m.sandbox.paypal.com/v1/oauth2/token" defp get_auth_token do headers = [ Accept: "application/json", "Accept-Language": "en_US" ] client_id = Application.get_env(:my_app, :paypal)[:client_id] client_secret = Application.get_env(:my_app, :paypal)[:client_secret] options = [ hackney: [basic_auth: {client_id, client_secret}] ] body = "grant_type=client_credentials" case HTTPoison.post(@auth_token_url, body, headers, options) do {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> %{"access_token" => access_token} = Jason.decode!(body) {:ok, access_token} error -> Logger.error(inspect(error)) {:error, :no_access_token} end end defp verify_event(conn, auth_token, raw_body) do headers = [ "Content-Type": "application/json", Authorization: "Bearer #{auth_token}" ] body = %{ transmission_id: get_header(conn, "paypal-transmission-id"), transmission_time: get_header(conn, "paypal-transmission-time"), cert_url: get_header(conn, "paypal-cert-url"), auth_algo: get_header(conn, "paypal-auth-algo"), transmission_sig: get_header(conn, "paypal-transmission-sig"), webhook_id: Application.get_env(:papervault, :paypal)[:webhook_id], webhook_event: "raw_body" } |> Jason.encode!() |> String.replace("\"raw_body\"", raw_body) with {:ok, %{status_code: 200, body: encoded_body}} <- HTTPoison.post(@verification_url, body, headers), {:ok, %{"verification_status" => "SUCCESS"}} <- Jason.decode(encoded_body) do :ok else error -> Logger.error(inspect(error)) {:error, :not_verified} end end defp get_header(conn, key) do conn |> get_req_header(key) |> List.first() end
{ "language": "en", "url": "https://stackoverflow.com/questions/61399557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: charts disappear on-click? I am using dynamic feature I am using two different charts on the same page, so when I click on any chart of them the Gauge chart disappear. var gauge1 = new RGraph.Gauge({ id: 'gauge', min:0, max: 100, value: #{mbCardHistory.creditCardPrecentage}, options: { centery: 120, radius: 130, anglesStart: RGraph.PI, anglesEnd: RGraph.TWOPI, needleSize: 85, borderWidth: 0, shadow: false, needleType: 'line', colorsRanges: [[0,30,'red'], [30,70,'yellow'],[70,100,'#0f0']], borderInner: 'rgba(0,0,0,0)', borderOuter: 'rgba(0,0,0,0)', borderOutline: 'rgba(0,0,0,0)', centerpinColor: 'rgba(0,0,0,0)', centerpinRadius: 0, textAccessible: true } }).draw(); before after
{ "language": "en", "url": "https://stackoverflow.com/questions/53722359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL Query COUNTing incorrectly Well, I realise that in fact it's more likely to be my logic that's counting wrong ;) So here's my query: SELECT code.id AS codeid, code.title AS codetitle, code.summary AS codesummary, code.author AS codeauthor, code.date, code_tags.*, tags.*, users.firstname AS authorname, users.id AS authorid, ratingItems.*, FORMAT((ratingItems.totalPoints / ratingItems.totalVotes), 1) AS rating, GROUP_CONCAT(tags.tag SEPARATOR ', ') AS taggroup, COUNT(comments.codeid) AS commentcount FROM code join code_tags on code_tags.code_id = code.id join tags on tags.id = code_tags.tag_id join users on users.id = code.author left join comments on comments.codeid = code.id left join ratingItems on uniqueName = code.id GROUP BY code_id ORDER BY date DESC LIMIT 0, 15 Sorry there's quite a bit of 'bloat' in that. The problem I'm having is with commentcount or (COUNT(comments.codeid) AS commentcount) - I want to count the total number of comments a code submission has. Previously, it was working correctly but I restructured my MySQL syntax and now it's stopped working :( There's only 2 code submissions in the database that have comments. The first of these results that is returned correctly identifies it has more than 0 comments, but reports it as having '2' in commentcount, when in fact it has only 1. The second submission ALSO only has one comment, but, it tells me that it has 4! Can someone tell me what's wrong my logic here? Thanks! Jack A: Try eliminating the GROUP BY constraint. Then see where your duplicate rows are coming from, and fix your original query. This will fix your COUNTs as well. A: Try either: COUNT(DISTINCT comments.codeid) AS commentcount or (SELECT COUNT(*) FROM comments WHERE comments.codeid = code.id) AS commentcount A: Try starting with a simple query, and building up from that. If I have understood your structure correctly, the following query will return the correct number of comments for each code submission: SELECT code.*, COUNT(code.id) AS comment_count FROM code JOIN comments ON comments.codeid = code.id GROUP BY(code.id); There's a few odd looking column names and joins in your example, which may be contributing to the problem … or it might just be an odd naming scheme :-) For example, you are joining ratingItems to code by comparing code.id with ratingItems.uniqueName. That might be correct, but it doesn't quite look right. Perhaps it should be more like: LEFT JOIN ratingItems ON ratingItems.code_id = code.id Start with a basic working query, then add the other joins.
{ "language": "en", "url": "https://stackoverflow.com/questions/3193323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to trim out multiple time-points in an AVAsset (Swift)? I am working on a video editor app, where based on some processing, I have an array of samples/time-points to remove from the video clip. For example, timePoints = [0 8.2 15.5 20.6...]. //seconds I would like to remove these specific frames from the video clip (i.e. AVAsset), which correspond to these time-points. From what I understand so far, you can use AVAssetExportSession to trim a specific time range (e.g. tstart to tend) but not multiple time-points (e.g. timePoints array above). Hence, is there a way to export with multiple time-points discarded? i.e. the output video will merge together all clips, except the frames corresponding to those time-points to be discarded? Would appreciate any help, Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/67323555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Phone not recognized in android debugger I am trying to run the android debugger on my phone, but the console as well as eclipse plugin reports a ??? in place of the device name. The attached phone is a sony ericsson xperia mini, running android 2.3 and the computer is running on ubuntu 10.10 . I have enabled the usb debugging option on the phone. A: You need to enter the Phone USB configuration for your device in the udev file on ubuntu You need to add a udev rules file that contains a USB configuration for each type of device you want to use for development. In the rules file, each device manufacturer is identified by a unique vendor ID, as specified by the ATTR{idVendor} property. For a list of vendor IDs, see USB Vendor IDs, below. To set up device detection on Ubuntu Linux: Log in as root and create this file: /etc/udev/rules.d/51-android.rules. Use this format to add each vendor to the file: SUBSYSTEM=="usb", ATTR{idVendor}=="0bb4", MODE="0666", GROUP="plugdev" In this example, the vendor ID is for HTC. The MODE assignment specifies read/write permissions, and GROUP defines which Unix group owns the device node. Note: The rule syntax may vary slightly depending on your environment. Consult the udev documentation for your system as needed. For an overview of rule syntax, see this guide to writing udev rules. Now execute: chmod a+r /etc/udev/rules.d/51-android.rules Vendor ID for Sony Ericcson is Sony Ericsson 0FCE
{ "language": "en", "url": "https://stackoverflow.com/questions/8470155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC2 and mySQL database I'm following the example from the ASP.NET MVC 2 Framework book (Steven Sanderson), except instead of using SQLServer, I'm using mySQL. public class ProductsController : Controller { private IProductsRepository productsRepository; public ProductsController() { // Temporary hard-coded connection string until we set up dependency injection string connString = "server=xx.xx.xxx.xxx;Database=db_SportsStore;User Id=dbUser;Pwd=xxxxxxxxx;Persist Security Info=True;"; productsRepository = new SportsStore.Domain.Concrete.SqlProductsRepository(connString); } public ViewResult List() { return View(productsRepository.Products.ToList()); } } When I run the project I get the following error: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) I have downloaded the MySQL .Net connector and in the Server Explorer I was able to view the tables on that DB. I also have made sure that the DBs on the server allows for remote connections. I am creating and running the code locally via VS2010 and the MySQL DB is on hosted server. What do I have to do to get this MVC2 example to function for MySQL? Update: I was playing around with the code while waiting for an answer and I updated the ProductsController to the following: using MySql.Data.MySqlClient; string connString = "server=xx.xx.xxx.xxx;Database=db_SportsStore;User Id=dbUser;Pwd=xxxxxx;"; var connection = new MySqlConnection(connString); productsRepository = new SportsStore.Domain.Concrete.SqlProductsRepository(connection); Then in the repository: public SqlProductsRepository(MySql.Data.MySqlClient.MySqlConnection connection) { connection.Open(); productsTable = (new DataContext(connection)).GetTable<Product>(); connection.Close(); } Now I get a totally different error: {"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[t0].[ProductID], [t0].[Name], [t0].[Description], [t0].[Price], [t0].[Category]' at line 1"} I should also mention... This example is using LINQ to SQL. I'm not sure if that matters or not. Please advise. A: A couple of thoughts come to mind. * *The connection string you are using is the connection string if you are connecting to a SQL Server DB instead of a MySQL .Net Connector connection string. You're going to have to change the connection string example from the book to what MySQL needs. For example, MySQL doesn't have a Trusted Connection option. (http://dev.mysql.com/doc/refman/5.1/en/connector-net-connection-options.html) *In your SQLProductsRepository you'll need to use the MySQLConnection Object and so forth instead of a SQLConnection object if used. I think the book used Linq To SQL or Linq to Entity Framework. Either way you'll have to modify the code to use the MySQL... objects or modify the model to hit your MySQL if it's Entity Framework. If you already did this then the connection string in it will give a good idea of what you need in #1. http://dev.mysql.com/doc/refman/5.1/en/connector-net-tutorials-intro.html EDIT - With your update... MySQL doesn't have the same syntax as SQL Server sometimes. I am assuming that is what this error is pointing to. On the MySQL Connector connection string, it has an option to use SQL Server Syntax called SQL Server Mode. Set this to true and see if this works.... Something like: Server=serverIP;Database=dbName;Uid=Username;Pwd=Password;SQL Server Mode=true;
{ "language": "en", "url": "https://stackoverflow.com/questions/5843376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are Google Cloud Disks OK to use with SQLite? Google Cloud disks are network disks that behave like local disks. SQLite expects a local disk so that locking and transactions work correctly. A. Is it safe to use Google Cloud disks for SQLite? B. Do they support the right locking mechanisms? How is this done over the network? C. How does disk IOP's and Throughput relate to SQLite performance? If I have a 1GB SQLite file with queries that take 40ms to complete locally, how many IOP's would this use? Which disk performance should I choose between (standard, balanced, SSD)? Thanks. Related https://cloud.google.com/compute/docs/disks#pdspecs Persistent disks are durable network storage devices that your instances can access like physical disks https://www.sqlite.org/draft/useovernet.html the SQLite library is not tested in across-a-network scenarios, nor is that reasonably possible. Hence, use of a remote database is done at the user's risk. A: Yeah, the article you referenced, essentially stipulates that since the reads and writes are "simplified", at the OS level, they can be unpredictable resulting in "loss in translation" issues when going local-network-remote. They also point out, it may very well work totally fine in testing and perhaps in production for a time, but there are known side effects which are hard to detect and mitigate against -- so its a slight gamble. Again the implementation they are describing is not Google Cloud Disk, but rather simply stated as a remote networked arrangement. My point is more that Google Cloud Disk may be more "virtual" rather than purely networked attached storage... to my mind that would be where to look, and evaluate it from there. Checkout this thread for some additional insight into the issues, https://serverfault.com/questions/823532/sqlite-on-google-cloud-persistent-disk Additionally, I was looking around and I found this thread, where one poster suggest using SQLite as a read-only asset, then deploying updates in a far more controlled process. https://news.ycombinator.com/item?id=26441125 A: the persistend disk acts like a normal disk in your vm. and is only accessable to one vm at a time. so it's safe to use, you won't lose any data. For the performance part. you just have to test it. for your specific workload. if you have plenty of spare ram, and your database is read heavy, and seldom writes. the whole database will be cached by the os (linux) disk cache. so it will be crazy fast. even on hdd storage. but if you are low on spare ram. than the database won't be in the os cache. and writes are always synced to disk. and that causes lots of I/O operations. in that case use the highest performing disk you can / are willing to afford.
{ "language": "en", "url": "https://stackoverflow.com/questions/73459746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: while loop with a multiple tableX union i want to know please how i can put union of table 2014 to 2017 only in loop in this query: select xxx, xxx, xxx, from ( select colonne, colonne, from CA left join ( select xx, sum(xx) as xx, xx from ( select sum(MONTANT) as MONTANT, CONCAT(NUM_SIN, CLE_SIN) as cle, EXER_SIN from fa where CD_TYP_CNT='PREV' group by NUM_SIN, CLE_SIN, EXER_SIN union select sum(MONTANT) as MONTANT, CONCAT(NUM_SIN, CLE_SIN) as cle, EXER_SIN from table2014 where CD_TYP_CNT='PREV' group by NUM_SIN, CLE_SIN, EXER_SIN union select sum(MONTANT) as MONTANT, CONCAT(NUM_SIN, CLE_SIN) as cle, EXER_SIN from table2015 where CD_TYP_CNT='PREV' group by NUM_SIN, CLE_SIN, EXER_SIN union select sum(MONTANT) as MONTANT, CONCAT(NUM_SIN, CLE_SIN) as cle, EXER_SIN from table2016 where CD_TYP_CNT='PREV' group by NUM_SIN, CLE_SIN, EXER_SIN union select sum(MONTANT) as MONTANT, CONCAT(NUM_SIN, CLE_SIN) as cle, EXER_SIN from table2017 where CD_TYP_CNT='PREV' group by NUM_SIN, CLE_SIN, EXER_SIN ) as tab group by cle, EXER_SIN) as reglmt on reglmt.cle = CPM.dossiers left join ( select CONCAT(colonne, colonne) as cle, from production group by colonne, colonne1, colonne3, colonne4) as xx on ptf_CPM.cle = CPM.dossiers group by xx, xx ) as xx where vérif <> 0
{ "language": "en", "url": "https://stackoverflow.com/questions/73792070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Webpack "Not a function" error for calling a class in React In a react app, I have some business logic I'm trying to encapsulate in class called Authentication. When I try to call a method called configure on the Authentication class I get the following error: TypeError: WEBPACK_IMPORTED_MODULE_5__authentication_js.a.configure is not a function In my React app.js file I import the authentication class with: import Authentication from './authentication.js'; and then I try to access it inside my constructor as follows: constructor(props) { super(props); Authentication.configure(); } The code for authentication.js is as follows: class Authentication { constructor(props) { console.log('inside constructor of Authentication class'); } configure(){ //some setup logic, still fails if I comment it all out } } export default Authentication; I'm unsure how exactly to troubleshoot this issue. I know I've seen similar issues in react before where an internal method has not had the bind method called against it, but I'm unsure if that is needed for a public method of an external class and if it is required, I'm not sure how to implement it. Any help/guidance would be greatly appreciated. A: configure is an instance method of the Authentication class. Either make configure static, or export an instance of Authentication.
{ "language": "en", "url": "https://stackoverflow.com/questions/51620624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google Places Autocomplete Dropdown Invisible In my site, I have a functional google places autocomplete, but it is invisible. I know that it works because if I type in "123 Main Street" and then move my arrow key down and hit enter- the address information will append to the inputs as normal. I attempted adding this to my CSS: .pac-container { z-index: 1051 !important; } But it did not work. Has anyone else had this issue? A: My solution was simple. I just increased the z-index even more. .pac-container { z-index: 9999 !important; }
{ "language": "en", "url": "https://stackoverflow.com/questions/39733079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Merge Duplicate Columns On the top column of my report are dates (mm/dd/yyyy) with corresponding data below. When I run the report, it shows multiple columns with the same date but different data. For example 5/12/2011 | 5/12/2011 | 6/7/2011 --------------------------------- 10 | 6 | 11 How do I merge columns with the same dates while also combining the data as well? A: You should create a column group to your tablix on the date field so that it will actually group your dates instead of displaying each one individually. You can then use the SSRS aggregate functions in your details fields to combine the data from the grouped columns & rows. More info: * *Understanding Groups (Report Builder and SSRS) *Aggregate Functions Reference (Report Builder and SSRS)
{ "language": "en", "url": "https://stackoverflow.com/questions/24497853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript ignores # in url I was trying to extract url after domain. According to this question it is possible by calling window.location.pathname, but in my url http://domain:host/something#random=123 it drops everything after # inclusive. Is there anything better out there than splitting or regex? In code: window.location.pathname("http://domain:host/something#random=123") returns /something Desired behavior: window.location.unknownMethodToMe("http://domain:host/something#random=123") should return /something#random=123 Thanks in advance. A: Try using location.hash which should return #random=123
{ "language": "en", "url": "https://stackoverflow.com/questions/37903559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery resizable problem on rotated elements I am truing to do a jQuery UI resize on a div that is rotated with 77deg. The result is totally uncontrollable. To replicate this please: * *Go to http://jqueryui.com/demos/resizable/ *Click on inspect with the Chrome/Mozila console the gray resizable element should be id="resizable". *Apply -webkit-transform: rotate(77deg) or -moz-transform: rotate(77deg) *Now try to resize that element Is there a way to fix this? Thank you A: Change the following functions in JQuery-ui resizable plugin _mouseStart: function(event) { var curleft, curtop, cursor, o = this.options, iniPos = this.element.position(), el = this.element; this.resizing = true; // bugfix for http://dev.jquery.com/ticket/1749 if ( (/absolute/).test( el.css("position") ) ) { el.css({ position: "absolute", top: el.css("top"), left: el.css("left") }); } else if (el.is(".ui-draggable")) { el.css({ position: "absolute", top: iniPos.top, left: iniPos.left }); } this._renderProxy(); curleft = num(this.helper.css("left")); curtop = num(this.helper.css("top")); if (o.containment) { curleft += $(o.containment).scrollLeft() || 0; curtop += $(o.containment).scrollTop() || 0; } //Store needed variables this.offset = this.helper.offset(); this.position = { left: curleft, top: curtop }; this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalPosition = { left: curleft, top: curtop }; this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; this.originalMousePosition = { left: event.pageX, top: event.pageY }; var angle=0; var matrix = $(el).css("-webkit-transform") || $(el).css("-moz-transform") || $(el).css("-ms-transform") || $(el).css("-o-transform") || $(el).css("transform"); if(matrix !== 'none') { var values = matrix.split('(')[1].split(')')[0].split(','); var a = values[0]; var b = values[1]; var angle = Math.round(Math.atan2(b, a) * (180/Math.PI)); } else { var angle = 0; } if(angle < 0) angle +=360; this.angle = angle; thi.rad = this.angle*Math.PI/180; //Aspect Ratio this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); cursor = $(el).find(".ui-resizable-" + this.axis).css("cursor"); $("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor); var cornerItem = 0; if(this.axis == 'ne') cornerItem = 3; else if(this.axis == 'nw') cornerItem = 2; else if(this.axis == 'sw') cornerItem = 1; else if(this.axis == 'se') cornerItem = 0; this.cornerItem = cornerItem; var t1 = this.position.top; var l1 = this.position.left; var w1 = this.size.width; var h1 = this.size.height; var midX = l1 + w1/2; var midY = t1 + h1/2; var cornersX = [l1-midX, l1+w1-midX , l1+w1-midX, l1-midX]; var cornersY = [t1-midY, midY-(t1+h1), midY-t1, t1+h1-midY]; var newX = 1e10; var newY = 1e10; for (var i=0; i<4; i++) { if(i == this.cornerItem){ this.prevX = cornersX[i]*Math.cos(this.rad) - cornersY[i]*Math.sin(this.rad) + midX; this.prevY = cornersX[i]*Math.sin(this.rad) + cornersY[i]*Math.cos(this.rad) + midY; } } el.addClass("ui-resizable-resizing"); this._propagate("start", event); return true; }, _mouseDrag: function(event) { //Increase performance, avoid regex var data, el = this.helper, props = {}, smp = this.originalMousePosition, a = this.axis, prevTop = this.position.top, prevLeft = this.position.left, prevWidth = this.size.width, prevHeight = this.size.height; dx1 = (event.pageX-smp.left)||0, dy1 = (event.pageY-smp.top)||0; dx = ((dx1)*Math.cos(this.rad) + (dy1)*Math.sin(this.rad)); dy =((dx1)*Math.sin(this.rad) - (dy1)*Math.cos(this.rad)); el = this.element; var t1 = this.position.top; var l1 = this.position.left; var w1 = this.size.width; var h1 = this.size.height; var midX = l1 + w1/2; var midY = t1 + h1/2; var cornersX = [l1-midX, l1+w1-midX , l1+w1-midX, l1-midX]; var cornersY = [t1-midY, midY-(t1+h1), midY-t1, t1+h1-midY]; var newX = 1e10 , newY = 1e10 , curX =0, curY=0; for (var i=0; i<4; i++) { if(i == this.cornerItem){ newX = cornersX[i]*Math.cos(this.rad) - cornersY[i]*Math.sin(this.rad) + midX; newY = cornersX[i]*Math.sin(this.rad) + cornersY[i]*Math.cos(this.rad) + midY; curX = newX - this.prevX; curY = newY - this.prevY; } } trigger = this._change[a]; if (!trigger) { return false; } // Calculate the attrs that will be change data = trigger.apply(this, [event, dx, dy]); // Put this in the mouseDrag handler since the user can start pressing shift while resizing this._updateVirtualBoundaries(event.shiftKey); if (this._aspectRatio || event.shiftKey) { data = this._updateRatio(data, event); } data = this._respectSize(data, event); this._updateCache(data); // plugins callbacks need to be called first this._propagate("resize", event); this.position.left = this.position.left - curX; this.position.top = this.position.top - curY; if (this.position.top !== prevTop) { props.top = this.position.top + "px"; } if (this.position.left !== prevLeft) { props.left = this.position.left + "px"; } if (this.size.width !== prevWidth) { props.width = this.size.width + "px"; } if (this.size.height !== prevHeight) { props.height = this.size.height + "px"; } el.css(props); if (!this._helper && this._proportionallyResizeElements.length) { this._proportionallyResize(); } // Call the user callback if the element was resized if ( ! $.isEmptyObject(props) ) { this._trigger("resize", event, this.ui()); } return false; }, _mouseStop: function(event) { this.resizing = false; var pr, ista, soffseth, soffsetw, s, left, top, o = this.options, that = this; if(this._helper) { pr = this._proportionallyResizeElements; ista = pr.length && (/textarea/i).test(pr[0].nodeName); soffseth = ista && $.ui.hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height; soffsetw = ista ? 0 : that.sizeDiff.width; s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) }; left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null; top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; if (!o.animate) { this.element.css($.extend(s, { top: top, left: left })); } that.helper.height(that.size.height); that.helper.width(that.size.width); if (this._helper && !o.animate) { this._proportionallyResize(); } } $("body").css("cursor", "auto"); this.element.removeClass("ui-resizable-resizing"); this._propagate("stop", event); if (this._helper) { this.helper.remove(); } return false; }, _change: { e: function(event, dx, dy) { var cs = this.originalSize, sp = this.originalPosition,elwidth, elheight,lleft=0, ttop =0; if(this.axis == 'se'){ elwidth = this.originalSize.width + dx; elheight = this.originalSize.height - dy; return { height: elheight , width: elwidth }; } else{ elwidth = this.originalSize.width + dx; elheight = this.originalSize.height + dy; return { height: elheight , width: elwidth }; } }, w: function(event, dx, dy) { var cs = this.originalSize, sp = this.originalPosition,elwidth, elheight,lleft=0, ttop =0; if(this.axis == 'nw'){ elwidth = cs.width - dx; elheight = this.originalSize.height + dy; return { height: elheight , width: elwidth }; } else{ elwidth = cs.width - dx; elheight = this.originalSize.height - dy; return { height: elheight , width: elwidth }; } }, n: function(event, dx, dy) { var cs = this.originalSize, sp = this.originalPosition,elwidth, elheight,lleft=0, ttop =0; if(this.axis == 'nw'){ elwidth = this.originalSize.width - dx; elheight = cs.height + dy; return { height: elheight , width: elwidth }; } else{ elwidth = this.originalSize.width + dx; elheight = cs.height + dy; return { height: elheight , width: elwidth }; } }, s: function(event, dx, dy) { var cs = this.originalSize, sp = this.originalPosition,elwidth, elheight,lleft=0, ttop =0; if(this.axis == 'se'){ elwidth = this.originalSize.width + dx; elheight = this.originalSize.height - dy; return { height: elheight , width: elwidth }; } else { elwidth = this.originalSize.width - dx; elheight = this.originalSize.height - dy; return { height: elheight , width: elwidth }; } }, se: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, sw: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); }, ne: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, nw: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); } }, A: The mouse movements for the handles have not been rotated with the element. If you select the right handle (which will be near the bottom if you use rotate(77deg), moving it left will shrink the width of the element, (which will appear similar to the height due to the rotation.) To adjust the element size relative to its center, you will most probably have to update the code that resizes the element by vectoring the mouse movements to adjust the width/height.
{ "language": "en", "url": "https://stackoverflow.com/questions/7026061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: PHP: Mathematical Calculations on a "Multibyte" String Representing a Number In PHP, I have a string variable that contains a number. The string is a multibyte string and with UTF-8 encoding. When I echo the variable($str), it prints 1392. But the problem is that calculations on this variable fails. Consider the output of the following lines: echo $str; // Prints 1392 echo $str + 0; // Prints 0 (it should print 1392) echo $str + 1; // Prints 1 (it should print 1393) echo bin2hex($str); // Prints: dbb1dbb3dbb9dbb2
{ "language": "en", "url": "https://stackoverflow.com/questions/21935259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get json banner by selecting key:value pair I have a json banner file as "extract_3month_fromshodan.json" which have key-value for multiple tag i.e. ip_str=XXX.XX.XXX.XX, port=80, timestamp="2018-08-11T04:56:17.312039", data= "210!connection successful" etc. In this way the file has banner for almost 400 IP's. Sample of source/json banner (extract_3month_fromshodan.json) file: { "asn": "AS17676", "hash": -619087650, "ip": 2120548325, "isp": "Softbank BB", "transport": "udp", "data": "HTTP/1.1 200 OK\r\nCache-Control: max-age=120\r\nST: upnp:rootdevice\r\nUSN: uuid:12342409-1234-1234-5678-ee1234cc5678::upnp:rootdevice\r\nEXT:\r\nServer: miniupnpd/1.0 UPnP/1.0\r\nLocation: http://192.168.2.1:52869/picsdesc.xml\r\n\r\n", "port": 1900, "hostnames": [ "softbank126100255229.bbtec.net" ], "location": { "city": "Toyota", "region_code": "01", "area_code": null, "longitude": 137.14999999999998, "country_code3": "JPN", "latitude": 35.08330000000001, "postal_code": "457-0844", "dma_code": null, "country_code": "JP", "country_name": "Japan" }, "timestamp": **"2018-09-12T15:42:34.012436",** "domains": [ "bbtec.net" ], "org": "XXXXXX BB", "os": null, "_shodan": { "crawler": "d264629436af1b777b3b513ca6ed1404d7395d80", "options": {}, "module": "upnp", "id": null }, "opts": {}, "ip_str": **"126.100.255.229"** } { "asn": "AS17676", "hash": 1371060454, "ip": 2120509894, "isp": "Softbank BB", "transport": "udp", "data": "HTTP/1.1 200 OK\r\nCache-Control: max-age=1800\r\nST: upnp:rootdevice\r\nUSN: uuid:63041253-1019-2006-1228-00018efed688::upnp:rootdevice\r\nEXT:\r\nServer: OS 1.0 UPnP/1.0 Realtek/V1.3\r\nLocation: http://192.168.2.1:52881/simplecfg.xml\r\n\r\n", "port": 1900, "hostnames": [ "softbank126100105198.bbtec.net" ], "location": { "city": "Yamashitacho", "region_code": "18", "area_code": null, "longitude": 130.55, "country_code3": "JPN", "latitude": 31.58330000000001, "postal_code": "892-0816", "dma_code": null, "country_code": "JP", "country_name": "Japan" }, "timestamp": **"2018-08-11T04:56:17.312039"**, "domains": [ "bbtec.net" ], "org": "Softbank BB", "os": null, "_shodan": { "crawler": "6ff540e4d43ec69d8de2a7b60e1de2d9ddb406dc", "options": {}, "module": "upnp", "id": null }, "opts": {}, "ip_str": **"126.100.105.198"** } Now I want to get another new json banner from the source json file above (extract_3month_fromshodan.json) by filtering the parameter i.e. ip_str="126.100.105.198" and timestamp="2018-08-11T04:56:17.312039". The iterative values for each ip_str and timestamp are to come from separate .csv and/or .txt file. And the output (filtered banner) is needed to save as json format. What I have done so far : jq '. | select (.timestamp="2018-08-11T04:56:17.312039") | select(.ip_str==""12X.10X.XXX.X9X")' extract_3month_fromshodan.json > all.json In this way I need to get for almost 290 times of ip_str,timestamp values which are kept in a csv and or .txt file. What I have done is for single ip_str and timestamp. But I could not able to run the above command as a loop. Expected Output : I should get extracted/filtered json banner including all relevant fields w.r.t 290 IPs and timestamp (kept in csv or txt file) from the main json banner (containing more than 500 IPs). The extraction should be done automatically i.e. like a loop command by one/group of code. the values (timestamp and ip_str) for loop will come from .csv or .txt file. For the mini use case here (filtering 1 out of two ), In input,I have input banner for two IPs i.e. 126.100.255.229 and 126.100.105.198. Now after running loop command I should get banner for ip_str=126.100.105.198 having timestamp = 2018-08-11T04:56:17.312039 as below. In real case I will have banner for more than 500 IPs and timestamp in one json file from I which I have to filtered for 290 IPs and timestamp. Output : { "asn": "AS17676", "hash": 1371060454, "ip": 2120509894, "isp": "Softbank BB", "transport": "udp", "data": "HTTP/1.1 200 OK\r\nCache-Control: max-age=1800\r\nST: upnp:rootdevice\r\nUSN: uuid:63041253-1019-2006-1228-00018efed688::upnp:rootdevice\r\nEXT:\r\nServer: OS 1.0 UPnP/1.0 Realtek/V1.3\r\nLocation: http://192.168.2.1:52881/simplecfg.xml\r\n\r\n", "port": 1900, "hostnames": [ "softbank126100105198.bbtec.net" ], "location": { "city": "Yamashitacho", "region_code": "18", "area_code": null, "longitude": 130.55, "country_code3": "JPN", "latitude": 31.58330000000001, "postal_code": "892-0816", "dma_code": null, "country_code": "JP", "country_name": "Japan" }, "timestamp": "2018-08-11T04:56:17.312039", "domains": [ "bbtec.net" ], "org": "Softbank BB", "os": null, "_shodan": { "crawler": "6ff540e4d43ec69d8de2a7b60e1de2d9ddb406dc", "options": {}, "module": "upnp", "id": null }, "opts": {}, "ip_str": **"126.100.105.198"** } Actual Result: I am getting the filtered output/json banner based on filter parameter (here in this case ip_str and timestamp) for one single combination by running the above code. jq '. | select (.timestamp="2018-08-11T04:56:17.312039") | select(.ip_str=="126.100.105.198")' extract_3month_fromshodan.json > all.json Actual Problem: But the problem is I have to run the above code manually for 290 times for IP's which is trouble some. So, how can I use this command so that it could run for other 290 times repetitively automatically. A: It would seem that the piece of the puzzle you're missing is the ability to pass values into jq using command-line options such as --arg. The following should therefore get you over the hump: while read -r ts ip do jq --arg ts "$ts" --arg ip "$ip" ' select(.timestamp==$ts and .ip_str==$ip) ' extract_3month_fromshodan.json done < <(cat<<EOF 2018-08-11T04:56:17.312039 126.100.105.198 EOF ) inputfile.txt So if inputfile.txt contains the ts-ip pairs as above, you could write: while read -r ts ip do jq --arg ts "$ts" --arg ip "$ip" ' select(.timestamp==$ts and .ip_str==$ip) ' extract_3month_fromshodan.json done < inputfile.txt
{ "language": "en", "url": "https://stackoverflow.com/questions/56205157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: External Css file not linked to HTML page - refresh not working (See edit for solution) I coded a simple web page with a nav bar but the relative external css file is not loaded, even after refreshing the page once opened and even when I paste the full path. (Edit: added css code; Edit2: the css code works if embedded in the index file, I also overcame the Error shown in comments. Still nothing. OK, final edit... I just saved the same css file again substituting the existing one and it worked. If you have the same problem check if you can open the css in the browser from the source code. If not you have a problem with the file. Just try saving it again as a css file in the same css folder.) Here's the code: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" type="text/css" href="./css/style.css"/> </head> <body> So my question is, what should I do now to make the web page load the css style sheet properly? .nav{ height: 50px; background:blue; } .nav div{ display: inline-block; position:absolute; left:0; padding:15px; font-size:20px; color:white; } .nav ul{ position:absolute; right:5px; } .nav ul li{ display:inline-block; } .nav ul li a{ color:white; padding:5px; } A: Are you sure about your css file address? I suggest you to move your css file in the root of your project and change your address like this: <link rel="stylesheet" type="text/css" href="style.css"/> If it will be work then you should resolve your css address and move your file. A: You may have to press CTRL + F5 to clear your browser cache, or failing that add a meaningless parameter to the css link to force the browser to take the latest file instead of a cached version eg add ?version=1.1 <link rel="stylesheet" type="text/css" href="./css/style.css?version=1.1"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/63585206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery - response text as a variable I'm using this following jquery code to insert the responsetext in the div. $("#div").load('page.php?val='+myvalue) Is it possible to get the responsetext into a javascript variable instead of applying it to a div.? A: You would need to replace .load() with .get() for instance. $.get('page.php?val='+myvalue, function( data ) { console.log( data ); // you might want to "store" the result in another variable here }); One word of caution: the data parameter in the above snippet does not necesarilly shim the responseText property from the underlaying XHR object, but it'll contain whatever the request returned. If you need direct access to that, you can call it like $.get('page.php?val='+myvalue, function( data, status, jXHR ) { console.log( jXHR.responseText ); }); A: Define a callback function like: $("#div").load('page.php?val='+myvalue, function(responseText) { myVar = responseText; }); Noticed everyone else is saying use $.get - you dont need todo this, it will work fine as above. .load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] ) See http://api.jquery.com/load/ A: Yes, you should use $.get method: var variable = null; $.get('page.php?val='+myvalue,function(response){ variable = response; }); More on this command: http://api.jquery.com/jQuery.get/ There's also a $.post and $.ajax commands A: Try something like this: var request = $.ajax({ url: "/ajax-url/", type: "GET", dataType: "html" }); request.done(function(msg) { // here, msg will contain your response. });
{ "language": "en", "url": "https://stackoverflow.com/questions/8726375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is my DelegatingHandler firing for MVC requests? I have a hybrid MVC/Web API project and I added a simple DelegatingHandler implementation to wrap the API responses. This works great, but the handler is also being invoked for requests to MVC controllers. My understanding is that DelegatingHandlers are only invoked for API routes. I'm using OWIN and some attribute routes if that matters. The relevant code in Startup.cs is: var config = new HttpConfiguration(); // ... var debugging = HttpContext.Current == null || HttpContext.Current.IsDebuggingEnabled; config.MessageHandlers.Add(new ApiResponseDelegatingHandler(debugging)); This causes both API and web requests to be wrapped and sent as JSON. Commenting it out resolves the problem but API requests are not wrapped. The error message on a web page is: No HTTP resource was found that matches the request URI 'xxx'. No route data was found for this request. I tried forcing the order that routes are registered so that MVC routes are added before Web API but that didn't help. A: This is easy to reproduce and I'm not sure if it's a bug or not. * *Create a new web app using the ASP.NET MVC template *Install the Microsoft.AspNet.WebApi.Owin and Microsoft.Owin.Host.SystemWeb NuGet packages *Move Web API startup from WebApiConfig.cs to a new Startup.cs file *Create a DelegatingHandler and add it to config.MessageHandlers in the Startup class *The DelegatingHandler will be invoked for MVC and API requests I tried several combinations of initializing in Startup.cs and WebApiConfig.cs without success. If you;re not using attribute routing, the solution is to add the handler to the route. If you are, the only workaround I found was to examine the route in the handler and only wrap the API response if the route starts with "/api/". public class WtfDelegatingHandler : DelegatingHandler { protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var response = await base.SendAsync(request, cancellationToken); if (request.RequestUri.LocalPath.StartsWith("/api/", StringComparison.OrdinalIgnoreCase)) { response = new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent("I'm an API response") }; } return response; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/36654088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Combine multiple es6 classes into single library using rollup js How can I import a.js and b.js and export as combined bundle.js in UMD format using rollupjs? Here is the example: //a.js export default class A { ... } //b.js export default class B { ... } My current rollup.config.js is: export default [ { input: ["path/a.js", "path/b.js"], output: { file: "path/bundle.js", format: "umd", name: "Bundle" }, plugins: [ // list of plugins ] } } However, this is not working as intended. Anything wrong with this config? Thanks for your help. A: You need a file to tie them together. So along with a.js and b.js, have a main.js that looks like this: import A from './a'; import B from './b'; export default { A, B, }; Then update your rollup.config.js with input: path/main.js.
{ "language": "en", "url": "https://stackoverflow.com/questions/50685153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: custom placed arrows in magnific-popup I'd like to have arrows placed next to counter, roughly like this: < 2 of 19 > where '<' and '>' are the arrow buttons under the photo in "figcaption .mfp-bottom-bar". Since the default arrows are in the .mfp-container, I cannot just absolutely position them, because the picture can have any height and width and I need it to be pixel perfect. I have one nonfunctional solution: in the gallery object in the $('').magnificPopup call { tCounter: "<button title='previous' type='button' class='mfp-arrow mfp-arrow-left mfp-prevent-close'>&lt;</button>" + " %curr%/%total% " + "<button title='next' type='button' class='mfp-arrow mfp-arrow-right mfp-prevent-close'>&gt;</button>" } this unfortunately doesn't trigger anything even though original arrows still work. So I would like to know either: * *How can I place the default arrows to the figcaption in the HTML? *How to make the buttons in the tCounter trigger the previous and next picture functions A: Looks like I didn't read api carefully enough var magnificPopup = $.magnificPopup.instance; $('body').on('click', '#photo-prev', function() { magnificPopup.prev(); }); where #photo-prev is id of previous button A: I think it's a better solution https://codepen.io/dimsemenov/pen/JGjHK just make a small change if you want to append it to the counter area. this.content.find('div.mfp-bottom-bar').append(this.arrowLeft.add(this.arrowRight));
{ "language": "en", "url": "https://stackoverflow.com/questions/20940348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Models haskell Beginner Hi there im new to haskell and im stuck on this Question, which is given a formula, it returns the model of that formula, where the Model is a valuation which makes the formula true. An example would be model eg ==[[("p",True),("q",True)],[("p",True),("q",False)]] Using this definiton of Prop: data Prop = Falsum -- a contradiction, or |Var Variable -- a variable,or |Not Prop -- a negation of a formula, or |Or Prop Prop -- a disjunction of two formulae,or |And Prop Prop -- a conjunction of two formulae, or |Imp Prop Prop -- a conditional of two formulae deriving (Eq,show) And Valuations: valuations ::[Variable]->[Valuation] valuations [] = [[]] valuations (v:vs) = map ((v,True):) ds ++ map ((v,False):) ds where ds = valuations vs So far I have this code: models :: Prop-> Prop-> Bool models p q = and $ valuations (p == q) However it doesn't seem to be working and I've been stuck on this for a while so was wondering if anyone can help out? A: This is the same homework question that I am trying to answer. It appears that your understanding of the question is somewhat incorrect. They type line for models should be: models :: Prop -> [Valuation] You are trying to return only the formulas that give an overall evaluation of True. example = And p (Or q (Not q)) When 'example' is passed to the models function it produces the following list: [[("p",True),("q",True)],[("p",True),("q",False)]] This is because an And statement can only ever evaluate to True if both inputs are True. The second input of the And statement, (Or q (Not q)) always evaluates to True as an Or statement always evaluates to True if one of the inputs is True. This is always the case in our example as our Or can be either (Or True (Not True)) or (Or False (Not False)) and both will always evaluate to True. So as long as the first input evaluates to True then the overall And statement will evaluate to True. Valuations has to be passed a list of Variables and you have a function that does this. If you pass it just the Var "p" then you get [[("p",True)],[("p",False)]] as those are the only two possible combinations. What you (we) are wanting is to pass the Valuations list and only return those that evaluate to True. For example if your list was just Var "p" and your formula was Not p then only the second list, [("p",False)], would be returned as p only evaluates to True when you assign False to Not p as Not False = True. Almost forgot, all the possible combinations for And p (Or q (Not q)) --remember (Or q (Not q) is True And False (False (Not False)) = And False True = False -- [("p",False),("q",False)]] And False True (True (Not True) = And False True = False -- [("p",False),("q",True)]] And True (False (Not False)) = And True True = True -- [("p",True),("q",False)]] And True (True (Not True) = And True True = True -- [("p",True),("q",True)]] As you can see the bottom two lines are the ones the homework question says will be returned. I just haven't worked out how to finish it myself yet. I can get the full list of [Valuations] I just can't work out how to get only the True ones and discard the ones that evaluate False.
{ "language": "en", "url": "https://stackoverflow.com/questions/20036293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Import error with GeoPandas in Jupyter Notebook on OSX10.11.6 When importing geopandas into my Jupyter Notebook, it throws the following error. ImportError: dlopen(/opt/anaconda3/lib/python3.7/site-packages/pyproj/_datadir.cpython-37m-darwin.so, 2): Symbol not found: _clock_gettime Referenced from: /opt/anaconda3/lib/python3.7/site-packages/pyproj/.dylibs/liblzma.5.dylib (which was built for Mac OS X 10.13) Expected in: /usr/lib/libSystem.B.dylib in /opt/anaconda3/lib/python3.7/site-packages/pyproj/.dylibs/liblzma.5.dylib I have installed geopandas through a pip install from the command line. My machine runs OSX 10.11.6 (and can't upgrade). I have also tried uninstalling the pip install and installing through conda instead. Importing geopandas in my JN then throws the following error: ImportError: cannot import name 'Iterable' from 'geopandas._compat' (/opt/anaconda3/lib/python3.7/site-packages/geopandas/_compat.py) A: Problem solved by restarting Jupyter Notebooks.
{ "language": "en", "url": "https://stackoverflow.com/questions/64587562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I have a problem with uploading the image to the canvas in UWP In my MainPage when I try to run the function(ShowEntity) the image wont show on the background. When i run it on my player(class in my project) then the image wont show up on the screen. i tried to change the format few time but i dont find the problem. i think there is something wrong in the ShowEntity function. this is an example of how i try to make it work. Player _player1 = new Player(500, 500, 150, 150, "ms-appx:///Asssets/Player5.gif"); public class Piece { private double _x; private double _y; public int _width; private int _height; public string _image; public Image _imagesource { get; set; } public Piece(double x, double y, int width, int height, string image)//BitmapImage imagesource) { _x = x; _y = y; _image = image; _width = width; _height = height; _imagesource = ShowEntity(); } private Image ShowEntity() { Image _img = new Image(); _img.Source = new BitmapImage(new Uri(_image)); _img.Height = _height; _img.Width = _width; Canvas.SetLeft(_img, _x); Canvas.SetTop(_img, _y); GameManager.MyCanvas.Children.Add(_img); return _img; } A: The problem looks your image was covered by other element, if you want to show element in the Canvas, you need to set ZIndex for element. Canvas.ZIndex declares the draw order for the child elements of a Canvas. This matters when there is overlap between any of the bounds of the child elements. A higher z-order value will draw on top of a lower z-order value. If no value is set, the default is -1. If you want to set image as background, you could set it's ZIndex with samll value. And other way is set Canvas Background with ImageBrush directly like the fllowing. MyCanvas.Background = new ImageBrush { ImageSource = new BitmapImage(new Uri(this.BaseUri, "ms-appx:///Assets/enemy.png")), Stretch = Stretch.Fill };
{ "language": "en", "url": "https://stackoverflow.com/questions/72437831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Orientdb - Traverse all possible N degree separation paths between vertexes Is it possible to find out all possible paths with N degree of separation between two nodes in Orientdb? A: Try this: SELECT $path FROM ( TRAVERSE out() FROM (select from entities where id ='A') WHILE $depth <= N ) where id ='B'
{ "language": "en", "url": "https://stackoverflow.com/questions/46324051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I manually make tcp zero window and drop? I have to request specific directory repeatedly. ex) https://example.org/home/dir/aaa/11 There is case if http response status code is 200 or else. If 200? read data from raw socket&and if there is 404, drop remainder packets. ex int bytes_received = SSL_read(ssl, response, 1370); printf("%s\nreceive : %d", response, bytes_received); if(strstr(response, "HTTP1.1 200 OK") goto(specific behavior); else{drop; goto(ssl_write)}; // goto first send point, I want to drop remainder packets in kernel buffer from this point. puts(""); Is this possible by manually modifying Kernel, or tcp structure or size of sliding window? Or else? If can't, then why? Thx.
{ "language": "en", "url": "https://stackoverflow.com/questions/71707205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linking models to assets on Swift Playgrounds for iPad (no Xcode) -- iOS App Dev Tutorials StackOverflow. This is my first post. Please excuse any issues with the format. I've been trying to teach myself some iOS development in order to create an app to help me at work (I'm a farmer). I do not own a Mac computer and am not able to get one currently, which means no Xcode, but I do have an iPad. Recently, Apple made it possible to develop and publish apps from iPad on Swift Playgrounds. I scoured the internet for Playgrounds-specific tutorials and didn't find a lot of stuff, I guess because the functionality is fairly new. The best SwiftUI tutorials I found come from Apple's own iOS App Dev Tutorials. I'm now working through the code for Scrumdinger and I ran into a problem with colors that were defined within an Assets folder in Xcode from .json files. Please, refer to this structure for my question: import Foundation struct DailyScrum { var title: String var attendees: [String] var lengthInMinutes: Int var theme: Theme } extension DailyScrum { static let sampleData: [DailyScrum] = [ DailyScrum(title: "Design", attendees: ["Cathy", "Daisy", "Simon", "Jonathan"], lengthInMinutes: 10, theme: .yellow), DailyScrum(title: "App Dev", attendees: ["Katie", "Gray", "Euna", "Luis", "Darla"], lengthInMinutes: 5, theme: .orange), DailyScrum(title: "Web Dev", attendees: ["Chella", "Chris", "Christina", "Eden", "Karla", "Lindsey", "Aga", "Chad", "Jenn", "Sarah"], lengthInMinutes: 5, theme: .poppy) ] } This piece of code from Apple's tutorial import SwiftUI struct CardView: View { let scrum: DailyScrum var body: some View { VStack(alignment: .leading) { Text(scrum.title) .font(.headline) Spacer() HStack { Label("\(scrum.attendees.count)", systemImage: "person.3") Spacer() Label("\(scrum.lengthInMinutes)", systemImage: "clock") .labelStyle(.trailingIcon) } .font(.caption) } .padding() .foregroundColor(scrum.theme.accentColor) } } struct CardView_Previews: PreviewProvider { static var scrum = DailyScrum.sampleData[0] static var previews: some View { CardView(scrum: scrum) .background(scrum.theme.mainColor) .previewLayout(.fixed(width: 400, height: 60)) } } is supposed to generate this preview on Xcode. However, this is what I get on iPad Playgrounds. Both the color and the preview size are off. I don't really care about the preview size, because it doesn't affect the app (this card will be shown into a list and have the appropriate size later), but I'd like to get the color right. The structure Theme that's used to specify the colors is defined in the file Theme.swift: import SwiftUI enum Theme: String { case bubblegum case buttercup case indigo case lavender case magenta case navy case orange case oxblood case periwinkle case poppy case purple case seafoam case sky case tan case teal case yellow var accentColor: Color { switch self { case .bubblegum, .buttercup, .lavender, .orange, .periwinkle, .poppy, .seafoam, .sky, .tan, .teal, .yellow: return .black case .indigo, .magenta, .navy, .oxblood, .purple: return .white } } var mainColor: Color { Color(rawValue) } } And the specified colors in the enumeration are .json Assets in Xcode with this folder structure. However, the online tutorial doesn't specify how Xcode knows to look for them without any explicit references to these folders or .json files in the code for Theme.swift. I tried recreating the same folder structure within Playgrounds (which was painful since you can't import folders), but my output didn't change. So here are my questions: * *How does Xcode link assets to custom data models (such as the enum in Theme.swift) that don't specifically reference it? Can I reproduce this with just code in Swift Playgrounds on iPad? *If I can't do that in Swift Playgrounds, do I have an alternative for creating custom colors and having them work with the enum in Theme.swift? Thank you very much. A: Following @loremipsum's suggestion, I replaced the mainColor property of the Theme enumeration with var mainColor: Color { switch self { case .bubblegum: return Color(red: 0.933, green: 0.502, blue: 0.820) case .buttercup: return Color(red: 1.000, green: 0.945, blue: 0.588) case .indigo: return Color(red: 0.212, green: 0.000, blue: 0.443) case .lavender: return Color(red: 0.812, green: 0.808, blue: 1.000) case .magenta: return Color(red: 0.647, green: 0.075, blue: 0.467) case .navy: return Color(red: 0.000, green: 0.078, blue: 0.255) case .orange: return Color(red: 1.000, green: 0.545, blue: 0.259) case .oxblood: return Color(red: 0.290, green: 0.027, blue: 0.043) case .periwinkle: return Color(red: 0.525, green: 0.510, blue: 1.000) case .poppy: return Color(red: 1.000, green: 0.369, blue: 0.369) case .purple: return Color(red: 0.569, green: 0.294, blue: 0.949) case .seafoam: return Color(red: 0.796, green: 0.918, blue: 0.898) case .sky: return Color(red: 0.431, green: 0.573, blue: 1.000) case .tan: return Color(red: 0.761, green: 0.608, blue: 0.494) case .teal: return Color(red: 0.133, green: 0.561, blue: 0.620) case .yellow: return Color(red: 1.000, green: 0.875, blue: 0.302) } } copying the RGB values for the themes from the .json asset files. This has fixed the problem and now colors appear as intended. What I don't understand is why SwiftUI couldn't process Color(rawValue) for the example data used in CardView(), which was DailyScrum(title: "Design", attendees: ["Cathy", "Daisy", "Simon", "Jonathan"], lengthInMinutes: 10, theme: .yellow). Sure, .periwinkle might not be previously defined, but .yellow certainly is. In fact, if I rewrite mainColor from Color(rawValue) to Color(.yellow), I get all cards colored yellow without having to pass any RGB value. So what's Color(rawValue) getting from the enumeration that it's unable to process .yellow when passed from rawValue?
{ "language": "en", "url": "https://stackoverflow.com/questions/70765916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Untrusted data is embedded straight into the output I am currently facing Checkmarx scan issue for the below snippet: The application's getResponse embeds untrusted data in the generated output with setCatList, at line 10 of MyClass.java. This untrusted data is embedded straight into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the output. This can enable a Reflected Cross-Site Scripting (XSS) attack. GetCatSP sp = getCatSP(); // GetCatSP extends StoredProcedure Map<String, Object> output = sp.getMyData(inParams); // This executes super.execute(inParams) and returns it List<Cat> catList = (List<Cat>) output.get("cat_info"); response.setCatList(catList); How do I handle this?
{ "language": "en", "url": "https://stackoverflow.com/questions/74993277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Moving towards a point when said point is within a radius Just as a disclaimer, I am new to Python. (this is in graphics.py) I have two points on a plane. One point "a" is the dot with a circle around it. Currently they look something akin to this: Assume that point "a" is moving on a trajectory that will cause the circle to touch the other point. My goal is to have point "a" begin moving towards the other point once the other point is within the bounds of the circle surrounding point "a" kinda like this situation: It should also be noted that point "a" is the only point that is supposedly moving. Ultimately, I want the points to touch. Is there a way for me to do this? One possible solution I can currently think of is to have point "a" move to the (x,y) coordinates on which the other point lies, but that would mean that point "a" isn't moving to the other point due to the circle coming in contact with the other point. Any and all help is appreciated! A: here's some pseudo code if (a.x-b.x)**2 + (a.y-b.y)**2 <= a.radius**2: vec_a_b = b-a # or you can do this component wise a.velocity = normalized(vec_a_b)*a.velocity.magnitude this assumes point a has a velocity vector, which encodes the direction it's currently headed in and its speed. now you can use the velocity to move a: a.x += a.velocity.x a.y += a.velocity.y
{ "language": "en", "url": "https://stackoverflow.com/questions/54745288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ruby on Rails - Activeadmin - Update model with virtual attribute I have a activeadmin form to which allows to add a youtube URL. I validate this URL in my video model. It does works well when I want to add a new video but does nothing when I'm editing the video. app/admin/video.rb : ActiveAdmin.register Media, as: 'Videos' do form do |f| f.inputs "Add youtube video" do f.input :category f.semantic_errors :error f.has_many :videos, allow_destroy: true do |g| g.input :mylink, :label => "Youtube link : ", :type => :text end actions end end end model/video.rb : class Video < ApplicationRecord belongs_to :media attr_accessor :mylink YT_LINK_FORMAT = /\A.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*\z/i before_create :before_add_to_galerie before_update :before_add_to_galerie def before_add_to_galerie uid = @mylink.match(YT_LINK_FORMAT) self.uid = uid[2] if uid && uid[2] if self.uid.to_s.length != 11 self.errors.add(:mylink, 'is invalid.') throw :abort false elsif Video.where(uid: self.uid).any? self.errors.add(:mylink, 'is not unique.') throw :abort false end end validates :mylink, presence: true, format: YT_LINK_FORMAT end It looks like the before_update method is never triggered. How can I make my edit work ? EDIT :I figured out that it is calling the before_update link for the Media model and not for the Video one.But the create is fine. A: Let me try to rephrase the issue: * *You have a model Video *Video has a virtual attribute my_link *Video has a before_update callback before_add_to_galerie *You want this callback to trigger when only my_link was changed does this look correct? If so you have 2 options, first - if you have updated_at change it along with my_link class Video < ApplicationRecord attr_reader :my_link # ... def my_link=(val) return val if val == my_link @my_link = val self.updated_at = Time.zone.now end end or you can use ActiveModel
{ "language": "en", "url": "https://stackoverflow.com/questions/43455063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Retrieve queue length with Celery (RabbitMQ, Django) I'm using Celery in a django project, my broker is RabbitMQ, and I want to retrieve the length of the queues. I went through the code of Celery but did not find the tool to do that. I found this issue on stackoverflow (Check RabbitMQ queue size from client), but I don't find it satisfying. Everything is setup in celery, so there should be some kind of magic method to retrieve what I want, without specifying a channel / connection. Does anyone have any idea about this question ? Thanks ! A: Here is an example on how to read the queue length in rabbitMQ for a given queue: def get_rabbitmq_queue_length(q): from pyrabbit.api import Client from pyrabbit.http import HTTPError count = 0 try: cl = Client('localhost:15672', 'guest', 'guest') if cl.is_alive(): count = cl.get_queue_depth('/', q) except HTTPError as e: print "Exception: Could not establish to rabbitmq http api: " + str(e) + " Check for port, proxy, username/pass configuration errors" raise return count This is using pyrabbit as previously suggested by Philip A: PyRabbit is probably what you are looking for, it is a Python interface to the RabbitMQ management interface API. It will allow you to query for queues and their current message counts. A: You can inspect the workers in celery by using inspect module. Here is the guide. Also for RabbitMQ there are some command line command.
{ "language": "en", "url": "https://stackoverflow.com/questions/17863626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to add image in google chart function test() { $array['cols'][] = array('type' => 'string'); $array['cols'][] = array('type' => 'string'); $array['cols'][] = array('type' => 'string'); $array['rows'][] = array('c' => array( array('v'=>'Name'), array('v'=>22)) ); $array['rows'][] = array('c' => array( array('v'=>'Name1'), array('v'=>26))); $array['rows'][] = array('c' => array( array('v'=>'Name2'), array('v'=>12))); return $array; } print json_encode(test()); I am using above code to build organization chart in using google chart. I want to add image and designation with name. Could you please tell me how can i modify the code. A: I Tried to solve your problem. We can use {allowHtml:true} to embed and process HTML code with Google chart. function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Name'); data.addColumn('string', 'Parent'); data.addRows([ [{ v: 'parent_node', f: 'Parent Node' }, null], [{ v: 'child_node_1', f: '<b>Child Node</b> <img src="http://www.mapsysinc.com/wp-content/uploads/2013/08/oracle-logo.gif" height="42" width="50"> </img>' }, 'parent_node'], [{ v: 'child_node_2', f: 'Child Node' }, 'parent_node'] ]); var chart = new google.visualization.OrgChart(document.querySelector('#chart_div')); chart.draw(data, { allowHtml: true }); } google.load('visualization', '1', { packages: ['orgchart'], callback: drawChart }); Here I created Example Please check it: https://jsfiddle.net/1gvwLy8n/5/
{ "language": "en", "url": "https://stackoverflow.com/questions/26814414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php call function name from array hi i want get function name from array how to do that public function cuturls($url){ $long_url = urlencode($url); $api_token = 'xxx'; $api_url = "https://cut-urls.com/api?api={$api_token}&url={$long_url}"; $result = @json_decode(file_get_contents($api_url),TRUE); if($result["shortenedUrl"]) { return $result["shortenedUrl"]; } else { return $this->ouo($url); } } want to convert this function public function docut($url){ global $filesize77; global $cutpost; if(empty($cutpost) or $cutpost==='cutearn'){ if($filesize77 <= '1073741824'){ return array($this->cuturls($url),'cuturls'); }else if($filesize77 > '1073741824' and $filesize77 <= '2147483648'){ return array($this->cuturls($this->adlinkme($url)),'cuturls'); }else if($filesize77 > '2147483648' and $filesize77 <= '3221225472'){ return array($this->cuturls($this->adlinkme($this->cutearn($url))),'cuturls'); } } want to convert for this type by using array have functions names how to callback public function docut($url){ global $filesize77; global $cutpost; $cutarray = array('cuturls', 'adlinkme', 'cutearn', 'cutwin'); if(empty($cutpost) or $cutpost===$cutarray[3]){ if($filesize77 <= '1073741824'){ return array($this->$cutarray[0]($url),$cutarray[0]); }else if($filesize77 > '1073741824' and $filesize77 <= '2147483648'){ return array($this->$cutarray[0]($this->$cutarray[1]($url)),$cutarray[0]); }else if($filesize77 > '2147483648' and $filesize77 <= '3221225472'){ return array($this->$cutarray[0]($this->$cutarray[1]($this->$cutarray[2]($url))),$cutarray[0]); } } A: call_user_func_array($func,$parameters); $func is function name as string , $parameters is parameteres to $func as array. read the doc :- http://php.net/manual/en/function.call-user-func-array.php usage:- <?php function abc($str){ print $str; } call_user_func_array("abc",array('Working')); ?> When it put in your question:- public function docut($url){ global $filesize77; global $cutpost; $cutarray = array('cuturls', 'adlinkme', 'cutearn', 'cutwin'); if(empty($cutpost) or $cutpost===$cutarray[3]){ if($filesize77 <= '1073741824'){ return array(call_user_func_array(array($this,$cutarray[0]),$url),$cutarray[0]); }else if($filesize77 > '1073741824' and $filesize77 <= '2147483648'){ return array( call_user_func_array(array($this,$cutarray[0]),call_user_func_array(array($this,$cutarray[0]),$url)),$cutarray[0]); }else if($filesize77 > '2147483648' and $filesize77 <= '3221225472'){ return array(call_user_func_array(array($this,$cutarray[0]),call_user_func_array(array($this,$cutarray[1]),call_user_func_array(array($this,$cutarray[2]),$url))),$cutarray[0]); } } } A: Just use the {..}(..) syntax. I.e $this->{$cutarray[0]}(...) public function docut($url){ global $filesize77; global $cutpost; $cutarray = ['cuturls', 'adlinkme', 'cutearn', 'cutwin']; if(empty($cutpost) or $cutpost===$cutarray[3]){ if($filesize77 <= '1073741824') { return [$this->{$cutarray[0]}($url), $cutarray[0]]; } else if($filesize77 > '1073741824' and $filesize77 <= '2147483648'){ return [$this->{$cutarray[0]}($this->$cutarray[1]($url)), $cutarray[0]]; } else if($filesize77 > '2147483648' and $filesize77 <= '3221225472') { return [$this->{$cutarray[0]}($this->{$cutarray[1]}($this->{$cutarray[2]}($url))), $cutarray[0]]; } } If you add more cases to this function, you should really think about wrapping this inside an loop or something else. Currently your code is very hard to read and understand... public function docut($url){ global $filesize77; global $cutpost; $cutarray = ['cuturls', 'adlinkme', 'cutearn', 'cutwin']; if(empty($cutpost) or $cutpost === $cutarray[3]) { switch { case: $filesize77 > 0x80000000 && $filesize77 <= 0xC0000000: $url = $this->{$cutarray[2]}($url); case: $filesize77 > 0x40000000 && $filesize77 <= 0x80000000: $url = $this->{$cutarray[1]}($url); case $filesize77 < 0x40000000; $url = $this->{$cutarray[0]}($url); } return [$url, $cutarray[0]]; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/47798244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set value in createMaterialBottomTabNavigator from AsyncStorage I am using createMaterialBottomTabNavigator , but before export that i want to assign value for its navigationOptions barStyle: { backgroundColor:someVariable} here problem is , i want to get value of someVariable from AsyncStorage. And it returns promise , because of that createMaterialBottomTabNavigator is getting exported first , after that I get value of someVariable . I can't write export default in async function otherwise createMaterialBottomTabNavigator will returned as promise again .Please give suggestions. I am using redux , but there also i have to update store from AsyncStorage before exporting createMaterialBottomTabNavigator. Sample code // tabnavigator.js // I Imported this file in app.js , there i use this in createSwitchNavigator // so this will execute on app starts only var theme = {}; AsyncStorage.getItem('theam').then((res) => { theme = res }); // I want theme from storage because i am going to apply theme on app // start // Here I can get theme from ReduxStore but i returns the initial one const DashTabsNav = createMaterialBottomTabNavigator({ ProfileStack: { screen: ProfileStack,//this is stack created with createStacknavigator , navigationOptions: { tabBarIcon: ({ tintColor }) => (<Icon name="user" size={25} color={tintColor} />), }, }, Messages: { screen: MessageScreen, navigationOptions: { tabBarColor: 'red', tabBarIcon: ({ tintColor }) => (<Icon name="comments" size= {25} color={tintColor} />) }, }, }, { activeColor: 'white', inactiveColor: 'white', barStyle: { backgroundColor: theme.themeColor }, }, ); export default DashTabsNav; A: Read https://reactnavigation.org/docs/en/headers.html#overriding-shared-navigationoptions within your ProfileScreen and MessageScreen override the header color by doing static navigationOptions = ({ navigation, navigationOptions }) => { return { headerStyle: { backgroundColor: theme.themeColor, }, }; };
{ "language": "en", "url": "https://stackoverflow.com/questions/56649973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check if any of the files within a folder contain a pattern then return filename I'm writing a script that aim to automate the fulfill of some variables and I'm looking for help to achieve this: I have a nginx sites-enabled folder which contain some reverses proxied sites. I need to: * *check if a pattern $var1 is found in any of the files in "/volume1/nginx/sites-enabled/" *return the name of the file containing $var1 as $var2 Many thanks for your attention and help! I have found some lines but none try any files in a folder if grep -q $var1 "/volume1/nginx/sites-enabled/testfile"; then echo "found" fi A: This command is the most traditional and efficient one which works on any Unix without the requirement to have GNU versions of grep with special features. The efficiency is, that xargs feeds the grep command as many filenames as arguments as it is possible according to the limits of the system (how long a shell command may be) and it excecutes the grep command by this only as least as possible. With the -l option of grep it shows you only the filename once on a successful pattern search. find /path -type f -print | xargs grep -l pattern A: Assuming you have GNU Grep, this will store all files containing the contents of $var1 in an array $var2. for file in /volume1/nginx/sites-enabled/* do if grep --fixed-strings --quiet "$var1" "$file" then var2+=("$file") fi done This will loop through NUL-separated paths: while IFS= read -d'' -r -u9 path do …something with "$path" done 9< <(grep --fixed-strings --files-without-match --recursive "$var1" /volume1/nginx/sites-enabled) A: find and grep can be used to produce a list of matching files: find /volume1/nginx/sites-enabled/ -type f -exec grep -le "${var1}" {} + The ‘trick’ is using find’s -exec and grep’s -l. If you only want the filenames you could use: find /volume1/nginx/sites-enabled/ -type f -exec grep -qe "${var1}" {} \; -exec basename {} \; If you want to assign the result to a variable use command substitution ($()): var2="$(find …)" Don’t forget to quote your variables!
{ "language": "en", "url": "https://stackoverflow.com/questions/56355405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set annotation params from environment variable Say you have: @NotBlank(message = "forenames must not be blank") ...and a dubious requirement comes along that the message needs to be configured via an environment variable. It looks like in with SpringBoot (as per here) you can do something like: @NotBlank(message = '${MESSAGE}') Is there a standard/known way to do this outside of spring?
{ "language": "en", "url": "https://stackoverflow.com/questions/72994357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UINavigationBar title label text Is it possible to get the title text to shrink to fit in the UINavigationBar in iOS. (for portrait iPhone app with no autolayout). I'm setting the title bar dynamically but sometimes the text is too long and at the moment it just cuts it off with an ellipsis. i.e. "This is the t..." I'd like it to shrink the text instead. A: Xcode 7.1 - Swift 2.0 //Adding Title Label var navigationTitlelabel = UILabel(frame: CGRectMake(0, 0, 200, 21)) navigationTitlelabel.center = CGPointMake(160, 284) navigationTitlelabel.textAlignment = NSTextAlignment.Center navigationTitlelabel.textColor = UIColor.whiteColor() navigationTitlelabel.text = "WORK ORDER" self.navigationController!.navigationBar.topItem!.titleView = navigationTitlelabel A: You can create your own title view to make it. Something like this: - (void)viewDidLoad { [super viewDidLoad]; //Do any additional setup after loading the view, typically from a nib. UILabel *titleLabelView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)]; //<<---- Actually will be auto-resized according to frame of navigation bar; [titleLabelView setBackgroundColor:[UIColor clearColor]]; [titleLabelView setTextAlignment: NSTextAlignmentCenter]; [titleLabelView setTextColor:[UIColor whiteColor]]; [titleLabelView setFont:[UIFont systemFontOfSize: 27]]; //<<--- Greatest font size [titleLabelView setAdjustsFontSizeToFitWidth:YES]; //<<---- Allow shrink // [titleLabelView setAdjustsLetterSpacingToFitWidth:YES]; //<<-- Another option for iOS 6+ titleLabelView.text = @"This is a Title"; navigationBar.topItem.titleView = titleLabelView; //.... } Hope this helps. A: I used this code for swift 4 (note label rect is NOT important..) func navBar()->UINavigationBar?{ let navBar = self.navigationController?.navigationBar return navBar } override func viewDidLoad() { super.viewDidLoad() setTNavBarTitleAsLabel(title: "VERYYYY VERYYYY VERYYYY VERYYYY VERYYYY VERYYYY VERYYYY LONGGGGGG") } // will shrink label... func setTNavBarTitleAsLabel(title: String, color: UIColor ){ // removed some code.. let navigationTitlelabel = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) navigationTitlelabel.numberOfLines = 1 navigationTitlelabel.lineBreakMode = .byTruncatingTail navigationTitlelabel.adjustsFontSizeToFitWidth = true navigationTitlelabel.minimumScaleFactor = 0.1 navigationTitlelabel.textAlignment = .center navigationTitlelabel.textColor = color navigationTitlelabel.text = title if let navBar = navBar(){ //was navBar.topItem?.title = title self.navBar()?.topItem?.titleView = navigationTitlelabel //navBar.titleTextAttributes = [.foregroundColor : color ?? .black] } }
{ "language": "en", "url": "https://stackoverflow.com/questions/14505331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Python 2.6 Generator expression must be parenthesized if not sole argument I rewrote the following Python 2.7+ code as follows for Python 2.6. Python 2.7+ options = {key: value for key, value in options.items() if value is not None} Python 2.6 options = dict((key, value) for key, value in options.items() if value is not None) But I am getting the following error SyntaxError: Generator expression must be parenthesized if not sole argument What did I do wrong? A: I found this question while looking for the "SyntaxError: Generator expression must be parenthesized" in a "code wars" kata I did in 3.8. My presumably similar example was: max(word for word in x.split(), key=score) I was looking for the word in the given string x with the highest score that was calculated by the existing but (at least here) irrelevant method named score. After reducing my code down to this statement, I found the problem in word for word in x.split() not being in parenthesized seperately from the second argument. Changing that made my code run just fine: max((word for word in x.split()), key=score) Since your example does not have additional arguments but there is a comma between key dan value, I assume there is a hiccup in the parser when faced with comma and generator expressions. Avoiding to unpack the item and thus removing the comma should solve the problem: options = dict(item for item in options.items() if item[1] is not None) We only have to fetch the value from the tuple instead of using a separate variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/50935610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I require a node module in my client side javascript? I am trying to build a natural language processing bot using javascript and jQuery for the logic and node and express as the framework. I discovered a natural language processing facility that would be extremely useful for my project https://github.com/NaturalNode/natural unfortunately the documentation is sparse and I have only been using node for a couple of weeks. This is the code I have on my server side app.js var natural = require('natural'), tokenizer = new natural.WordTokenizer(); stemmer.attach(); var express = require("express"); app = express(); app.set("view engine", "ejs"); app.use(express.static(__dirname + '/public')); I am requiring the 'natural' module here but I am unable to use the methods that are outlined in the documentation. var natural = require('natural'), tokenizer = new natural.WordTokenizer(); console.log(tokenizer.tokenize("your dog has fleas.")); // [ 'your', 'dog', 'has', 'fleas' ] The method 'tokenizer' is undefined. I have done quite a bit of research on this and looked into using module.export and passing variables through the app.get function for the index.ejs page I am using but I have been unsuccessful so far. NOTE: The javascript file I am trying to use these methods in is located in the public/javascript directory while the app.js file is located in the main project directory. I have tried to require the 'natural' package directly in the javascript file I am trying to use the methods in but an error was thrown saying require is an undefined method. here is the package.json file: { "name": "JSAIN", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "dependencies": { "ejs": "^2.3.1", "express": "^4.12.3", "natural": "^0.2.1", "underscore": "^1.8.2" } } A: maybe you can try browserify which allow you to use some npm modules in browser. A: Converting my comment into an answer... The natural module says it's for running in the node.js environment. Unless it has a specific version that runs in a browser, you won't be able to run this in the browser. A: have you install that module with global mode and have defined that in package.json? Otherwise, try this: npm install -g natural
{ "language": "en", "url": "https://stackoverflow.com/questions/29326211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: App closes when item on bottom navigation view is selected to replace fragment My app closes, not crashing but just goes to the background,when i select item on the bottom navigation. i was using material botton navigation view but the problem persisted so i decided to use AHBottomNavigation library but the issue is still there. Set up bottom navigation code AHBottomNavigation bottomNavigation = findViewById(R.id.navigation); AHBottomNavigationItem item1 = new AHBottomNavigationItem(getString(R.string.orders), R.drawable.ic_m_orders); AHBottomNavigationItem item2 = new AHBottomNavigationItem(getString(R.string.pickup), R.drawable.ic_m_location); bottomNavigation.setAccentColor(Color.parseColor("#2DA1D1")); bottomNavigation.setInactiveColor(Color.parseColor("#C4C4C4")); bottomNavigation.addItem(item1); bottomNavigation.addItem(item2); bottomNavigation.setTitleState(AHBottomNavigation.TitleState.ALWAYS_SHOW); bottomNavigation.setOnTabSelectedListener(tabSelectedListener); bottomNavigation.setBehaviorTranslationEnabled(true); openFragment(fragmentHolder); private void openFragment(final Fragment fragment) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.host_fragment, fragment); transaction.addToBackStack(null); transaction.commit(); } private final AHBottomNavigation.OnTabSelectedListener tabSelectedListener = (position, wasSelected) -> { switch (position) { case 0: openFragment(fragmentHolder); break; case 1: openFragment(PickupStationFragment.newInstance()); break; } return true; }; the xml code <androidx.fragment.app.FragmentContainerView android:layout_marginBottom="56dp" android:id="@+id/host_fragment" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintBottom_toTopOf="@id/cl" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> <com.aurelhubert.ahbottomnavigation.AHBottomNavigation android:id="@+id/navigation" android:layout_width="match_parent" android:layout_height="56dp" android:layout_alignParentBottom="true" android:background="@color/white" android:visibility="visible" android:layout_gravity="bottom"/> A: I found the solution, i was overriding ondestroy view on one of my fragment and added requireActivity.finish() in the overridden method
{ "language": "en", "url": "https://stackoverflow.com/questions/66559893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use angular.filter in controller's function? On change select choosen type and value passed to the function (ng-change="sortEvents(type, value)") I need to filter all elements of $scope.events to select elements with "state" equal to "NSW" only. $scope.sortEvents = function(type, value, $scope, $filter) { $scope.events = $filter('filterBy')($scope.events, ['state'], 'NSW'); console.log($scope.events); } But in console is see http://prntscr.com/bmyj74 Angular filter works appropriately using ng-repeat, and in app.js in dependencies, I have specified angular.filter. A: You can write your filter like this: $scope.events = $filter('filter')($scope.events, function(e){ return e.state === 'NSW'; });
{ "language": "en", "url": "https://stackoverflow.com/questions/38118890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Easiest way to write and read an XML I'd like to know what is the easiest way to write to and parse a XML file in Android. My requirement is very simple. A sample file would be something like: <Item ID="1" price="$100" Qty="20" /> And I only want to retrieve an item by the ID and read price and Qty. I was referring to Using XmlResourceParser to Parse Custom Compiled XML, but wondering if there is a much lightweight way to do something trivial as this (still using tags). A: If it's really that simple, you can just write it with printf() or similar. For parsing, you're best off using a real XML parser (perhaps the SimpleXML that @netpork suggested). But for something truly this trivial, you could just use regexes -- here's my usual set, from which you'd need mainly 'attrlist' and 'stag' (for attribute list and start-tag). xname = "([_\\w][-_:.\\w\\d]*)"; # XML NAME (imperfect charset) xnmtoken = "([-_:.\\w\\d]+)"; # xncname = "([_\\w][-_.\\w\\d]*)"; # qlit = '("[^"]*"|\'[^\']*\')'; # Includes the quotes attr = "$xname\\s*=\\s*$qlit"; # Captures name and value attrlist = "(\\s+$attr)*"; # startTag = "<$xname$attrlist\\s*/?>"; # endTag = "</$xname\\s*>"; # comment = "(<!--[^-]*(-[^-]+)*-->)"; # Includes delims pi = "(<\?$xname.*?\?>)"; # Processing instruction dcl = "(<!$xname\\s+[^>]+>)"; # Markup dcl (imperfect) cdataStart = "(<!\[CDATA\[)"; # Marked section open cdataEnd = "(]]>)"; # Marked section close charRef = "&(#\\d+|#[xX][0-9a-fA-F]+);"; # Num char ref (no delims) entRef = "&$xname;"; # Named entity ref pentRef = "%$xname;"; # Parameter entity ref xtext = "[^<&]*"; # Neglects ']]>' xdocument = "^($startTag|$endTag|$pi|$comment|$entRef|$xtext)+\$"; A draft of the XML spec even included a "trivial" grammar for XML, that can find node boundaries correctly, but not catch all errors, expanding entity references, etc. See https://www.w3.org/TR/WD-xml-lang-970630#secF. The main drawback is that if you run into fancier data later, it may break. For example, someone might send you data with a comment in there, or a syntax error, or an unquoted attribute, or using &quo;, or whatever. A: You can use XmlPullParser for first time parsing. Then I would suggest storing the data in sqllite or shared preferences depending on the complexity of queries or size of data. https://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html
{ "language": "en", "url": "https://stackoverflow.com/questions/8240957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Java Spigot, Popultate and block.setType cause StackOverflow i'm actually developing a little ore remover plugin using Spigot 1.15 API. Here is my problem. when i use block.setType() in my populate method (which is called by minecraft generator), it seems to call back the minecraft generator. This cause a StackOverflowError. See this log My question is, how could i do to stop this callback. Here are my sources : Plugin.yml : ##################################### # General Plugin Informations # ##################################### name: Remover author: me version: 1.0 api-version: 1.15 prefix: Remover main: OresRemover.Remover load: startup Remover Class: package OresRemover; import org.bukkit.plugin.java.JavaPlugin; public class Remover extends JavaPlugin { @Override public void onEnable() { getServer().getPluginManager().registerEvents(new RemoverListener(), this); } @Override public void onDisable() { } } RemoverListener Class package OresRemover; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.world.WorldInitEvent; import java.util.logging.Logger; public class RemoverListener implements Listener { Logger logger; public RemoverListener () { logger = Logger.getLogger("Minecraft"); } @EventHandler public void onWorldInit(WorldInitEvent e) { if (e.getWorld().getName().equals("world")) e.getWorld().getPopulators().add(new CustomPopulator()); } } CustomPopulator Class: package OresRemover; import org.bukkit.Chunk; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.generator.BlockPopulator; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.logging.Logger; public class CustomPopulator extends BlockPopulator { Logger logger; public CustomPopulator() { logger = Logger.getLogger("Minecraft"); } @Override public void populate(World world, Random random, Chunk chunk) { int X, Y , Z; for (X = 0; X < 16; X++) for (Z = 0; Z < 16; Z++) { for (Y = world.getMaxHeight() - 1; chunk.getBlock(X, Y, Z).getType() == Material.AIR; Y--); logger.info("Surface at x:" + X + " y:" + Y + " z:" + Z); for (; Y > 0; Y--) if (isOreType(chunk.getBlock(X, Y, Z).getType())) { logger.info("Cave block found at x:" + X + " y:" + Y + " z:" + Z + " and Type is " + chunk.getBlock(X, Y, Z).getType().toString()); chunk.getBlock(X, Y, Z).setType(Material.STONE); } } } private List<Material> oreMaterial = Arrays.asList( // Ores Material.COAL_ORE, Material.IRON_ORE, Material.LAPIS_ORE, Material.REDSTONE_ORE, Material.GOLD_ORE, Material.DIAMOND_ORE, Material.EMERALD_ORE ); private boolean isOreType(Material block) { for (Material material : oreMaterial) if (block == material) return (true); return (false); } } Any help would be appreciate. Thanks A: Block.setType by default updates neighboring blocks, which, if happening near a yet unpopulated chunk, causes it to populate as well, and so on. This needs to be turned off with the second boolean parameter: setType(Material.STONE, false).
{ "language": "en", "url": "https://stackoverflow.com/questions/61844520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Connect to a remote server mongoDB in Docker via ssh in nodeJS using tunnel-ssh, AuthenticationFailed I am trying to connect to a remote server MongoDB in Docker through ssh in Nodejs as below : sshConfig = { username: 'username', password: 'password', host: 'host', port: 22, dstHost: '172.17.0.3', dstPort: 27017, localPort: 5000 }; const uri = 'mongodb://admin:password@localhost:27017/admin'; tunnel(sshConfig, async error => { if (error) { throw new Error(`SSH connection error: ${error}`); } const client = new MongoClient(uri); async function run() { try { // Connect the client to the server await client.connect(); // Establish and verify connection await client.db('admin').command({ ping: 1 }); console.log('Connected successfully to server'); } finally { // Ensures that the client will close when you finish/error await client.close(); } } await run().catch(console.dir); }); But I am getting error as below : MongoServerError: Authentication failed. at MessageStream.messageHandler (/node_modules/mongodb/src/cmap/connection.ts:740:20) at MessageStream.emit (node:events:390:28) at MessageStream.emit (node:domain:475:12) at processIncomingData (/node_modules/mongodb/src/cmap/message_stream.ts:167:12) at MessageStream._write (/node_modules/mongodb/src/cmap/message_stream.ts:64:5) at writeOrBuffer (node:internal/streams/writable:389:12) at _write (node:internal/streams/writable:330:10) at MessageStream.Writable.write (node:internal/streams/writable:334:10) at Socket.ondata (node:internal/streams/readable:754:22) at Socket.emit (node:events:390:28) { ok: 0, code: 18, codeName: 'AuthenticationFailed' }, and I open http://localhost:5000/ by browser, it shows that: It looks like you are trying to access MongoDB over HTTP on the native driver port. I can connect the database via: * *Use MongoDB compass to connect the database via ssh *Use mongo 'mongodb://admin:password@remote-host:27017/admin' in local machine terminal *Use MongoClient(mongodb://admin:password@remote-host:27017/admin) in Nodejs without ssh-tunnel *Use mongo 'mongodb://admin:password@localhost:27017/admin' in both remote host and remote host docker contaniner I am sure the password is correct.
{ "language": "en", "url": "https://stackoverflow.com/questions/69387103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I detect Android library modules that could be plain Kotlin modules? I work on a big project with hundreds of modules. Some of them are declared as Android library modules, but they don't have any Android-specific dependencies, so they could be converted to plain Kotlin modules. Is there a way to detect this fact? How can I detect automatically that an Android library module could be a plain Kotlin module?
{ "language": "en", "url": "https://stackoverflow.com/questions/73960089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using StreamSocketListener in the background with SocketActivityTrigger In order to make a UWP App act like an HTTP server, restup does the job. But the problem is that it does not provide an HTTP server that works even after the app is closed. In order to achieve this, a background task with SocketActivityTrigger has to be created and the socket ownership of StreamSocketListener has to be transferred to the socket broker so that the background task is triggered when a request comes (as explained here). And here is an example for an app that connects to a socket and keeps receiving messages even after the app is closed. I tried to adapt this to make restup work in the background as well, but in vain! Could someone help on this please?
{ "language": "en", "url": "https://stackoverflow.com/questions/59716347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to re-calculate a style on sibling elements? Not sure if i'm even asking this correctly. So allow me to explain further. HTML <div class='col'> <div id='q1' class='qBlock' </div> <div class='col'> <div id='q2' class='qBlock' </div> <div class='col'> <div id='q3' class='qBlock' </div> LESS @qBlockBG: #ccc; .qBlock { color: white; } #q1: { background-color: @qBlockBG; } #q{n}: { background-color: darken(#q{n-1}, 10%); } <--- doesn't work, but that's the idea What I want to do is have the base style for #q1 be re-calculated for each sibling such that the color is darker for each additional sibling. So #q2 is 10% darker than #q1 and #q3 is 10% darker than #q2, and so on. A: You can mock loops in LESS using a recursive mixin with a guard expression. Here's an example applied to your case: #q1 { background-color: #ccc; } /* recursive mixin with guard expression - condition */ .darker-qs(@color, @index) when (@index < 10) { @darker-color: darken(@color, 10%); /* the statement */ #q@{index} { background-color: @darker-color; } /* end of the statement */ /* the next iteration's call - final expression */ .darker-qs(@darker-color, @index + 1); } /* the primary call - initialization */ .darker-qs(#ccc, 2);
{ "language": "en", "url": "https://stackoverflow.com/questions/66440570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: QDesktopServices::openUrl() doesn't open page in chrome on windows. Workaround? QDesktopServices::openUrl(QUrl("http://google.com")); works if default browser ie9, ie8, firefox or opera if default browser is chrome nothing happens QtCreator debugger log i can see lines like ModLoad: 00000000`05250000 00000000`05308000 iexplore.exe or ModLoad: 00000000`04db0000 00000000`04ef8000 chrome.exe so it actually works, but ie, ff etc. opens new tab with specified url and chrome doesn't i suppose it's bug some time ago it worked perfectly could it be problem with my system (ENV vars etc.)? please help with workaround i prefer crossplatform, but proper work on windows has max priority possible solution (winapi SHELLEXECUTE) - really hate that way with ugly #ifdef, but can be an option PS: sorry for poor english. A: I dont think it's really a problem of your application.. I think it's more about how Chrome is treated such invocations. Being on your place I would go for winpai SHELLEXECUTE solution. And #ifdef is not really ugly comparing with benefits that you move default browser invocation to operation system rather then on Qt library.
{ "language": "en", "url": "https://stackoverflow.com/questions/16103589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Creating a folder in Kotlin I am new to Kotlin and have read lots of tutorials, tried bunches of code but still can't understand how to create a folder in internal storage. I need to create a folder in which I wil put a json resource file. Manifest file contains <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> and <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> My code sample is: class MainActivity() : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val folder = File( Environment.getDataDirectory().toString() + separator.toString() + "MetroPol" ) if (folder.exists()) { d("folder", "exists") } else { d("folder", "not exists") folder.mkdirs() } } I test it using my phone connected to a pc and recognised by Android Studio. When this app launches I go to a browser and don't see any new folder. What should be done here? A: To create a folder inside your Internal Storage, try out this code snippet val folder = filesDir val f = File(folder, "folder_name") f.mkdir() Finally to check if the folder is created open Device Explorer in Android Studio, then follow the path data->data->your app package name -> files-> here should be your folder that you created programmatically. Hope this helps A: I am new to Kotlin and have read lots of tutorials, tried bunches of code but still can't understand how to create a folder in internal storage. It seems as though you really want to be creating a directory in external storage. Since that is no longer being supported on Android 10 (by default) and Android R+ (for all apps), I recommend that you let the user create the directory themselves, and you get access to it via ACTION_OPEN_DOCUMENT_TREE and the Storage Access Framework. When this app launches I go to a browser and don't see any new folder. The root of external storage is Environment.getExternalStorageDirectory(). A: val appDirctory =File(Environment.getExternalStorageDirectory().path + "/test") appDirctory.mkdirs() A: Can you try this ? class MainActivity() : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var filename = "test.txt" val folder = File("/sdcard/MetroPol/") folder.mkdirs() val outputFile = File(folder, filename) try { val fos = FileOutputStream(outputFile) } catch (e: FileNotFoundException) { e.printStackTrace() } }
{ "language": "en", "url": "https://stackoverflow.com/questions/60004199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to display single quotes inside double quotes in string in python I know this is very basic question, but not able to frame it out. I need to execute a customized python command based command with in a script. ex: below is the actual commands. command-dist --host='server1' -- cmd -- 'command1;command2' I need to use this command in my python script form my script , this command needs be to executed on remote server I need this command format to use in my script cmd="ssh -q %s "command-dist --host=%s -- cmd -- 'cmd1;cmd2'"" %(host1,host2) but the above is failing due to quotes, tried number of ways still no luck. When I tried this way cmd="ssh -q %s \"command-dist --host=%s -- cmd -- 'cmd1;cmd2'\"" %(host1,host2) I don't under why back slashes are appearing before and after cmd1;cmd2? This is what I am not getting. cmd 'ssh -q %s "command-dist --host=%s -- cmd -- /'cmd1;cmd2'/""' %(host1,host2) Please help how do I get the above value A: This cmd="ssh -q %s "command-dist --host=%s -- cmd -- 'cmd1;cmd2'"" %(host1,host2) is understood by Python as cmd = <some string>command-dist --host=%s -- cmd -- 'cmd1;cmd2'<some string> because you use the same quotes inside and outside. Try instead to escape the internal quotes with a backslash: cmd="ssh -q %s \"command-dist --host=%s -- cmd -- 'cmd1;cmd2'\"" %(host1,host2) Aside from that, you should use the subprocess module and supply your command as a list to subprocess.Popen.
{ "language": "en", "url": "https://stackoverflow.com/questions/40951545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can a Bacon.interval be stopped? I have an event that is fired periodically: let periodicEvent = Bacon.interval(1000, {}); periodicEvent.onValue(() => { doStuff(); }); What I would like is to pause and restart periodicEvent when I need it. How can periodicEvent be paused and restarted? Or is there a better way to do it with baconjs? A: * *An impure way to do it is to add a filter that checks for a variable before you subscribe, and then change the variable when you don't want the subscribed action to occur: var isOn = true; periodicEvent.filter(() => isOn).onValue(() => { doStuff(); }); *A "pure-r" way to do it would be turn an input into a property of true/false and filter you stream based on the value of that property: // make an eventstream of a dom element and map the value to true or false var switch = $('input') .asEventStream('change') .map(function(evt) { return evt.target.value === 'on'; }) .toProperty(true); var periodEvent = Bacon.interval(1000, {}); // filter based on the property b to stop/execute the subscribed function periodEvent.filter(switch).onValue(function(val) { console.log('running ' + val); }); Here is a jsbin of the above code There might be an even better/fancier way of doing it using Bacon.when, but I'm not at that level yet. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/43611681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Validation DropDownList value from ViewModel in ASP.Net MVC I tried to search posts, without any result either, maybe I didn't use the right words. I need a solution in MVC for validate the DropDownList value, populated from database using Model class and the Html.DropDownListFor Helper method and MySql. In the view I have added new DDL and this is populated correctly from database @Html.DropDownListFor(m => m.Fruits, Model.Fruits, "[ === Please select === ]", new { @Class = "textarea" }) @Html.ValidationMessageFor(m => m.Fruits, "", new { @class = "text-danger" }) <div class="form-group"> <div class="col-md-offset-5 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> But when on click the <input type="submit" value="Create" class="btn btn-default" /> The form is validate and does not stop sending when the DDL has not selected any value. Without DDL the validation working correctly. Please, help me. My code below Model namespace InsGE.Models { public class PersonModel { [Required] [Display(Name = "Fruits")] public List<SelectListItem> Fruits { get; set; } public string Namex { get; set; } public string Codex { get; set; } [Required] [Display(Name = "CL")] public string CL { get; set; } [Required] [Display(Name = "Ticket")] public string Ticket { get; set; } } } Controller namespace InGE.Controllers { public class HomeController : Controller { private static List<SelectListItem> PopulateFruits() { string sql; List<SelectListItem> items = new List<SelectListItem>(); string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString; using (MySqlConnection con = new MySqlConnection(constr)) { sql = @String.Format("SELECT * FROM `dotable`; "); using (MySqlCommand cmd = new MySqlCommand(sql)) { cmd.Connection = con; con.Open(); using (MySqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { items.Add(new SelectListItem { Text = sdr["sName"].ToString(), Value = sdr["sCode"].ToString() }); } } con.Close(); } } return items; } [HttpPost] public ActionResult Index(PersonModel person) { string sCl = person.CL; string sTicket = person.Ticket; string sName = person.Namex; string sCode = person.Codex; return View(); } [HttpGet] public ActionResult Index() { PersonModel fruit = new PersonModel(); fruit.Fruits = PopulateFruits(); return View(fruit); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } update Controller public class HomeController : Controller { public class Fruit { public string Code { get; } public string Name { get; } public Fruit(string code, string name) { Code = code; Name = name; } } public class FruitsRepository { private static List<Fruit> GetAll() { string sql; var fruits = new List<Fruit>(); string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString; using (MySqlConnection con = new MySqlConnection(constr)) { sql = @String.Format("SELECT * FROM `dotable`; "); using (MySqlCommand cmd = new MySqlCommand(sql)) { cmd.Connection = con; con.Open(); using (MySqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { var fruit = new Fruit(sdr["sCode"].ToString(), sdr["sName"].ToString()); fruits.Add(fruit); } } con.Close(); } } return fruits; } } [HttpGet] public ActionResult Index() <<<<<< Error “not all code paths return a value” { var personModel = new PersonModel(); var fruitsRepo = new FruitsRepository(); var fruits = fruitsRepo.GetAll(); <<<<<< Error “is inaccessible due to its protection level” var fruitsSelecteListItems = fruits.Select(fruit => new SelectListItem { Text = fruit.Name; Value = fruit.Code; <<<<<< Error “The name 'Value' does not exist in the current context” }); return View(personModel); <<<<<<Error “The type or namespace name could not be found” } Model public class PersonModel { [Required] [Display(Name = "Fruits")] public string SelectedFruitCode { get; set; } public List<SelectListItem> Fruits { get; set; } public string Namex { get; set; } public string Codex { get; set; } [Required] [Display(Name = "CL")] public string CL { get; set; } [Required] [Display(Name = "Ticket")] public string Ticket { get; set; } } Complete View @using (Html.BeginForm("Index", "Home", FormMethod.Post)) { @Html.AntiForgeryToken() <div> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <table> <tr> <td class="textarea">CL</td> <td> @Html.TextBoxFor(m => m.CL, new { @Class = "textarea", placeholder = "CL" }) @Html.ValidationMessageFor(m => m.CL, "", new { @class = "text-danger" }) </td> <td class="textarea"></td> <tr> <td class="textarea">Ticket</td> <td> @Html.TextBoxFor(m => m.Ticket, new { @Class = "textarea", placeholder = "Ticket" }) @Html.ValidationMessageFor(m => m.Ticket, "", new { @class = "text-danger" }) </td> <td class="textarea"></td> <td class="textarea">Fruits</td> <td> @Html.DropDownListFor(m => m.SelectedFruitCode, Model.Fruits, "[ === Please select === ]", new { @Class = "textarea" }) @Html.ValidationMessageFor(m => m.SelectedFruitCode, "", new { @class = "text-danger" }) </td> </tr> </table> <br /> <hr class="new3"> <div class="form-group"> <div class="col-md-offset-5 col-md-10"> <input type="submit" value="Create" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> @section Scripts { @Scripts.Render("~/bundles/jqueryui") @Styles.Render("~/Content/cssjqryUi") <script type="text/javascript"> $(document).ready(function () { $('input[type=datetime]').datepicker({ dateFormat: "dd/mm/yy", changeMonth: true, changeYear: true, yearRange: "-2:+0" }); }); </script> } Complete Controller public class HomeController : Controller { [HttpPost] public ActionResult Index(PersonModel person) { if (ModelState.IsValid) { string cl = person.CL; string ticket = person.Ticket; } return View(); } public class Fruit { public string Code { get; } public string Name { get; } public Fruit(string code, string name) { Code = code; Name = name; } } public class FruitsRepository { public List<Fruit> GetAll() { string sql; var fruits = new List<Fruit>(); string constr = ConfigurationManager.ConnectionStrings["cnx"].ConnectionString; using (MySqlConnection con = new MySqlConnection(constr)) { sql = @String.Format("SELECT * FROM `dotable`; ") using (MySqlCommand cmd = new MySqlCommand(sql)) { cmd.Connection = con; con.Open(); using (MySqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { var fruit = new Fruit(sdr["sCode"].ToString(), sdr["sName"].ToString()); fruits.Add(fruit); } } con.Close(); } } return fruits; } } [HttpGet] public ActionResult Index() { var personModel = new PersonModel(); var fruitsRepo = new FruitsRepository(); var fruits = fruitsRepo.GetAll(); var fruitsSelecteListItems = fruits.Select(fruit => new SelectListItem { Text = fruit.Name, Value = fruit.Code }).ToList(); personModel.Fruits = fruitsSelecteListItems; return View(personModel); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } A: You need some changes. Let's start with database related code. Instead of mixing database related things (MySqlConnection, MySqlCommand etc.) with presentation layer things (SelectListItem, List<SelectListItem> etc.) and doing that also inside a Controller, you should * *Create a separate class for accessing the database and fetching the data. *The method that would be called should return a List of some kind of domain/entity object that would represent the Fruit. So, let's define initially our class, Fruit: public class Fruit { public string Code { get; } public string Name { get; } public Fruit(string code, string name) { Code = code; Name = name; } } Then let's create a class that would be responsible for accessing the database and fetch the fruits: public class FruitsRepository { public List<Fruits> GetAll() { string sql; var fruits = new List<Fruit>(); string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString; using (MySqlConnection con = new MySqlConnection(constr)) { sql = @String.Format("SELECT * FROM `dotable`; "); using (MySqlCommand cmd = new MySqlCommand(sql)) { cmd.Connection = con; con.Open(); using (MySqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { var fruit = new Fruit(sdr["sCode"].ToString(), sdr["sName"].ToString()); fruits.Add(fruit); } } con.Close(); } } return fruits; } } Normally, this class should implement an interface, in order we decouple the controller from the actual class that performs the database operations, but let's not discuss this at this point. Then at your controller: * *We should use the above class to fetch the fruits. *We should create a list of SelectListItem objects and you would provide that list to the model. *We should change the model, in a way that it would hold an info about the selected fruit (check below). *We should change the view. Changes in the model public class PersonModel { [Required] [Display(Name = "Fruits")] public string SelectedFruitCode { get; set; } public List<SelectListItem> Fruits { get; set; } public string Namex { get; set; } public string Codex { get; set; } [Required] [Display(Name = "CL")] public string CL { get; set; } [Required] [Display(Name = "Ticket")] public string Ticket { get; set; } } Changes in the View @Html.DropDownListFor(model => model.SelectedFruitCode, Model.Fruits, "[ === Please select === ]", new { @Class = "textarea" }) @Html.ValidationMessageFor(model => model.SelectedFruitCode, "", new { @class = "text-danger" }) Changes in the Controller [HttpGet] public ActionResult Index() { var personModel = new PersonModel(); // THIS IS **BAD CODE**...Normaly, you should create an interface that describes // what is expected from the class that communicates with the DB for operations // related with the Fruit and then inject the dependency in the HomeController // Constructor. var fruitsRepo = new FruitsRepository(); var fruits = fruitsRepo.GetAll(); var fruitsSelecteListItems = fruits.Select(fruit => new SelectListItem { Text = fruit.Name, Value = fruit.Code }).ToList(); personModel.Fruits = fruitsSelecteListItems; return View(personModel); } Please check thoroughly the comments in the code above ^^. As a starting point for that mentioned in the comments, you could see this. UPDATE We have also to change the post action: [HttpPost] public ActionResult Index(PersonModel person) { // Removed the Model.IsValid check since it's redundant in your case // Usually we use it and when it is valid we perform a task, like update // the corresponding object in the DB or doing something else. Otherwise, // we return a view with errors to the client. var fruitsRepo = new FruitsRepository(); var fruits = fruitsRepo.GetAll(); var fruitsSelecteListItems = fruits.Select(fruit => new SelectListItem { Text = fruit.Name, Value = fruit.Code, Selected = String.Equals(fruit.Code, person.SelectedFruitCode, StringComparison.InvariantCultureIgnoreCase) }).ToList(); person.Fruits = fruitsSelecteListItems; return View(person); }
{ "language": "en", "url": "https://stackoverflow.com/questions/64941538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Clustering lists having maximum overlap with size restriction I have the following group of numbers: group1: 12 56 57 58 59 60 61 62 63 64 75 89 91 100 105 107 108 Group Size: 40 group2: 56 57 60 71 72 73 74 91 92 93 94 100 105 107 108 110 111 Group Size: 30 group3: 57 58 91 107 108 110 112 114 117 118 120 127 129 139 184 Group Size: 15 group4: 1 2 4 6 7 8 9 10 17 18 20 41 42 43 45 47 Group Size: 40 group5: 57 58 91 201 205 207 210 212 214 216 217 218 219 220 221 225 Group Size: 30 . groupN: 50 51 52 53 54 210 214 216 219 225 700 701 702 705 706 708 Group Size: 40 Now I want to cluster together groups having maximum overlap such that after clustering, maximum size within a cluster does not exceed 90. For example here, the clusters are: (group1,group2,group3),(group5,groupN) and group4. The overlapping elements in the 3 groups are shown below: Cluster1: (group1,group2,group3): 57 91 107 108 Cluster Size: (Group1_size+group2_size+group3_size =85 <90) Cluster2: group4: 1 2 4 6 7 8 9 10 17 18 20 41 42 43 45 47 Cluster Size: (group4_size < 40) Cluster3: (group5,groupN): 201 214 216 219 225 Cluster Size: (group5_size + groupN_size 70 <90) If I include group5 in cluster1 then its size will be 85+30=115 and I want to return a size<90, therefore I can not include group4 in cluster1. The elements in the respective clusters after removing the duplicate overlapping elements are: Cluster1: (group1, group2, group3): 12 56 57 58 59 60 61 62 63 64 71 72 73 74 75 89 91 92 93 94 100 105 107 108 110 111 112 114 117 118 120 127 129 139 184 Cluster2: group4: 1 2 4 6 7 8 9 10 17 18 20 41 42 43 45 47 Cluster3: (group5,groupN): 50 51 52 53 54 57 58 91 201 205 207 210 212 214 216 217 218 219 220 221 225 700 701 702 705 706 708 Is there some existing algorithm or technique which may help me achieve this clustering with size constraint. I tried to form clusters by finding the common elements between any two groups and including in the group if cluster size after inclusion is <90. But is there any existing algorithm in any of the programming language libraries like C++,python,java which may help me achieve this efficiently. If not, then is there any existing algorithm which achieves the same. If possible, it will be great if the algorithm is optimal also. A: There is no easy optimal solution. One approximation is as follows: * *Pick the group with the largest size. Let its size be x *Pick the largest group such that its size is less than 90-x *Keep repeating step 2 until you cannot find such a group *Remove the selected groups and repeat the process starting from Step 1 Eg. You would pick group1 (or group4 or groupN) first is step 1. In step 2 you would pick group4. Now the size is 80 and there are no groups smaller than 90-80=10. So stop and remove these two groups. In the next iteration, you will select groupN, followed by group2, and at last group3. In the last iteration you have only one group, that is group5.
{ "language": "en", "url": "https://stackoverflow.com/questions/28560963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Float number and subquery I have query: SELECT DISTINCT `g`.`id` , `g`.`steam_id` , `g`.`type` , `g`.`title` , `g`.`price` , `g`.`metascore` , `g`.`image` , ( SELECT `id` FROM `game_promotions` WHERE `game_promotions`.`game_id` = `g`.`id` ) AS `promotion_id`, ( SELECT `price` FROM `game_promotions` WHERE `game_promotions`.`game_id` = `g`.`id` ) AS `promotion_price`, ( SELECT COUNT( `id` ) FROM `bot_games` WHERE `game_id` = `g`.`id` AND `buyer` IS NULL ) AS `copies` FROM `games` AS `g` , `game_genres` AS `gg` WHERE `gg`.`game_id` = `g`.`id` AND `g`.`title` LIKE "Counter%" GROUP BY `promotion_id` LIMIT 0 , 30 And problem is bad returned promotion_price. In game_promotions table, price is "24.99", but in query result promotion_price is "14.9899997711182". The returned promotion ID is good. Only float price is invalid. Why this number has changed? A: Ok, I'm not sure if this is exactly what you wanted, but I'm posting my modified query below. First of all, I got rid of the implicit join and changed it with an explicit INNER JOIN. I also moved your subquerys with LEFT JOINs for better performance. And I deleted the DISTINCT and the GROUP BY because I couldn't really understand why you needed them. SELECT `g`.`id` , `g`.`steam_id` , `g`.`type` , `g`.`title` , `g`.`price` , `g`.`metascore` , `g`.`image`, `gp`.`id` AS `promotion_id`, `gp`.`price` AS `promotion_price`, `bg`.`copies` FROM `games` AS `g` INNER JOIN `game_genres` AS `gg` ON `gg`.`game_id` = `g`.`id` LEFT JOIN `game_promotions` as `gp` ON `g`.`id` = `gp`.`game_id` LEFT JOIN ( SELECT `game_id`, COUNT(`id`) `copies` FROM `bot_games` WHERE `buyer` IS NULL GROUP BY `game_id`) `bg` ON `bg`.`game_id` = `g`.`id` WHERE `g`.`title` LIKE "Counter%" LIMIT 0 , 30 A: Do you mean the result is 24.9899997711182? That's within the single precision float margin of error. You get the expected result, you just have to round it to two decimals for display.
{ "language": "en", "url": "https://stackoverflow.com/questions/14781353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android videoview playable logo Hi my android coding have a videoview and I want to put playable logo overlay on it when it's stop but when it's playing the logo disappear, how can I do it? here is my coding on videoview final VideoView videoView = (VideoView)rootView.findViewById(R.id.videoview); videoView.setVideoURI(Uri.parse("android.resource://" + getActivity().getPackageName() + "/" + R.raw.complete)); videoView.setMediaController(new MediaController(getActivity().getApplicationContext())); videoView.requestFocus(); videoView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { if (videoView.isPlaying()) { videoView.pause(); } else { videoView.start(); } } return true; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/33819957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: new column is the sum of two consecutive rows please your gentile help, anyone can help me with pandas-python I need a new column, this new column is the sum of two consecutive rows, (figure) enter image description here A: You could look at the table.assign(<new column> = <formula>) function to build out your dataframe.
{ "language": "en", "url": "https://stackoverflow.com/questions/69730723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ProcessPoolExecuter and global variables I have a question regarding global variables and using different processes. For my main python script I have a main function which calls Initialize to initialize a global variable in Metrics.py. I've also created a getter function to retrieve this variable. Main.py: from Metrics import * import pprint def doMultiProcess(Files): result = {} with concurrent.futures.ProcessPoolExecutor() as executor: futures = [executor.submit(ProcessFile, file) for file in Files] for f in concurrent.futures.as_completed(futures): # future.result needs to be evaluated to catch any exception try: filename, distribution = f.result() result[filename] = {} result[filename] = distribution except Exception as e: pprint.pprint(e) return result Files = ["A.txt", "B.txt", "C.txt"] def main: Initialize() results = doMultiProcess(Files) if __name__ == '__name__': main() Metrics.py Keywords = ['pragma', 'contract'] def Initialize(): global Keywords Keywords= ['pragma', 'contract', 'function', 'is'] def GetList(): global Keywords # I believe this is not necessary. return Keywords def ProcessFile(filename): # Read data and extract all the words from the file, then determine the frequency # distribution of the words, using nltk.freqDist, which is stored in: freqDistTokens distribution = {keyword:freqDistTokens[keyword] for keyword in Keywords} return (filename, distribution) I hope I've simplified the example enough and not left out important information. Now, what I don't understand is why the processes keep working with the initial value of Keywords which contains 'pragma' and 'contract'. I call the initialize before actually running the processes and therefore should set the global variable to something different then the initial value, right? What am I missing that is happening here. I've worked around this by actually supplying the Keywords list to the process by using the GetList() function but I would like to understand as to why this is happening.
{ "language": "en", "url": "https://stackoverflow.com/questions/67765918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Clickable ImageView over List view i have a app that has a listview. I want to place a imageview over part of the listview. When i set the onclick Listener for the imageview nothing happens. How do i make it so that the imageview is clickable and not the area of the listview that overlaps with the imageview. the imageview "id/imagemenu" should be clickable xml: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <RelativeLayout android:layout_width="match_parent" android:layout_alignParentTop="true" android:layout_height="wrap_content" > <ImageView android:id="@+id/imagemenu" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_alignParentLeft="true" android:src="@drawable/menub" /> <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:src="@drawable/header" /> <ImageView android:id="@+id/imageView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:src="@drawable/camerab" /> </RelativeLayout> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" > </ListView> </RelativeLayout> A: You forgot to add selector, check this out. <ImageButton android:id="@+id/imageButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/selector" /> The corresponding selector file looks like this: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/ico_100_checked" android:state_selected="true"/> <item android:drawable="@drawable/ico_100_unchecked"/> </selector> And in my onCreate I call: final ImageButton ib = (ImageButton) value.findViewById(R.id.imageButton); OnClickListener ocl =new OnClickListener() { @Override public void onClick(View button) { if (button.isSelected()){ button.setSelected(false); } else { ib.setSelected(false); //put all the other buttons you might want to disable here... button.setSelected(true); } } }; ib.setOnClickListener(ocl); //add ocl to all the other buttons Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/21655962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Array stops working when i update the value of a key to 0 i have a code where sales are made on a sales modal(on an invoice page) with database entry.When a product for sale is selected, the pieces available for that product is entered into another input and on submission, the product id and pieces sold of the product is added to a session array.The purpose of this is because when sales are made it's added to a sales table on the invoice page, just in case the user decides to add too or subtract from the number of pieces of a particular product already on the sales table,let the sales modal (pieces available)input be up to date on the values to display instead of getting it from the database again. here is a sample of the code i use in making a sales db entry and setting session array values: $productPieces = get_productPiecesForSale();//fetches product pieces from db $product_id = $_POST['product_id'];//product id $pieces = $_POST['pieces_sold'];// pieces sold $invoice_id = $_SESSION['invoice_id']; $query = "SELECT * FROM sales WHERE product_id = '$id' AND invoice_id = '$invoice_id' LIMIT 1";// check if product is in the sales table already $sales_set = mysqli_query($connect,$query); $sales = mysqli_fetch_array($sales_set); if(isset($sales['sales_key'])){ $pieces_update = $pieces + $sales['pieces']; // adds db pieces to pieces sold if($pieces_update > $productPieces){ if(in_array($product_id, $_SESSION['pieces_available'])){ $key = array_search($product_id , $_SESSION['pieces_available']); $_SESSION['pieces_available'][$key+1] = '0'; } //so that pieces can't be sold above what is available $query = "UPDATE sales SET pieces = '{$productPieces}' WHERE product_id = '{$product_id }' LIMIT 1"; $sales_set = mysqli_query($connect,$query); }else{ if(in_array($product_id , $_SESSION['pieces_available'])){ $key = array_search($product_id , $_SESSION['pieces_available']); $_SESSION['pieces_available'][$key+1] = $productPieces - $pieces_update; } $query = "UPDATE sales SET pieces = '{$pieces_update}'' WHERE product_id = '{$product_id }' LIMIT 1"; $sales_set = mysqli_query($connect,$query); }//if($pieces_update > $productPieces){ }else{ $_SESSION['pieces_available'][] = $_POST['product_id']; $_SESSION['pieces_available'][] = $_POST['pieces_remaining']; $query = "INSERT INTO sales() VALUE()"; $sales_set = mysqli_query($connect,$query); } and here's the php code for my ajax i use to populate my sales form input if(isset($_GET['p'])){ $p = $_GET['p']; if(isset($_SESSION['pieces_available'])){//$_SESSION['pieces_available'] is set if(in_array($p, $_SESSION['pieces_available']) !== false){//product_id is in array $key = array_search($p, $_SESSION['pieces_available']); $pieces = $_SESSION['pieces_available'][$key+1]; echo $pieces; }else{//product_id is not in array $query = "SELECT pieces FROM products WHERE product_id = '{$p}' LIMIT 1"; $result_set = mysqli_query($connect, $query); $result = mysqli_fetch_array($result_set); echo $result['pieces']; } }else{//$_SESSION['pieces_available'] isn't set $query = "SELECT pieces FROM products WHERE product_id = '{$p}' LIMIT 1"; $result_set = mysqli_query($connect, $query); $result = mysqli_fetch_array($result_set); echo $result['pieces']; } } Everything works how i want it to work, until i update the pieces of a product already existing on the sale table that the pieces remaining now becomes 0, then my sales form stops displaying the pieces available for a selected product. If the pieces remaining becomes any other number this doesn't happen. well just in case let me add my ajax and html code: <html> <head> <script> function loadDoc2(str){ if (str == "") { document.getElementById("pieces_available").value = ""; return; } else { //Check for browsers if(window.XMLHttpRequest){ xhttp = new XMLHttpRequest(); }else{ xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //ajax onready xhttp.onreadystatechange = function(){ if(xhttp.readyState == 4 && xhttp.status == 200){ document.getElementById("pieces_available").value = xhttp.responseText; } }; xhttp.open("POST","url?p="+str,true); xhttp.send(); } } </script> </head> <body> <select id='product_id' onchange='loadDoc2(this.value)'> <option value=''>Choose products</option> </select> <input type='number' id='pieces_avaible' readonly/> <input type='number' id='pieces' placeholder='enter pieces for sale'/> </body> </html> Sales table screen shots: saleTable Sales modal screen shots: sale Modal
{ "language": "en", "url": "https://stackoverflow.com/questions/40070608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Push non-angular object to AngularJs controller scope I have a Angular controller that have a FormData scope, e.g: $scope.FormData. Data is collected via model connected to a simple form. Also, I have an external non-angular js code on the page. I need to push one of its variables to $scope.FormData.name. How can I do that? Already tried acces it as a global variable via $window, but no luck. Here is the example code: Angular code: app.controller('mainController', function ($scope, $http) { $scope.formData = {}; $scope.formData.day = "1"; $scope.formData.month = "January"; ... And non-angular code: var data = [{data1: value1}, {data2:value2}]; Binding this data to a model in a form is not a good option, because this is an object, so, I will get a string in a formData, like [Object, Object].
{ "language": "en", "url": "https://stackoverflow.com/questions/26120206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Connecting to Cassandra on startup, and monitoring session health Two related questions 1) Currently, the session to C* is established in a lazy fashion - aka, only on the first any table is accessed. Instead, we would like to establish a session as soon as the application is started (in case there is a connectivity problem, etc. ). What would be the best way to do that? Should I just get a session object in my startup code? connector.provider.session 2) How would I then monitor the health of the connection? I could call connector.provider.session.isClosed() but I'm not sure it will do the job. A: I wouldn't manually rely on that mechanism per say as you may want to get more metrics out of the cluster, for which purpose you have native JMX support, so through the JMX protocol you can look at metrics in more detail. Now obviously you have OpsCenter which natively leverages this feature, but alternatively you can use a combination of a JMX listener with something like Graphana(just a thought) or whatever supports native compatibility. In terms of low level methods, yes, you are on the money: connector.provider.session.isClosed() But you also have heartbeats that you can log and look at and so on. There's more detail here.
{ "language": "en", "url": "https://stackoverflow.com/questions/41686161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: R: order data frame according to one column I have a data like this > bbT11 range X0 X1 total BR GDis BDis WOE IV Index 1 (1,23] 5718 194 5912 0.03281461 12.291488 8.009909 0.42822753 1.83348973 1.534535 2 (23,26] 5249 330 5579 0.05915039 11.283319 13.625103 -0.18858848 0.44163352 1.207544 3 (26,28] 3105 209 3314 0.06306578 6.674549 8.629232 -0.25685394 0.50206815 1.292856 4 (28,33] 6277 416 6693 0.06215449 13.493121 17.175888 -0.24132650 0.88874916 1.272937 5 (33,37] 4443 239 4682 0.05104656 9.550731 9.867878 -0.03266713 0.01036028 1.033207 6 (37,41] 4277 237 4514 0.05250332 9.193895 9.785301 -0.06234172 0.03686928 1.064326 7 (41,46] 4904 265 5169 0.05126717 10.541702 10.941371 -0.03721203 0.01487247 1.037913 8 (46,51] 4582 230 4812 0.04779717 9.849527 9.496284 0.03652287 0.01290145 1.037198 9 (51,57] 4039 197 4236 0.04650614 8.682287 8.133774 0.06526000 0.03579599 1.067437 10 (57,76] 3926 105 4031 0.02604813 8.439381 4.335260 0.66612734 2.73386708 1.946684 I need to add an additional column "Bin" that will show numbers from 1 to 10, depending on BR column being in descending order, so for example 10th row becomes first, then first row becomes second, etc. Any help would be appreciated A: A very straightforward way is to use one of the rank functions from "dplyr" (eg: dense_rank, min_rank). Here, I've actually just used rank from base R. I've deleted some columns below just for presentation purposes. library(dplyr) mydf %>% mutate(bin = rank(BR)) # range X0 X1 total BR ... Index bin # 1 (1,23] 5718 194 5912 0.03281461 ... 1.534535 2 # 2 (23,26] 5249 330 5579 0.05915039 ... 1.207544 8 # 3 (26,28] 3105 209 3314 0.06306578 ... 1.292856 10 # 4 (28,33] 6277 416 6693 0.06215449 ... 1.272937 9 # 5 (33,37] 4443 239 4682 0.05104656 ... 1.033207 5 # 6 (37,41] 4277 237 4514 0.05250332 ... 1.064326 7 # 7 (41,46] 4904 265 5169 0.05126717 ... 1.037913 6 # 8 (46,51] 4582 230 4812 0.04779717 ... 1.037198 4 # 9 (51,57] 4039 197 4236 0.04650614 ... 1.067437 3 # 10 (57,76] 3926 105 4031 0.02604813 ... 1.946684 1 If you just want to reorder the rows, use arrange instead: mydf %>% arrange(BR) A: bbT11$Bin[order(bbT11$BR)] <- 1:nrow(bbT11)
{ "language": "en", "url": "https://stackoverflow.com/questions/27183110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Telebot package problem with importing "Types" When i want to run my bot in pycharm, I receive this error: \Desktop\st\taxi\taxi.py", line 5, in <module> from telebot import types ImportError: cannot import name 'types' from 'telebot' (C:\Users\User\Desktop\st\taxi\venv\lib\site-packages\telebot\__init__.py) Here is my code: import config from telebot import TeleBot, types bot = TeleBot(config.TELEGRAM_BOT_TOKEN) @bot.message_handler(commands=['location']) #Запрос локации def request_location(message): keyboard = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True) button_geo = types.KeyboardButton(text="Отправить местоположение", request_l ocation=True) keyboard.add(button_geo) bot.send_message(message.chat.id, "Поделись местоположением", reply_markup=k eyboard) if __name__ == "__main__": bot.polling() How to fix this?
{ "language": "en", "url": "https://stackoverflow.com/questions/52499589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: QtQuick2 Video rendering quality and embedding QVideoWidget to Qml I am working on a Qml application based on the QtQuick2, and I am having problems with the Video component included in the QtMultimedia 5.0 module. The application is supposed to add video to Qml interface and most importantly is that any BLACK color (background, rectangle or object) must be REALLY BLACK so I can overlay other Qml components over the black areas. When a video is played in the C++ QvideWidget, the video quality is good, and all the black area are really black, but when I use the QtQuick2 Video component, the quality is a little bit yellowish. I was able to do it easily in the Qt 4.8.7 with QtQuick1 using QDeclarativeItem and QGraphicProxyWidget, but since Qt5 changed the QtQuick2 way, I couldn't find a way to easily embedded widget. I have made a custom QAbstractVideoSurface and set it as QMediaPlay->setVideoOutput, and paint it in QtQuickPaintedItem by grabbing QImage and calling update(), but still same. Even changed all qRGB below treshold of 16 to qRgb(0,0,0), but the result is bad, especially on fade-in or fade-out. Is there any way I could fix this? Thanks in advance Edit 1: inserted code import QtQuick 2.6 import QtMultimedia 5.0 Video{ id: video width: root.width height: root.height property string src: "main.mp4" source: src autoLoad: true autoPlay: true fillMode: VideoOutput.PreserveAspectFit } C++ Code with QVideoWidget QMediaPlayer *player = new QMediaPlayer(); QVideoWidget *view = new QVideoWidget(); player->setVideoOutput(view); player->play(); view->resize(700, 700); view->show(); Custom QAbstractSurface #include "videoframegrabber.h" VideoFrameGrabber::VideoFrameGrabber(QObject *parent) : QAbstractVideoSurface(parent) , imageFormat(QImage::Format_Invalid) { } QList<QVideoFrame::PixelFormat> VideoFrameGrabber::supportedPixelFormats(QAbstractVideoBuffer::HandleType handleType) const { Q_UNUSED(handleType); return QList<QVideoFrame::PixelFormat>() << QVideoFrame::Format_ARGB32 << QVideoFrame::Format_ARGB32_Premultiplied << QVideoFrame::Format_RGB32 << QVideoFrame::Format_RGB24 << QVideoFrame::Format_RGB565 << QVideoFrame::Format_RGB555 << QVideoFrame::Format_ARGB8565_Premultiplied << QVideoFrame::Format_BGRA32 << QVideoFrame::Format_BGRA32_Premultiplied << QVideoFrame::Format_BGR32 << QVideoFrame::Format_BGR24 << QVideoFrame::Format_BGR565 << QVideoFrame::Format_BGR555 << QVideoFrame::Format_BGRA5658_Premultiplied << QVideoFrame::Format_AYUV444 << QVideoFrame::Format_AYUV444_Premultiplied << QVideoFrame::Format_YUV444 << QVideoFrame::Format_YUV420P << QVideoFrame::Format_YV12 << QVideoFrame::Format_UYVY << QVideoFrame::Format_YUYV << QVideoFrame::Format_NV12 << QVideoFrame::Format_NV21 << QVideoFrame::Format_IMC1 << QVideoFrame::Format_IMC2 << QVideoFrame::Format_IMC3 << QVideoFrame::Format_IMC4 << QVideoFrame::Format_Y8 << QVideoFrame::Format_Y16 << QVideoFrame::Format_Jpeg << QVideoFrame::Format_CameraRaw << QVideoFrame::Format_AdobeDng; } bool VideoFrameGrabber::isFormatSupported(const QVideoSurfaceFormat &format) const { const QImage::Format imageFormat = QVideoFrame::imageFormatFromPixelFormat(format.pixelFormat()); const QSize size = format.frameSize(); return imageFormat != QImage::Format_Invalid && !size.isEmpty() && format.handleType() == QAbstractVideoBuffer::NoHandle; } bool VideoFrameGrabber::start(const QVideoSurfaceFormat &format) { const QImage::Format imageFormat = QVideoFrame::imageFormatFromPixelFormat(format.pixelFormat()); const QSize size = format.frameSize(); if (imageFormat != QImage::Format_Invalid && !size.isEmpty()) { this->imageFormat = imageFormat; imageSize = size; sourceRect = format.viewport(); QAbstractVideoSurface::start(format); //widget->updateGeometry(); //updateVideoRect(); return true; } else { return false; } } void VideoFrameGrabber::stop() { currentFrame = QVideoFrame(); targetRect = QRect(); QAbstractVideoSurface::stop(); //widget->update(); } bool VideoFrameGrabber::present(const QVideoFrame &frame) { if (frame.isValid()) { QVideoFrame cloneFrame(frame); cloneFrame.map(QAbstractVideoBuffer::ReadOnly); const QImage image(cloneFrame.bits(), cloneFrame.width(), cloneFrame.height(), QVideoFrame::imageFormatFromPixelFormat(cloneFrame .pixelFormat())); emit frameAvailable(image); // this is very important cloneFrame.unmap(); } if (surfaceFormat().pixelFormat() != frame.pixelFormat() || surfaceFormat().frameSize() != frame.size()) { setError(IncorrectFormatError); stop(); return false; } else { currentFrame = frame; //widget->repaint(targetRect); return true; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/58048837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Logstash: Missing data after migration I have been migrating one of the indexes in self-hosted Elasticsearch to amazon-elasticsearch using Logstash. we have around 1812 documents in our self-hosted Elasticsearch but in amazon-elasticsearch, we have only about 637 documents. Half of the documents are missing after migration. Our logstash config file input { elasticsearch { hosts => ["https://staing-example.com:443"] user => "userName" password => "password" index => "testingindex" size => 100 scroll => "1m" } } filter { } output { amazon_es { hosts => ["https://example.us-east-1.es.amazonaws.com:443"] region => "us-east-1" aws_access_key_id => "access_key_id" aws_secret_access_key => "access_key_id" index => "testingindex" } stdout{ codec => rubydebug } } We have tried for some of the other indexes as well but it still migrating only half of the documents. A: Make sure to compare apples to apples by running GET index/_count on your index on both sides. You might see more or less documents depending on where you look (Elasticsearch HEAD plugin, Kibana, Cerebro, etc) and if replicas are taken into account in the count or not. In your case you had more replicas in your local environment than in your AWS Elasticsearch service, hence the different count.
{ "language": "en", "url": "https://stackoverflow.com/questions/58390552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Program that checks if number can be divided to three numbers I need to make a program that checks if a number can be divided to three(or more) numbers. for example 8=2*2*2 and 153=3*3*17 and so on. And it has to work for all positive real numbers. I just can't wrap my head around it :( def loytyyko_kolme_tekijaa(luku): tekija = 2 kaikki = 0 while luku > tekija: if luku % tekija == 0: kaikki = kaikki + 1 tekija = tekija + 1 if kaikki >= 3: return True else: return False A: Ok now that I see that you tried. Is this what you want? Copied answer from here: Python - Integer Factorization into Primes def factorize(num): for possible_factor in range(2, num): if num % possible_factor == 0: return [possible_factor] + factorize(num // possible_factor) return [num] nums = [8,153] for num in nums: print("{}: {}".format(num, factorize(num))) Returns: 8: [2, 2, 2] 153: [3, 3, 17]
{ "language": "en", "url": "https://stackoverflow.com/questions/46662206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: How do I fill a rectangle or ellipse with a gradient in Processing? I am trying to get my paddles from white to gradient (linear) and the ball to have a radial gradient. Thanks for your help!You can find the code for the paddles in void drawPaddle. This is my goal: This is my code: //Ball int ballX = 500; int ballY = 350; int ballHeight = 35; int ballWidth = 35; int speedX = 4; int speedY = 4; int directionX = 1; int directionY = 1; //Paddles int player1X = 30; int player2X = 830; int player1Y = 350; int player2Y = 350; //Healthbars int bar1X = 100; int bar1Y = 20; int player1health = 100; int bar1colour = #22E515; int bar2X = 700; int bar2Y = 20; int player2health = 100; int bar2colour = #22E515; //Movements boolean upX = false; boolean downX = false; boolean upY = false; boolean downY = false; void setup() { size(900, 700); } void draw() { background(55, 68, 120); drawPaddle(); //EmptySpace** fill(55, 68, 120); noStroke(); rect(player1X, player1Y, 40, 140); rect(player2X, player2Y, 40, 140); //Healthbars fill(bar1colour); rect(bar1X, bar1Y, player1health, 15); fill(bar2colour); rect(bar2X, bar2Y, player2health, 15); //Ball fill(194, 16, 0); ellipse(ballX, ballY, ballHeight, ballWidth); moveCircle(); movePaddle(); moveCollisions(); } void drawPaddle() { fill(255); noStroke(); rect(30, 0, 40, 1000); rect(830, 0, 40, 1000); } void moveCircle() { ballX = ballX + speedX * 1; ballY = ballY + speedY * 1; if (ballX > width- ballWidth +20 || ballX < ballWidth) { speedX *= -1; } if (ballY > height- ballHeight +20 || ballY < ballHeight) { speedY *= -1; } } void movePaddle() { //key movements if (upX == true) { player1Y = player1Y - 5; } if (downX == true) { player1Y = player1Y + 5; } if (upY == true) { player2Y = player2Y - 5; } if (downY == true) { player2Y = player2Y + 5; } //Wrap around if (player1Y > 700) { player1Y = 0; } else if (player1Y + 140 < 0) { player1Y = 700; } if (player2Y > 700) { player2Y = 0; } else if (player2Y + 140 < 0) { player2Y = 700; } } void moveCollisions() { //Collisions if ((ballX - ballWidth / 2 < player1X + 40) && ((ballY - ballHeight / 2 > player1Y + 140) || (ballY + ballHeight / 2 < player1Y))) { if (speedX < 0) { player1health -= 20; speedX = -speedX*1; if (player1health == 20) { bar1colour = #F51911; } } } else if ((ballX + ballWidth / 2 > player2X) && ((ballY - ballHeight / 2 > player2Y + 140) || (ballY + ballHeight/2 < player2Y))) { if (speedX > 0) { player2health -= 20; bar2X += 20; speedX = -speedX*1; if (player2health == 20) { bar2colour = #F51911; } } } } void keyPressed() { if (key == 'w' || key == 'W') { upX = true; } else if (key == 's' || key == 'S') { downX = true; } else if (keyCode == UP) { upY = true; } else if (keyCode == DOWN) { downY = true; } } void keyReleased() { if (key == 'w' || key == 'W') { upX = false; } else if (key == 's' || key == 'S') { downX = false; } else if (keyCode == UP) { upY = false; } else if (keyCode == DOWN) { downY = false; } } A: I wrote a library just for this kind of purpose (drawing colour gradients in Processing) called PeasyGradients — download the .jar from the Github releases and drag-and-drop it onto your sketch. It renders 1D gradients as 2D spectrums into your sketch or a given PGraphics object. Here's an example of drawing linear and radial spectrums using your desired gradient: PeasyGradients renderer; PGraphics rectangle, circle, circleMask; final Gradient pinkToYellow = new Gradient(color(227, 140, 185), color(255, 241, 166)); void setup() { size(800, 800); renderer = new PeasyGradients(this); rectangle = createGraphics(100, 400); renderer.setRenderTarget(rectangle); // render into rectangle PGraphics renderer.linearGradient(pinkToYellow, PI/2); // gradient, angle circle = createGraphics(400, 400); renderer.setRenderTarget(circle); // render into circle PGraphics renderer.radialGradient(pinkToYellow, new PVector(200, 200), 0.5); // gradient, midpoint, zoom // circle is currently a square image of a radial gradient, so needs masking to be circular circleMask = createGraphics(400, 400); circleMask.beginDraw(); circleMask.fill(255); // keep white pixels circleMask.circle(200, 200, 400); circleMask.endDraw(); circle.mask(circleMask); } void draw() { background(255); image(rectangle, 50, 50); image(circle, 250, 250); } A: What you can try is make a PGraphics object for each rectangle you are drawing, fill it with gradient color using linear interpolation and then instead of using rect(x1, y1, x2, y2), in drawPaddle() use image(pgraphic, x, y). Here is how you can create a gradient effect using lerpColor() in processing: * *Make a start point say (x1, y1) and end point say (x2, y2) of the gradient. *Make a starting and a ending color say c1 and c2. *Now for a point P (x, y), calculate the distance between start point and P and divide it by the distance between the start point and and end point. This will be the 'amount' to lerp from start color and end color. float t = dist(x1, y1, x, y) / dist(x1, x2, y1, y2) *Put this value in lerpColor() as lerpColor(c1, c2, value). This will give you the color for point P. *Repeat the same for every point you want to calculate the gradient for. Here's an example: Note: here, i am taking t which is the amount to be lerped as the distance between the starting point of gradient divided by the distance between the start and end point of gradient, as it will always be a value in between 0 and 1. PGraphics g = createGraphics(50, 200); // set these values to the size(width, height) of paddle you want color startColor = color(255, 25, 25); // color of start of the gradient color endColor = color(25, 25, 255); // color of end of the gradient g.beginDraw(); //start drawing in this as you would draw in the screen g.loadPixels();//load pixels, as we are going to set the color of this, pixel-by-pixel int x1 = g.width/2; int y1 = 0; int x2 = g.width/2; int y2 = g.height; // (x1, y1) is the start point of gradient // (x2, y2) is the end point of gradient // loop through all the pixels for (int x=0; x<g.width; x++) { for (int y=0; y<g.height; y++) { //amout to lerp, the closer this is to (x2, y2) it will get closer to endColor float t = dist(x1, y1, x, y) / dist(x1, y1, x2, y2); // you need to convert 2D indices to 1D, as pixels[] is an 1D array int index = x + y * g.width; g.pixels[index] = lerpColor(startColor, endColor, t); } } g.updatePixels(); // update the pixels g.endDraw(); // we are done drawing into this // Now, you can draw this using image(g, x, y); Here is the result when i created this in the global scope and then drew it in draw() using image(g, width/2 ,height/2): Now, you can modify everything to your preference. Please mark this as answer if it helped you in any way. A: Nice question and great mycycle and void main's answers are great already. The PeasyGradients library looks great! I would like to contribute a minor workaround: using the P2D renderer to handle the gradient via shapes: size(100,100,P2D);// render via OpenGL noStroke(); // draw the rect by manually setting vertices beginShape(); // gradient start fill(#fef1a6); vertex(0 , 0); // TL vertex(100, 0); // TR // gradient end fill(#e28ab9); vertex(100,100); // BR vertex( 0,100); // BL endShape(); For more complex shapes this could be used be used in conjuction with mask(). Not only PImage can be masked, but also PGraphics, since they inherit from PImage: PGraphics gradient; PGraphics mask; void setup() { size(640, 360, P2D); gradient = getGradientRect(width, height, #fef1a6, #e28ab9); mask = getMaskRect(width, height); } void draw() { background(#483b6c); drawPongShapes(); // apply pong shapes mask to gradient gradient.mask(mask); // render masked gradient image(gradient, 0, 0); } // draw white shapes (masks) on black background void drawPongShapes(){ mask.beginDraw(); mask.background(0); mask.ellipse(width * 0.5, height * 0.5, 60, 60); mask.rect(width * .25, mouseY, 30, 150); mask.rect(width * .75, height-mouseY, 30, 150); mask.endDraw(); } PGraphics getMaskRect(int w, int h) { PGraphics layer = createGraphics(w, h, P2D); layer.beginDraw(); layer.background(0); layer.noStroke(); layer.fill(255); layer.ellipseMode(CENTER); layer.rectMode(CENTER); layer.endDraw(); return layer; } PGraphics getGradientRect(int w, int h, color grad1, color grad2) { PGraphics layer = createGraphics(w, h, P2D); layer.beginDraw(); layer.noStroke(); // draw rect as shape quad layer.beginShape(); // gradient start layer.fill(grad1); layer.vertex(0, 0); // TL layer.vertex(w, 0); // TR // gradient end layer.fill(grad2); layer.vertex(w, h); // BR layer.vertex(0, h); // BL layer.endShape(); layer.endDraw(); return layer; }
{ "language": "en", "url": "https://stackoverflow.com/questions/65756931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Sass build issue for sublime text 2 : no file is generated I've downloaded Ruby and installed Sass. I then installed Sass Build for Sublime Text 2 through the package manager but when I try to build my css file, nothing happens. It says : [Decode error - output not utf-8] [Finished in 0.1s with exit code 1] Does anyone know how to fix this ? A: By default, the output encoding in a sublime build is utf-8. This will cause an error if there are non-utf-8 characters in your sass or scss. You can create a custom sass .sublime-build along the lines of the following by going to Tools > Build System > New Build System. { "cmd": ["sass", "--update", "$file:${file_path}/${file_base_name}.css", "--stop-on-error", "--no-cache"], "selector": "source.sass, source.scss", "line_regex": "Line ([0-9]+):", "osx": { "path": "/usr/local/bin:$PATH" }, "windows": { "shell": "true" } "encoding": "cp1252" } Note the key (the only one that'll be surplus from the installed package) "encoding": "cp1252". Its value will have to match that of your source or be a superset thereof. There's a fairly comprehensive list of codecs in the Python docs.
{ "language": "en", "url": "https://stackoverflow.com/questions/32000383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use PermissionRequiredMixin in FBV? I am thinking about how I can use PermissionRequiredMixin in FBV.(I have used the same in CBV and it is working as expected). Please find the FBV(here need to implement permission). I don't want to use @login_required() @login_required() This will check only if the user is authenticated or not. def delete_viewgen(request,PermissionRequiredMixin,id): oneuser=ShiftChange.objects.get(id=id) permission_required = ('abc.add_shiftchange',) oneuser.delete()# delete return redirect('/gensall') I am getting ERROR : missing 1 required positional argument: 'PermissionRequiredMixin' CBV Case where it is working fine. class ShiftChangeUpdateView(PermissionRequiredMixin,UpdateView): permission_required = ('abc.change_shiftchange',) login_url = '/login/' model=ShiftChange fields='__all__' In CBV it is working fine and if user is not having change permission it is giving 403 Forbidden how to implement same in FBV and also how to customize 403 Forbidden message. Thanks! A: On function based views you would use decorators, in your particular case permission_required decorator @permission_required('abc.change_shiftchange', raise_exception=True) delete_viewgen(request,id)
{ "language": "en", "url": "https://stackoverflow.com/questions/65650217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to extract year from a date variable and decrement it in XSL From the following XML, i have to extract the year 1989 and decrement it by 2 and display the year. <?xml version="1.0" encoding="UTF-8"?> <catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>10/10/1989</year> </cd> </catalog> XSL: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <xsl:variable name="num1" select="catalog/cd/year" /> <xsl:variable name="num2" select="2" /> --1989-2 value should be displayed here----- </body> </html> </xsl:template> </xsl:stylesheet> A: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <xsl:variable name="num1" select="substring(catalog/cd/year,string-length(catalog/cd/year) - 3)" /> I want last 4 characters, so I did a minus 3. If its last n characters, do minus n-1 <xsl:variable name="num2" select="2" /> <xsl:value-of select="$num1 - $num2" /> </body> </html> </xsl:template> </xsl:stylesheet>
{ "language": "en", "url": "https://stackoverflow.com/questions/30796417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Apache reverse proxy to nodejs server on CentOS 7 (WHM) I'm trying to setup my site on the server. I've uploaded it and it's currently running on the server but the problem comes when I try to setup a reverse proxy on the domain so that I can access the site. I had followed the WHM documentation on how to do a reverse proxy and it worked but it also redirected the subdomains. Below is the tutorial i followed for modifying an individual virtual host. https://docs.cpanel.net/ea4/apache/modify-apache-virtual-hosts-with-include-files/ In short, I'd like to be able to access my site, example.com, without affecting my subdomains, webmail.example.com. Below is my conf file ServerName example.com ServerAlias www.example.com ProxyRequests Off <Proxy *> Require all granted </Proxy> ProxyPass / http://127.0.0.1:3000/ ProxyPassReverse / http://127.0.0.1:3000/ And below is the default setting for the same virtual host I'm trying to change located in the httpd.conf file <VirtualHost 196.41.123.76:80> ServerName example.com ServerAlias mail.example.com www.example.com DocumentRoot /home/gusqooqw/public_html ServerAdmin webmaster@mtsd.co.za UseCanonicalName Off ## User gusqooqw # Needed for Cpanel::ApacheConf <IfModule userdir_module> <IfModule !mpm_itk.c> <IfModule !ruid2_module> <IfModule !mod_passenger.c> UserDir enabled gusqooqw </IfModule> </IfModule> </IfModule> </IfModule> # Enable backwards compatible Server Side Include expression parser for Apache versions >= 2.4. # To selectively use the newer Apache 2.4 expression parser, disable SSILegacyExprParser in # the user's .htaccess file. For more information, please read: # http://httpd.apache.org/docs/2.4/mod/mod_include.html#ssilegacyexprparser <IfModule include_module> <Directory "/home/gusqooqw/public_html"> SSILegacyExprParser On </Directory> </IfModule> <IfModule suphp_module> suPHP_UserGroup gusqooqw gusqooqw </IfModule> <IfModule suexec_module> <IfModule !mod_ruid2.c> SuexecUserGroup gusqooqw gusqooqw </IfModule> </IfModule> <IfModule ruid2_module> RMode config RUidGid gusqooqw gusqooqw </IfModule> <IfModule mpm_itk.c> # For more information on MPM ITK, please read: # http://mpm-itk.sesse.net/ AssignUserID gusqooqw gusqooqw </IfModule> <IfModule mod_passenger.c> PassengerUser gusqooqw PassengerGroup gusqooqw </IfModule> <IfModule alias_module> ScriptAlias /cgi-bin/ /home/gusqooqw/public_html/cgi-bin/ </IfModule> # Global DCV Rewrite Exclude <IfModule rewrite_module> RewriteOptions Inherit </IfModule> Include "/etc/apache2/conf.d/userdata/std/2_4/gusqooqw/example.com/*.conf" # To customize this VirtualHost use an include file at the following location # Include "/etc/apache2/conf.d/userdata/std/2_4/gusqooqw/example.com/*.conf" <VirtualHost> And below is the default webmail virtual host found in httpd.conf <VirtualHost 196.41.123.76:443> ServerName mtsd.co.za ServerAlias mail.mtsd.co.za www.mtsd.co.za cpcalendars.mtsd.co.za webdisk.mtsd.co.za webmail.mtsd.co.za cpcontacts.mtsd.co.za cpanel.mtsd.co.za DocumentRoot /home/gusqooqw/public_html ServerAdmin webmaster@mtsd.co.za UseCanonicalName Off ## User gusqooqw # Needed for Cpanel::ApacheConf <IfModule userdir_module> <IfModule !mpm_itk.c> <IfModule !ruid2_module> <IfModule !mod_passenger.c> UserDir enabled gusqooqw </IfModule> </IfModule> </IfModule> </IfModule> # Enable backwards compatible Server Side Include expression parser for Apache versions >= 2.4. # To selectively use the newer Apache 2.4 expression parser, disable SSILegacyExprParser in # the user's .htaccess file. For more information, please read: # http://httpd.apache.org/docs/2.4/mod/mod_include.html#ssilegacyexprparser <IfModule mod_include.c> <Directory "/home/gusqooqw/public_html"> SSILegacyExprParser On </Directory> </IfModule> <Proxymatch ^https?://127\.0\.0\.1:(2082|2083|2077|2078|2079|2080|2086|2087|2095|2096)/> <IfModule security2_module> SecRuleEngine Off </IfModule> </Proxymatch> IfModule mod_suphp.c> suPHP_UserGroup gusqooqw gusqooqw </IfModule> <IfModule suexec_module> <IfModule !mod_ruid2.c> SuexecUserGroup gusqooqw gusqooqw </IfModule> </IfModule> <IfModule ruid2_module> RMode config RUidGid gusqooqw gusqooqw </IfModule> <IfModule mpm_itk.c> # For more information on MPM ITK, please read: # http://mpm-itk.sesse.net/ AssignUserID gusqooqw gusqooqw </IfModule> <IfModule mod_passenger.c> PassengerUser gusqooqw PassengerGroup gusqooqw </IfModule> <IfModule alias_module> ScriptAlias /cgi-bin/ /home/gusqooqw/public_html/cgi-bin/ </IfModule> <IfModule ssl_module> SSLEngine on SSLCertificateFile /var/cpanel/ssl/apache_tls/mtsd.co.za/combined SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown <Directory "/home/gusqooqw/public_html/cgi-bin"> SSLOptions +StdEnvVars </Directory> </IfModule> Include "/etc/apache2/conf.d/userdata/ssl/2_4/gusqooqw/mtsd.co.za/*.conf" # To customize this VirtualHost use an include file at the following location # Include "/etc/apache2/conf.d/userdata/ssl/2_4/gusqooqw/mtsd.co.za/*.conf" <IfModule headers_module> RequestHeader set X-HTTPS 1 </IfModule> RewriteEngine On RewriteCond %{HTTP_HOST} =cpanel.mtsd.co.za [OR] RewriteCond %{HTTP_HOST} =cpanel.mtsd.co.za:443 RewriteCond %{HTTP:Upgrade} !websocket [nocase] RewriteRule ^/(.*) /___proxy_subdomain_cpanel/$1 [PT] ProxyPass "/___proxy_subdomain_cpanel" "http://127.0.0.1:2082" max=1 retry=0 RewriteCond %{HTTP_HOST} =cpcalendars.mtsd.co.za [OR] RewriteCond %{HTTP_HOST} =cpcalendars.mtsd.co.za:443 RewriteCond %{HTTP:Upgrade} !websocket [nocase] RewriteRule ^/(.*) /___proxy_subdomain_cpcalendars/$1 [PT] ProxyPass "/___proxy_subdomain_cpcalendars" "http://127.0.0.1:2079" max=1 retry=0 RewriteCond %{HTTP_HOST} =cpcontacts.mtsd.co.za [OR] RewriteCond %{HTTP_HOST} =cpcontacts.mtsd.co.za:443 RewriteCond %{HTTP:Upgrade} !websocket [nocase] RewriteRule ^/(.*) /___proxy_subdomain_cpcontacts/$1 [PT] ProxyPass "/___proxy_subdomain_cpcontacts" "http://127.0.0.1:2079" max=1 retry=0 RewriteCond %{HTTP_HOST} =webdisk.mtsd.co.za [OR] RewriteCond %{HTTP_HOST} =webdisk.mtsd.co.za:443 RewriteCond %{HTTP:Upgrade} !websocket [nocase] RewriteRule ^/(.*) /___proxy_subdomain_webdisk/$1 [PT] ProxyPass "/___proxy_subdomain_webdisk" "http://127.0.0.1:2077" max=1 retry=0 RewriteCond %{HTTP_HOST} =webmail.mtsd.co.za [OR] RewriteCond %{HTTP_HOST} =webmail.mtsd.co.za:443 RewriteCond %{HTTP:Upgrade} !websocket [nocase] RewriteRule ^/(.*) /___proxy_subdomain_webmail/$1 [PT] ProxyPass "/___proxy_subdomain_webmail" "http://127.0.0.1:2095" max=1 retry=0 RewriteCond %{HTTP:Upgrade} websocket [nocase] RewriteCond %{HTTP_HOST} =cpanel.mtsd.co.za [OR] RewriteCond %{HTTP_HOST} =cpanel.mtsd.co.za:443 RewriteRule ^/(.*) /___proxy_subdomain_ws_cpanel/$1 [PT] RewriteCond %{HTTP:Upgrade} websocket [nocase] RewriteCond %{HTTP_HOST} =webmail.mtsd.co.za [OR] RewriteCond %{HTTP_HOST} =webmail.mtsd.co.za:443 RewriteRule ^/(.*) /___proxy_subdomain_ws_webmail/$1 [PT] </VirtualHost> A: So after having contacted the cpanel support, they could not answer why the method I used above wasnt working and they gave an alternative solution. I ended up using an interface called Application manager on Cpanel. It's the easiest way of installing a nodejs application on a cpanel server. Below is the documentation on how to use it to run yourr application https://docs.cpanel.net/knowledge-base/web-services/how-to-install-a-node.js-application/ Hope this helps someone
{ "language": "en", "url": "https://stackoverflow.com/questions/61922650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How i can define schema for array using jsonloader? I am using elephantbird project to load a json file to pig. But i am not sure how i can define the schema at load. Did not find a description about the same. data: {"id":22522,"name":"Product1","colors":["Red","Blue"],"sizes":["S","M"]} {"id":22523,"name":"Product2","colors":["White","Blue"],"sizes":["M"]} code: feed = LOAD '$INPUT' USING com.twitter.elephantbird.pig.load.JsonLoader() AS products_json; extracted_products = FOREACH feed GENERATE products_json#'id' AS id, products_json#'name' AS name, products_json#'colors' AS colors, products_json#'sizes' AS sizes; describe extracted_products; result: extracted_products: {id: chararray,name: bytearray,colors: bytearray,sizes: bytearray} how i can give the correct schema to them (int,string,array,array) and how can i flatten array elements into rows? thanks in advance A: to convert json array to tuple: feed = LOAD '$INPUT' USING com.twitter.elephantbird.pig.load.JsonLoader() AS products_json; extracted_products = FOREACH feed GENERATE products_json#'id' AS id:chararray, products_json#'name' AS name:chararray, products_json#'colors' AS colors:{t:(i:chararray)}, products_json#'sizes' AS sizes:{t:(i:chararray)}; to flatten a tuple flattened = foreach extracted_products generate id,flatten(colors);
{ "language": "en", "url": "https://stackoverflow.com/questions/29500998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a password reset request in wordpress I'm trying to use postman to make a post request to reset the password, to the wordpress site. Here is what query is obtained as a result: https://example.com/wp-login.php?action=lostpassword&user_login=User123 And in the end I get the answer: ERROR: Enter a username or email address. How to make a request correctly and is it even possible? A: I got it! What OP did wrong was sending the user_login value in Postman's Params instead of form-data or x-www-form-urlencoded. Here is the working Postman request But that's not all. I am using Flutter for developing my mobile app and http package to send the request and the normal http.post() won't work. It only works with MultipartRequest for some reason. Here is the full working request for Flutter's http package. String url = "https://www.yourdomain.com/wp-login.php?action=lostpassword"; Map<String, String> headers = { 'Content-Type': 'multipart/form-data; charset=UTF-8', 'Accept': 'application/json', }; Map<String, String> body = { 'user_login': userLogin }; var request = http.MultipartRequest('POST', Uri.parse(url)) ..fields.addAll(body) ..headers.addAll(headers); var response = await request.send(); // forgot password link redirect on success if ([ 200, 302 ].contains(response.statusCode)) { return 'success'; } else { print(response.statusCode); throw Exception('Failed to send. Please try again later.'); }
{ "language": "en", "url": "https://stackoverflow.com/questions/49360250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a library for showing long text in one single TextView with different formatting? E.g. similar looking to what apps like Fabulous are doing. My use case it that I have a longer text stored online, which should then be retrieved and displayed. So I cannot style every single one with different TextViews and would like to have something with tags or so inside. Maybe something like that? But doesn't seem to be usable as a library. I have looked for something in the Android must have libraries but no results. A: I think I found something really close to what I wanted with this library: SRML: "String Resource Markup Language"
{ "language": "en", "url": "https://stackoverflow.com/questions/55171948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Graphics.fillArc(); is not working properly I have written this java code for drawing a filled arc whose endpoint angle increases by 1 in each iteration of loop from 0 to 360 degrees, but this is not working properly so please help. import java.awt.Color; import java.awt.FlowLayout; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; public class A { public static void main(String arg[]) throws Exception { JFrame f = new JFrame(); f.setExtendedState(JFrame.MAXIMIZED_BOTH); f.setUndecorated(true); f.setVisible(true); f.getContentPane().setBackground(Color.BLACK); f.setLayout(new FlowLayout()); Circle c; for(int i=0; i<=360; i++) { c = new Circle(-i); f.add(c); Thread.sleep(6); f.getContentPane().remove(c); f.getContentPane().revalidate(); f.getContentPane().repaint(); } } } class Circle extends JPanel { int angle; public Circle(int angle) { this.angle=angle; } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.RED); g.fillArc(50, 50, 100, 100, 90, angle); } } A: I won't list all the errors that you have in your code. I fixed most of them. import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class Scratch { public static void main(String arg[]) throws Exception { JFrame f = new JFrame(); f.setSize(600, 600); f.setVisible(true); f.getContentPane().setBackground(Color.BLACK); f.setLayout(new BorderLayout()); for(int i=0; i<=360; i++) { final int fi = i; SwingUtilities.invokeLater(new Runnable() { public void run() { f.getContentPane().removeAll(); Circle c = new Circle(-fi); f.add(c); f.getContentPane().revalidate(); f.getContentPane().repaint(); } }); try { Thread.sleep(100); } catch (InterruptedException ie) { } } } } class Circle extends JPanel { int angle; public Circle(int angle) { this.angle=angle; } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.WHITE); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.RED); g.fillArc(50, 50, 100, 100, 0, angle); } } I recommend you to have one component that updates it's image rather than removing / adding different components.
{ "language": "en", "url": "https://stackoverflow.com/questions/25310033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Popup when a new message arrives I have a fully functioning messaging system on my website. I want to evolve this by having a box popup altering members when they have a new message. It would say something like "You have a new message, would you like to view?". You would be able to click Yes or No. How would I go about doing this? Never tried anything like this before! Thanks UPDATE. I am very inexperienced using the technologies required here. How would I go about ensuring this works on every page? What code would I include? This is something I need to improve on as it opens up so many more possibilities! A: You can have a looping AJAX call in the background that checks every few minutes. If the server returns a URL (or something distinguishable from "no messages") then you'll get the popup, and if they hit OK, are sent to the URL (using a basic confirm() dialog in Javascript). Be careful though, the users patience will wear thin if you munch their CPU power on this. A: You'd have to check regulary with the server if a new message is present for the user, using a timer in your javascript (so clientside code). Due to the nature of HTTP (it being stateless) it is not possible to push this notification from the server. A: You have 3 options: * *Show the message every time the user reloads the page. Easy and fast. *Show the message by sending AJAX requests to the server. Can be really bad when you have many users, so make sure the response take very little time. *Send the message from the server using WebSocket. Most up-to-date technology, but it's only supported in a few browsers, so check the compatibility issues before implementing it. I'd personally use #1, if I don't need instant user reaction. #2 is good for web chatting. #3 is universal, but rarely used yet. Normally you would have an AJAX script in the background, running with long timeout (30+ seconds), and functionality that shows the message after page reload. This combines #1 and #2. A: Firstly you should look at the following: http://stanlemon.net/projects/jgrowl.html you should load jQuery + jGrowl and create a heartbeat function which polls the server every X seconds like. When the server receives a request from the JavaScript you check the database for the latest messages marked un_notified (not read) You compile a list and mark them notified, and then send the list to the JavaScript again, this in turn gets passed to jGrowl and notifications are show,
{ "language": "en", "url": "https://stackoverflow.com/questions/4575944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: racket postfix to prefix I have a series of expressions to convert from postfix to prefix and I thought that I would try to write a program to do it for me in DrRacket. I am getting stuck with some of the more complex ones such as (10 (1 2 3 +) ^). I have the very simple case down for (1 2 \*) → (\* 1 2). I have set these expressions up as a list and I know that you have to use cdr/car and recursion to do it but that is where I get stuck. My inputs will be something along the lines of '(1 2 +). I have for simple things such as '(1 2 +): (define ans '()) (define (post-pre lst) (set! ans (list (last lst) (first lst) (second lst)))) For the more complex stuff I have this (which fails to work correctly): (define ans '()) (define (post-pre-comp lst) (cond [(pair? (car lst)) (post-pre-comp (car lst))] [(pair? (cdr lst)) (post-pre-comp (cdr lst))] [else (set! ans (list (last lst) (first lst) (second lst)))])) Obviously I am getting tripped up because (cdr lst) will return a pair most of the time. I'm guessing my structure of the else statement is wrong and I need it to be cons instead of list, but I'm not sure how to get that to work properly in this case. A: Were you thinking of something like this? (define (pp sxp) (cond ((null? sxp) sxp) ((list? sxp) (let-values (((args op) (split-at-right sxp 1))) (cons (car op) (map pp args)))) (else sxp))) then > (pp '(1 2 *)) '(* 1 2) > (pp '(10 (1 2 3 +) ^)) '(^ 10 (+ 1 2 3)) A: Try something like this: (define (postfix->prefix expr) (cond [(and (list? expr) (not (null? expr))) (define op (last expr)) (define args (drop-right expr 1)) (cons op (map postfix->prefix args))] [else expr])) This operates on the structure recursively by using map to call itself on the arguments to each call.
{ "language": "en", "url": "https://stackoverflow.com/questions/27346338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenSSL::SSL::SSLError at /auth/facebook/callback with omniauth I'm dealing with the OpenSLL error on windows, using omniauth. I've tried specifying the cacert.pem file. It is placed in my_app_dir\assets\cacert.pem (downloaded from the curl website), and provider :facebook, APP_ID, SECRET, {:client_options => {:ssl => {:ca_file => File.dirname(__FILE__) << "assets\cacert.pem"}}} does not work. I still get the OpenSSL Error. I decided that I don't need my windows machine to verify as I will be deploying to a linux server anyway, so for now I wanted to set it to not verify at all: SCOPE = 'email,read_stream' APP_ID = "2XXXXXXXXXXXXX" SECRET = "4XXXXXXXXXXXXXXXXXXXXXXX" use OmniAuth::Builder do provider :facebook, APP_ID, SECRET, {:client_options => {:ssl => {:verify => false}}} end I still get the error. At this point, I don't really care whether or not it uses a certificate (I would prefer it do), I need to get it to work so that I can get past this roadblock. The specific error says: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed What can I do to fix this? A: Try following the instructions given in this link: http://jimneath.org/2011/10/19/ruby-ssl-certificate-verify-failed.html And you have to make this minor change in fix_ssl.rb at the end: self.ca_file = Rails.root.join('lib/ca-bundle.crt').to_s I hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/9969661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Login working in localhost but error "secret option required for sessions" when deployed in Heroku My authentification works properly on localhost but gives me error 500 when deployed on Heroku. Error: {"type":"error","error":{"message":"secret option required for sessions"}} I have my secret session on a .env file that is ignored by .gitignore when pushing (maybe I should change that?) Heroku Logs: 2019-10-23T17:22:22.682593+00:00 heroku[router]: at=info method=GET path="/manifest.json" host=apppack-demo.herokuapp.com request_id=bb235945-cb82-4168-91ce-fd19d2109801 fwd="85.240.87.39" dyno=web.1 connect=0ms service=2ms status=304 bytes=237 protocol=https 2019-10-23T17:22:22.793594+00:00 heroku[router]: at=info method=GET path="/logo192.png" host=apppack-demo.herokuapp.com request_id=8a1d2243-45c9-4919-b2ad-3ee8f9148d9c fwd="85.240.87.39" dyno=web.1 connect=0ms service=2ms status=304 bytes=238 protocol=https 2019-10-23T17:22:35.594349+00:00 heroku[router]: at=info method=POST path="/api/signup" host=apppack-demo.herokuapp.com request_id=43907374-4de3-4658-92ce-9188f03e1624 fwd="85.240.87.39" dyno=web.1 connect=0ms service=3ms status=500 bytes=300 protocol=https 2019-10-23T17:22:35.592607+00:00 app[web.1]: POST /api/signup 500 1.206 ms - 74 A: I recently had this issue with my app. I was getting the 'Error: secret option required for sessions' ONLY when deployed to Heroku. Here is what my code looked like originally: app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false })) When I deployed to Heroku it kept giving me an "Internal server error". Once checking the logs, it showed me 'Error: secret option required for sessions'. Here is how I fixed it: app.use(session({ secret: 'secretidhere', resave: false, saveUninitialized: false })) Since my .env file wasn't viewable and that's where I had my secret code, it was giving me that error. Now, just by putting an arbitrary string 'secretidhere', I deployed to heroku again and it worked! ** However, please note that this should not be a permanent solution. As the poster above states, you should have a config file in your root directory, or another method so this session stays secret. Hope this helps! A: I was facing the same issue while I was deploying my code into AWS Elastic BeanStalk. In .env we could have - secret='my_secret' While in server.js: app.use(cookieParser()) app.use(session({ resave:true, saveUninitialized:true, secret:process.env.secret, cookie:{maxAge:3600000*24} })) The solution turned out to be adding secret to the environments in there. Just add it to your enviroments for production, be it heroku or AWS. A: Have you added your secret session from your .env file to heroku config? Since your .env is in your .gitignore it will not be pushed up to heroku. Your code is looking for a string from your process.env but the heroku environment does not have it yet. You have two solutions * *Go to your app console and click on settings. Once you are there, click on the box that says reveal config vars and add your secret there. or *In the root directory of your project you can set your config vars there using the command heroku config:set SECRET_SESSION="secretName"
{ "language": "en", "url": "https://stackoverflow.com/questions/58528070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: java.lang.LinkageError: loader constraint violation: when resolving field "MAX_HEADER_SIZE" I receive this error when I try to deploy my war on Wildfly 10.1.0.Final (I cannot change wildfly version) 18:53:58,467 WARN [org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext] (ServerService Thread Pool -- 78) Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field "MAX_HEADER_SIZE" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type 18:53:58,493 INFO [org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener] (ServerService Thread Pool -- 78) Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 18:53:58,536 ERROR [org.springframework.boot.SpringApplication] (ServerService Thread Pool -- 78) Application run failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field "MAX_HEADER_SIZE" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:628) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:175) at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:155) at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:97) at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:174) at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:186) at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:171) at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42) at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:234) at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:100) at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) at org.jboss.threads.JBossThread.run(JBossThread.java:320) Caused by: java.lang.LinkageError: loader constraint violation: when resolving field "MAX_HEADER_SIZE" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type at org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer.customize(UndertowWebServerFactoryCustomizer.java:81) at org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer.customize(UndertowWebServerFactoryCustomizer.java:59) at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.lambda$postProcessBeforeInitialization$0(WebServerFactoryCustomizerBeanPostProcessor.java:72) at org.springframework.boot.util.LambdaSafe$Callbacks.lambda$null$0(LambdaSafe.java:287) at org.springframework.boot.util.LambdaSafe$LambdaSafeCallback.invoke(LambdaSafe.java:159) at org.springframework.boot.util.LambdaSafe$Callbacks.lambda$invoke$1(LambdaSafe.java:286) at java.util.ArrayList.forEach(ArrayList.java:1257) at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1082) at org.springframework.boot.util.LambdaSafe$Callbacks.invoke(LambdaSafe.java:286) at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.postProcessBeforeInitialization(WebServerFactoryCustomizerBeanPostProcessor.java:72) at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.postProcessBeforeInitialization(WebServerFactoryCustomizerBeanPostProcessor.java:58) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:440) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ... 34 more 18:53:58,543 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 78) MSC000001: Failed to start service jboss.undertow.deployment.default-server.default-host."/custom-crm-ticket-0.0.1-SNAPSHOT": org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host."/custom-crm-ticket-0.0.1-SNAPSHOT": java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field "MAX_HEADER_SIZE" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:85) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run(Thread.java:748) at org.jboss.threads.JBossThread.run(JBossThread.java:320) Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field "MAX_HEADER_SIZE" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:236) at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:100) at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:82) ... 6 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field "MAX_HEADER_SIZE" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:628) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:175) at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:155) at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:97) at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:174) at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:186) at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:171) at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42) at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44) at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:234) ... 8 more Caused by: java.lang.LinkageError: loader constraint violation: when resolving field "MAX_HEADER_SIZE" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type at org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer.customize(UndertowWebServerFactoryCustomizer.java:81) at org.springframework.boot.autoconfigure.web.embedded.UndertowWebServerFactoryCustomizer.customize(UndertowWebServerFactoryCustomizer.java:59) at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.lambda$postProcessBeforeInitialization$0(WebServerFactoryCustomizerBeanPostProcessor.java:72) at org.springframework.boot.util.LambdaSafe$Callbacks.lambda$null$0(LambdaSafe.java:287) at org.springframework.boot.util.LambdaSafe$LambdaSafeCallback.invoke(LambdaSafe.java:159) at org.springframework.boot.util.LambdaSafe$Callbacks.lambda$invoke$1(LambdaSafe.java:286) at java.util.ArrayList.forEach(ArrayList.java:1257) at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1082) at org.springframework.boot.util.LambdaSafe$Callbacks.invoke(LambdaSafe.java:286) at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.postProcessBeforeInitialization(WebServerFactoryCustomizerBeanPostProcessor.java:72) at org.springframework.boot.web.server.WebServerFactoryCustomizerBeanPostProcessor.postProcessBeforeInitialization(WebServerFactoryCustomizerBeanPostProcessor.java:58) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:440) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620) ... 34 more 18:53:58,560 ERROR [org.jboss.as.controller.management-operation] (DeploymentScanner-threads - 1) WFLYCTL0013: Operation ("deploy") failed - address: ([("deployment" => "custom-crm-ticket-0.0.1-SNAPSHOT.war")]) - failure description: { "WFLYCTL0080: Failed services" => {"jboss.undertow.deployment.default-server.default-host.\"/custom-crm-ticket-0.0.1-SNAPSHOT\"" => "org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host.\"/custom-crm-ticket-0.0.1-SNAPSHOT\": java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field \"MAX_HEADER_SIZE\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field \"MAX_HEADER_SIZE\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field \"MAX_HEADER_SIZE\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type Caused by: java.lang.LinkageError: loader constraint violation: when resolving field \"MAX_HEADER_SIZE\" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type"}, "WFLYCTL0412: Required services that are not installed:" => ["jboss.undertow.deployment.default-server.default-host.\"/custom-crm-ticket-0.0.1-SNAPSHOT\""], "WFLYCTL0180: Services with missing/unavailable dependencies" => undefined } 18:53:58,665 INFO [org.jboss.as.server] (DeploymentScanner-threads - 1) WFLYSRV0010: Deployed "custom-crm-ticket-0.0.1-SNAPSHOT.war" (runtime-name : "custom-crm-ticket-0.0.1-SNAPSHOT.war") 18:53:58,666 INFO [org.jboss.as.controller] (DeploymentScanner-threads - 1) WFLYCTL0183: Service status report WFLYCTL0186: Services which failed to start: service jboss.undertow.deployment.default-server.default-host."/custom-crm-ticket-0.0.1-SNAPSHOT": org.jboss.msc.service.StartException in service jboss.undertow.deployment.default-server.default-host."/custom-crm-ticket-0.0.1-SNAPSHOT": java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'undertowServletWebServerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/ServletWebServerFactoryConfiguration$EmbeddedUndertow.class]: Initialization of bean failed; nested exception is java.lang.LinkageError: loader constraint violation: when resolving field "MAX_HEADER_SIZE" the class loader (instance of org/jboss/modules/ModuleClassLoader) of the referring class, io/undertow/UndertowOptions, and the class loader (instance of org/jboss/modules/ModuleClassLoader) for the field's resolved type, org/xnio/Option, have different Class objects for that type This is my pom <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.hpe.du</groupId> <artifactId>custom-crm-ticket</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>custom-crm-ticket</name> <description>custom ticketing</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20220320</version> </dependency> <dependency> <groupId>javax.jms</groupId> <artifactId>javax.jms-api</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>javax.jms</groupId> <artifactId>jms</artifactId> <version>1.1</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.wildfly</groupId> <artifactId>wildfly-jms-client-bom</artifactId> <version>10.1.0.Final</version> <type>pom</type> </dependency> <dependency> <groupId>org.wildfly</groupId> <artifactId>wildfly-naming-client</artifactId> <version>1.0.15.Final</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> I tried also to change the pom as following <dependency> <groupId>org.wildfly</groupId> <artifactId>wildfly-jms-client-bom</artifactId> <version>10.1.0.Final</version> <type>pom</type> <exclusions> <exclusion> <groupId>org.jboss.xnio</groupId> <artifactId>xnio-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.wildfly</groupId> <artifactId>wildfly-naming-client</artifactId> <version>1.0.15.Final</version> <exclusions> <exclusion> <groupId>org.jboss.xnio</groupId> <artifactId>xnio-api</artifactId> </exclusion> </exclusions> </dependency> The Error disappear, and the war deployed, but when I call the REST, I receive the error 19:02:49,017 ERROR [stderr] (Thread-133) Exception in thread "Thread-133" java.lang.NoClassDefFoundError: org/xnio/Options 19:02:49,021 ERROR [stderr] (Thread-133) at org.jboss.naming.remote.client.InitialContextFactory.<clinit>(InitialContextFactory.java:92) 19:02:49,022 ERROR [stderr] (Thread-133) at java.lang.Class.forName0(Native Method) 19:02:49,025 ERROR [stderr] (Thread-133) at java.lang.Class.forName(Class.java:348) 19:02:49,027 ERROR [stderr] (Thread-133) at org.jboss.as.naming.InitialContext.getDefaultInitCtx(InitialContext.java:113) 19:02:49,032 ERROR [stderr] (Thread-133) at org.jboss.as.naming.InitialContext.init(InitialContext.java:99) 19:02:49,034 ERROR [stderr] (Thread-133) at javax.naming.ldap.InitialLdapContext.<init>(InitialLdapContext.java:154) 19:02:49,046 ERROR [stderr] (Thread-133) at org.jboss.as.naming.InitialContext.<init>(InitialContext.java:89) 19:02:49,049 ERROR [stderr] (Thread-133) at org.jboss.as.naming.InitialContextFactory.getInitialContext(InitialContextFactory.java:43) 19:02:49,060 ERROR [stderr] (Thread-133) at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:684) 19:02:49,063 ERROR [stderr] (Thread-133) at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313) 19:02:49,064 ERROR [stderr] (Thread-133) at javax.naming.InitialContext.init(InitialContext.java:244) 19:02:49,065 ERROR [stderr] (Thread-133) at javax.naming.InitialContext.<init>(InitialContext.java:216) 19:02:49,066 ERROR [stderr] (Thread-133) at com.hpe.du.customcrmticket.JMSUtils.customTTJMSCommunication.elaborateRequest(customTTJMSCommunication.java:100) 19:02:49,066 ERROR [stderr] (Thread-133) at com.hpe.du.customcrmticket.customCrmTicketController.lambda$createTT$0(customCrmTicketController.java:36) 19:02:49,067 ERROR [stderr] (Thread-133) at java.lang.Thread.run(Thread.java:748) 19:02:49,072 ERROR [stderr] (Thread-133) Caused by: java.lang.ClassNotFoundException: org.xnio.Options from [Module "deployment.custom-crm-ticket-0.0.1-SNAPSHOT.war:main" from Service Module Loader] 19:02:49,093 ERROR [stderr] (Thread-133) at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:198) 19:02:49,094 ERROR [stderr] (Thread-133) at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:363) 19:02:49,095 ERROR [stderr] (Thread-133) at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:351) 19:02:49,096 ERROR [stderr] (Thread-133) at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:93) 19:02:49,097 ERROR [stderr] (Thread-133) ... 15 more I don't understand why without exclusions there is this error, but with the exclusion it needs the dependecy A: I solved the problem in this way in pom.xml I excluded xnio-api (as in the question) <dependency> <groupId>org.wildfly</groupId> <artifactId>wildfly-jms-client-bom</artifactId> <version>10.1.0.Final</version> <type>pom</type> <exclusions> <exclusion> <groupId>org.jboss.xnio</groupId> <artifactId>xnio-api</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.wildfly</groupId> <artifactId>wildfly-naming-client</artifactId> <version>1.0.15.Final</version> <exclusions> <exclusion> <groupId>org.jboss.xnio</groupId> <artifactId>xnio-api</artifactId> </exclusion> </exclusions> </dependency> Then I created jboss-deployment-structure.xml under webapp/WEB-INF folder, with this content <jboss-deployment-structure> <ear-subdeployments-isolated>true</ear-subdeployments-isolated> <deployment> <dependencies> <module name="org.jboss.xnio" /> </dependencies> </deployment> </jboss-deployment-structure> now the WAR is deployed with no problems Hope this help
{ "language": "en", "url": "https://stackoverflow.com/questions/73337657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to overwrite ScrollView content in ios or change focus I'm beginner in ios .... In One of my activity I have created Custom scrollView and on it I have created Some custom textField ..Now when we click on textField then my custom tableView opens but this table mixup with already existing textField ....If I add this table on UIView then it does not scroll ......so how to overwrite on scroll view textField and scroll tabel with textField.....I Have Declared all table delegates and table appears properly but on scroll problem occur .... scrollview=[[UIScrollView alloc]initWithFrame:CGRectMake(0,60,320,540)]; [scrollview setContentSize:CGSizeMake(800,1500)]; scrollview.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight); scrollview.autoresizesSubviews = YES; scrollview.scrollEnabled = YES; scrollview.delegate = self; scrollview.directionalLockEnabled = YES; scrollview.showsVerticalScrollIndicator = YES; scrollview.showsHorizontalScrollIndicator = YES; scrollview.autoresizesSubviews = YES; scrollview.backgroundColor=[UIColor whiteColor]; [self.view addSubview:scrollview]; AdviseDr=[[UITextField alloc]initWithFrame:CGRectMake(150,110,140,30)]; AdviseDr.font = [UIFont boldSystemFontOfSize:15.0]; AdviseDr.borderStyle = UITextBorderStyleLine; AdviseDr.clearButtonMode = UITextFieldViewModeWhileEditing; AdviseDr.delegate =self; AdviseDr.tag=1; [scrollview addSubview:AdviseDr]; table_AdviseDoctor=[[UITableView alloc]initwithframe:CGRectMake(150,200,170,200)style:UITableViewStylePlain]; table_AdviseDoctor.delegate=self; table_AdviseDoctor.dataSource=self; table_AdviseDoctor.layer.borderWidth = 2.0; table_AdviseDoctor.layer.borderColor = [UIColor grayColor].CGColor; [self.view addSubview:table_AdviseDoctor]; table_AdviseDoctor.hidden=YES; Medicalfacility=[[UITextField alloc]initWithFrame:CGRectMake(150,150,170,30)]; Medicalfacility.font = [UIFont boldSystemFontOfSize:15.0]; Medicalfacility.borderStyle = UITextBorderStyleLine; Medicalfacility.delegate =self; Medicalfacility.tag=2; [scrollview addSubview:Medicalfacility]; [Medicalfacility addTarget:self action:@selector(btnpress1:)forControlEvents:UIControlEventEditingDidBegin]; A: The Better option is that when you clicked on UITextField at that time also hide your UITextField so your UITextField is not mixup with your UITableView and when You remove/hide your UITableView at that time your hidden UITextField again unHide( give hidden = NO). Other wise there are many ways for solve your problem, i like this option so i suggest you. Other Option is. Take your UITableView in UIView, i hope that you have already know that UITableView have its own ScrollView so you not need to put in/over any scrollView. And when you click on UITextFiled that are in UIScrollView at that time you also put restriction that user can not do with UIScrollView and UITextField also (give userInteraction = NO). so also give (give userInteraction = YES) when your UITableView is hide. A: UserInteraction is right for but You know when we write this [self.view addsubview:Table_AdviseDoctor] then ....when we scroll already and then click on text field then my table open long below from required position then we write code UserInteraction.enable=No; then scroll not work this right but first scroll and then click on text filed then ..problem occur not right position .....
{ "language": "en", "url": "https://stackoverflow.com/questions/17424615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: using array offsets to calculate delta in numpy I need to create delta and growth rate with a lot of data points. I'm new to numpy but I see it can do internal operations like this. (Pdb) data = np.array([11,22,33,44,10,3]) (Pdb) data + data array([22, 44, 66, 88, 20, 6]) Is it possible to add data offsets in numpy array operations? Like this delta calculation. (Pdb) [data[i] - data[i-2] for i in range(2,len(data))] [22, 22, -23, -41] (Pdb) [data[i] - data[i-1] for i in range(1,len(data))] [11, 11, 11, -34, -7]
{ "language": "en", "url": "https://stackoverflow.com/questions/63081854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to generate a signed certificate with an existing CA which has a different key pair? I create a signed certificate with an existing CA as I explained in this post: Bouncy Castle: Signed Certificate with an existing CA However, my generated certificate has the same public and private keys that the CA certificate. Is it possible to generate a certificate which has another key pair? I have tried the example code in the following post but my pdf signature is invalid: Generating X509 Certificate using Bouncy Castle Java I will appreciate any comment or information that can help me. Thanks in advance. A: A public key certificate (PKC) will have the same key pair (public key) as the issuer only if the certificate is a self signed one. It's always possible for a CA to issue a certificate for another key-pair, in which case the new certificate will have the public key of the new key-pair and will be signed by the CA's private key. The subject of this new certificate can in turn be made a CA (through BasicConstraint extension and KeyUsage extension) in which case the new key-pair can be used to issue yet other certificates, thus creating a certificate path or chain. Please see the following code snippet. public static X509Certificate getCertificte(X500Name subject, PublicKey subjectPublicKey, boolean isSubjectCA, X509Certificate caCertificate, PrivateKey caPrivateKey, String signingAlgorithm, Date validFrom, Date validTill) throws CertificateEncodingException { BigInteger sn = new BigInteger(64, random); X500Name issuerName = new X500Name(caCertificate.getSubjectDN().getName()); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded()); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerName, sn, validFrom, validTill, subject, subjectPublicKeyInfo); JcaX509ExtensionUtils extensionUtil; try { extensionUtil = new JcaX509ExtensionUtils(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("No provider found for SHA1 message-digest"); } // Add extensions try { AuthorityKeyIdentifier authorityKeyIdentifier = extensionUtil.createAuthorityKeyIdentifier(caCertificate); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier); SubjectKeyIdentifier subjectKeyIdentifier = extensionUtil.createSubjectKeyIdentifier(subjectPublicKey); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyIdentifier); BasicConstraints basicConstraints = new BasicConstraints(isSubjectCA); certBuilder.addExtension(Extension.basicConstraints, true, basicConstraints); } catch (CertIOException e) { throw new RuntimeException("Could not add one or more extension(s)"); } ContentSigner contentSigner; try { contentSigner = new JcaContentSignerBuilder(signingAlgorithm).build(caPrivateKey); } catch (OperatorCreationException e) { throw new RuntimeException("Could not generate certificate signer", e); } try { return new JcaX509CertificateConverter().getCertificate(certBuilder.build(contentSigner)); } catch (CertificateException e) { throw new RuntimeException("could not generate certificate", e); } } Please note the arguments: subjectPublicKey: public key corresponding to the new key-pair for which a new certificate will be issued. caCertificate: CA certificate which corresponds to the key-pair of the current CA. caPrivateKey: private key of the CA (private key corresponding to the caCertificate above). This will be used to sign the new certificate. isSubjectCA: a boolean indicating whether the new certificate holder (subject) will be acting as a CA. I have omitted keyUsage extensions for brevity, which should be used to indicate what all purposes the public key corresponding to the new cert should be used.
{ "language": "en", "url": "https://stackoverflow.com/questions/51921657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to check if an element has a class in cypress.io? I don't want to test that it has the class like ...should('have.class', "some-class") I just want know if it does, and if doesn't then perform some action that gives it that class. Basically, I want to see if the element has Mui-checked and if it doesn't them programmatically check it. A: You can use the hasClass() jquery method for this: cy.get('selector').then(($ele) => { if ($ele.hasClass('foo')) { //Do something when you have the class } else { //Do something when you don't have the class } }) A: Add the class like this. You don't need to check the condition since $el.addClass() works either way. cy.get('selector').then($el => $el.addClass("blue")) A: You can retrieve the class attribute with should() and check that it contains your class, something like: cy.get('.selector') .should('have.attr', 'class') .and('contain', 'some-class');
{ "language": "en", "url": "https://stackoverflow.com/questions/71385871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: BigQuery: DDL statement not executing via client API I am executing CREATE TABLE IF NOT EXIST via client API using following JobConfigurationQuery: queryConfig.setUseLegacySql(false) queryConfig.setFlattenResults(false) queryConfig.setQuery(query) As I am executing CREATE TABLE DDL, I cannot specify destination table, write dispositions, etc. In my Query History section of Web UI, I see job being executed successfully without any exceptions, and with no writes happening. Is DDL statement not supported via client API? I am using following client: "com.google.apis" % "google-api-services-bigquery" % "v2-rev397-1.23.0" A: From BigQuery docs which says it seems that no error is returned when table exists: The CREATE TABLE IF NOT EXISTS DDL statement creates a table with the specified options only if the table name does not exist in the dataset. If the table name exists in the dataset, no error is returned, and no action is taken. Answering your question, DDL is supported from API which is also stated in doc, to do this: Call the jobs.query method and supply the DDL statement in the request body's query property.
{ "language": "en", "url": "https://stackoverflow.com/questions/51551968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Concurrency, Locking in SQL Server Database I have a requirement to Save/Update data in 15 tables. I have to ensure at the time of updation the concurrency and locking should be maintained, so that no dirty read happens. I am updating data using storeed procedure. What I can do in oredr to implement locking and concurrency? A: Other answers are assuming that you are already using a transaction. I won't omit this, since you might be missing it. You should use a transaction to ensure that records in all 15 tables or none are inserted/updated. The transaction ensures you atomicity in your operation. If something fails during the stored procedure and you don't use a transaction, some of the save/update operations will be made, and some not (the ones from the query that has produced the error). If you use BEGIN TRAN, and COMMIT for successful operations or ROLLBACK in case of failure, you will get all done or nothing. You should check for errors after each query execution, and call ROLLBACK TRANSACTION if there is one, or call COMMIT at the end of the stored procedure. There is a good sample in the accepted answer of this Stackoverflow question on how to handle transaction inside a stored procedure. Once you have the transaction, the second part is how to avoid dirty reads. You can set the isolation level of your database to READ COMMITED, this will prevent, by default, dirty reads on your data. But the user can still chose to do dirty reads by specifying WITH (NOLOCK) or READUNCOMMITED in his query. You cannot prevent that. Besides, there are the snapshot isolation levels (Snapshot and Read Commited Snapshot) that could prevent locking (which is not always good), avoiding dirty reads at the same time. There is a lot of literature on this topic over the internet. If you are interested in snapshot isolation levels, I suggest you to read this great article from Kendra Little at Brent Ozar. A: You can't prevent that dirty read does not happen. Is the reader that does the dirty reads, not you (the writer). All you can do is ensure that your write is atomic, and that is accomplished by wrapping all writes in a single transaction. This way readers that do not issue dirty reads will see either all your updates, either none (atomic). If a reader chooses to issue dirty reads there's nothing you can do about it. Note that changing your isolation level has no effect whatsoever on the reader's isolation level. A: All you need to do to ensure that the sql server isolation level is set appropriately. To eliminate dirty reads, it needs to be at Read Committed or higher, (Not at Read Uncommitted). Read Committed is the default setting out of the box. It might be worth while, however, to review the link above and see what benefits, (and consequences) the higher settings provide. A: You can set the transaction isolation level to SERIALIZABLE. by using the following statement SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; Before you BEGIN TRANSACTION but Warning it can slow down other user who will be try to see on update or insert data into your tables, Your can also make use of the SNAP_SHOT Isolation Level which shows you only the last Commited/Saved data but it makes extensive use of Temp DB which can also effect the performance.
{ "language": "en", "url": "https://stackoverflow.com/questions/19361525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Highlighting when HTML and Xpath is given Given the HTML as a string, the Xpath and offsets. I need to highlight the word. In the below case I need to highlight Child 1 HTML text: <html> <body> <h2>Children</h2>Joe has three kids:<br/> <ul> <li> <a href="#">Child 1 name</a> </li> <li>kid2</li> <li>kid3</li> </ul> </body> </html> XPATH as : /html/body/ul/li[1]/a[1] Offsets: 0,7 Render - I am using react in my app. The below is what I have done so far. public render(){ let htmlText = //The string above let doc = new DOMParser().parseFromString(htmlRender,'text/html'); let ele = doc.evaluate("/html/body/ul/li[1]/a[1]", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); //This gives the node itself let spanNode = document.createElement("span"); spanNode.className = "highlight"; spanNode.appendChild(ele); // Wrapping the above node in a span class will add the highlights to that div //At this point I don't know how to append this span to the HTML String return( <h5> Display html data </h5> <div dangerouslySetInnerHTML={{__html: htmlText}} /> ) I want to avoid using jquery. Want to do in Javascript(React too) if possible! Edit: So if you notice the Render function it is using dangerouslySetHTML. My problem is I am not able manipulate that string which is rendered. A: This is what I ended up doing. public render(){ let htmlText = //The string above let doc = new DOMParser().parseFromString(htmlRender,'text/html'); let xpathNode = doc.evaluate("/html/body/ul/li[1]/a[1]", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); const highlightedNode = xpathNode.singleNodeValue.innerText; const textValuePrev = highlightedNode.slice(0, char_start); const textValueAfter = highlightedNode.slice(char_end, highlightedNode.length); xpathNode.singleNodeValue.innerHTML = `${textValuePrev} <span class='pt-tag'> ${highlightedNode.slice(char_start, char_end)} </span> ${textValueAfter}`; return( <h5> Display html data </h5> <div dangerouslySetInnerHTML={{__html: doc.body.outerHTML}} /> ) A: Xpath is inherently cross component, and React components shouldn't know much about each other. Xpath also basically requires all of the DOM to be created in order to query it. I would render your component first, then simply mutate the rendered output in the DOM using the Xpath selector. https://jsfiddle.net/69z2wepo/73860/ var HighlightXpath = React.createClass({ componentDidMount() { let el = document.evaluate(this.props.xpath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); el.singleNodeValue.style.background = 'pink'; }, render: function() { return this.props.children; } }); Usage: <HighlightXpath xpath="html//body//div/p/span"> ... app ... </HighlightXpath>
{ "language": "en", "url": "https://stackoverflow.com/questions/42869993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Setting up a Git repository for a .NET solution I have a solution with 15 C# projects and I'm trying to set up an efficient git repository for them. Should I create a repository on that level or for each project under the solution? WebServices/ |- WebServices.sln |- WebService1/ `- WebService1.csproj |- WebService2/ `- WebService2.csproj The solution has a project reference to ../framework/framework.csproj which is a seperate repository and all the other projects have a reference to. The projects under the solution are not linked in any way, but they all use the framework. I would like any changes to the framework would be passed to the projects. Do you have any guide for me how to achieve that in the best possible way? A: There is no one answer to how to set up your repository. It depend on your specific needs. Some questions you should ask yourself include: * *Are all projects going to be released and versioned separately? *Are the projects really independent of each other? *How is your development team structured? Do individual developers stick to a single project? *Is your framework project stable? *Does your build process build each project separately? Assuming that the answers to all of the above is "yes", then I would set it up like so: * *Continue maintaining the framework code in its own repository, and publish it to an internal server using NuGet (as suggested in ssube's comment). *Create a separate repository for each project, each with their own solution file. If you can say "yes" to all except #5 (and possibly #1), above, then I would add one more repository that consists of submodules of each of the individual projects and a global solution file that your build server can use. If you add a new project, you have to remember to also update this repository! If you have to say "no" to #2, then just build a single repository. If you have to say "no" to #3, then you'll have to make a judgement call, between separation of the code and developers' need to switch between repos. You could create a separate repository including submodules, but if all your developers wind up using that repo, you are really only introducing new maintenance with little gain. If your framework is not stable (#4), then you may want to include that as a submodule in any of these cases. I recommend that once it becomes stable, then you look into removing the submodule and switching to NuGet at that time. A: What i have done for such a situation was the following. Note that in my case there were 2-3 developers. So i have 3 things in this: * *The empty project structure that i would like to replicate [OPTIONAL] *The common library projects *The actual end projects that use common library projects 1) I just create my scaffold development directory structure and i am putting a .gitkeep file in each and everyone of them in order for git to include it. In this way when i want to setup myself in a new pc i just clone this and i have my empty development "universe" structure. Then i populate (git clone) with the projects i need. 2) The common libraries project is just a normal repo. 3) My end projects reference the common library projects. There are prons and cons about it and depends on your situation, but i what i gain is that i can change the common libraries either directly from the common library project, or from the end project which references it. In both ways i get the changes in git and commit normally and separately. In your case i would have my empty structure and then do 2 separate clones. The framework project in the correct place and then the entire webservices repo. Its up to you if you want to have a separate repo for each web service or one for all. It depends on your person count and work flow. Also do not forget a proper .gitignore Here: LINK A: If * *you really want to have all projects in the same solution *the common project "Framework" is in active development (and some modifications for one project could break others...) i think you must have each WebService as a git project with his own copy of Framework project as submodule: WebServices/ |- WebServices.sln |- WebService1/ `|-.git |-WebService1.csproj |-Framework (as submodule) |- WebService2/ `|-.git |-WebService2.csproj\ |-Framework (as submodule) This way each WebService will use the Framework version that is compatible with. (of course you must be aware of git submodule workings... you could read for example this, specially the section "Issues with Submodules"!) Important: with this configuration each deployed webservice must reference the Framework library with the actual version it is using! A: Depending on "how independent" development going to be for each of your projects you might consider two option. * *in case you are mostly working on entire solution - create one repo for entire solution *in case some projects are really independent , create separate repos for those projects and create solution file for each project aside project file, then use git submodules to reference those repos in the repo of the main solution, that make use of those projects. Git Submodules Tips
{ "language": "en", "url": "https://stackoverflow.com/questions/23414771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Does Akka Decider have access to the full failure scenario? New to Akka. Creating a new Scala class that extends SupervisorStrategy gives me the following template to work with: class MySupervisorStrategy extends SupervisorStrategy { override def decider: Decider = ??? override def handleChildTerminated(context: ActorContext, child: ActorRef, children: Iterable[ActorRef]): Unit = ??? override def processFailure(context: ActorContext, restart: Boolean, child: ActorRef, cause: Throwable, stats: ChildRestartStats, children: Iterable[ChildRestartStats]): Unit = ??? } I'm looking for a way to access: * *The Throwable/Exception that was thrown from the child actor *The child actor ActorRef that threw the exception *The message that was passed to the child actor that prompted the exception to be thrown I think the Decider (which is actually a PartialFunction[Throwable,Directive]) gets passed the Throwable whenever the child throws the exception, but I'm not seeing where I could get access to #2 and #3 from my list above. Any ideas? Update From the posted fiddle, it looks like a valid Decider is: { case ActorException(ref,t,"stop") => println(s"Received 'stop' from ${ref}") Stop case ActorException(ref,t,"restart") => println(s"Received 'restart' from ${ref}") Restart case ActorException(ref,t,"resume") => println(s"Received 'resume' from ${ref}") Resume } Above, I see all three: * *The exception that was thrown by the child *The child (ref) that threw the exception *The message that was sent to the child originally (that caused the exception to be thrown) It looks like there's nothing in that Decider that needs to be defined inside that Supervisor class. I'd like to pull the Decider logic out into, say, MyDecider.scala and find a way to refactor the Supervisor so that its supervisorStrategy uses an instance of MyDecider, so maybe something similar to: class Supervisor extends Actor { import akka.actor.OneForOneStrategy import akka.actor.SupervisorStrategy._ import scala.concurrent.duration._ var child: ActorRef = _ override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute, decider = myDecider) ... } A: For #2 you could access the sender "if the strategy is declared inside the supervising actor" If the strategy is declared inside the supervising actor (as opposed to within a companion object) its decider has access to all internal state of the actor in a thread-safe fashion, including obtaining a reference to the currently failed child (available as the sender of the failure message). The message is not made available so the only option is to catch your exception and throw a custom one with the message that was received. Here is a quick fiddle class ActorSO extends Actor { def _receive: Receive = { case e => println(e) throw new RuntimeException(e.toString) } final def receive = { case any => try { _receive(any) } catch { case t:Throwable => throw new ActorException(self,t,any) } } } Update A Decider is just a PartialFunction so you can pass it in the constructor. object SupervisorActor { def props(decider: Decider) = Props(new SupervisorActor(decider)) } class SupervisorActor(decider: Decider) extends Actor { override val supervisorStrategy = OneForOneStrategy()(decider) override def receive: Receive = ??? } class MyDecider extends Decider { override def isDefinedAt(x: Throwable): Boolean = true override def apply(v1: Throwable): SupervisorStrategy.Directive = { case t:ActorException => Restart case notmatched => SupervisorStrategy.defaultDecider.apply(notmatched) } } object Test { val myDecider: Decider = { case t:ActorException => Restart case notmatched => SupervisorStrategy.defaultDecider.apply(notmatched) } val myDecider2 = new MyDecider() val system = ActorSystem("stackoverflow") val supervisor = system.actorOf(SupervisorActor.props(myDecider)) val supervisor2 = system.actorOf(SupervisorActor.props(myDecider2)) } By doing so, you won't be able to access supervisor state like the ActorRef of the child that throw the exception via sender() (although we are including this in the ActorException) Regarding your original question of accessing from the supervisor the child message that cause the exception, you can see here (from akka 2.5.3) that the akka developers choose to not make it available for decision. final protected def handleFailure(f: Failed): Unit = { // ¡¡¡ currentMessage.message is the one that cause the exception !!! currentMessage = Envelope(f, f.child, system) getChildByRef(f.child) match { /* * only act upon the failure, if it comes from a currently known child; * the UID protects against reception of a Failed from a child which was * killed in preRestart and re-created in postRestart */ case Some(stats) if stats.uid == f.uid ⇒ // ¡¡¡ currentMessage.message is not passed to the handleFailure !!! if (!actor.supervisorStrategy.handleFailure(this, f.child, f.cause, stats, getAllChildStats)) throw f.cause case Some(stats) ⇒ publish(Debug(self.path.toString, clazz(actor), "dropping Failed(" + f.cause + ") from old child " + f.child + " (uid=" + stats.uid + " != " + f.uid + ")")) case None ⇒ publish(Debug(self.path.toString, clazz(actor), "dropping Failed(" + f.cause + ") from unknown child " + f.child)) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/50353738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to install packages with conda into /usr/bin/python3 I have a package, that is only downloadable with conda. When I startup a shell and type which python3, I get /home/usr/miniconda3/bin/python. Then I do conda deactivate and my python3 is /usr/bin/python3. Is there any chance to install packages from conda, so that the python-interpreter in that location finds them?
{ "language": "en", "url": "https://stackoverflow.com/questions/60789708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Map newlines in GHCi Simple question, but I can't seem to figure it out. I have a list, and I want to print out each element of it on its own line. I can do map show [1..10] for example, which will print out them all together, but with no newlines. My thought was to do map (putStrLn $ show) [1..10] but this won't work because I just get back an [IO()]. Any thoughts? A: Aren't these answers putting too much emphasis on IO? If you want to intersperse newlines the standard Prelude formula is : > unlines (map show [1..10]) "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n" This is the thing you want written - newlines are characters not actions, after all. Once you have an expression for it, you can apply putStrLn or writeFile "Numbers.txt" directly to that. So the complete operation you want is something like this composition: putStrLn . unlines . map show In ghci you'd have > (putStrLn . unlines . map show) [1,2,3] 1 2 3 A: Try this: mapM_ (putStrLn . show) [1..10] A: Here is my personal favourite monad command called sequence: sequence :: Monad m => [m a] -> m [a] Therefore you could totally try: sequence_ . map (putStrLn . show) $ [1..10] Which is more wordy but it leads upto a function I find very nice (though not related to your question): sequence_ . intersperse (putStrLn "") Maybe an ugly way to do that but I thought it was cool.
{ "language": "en", "url": "https://stackoverflow.com/questions/5149916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google Maps API Drawing Rectangle This is the meat of the code I am using and I am not getting errors, but I am not seeing the points that are in the area of the rectangle. Any help would be appreciated: `enter code here`/** @this {google.maps.Rectangle} */ function showNewRect(event) { var ne = rectangle.getBounds().getNorthEast(); var sw = rectangle.getBounds().getSouthWest(); google.maps.event.addlistener(rectangle, "bounds_changed", function(){ document.getElementById("map-selected").innerHTML=rectangle.getBounds(); var rectA = (ne*sw); }) } function listSelected () { var inside = $.map( sites, function ( s ) { var d; if ( ( (d = google.maps.geometry.poly.containsLocation( s.position )) <= rectA ) ) return s.location + ' ('+(Math.round(d/100)/10)+' km)'; $('#map-selected').html( inside.sort().join('') ); }); } google.maps.event.addListener(drawingManager, 'rectanglecomplete', function( rectangle ) { selectedArea = rectangle; listSelected(); google.maps.event.addListener(rectangle, 'center_changed', listSelected); google.maps.event.addListener(rectangle, 'bounds_changed', listSelected);I am working with the Google maps API and I have a map I am drawing on with a rectangle. I need to have a user draw the rectangle, and on the map there will be predefined locations, that when the rectangle crosses the locations there will be details of each location put into a list. This is an example: http://hmoodesigns.com/ksi/ I have an example using the circle draw tool, which I can get to work fine, but the rectangle tool I have not been able to have this identify the points on the map. How can I check for these points without having a predefined rectangle on the page? Thanks, A: When the Rectangle has been drawn iterate over the locations and use the method contains() of the Rectangle's bounds to test if the LatLng's are within the bounds of the Rectangle
{ "language": "en", "url": "https://stackoverflow.com/questions/23618188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: PHP DomDocument appendChildNode where I have tags in the text I would like to append some text to a dom element as a child node. The problem is that in the text I can have tags as <i>, <bold> etc. Actually, with this method: private function appendChildNode($dom_output, $cit_node, $nodeName, $nodeText) { if ($nodeText != null && $nodeText != "" ) { $node = $dom_output->createElement($nodeName); $node->appendChild($dom_output->createTextNode($nodeText)); $cit_node->appendChild($node); return $node; } } When I have tags in the $nodeText, then the <i> will be converted to &lt;i&gt; and so on. How can I append this text by keeping the tags as they are? Thank you. A: I managed to find the solution. Thanks to this post: DOMDocument append already fixed html from string I did: private function appendChildNode($dom_output, $cit_node, $nodeName, $nodeText) { if ($nodeText != null && $nodeText != "" ) { $node = $dom_output->createElement($nodeName); $fragment = $dom_output->createDocumentFragment(); $fragment->appendXML( $nodeText); $node->appendChild($fragment); $cit_node->appendChild($node); return $node; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/22009512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to type "line1", "line2", "line3".... using for loop in python For example, I want to generate below output using a "for" loop, having the for loop automatically populate the number at the end of the word line: line1 line2 line3 line4 line5 line6 line7 A: Here is how to do it with "f-strings" and the range() class object in a for loop: for_loop_basic_demo.py: #!/usr/bin/python3 END_NUM = 7 for i in range(1, END_NUM + 1): print(f"line{i}") Run command: ./for_loop_basic_demo.py Output: line1 line2 line3 line4 line5 line6 line7 Going further: 3 ways to print The 3 ways I'm aware of to print formatted strings in Python are: * *formatted string literals; AKA: "f-strings" *the str.format() method, or *the C printf()-like % operator Here are demo prints with all 3 of those techniques to show each one for you: #!/usr/bin/python3 END_NUM = 7 for i in range(1, END_NUM + 1): # 3 techniques to print: # 1. newest technique: formatted string literals; AKA: "f-strings" print(f"line{i}") # 2. newer technique: `str.format()` method print("line{}".format(i)) # 3. oldest, C-like "printf"-style `%` operator print method # (sometimes is still the best method, however!) print("line%i" % i) print() # print just a newline char Run cmd and output: eRCaGuy_hello_world/python$ ./for_loop_basic_demo.py line1 line1 line1 line2 line2 line2 line3 line3 line3 line4 line4 line4 line5 line5 line5 line6 line6 line6 line7 line7 line7 References: * ****** This is an excellent read, and I highly recommend you read and study it!: Python String Formatting Best Practices *Official Python documentation for all "Built-in Functions". Get used to referencing this: https://docs.python.org/3/library/functions.html * *The range() class in particular, which creates a range object which allows the above for loop iteration: https://docs.python.org/3/library/functions.html#func-range A: You can use f strings.\ n = 7 for i in range(1, n + 1): print(f"line{i}")
{ "language": "en", "url": "https://stackoverflow.com/questions/71376733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Getting Facebook Access Token from User Id and Facebook App Secret? I'm trying to understand how the facebook api works. The end goal is to be able to read the posts from a facebook page. If someone has connected with my app on facebook can my c# application then get the posts from a public facebook page if it knows their facebook account id (and has the facebook app secret hard coded). If so what are the http requests it needs to make in order to get the access token which can then be used to get the posts, and what are the requests to get a new access token before one expires? If you could provide an example in c# (maybe using the acebooksdk.net library) that would be great! Thanks. A: The way to do it was using "The Login Flow for Web (without JavaScript SDK)" api to get a user access token. A user access token is required to be sent with graph api queries in order to get page posts. The first step is to create an app on facebook where you specify what information you want the program to be able to access via the graph api. The end user will then choose to accept these permissions later. The program creates a web browser frame and navigates to https://www.facebook.com/dialog/oauth?client_id={app-id}&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token The response type "token" means that when the (embedded) web browser is redirected to the redirect_uri the user access token will be added to the end of the url as a fragment. E.g the browser would end up on the page with url https://www.facebook.com/connect/login_success.html#access_token=ACCESS_TOKEN... The redirect uri can be anything but facebook has that specific one set aside for this scenario where you are not hosting another server which you want to receive and process the response. Basically facebook gathers all the information required from the user and then sends them to the redirect_uri. Some information they may require is for them to login and accept permissions your app on facebook requires. So the program simply keeps an eye on what url the embedded browser is on and when it matches the redirect_uri it parses the url which will contain the data as fragments and can then close the browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/18196667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: "Call to undefined method PHPUnit\Framework\TestSuite::sortId()" Error while executing Test Case with Coverage Call to undefined method PHPUnit\Framework\TestSuite::sortId() Getting this error while trying to execute test case with coverage. Command: phpunit -v --debug ./Test.php --coverage-clover ../clover.xml Putput: (first two lines) PHPUnit 9.5.4 by Sebastian Bergmann and contributors. Runtime: PHP 7.3.33-1+ubuntu21.10.1+deb.sury.org+1 ... A: It appears that you have different installations of PHPUnit mixed up. For instance, you may have used Composer to install PHPUnit and have configured the autoloader generated by Composer as PHPUnit's bootstrap script but then you invoke PHPUnit using an executable other than vendor/bin/phpunit.
{ "language": "en", "url": "https://stackoverflow.com/questions/70389249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: python csv delimiter doesn't work properly I try to write a python code to extract DVDL values from the input. Here is the truncated input. A V E R A G E S O V E R 50000 S T E P S NSTEP = 50000 TIME(PS) = 300.000 TEMP(K) = 300.05 PRESS = -70.0 Etot = -89575.9555 EKtot = 23331.1725 EPtot = -112907.1281 BOND = 759.8213 ANGLE = 2120.6039 DIHED = 4231.4019 1-4 NB = 940.8403 1-4 EEL = 12588.1950 VDWAALS = 13690.9435 EELEC = -147238.9339 EHBOND = 0.0000 RESTRAINT = 0.0000 DV/DL = 13.0462 EKCMT = 10212.3016 VIRIAL = 10891.5181 VOLUME = 416404.8626 Density = 0.9411 Ewald error estimate: 0.6036E-04 R M S F L U C T U A T I O N S NSTEP = 50000 TIME(PS) = 300.000 TEMP(K) = 1.49 PRESS = 129.9 Etot = 727.7890 EKtot = 115.7534 EPtot = 718.8344 BOND = 23.1328 ANGLE = 36.1180 DIHED = 19.9971 1-4 NB = 12.7636 1-4 EEL = 37.3848 VDWAALS = 145.7213 EELEC = 739.4128 EHBOND = 0.0000 RESTRAINT = 0.0000 DV/DL = 3.7510 EKCMT = 76.6138 VIRIAL = 1195.5824 VOLUME = 43181.7604 Density = 0.0891 Ewald error estimate: 0.4462E-04 Here is the script. Basically we have a lot of DVDL in the input (not in the above truncated input) and we only want the last two. So we read all of them into a list and only get the last two. Finally, we write the last two DVDL in the list into a csv file. The desire output is 13.0462, 3.7510 However, the following script (python 2.7) will bring the output like this. Could any guru enlighten? Thanks. 13.0462""3.7510"" Here is the script: import os import csv DVDL=[] filename="input.out" file=open(filename,'r') with open("out.csv",'wb') as outfile: # define output name line=file.readlines() for a in line: if ' DV/DL =' in a: DVDL.append(line[line.index(a)].split(' ')[1]) # Extract DVDL number print DVDL[-2:] # We only need the last two DVDL yeeha="".join(str(a) for a in DVDL[-2:]) print yeeha writer = csv.writer(outfile, delimiter=',',lineterminator='\n')#Output the list into a csv file called "outfile" writer.writerows(yeeha) A: As the commenter who proposed an approach has not had the chance to outline some code for this, here's how I'd suggest doing it (edited to allow optionally signed floating point numbers with optional exponents, as suggested by an answer to Python regular expression that matches floating point numbers): import re,sys pat = re.compile("DV/DL += +([+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)") values = [] for line in open("input.out","r"): m = pat.search(line) if m: values.append(m.group(1)) outfile = open("out.csv","w") outfile.write(",".join(values[-2:])) Having run this script: $ cat out.csv 13.0462,3.7510 I haven't used the csv module in this case because it isn't really necessary for a simple output file like this. However, adding the following lines to the script will use csv to write the same data into out1.csv: import csv writer = csv.writer(open("out1.csv","w")) writer.writerow(values[-2:])
{ "language": "en", "url": "https://stackoverflow.com/questions/26196007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Perl (opendir): Receiving "Can't use an undefined value as a symbol reference at line 46." I am trying to use opendir to open a directory. When ever this happens I get the error: "Can't use an undefined value as a symbol reference at line." From searching other questions this usually originates from trying to use a variable that is out of scope. From all that I can tell my variable that I am using for my directory location is in scope and my handler for opendir is defined in the function like all examples. Please help me figure out what is going wrong. Line 46 where it is claiming the error is at is double starred. use File::Find; use File::Copy; use File::Path; my @imagelocations = ('/some/location1','/some/location2'); my $destination = '/some/location'; foreach $a (@imagelocations) { find (\&Move_Images, $a); } sub Move_Images { my $file = $_; if (-e $file && $File::Find::dir eq $a && $file ne ".") { if (-M $file < 1) { my @folder = split(/_/, $file); my ($var1,$var2,$var3) = @folder[0,1,4]; if (lc $var1 ne "manual" && lc $var1 ne "test") { if (-d ($File::Find::dir.'/'.$file)) { $var3 = substr ($var3,1,-2); my $open = $File::Find::dir."/$file"; **opendir (my $dh, $open) or die "Can't open directory $!";** my @files = readdir($dh); ...
{ "language": "en", "url": "https://stackoverflow.com/questions/40621369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to fix unexpected token in ESLint? I install ESLint globally using the command npm install -g eslint on my Mac. It was successful installing, but when I run eslint -v this is the issue I encounter: $ npm install -g eslint path/to/bin/eslint -> path/to/lib/node_modules/eslint/bin/eslint.js + eslint@7.3.1 added 107 packages from 63 contributors in 4.823s $ eslint -v path/to/lib/node_modules/eslint/bin/eslint.js:93 } catch { ^ SyntaxError: Unexpected token { at createScript (vm.js:80:10) at Object.runInThisContext (vm.js:139:10) at Module._compile (module.js:617:28) at Object.Module._extensions..js (module.js:664:10) at Module.load (module.js:566:32) at tryModuleLoad (module.js:506:12) at Function.Module._load (module.js:498:3) at Function.Module.runMain (module.js:694:10) at startup (bootstrap_node.js:204:16) at bootstrap_node.js:625:3 I would like to know what are the missing steps that cause this issue? I'm using Node.js v8.16.2 and NPM v6.4.1. A: The error happens because } catch { is a relatively recent (ES2019) language feature called "optional catch binding"; prior to its introduction, binding the caught error (e.g. } catch (err) {) was required syntactically. Per node.green, you need at least Node 10 to have that language feature. So why does this happen in ESLint? Per e.g. the release blog, version 7 has dropped support for Node 8; they're no longer testing against that version and more modern language features will be assumed to be supported. To fix it, either: * *Upgrade Node (Node 8 is out of LTS, which is why ESLint dropped support); or *npm install eslint@6 (with -g if you want to install globally) to use the older version of ESLint with Node 8 support. A: In case it's helpful for anyone, I had a slightly different twist on the other answer. In my case, the error was happening during the Travis CI build process and causing it to fail. The solution in my case was to update my .travis.yml file to node_js: "16"
{ "language": "en", "url": "https://stackoverflow.com/questions/62636329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: IE11 emulates IE7 even though it's set to EDGE My website has the following settings: But IE11 renders the page in IE7 mode: This is on a machine with a fresh IE11 install, and it's the first time I'm visiting the website with the browser. Any idea what could be wrong? A: Does moving the X-UA-Compatible tag to be immediately underneath the tag make a difference? See answer by neoswf: X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode Cheers,
{ "language": "en", "url": "https://stackoverflow.com/questions/23579763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create read-only user in pgAdmin 4? Creating a read-only user in pgAdmin 4 is a little tricky. Here is a guide on how I did it. First of all a few words about the process. The whole process is based on editing a schema (very simple and safe) for your DB, so this creates limitations for using the method for all the DBs you have unless you edit schemas for each DB (again, it is easy). First, we have to open a main dialogue, select the target DB you need the read-only user for -> Schemas -> right mouse click on "public" schema -> Properties. In the opened window go to "Default privileges" and click the "+" in the right corner. * *In the "Grantee" column enter: "pg_read_all_data", *in "Privileges" column click on the field and you will see options. Enable only "Select". On the rest tabs (Sequences, Functions, Types) you can do the same (Select or Usage). Hit "Save". In the left sidebar scroll down and find "Login/Group Roles". Click right button -> Create -> Login/Group Role. OR if you have an existed user role you want to make read-only, click the right button on it and select "Properties". In the opened window enter the name of the user, on the "Definition" tab enter a password, on the "Previliges" tab select "Can login" and "Inherit rights from the parent roles?" In the "Membership" tab hit "+" in the "Member of" table and type "pg_read_all_data" into the "User/Role" column. In the "Parameters" tab hit "+". Select "role" in the "Name" column's dropdown, type "pg_read_all_data" in the "Value" column. In the "Database" column select the desired DB (where you have edited the schema in the previous steps). Note, you can add more rows with the same settings for different databases (of course, if those DBs have edited schemas as shown above). Click "Save". Now you can log into your PhpPgAdmin (or psql or wherever you need) under this user and do only selects. A real read-only user role. I hope it will help someone. A: I don't have enough reputation to comment on your very helpful post, but wanted to add that the public schema by default gives full access to the PUBLIC role (implicit role that all users belong to). So you would first need to revoke this access. This can be done in pgAdmin in the Security tab of the schema properties dialog, or with the SQL command REVOKE CREATE ON SCHEMA public FROM PUBLIC; See also: * *Issue creating read-only user in PostgreSQL that results in user with greater permission with public schema *PostgreSQL - Who or what is the "PUBLIC" role?
{ "language": "en", "url": "https://stackoverflow.com/questions/72791383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }