text
stringlengths
15
59.8k
meta
dict
Q: find the k-th element in a unimodal array Given a unimodal array A of n distinct elements (meaning that its entries are in increasing order up until its maximum element, after which its elements are in decreasing order), an integer p (that is the length of the increasing first part) and k (the k-th minimum element) Give an algorithm to compute the value of the kth minimal element that runs in O(log n) time. Example: A= {1,23,50,30,20,2} p= 2 k=3 Answer: 20 Edit I tried this: def ksmallest(arr1, arr2, k): if len(arr1) == 0: return arr2[len(arr2)-k-1] elif len(arr2) == 0: return arr1[k] mida1 = (int)(len(arr1)/2) mida2 = (int)((len(arr2)-1)/2) if mida1+mida2<k: if arr1[mida1]>arr2[mida2]: return ksmallest(arr1, arr2[:mida2], k-(len(arr2)-mida2)) else: return ksmallest(arr1[mida1+1:], arr2, k-mida1-1) else: if arr1[mida1]>arr2[mida2]: return ksmallest(arr1[:mida1], arr2, k) else: return ksmallest(arr1, arr2[mida2+1:], k) A: For starters have another look at your indexes. You begin with: if len(arr1) == 0: return arr2[len(arr2)-k-1] elif len(arr2) == 0: return arr1[len(arr1)-k-1] But surely if arr1 is in ascending order, and arr2 is in descending order the kth minimal element will not be found in the same location.
{ "language": "en", "url": "https://stackoverflow.com/questions/15625316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: flatten dataframe containing list with multiple dictionaries I have currently a pandas dataframe with 100+ columns, that was achieved from pd.normalize_json() and there is one particular column (children) that looks something like this: name age children address... 100 more columns Mathew 20 [{name: Sam, age:5}, {name:Ben, age: 10}] UK Linda 30 [] USA What I would like for the dataframe to look like is: name age children.name children.age address... 100 more columns Mathew 20 Sam 5 UK Mathew 20 Ben 10 UK Linda 30 USA There can be any number of dictionaries within the list. Thanks for the help in advance!
{ "language": "en", "url": "https://stackoverflow.com/questions/68127827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: React-router Uncaught TypeError: type.toUpperCase is not a function I'm using the latest version of react, react-router, gulp and browserify I got this in beowser console: Uncaught TypeError: type.toUpperCase is not a function my code in app.js: "use strict"; var React = require('react'); var Router = require('react-router'); var Header = require('./components/Header'); var Index = require('./components/Index'); var About = require('./components/About') var Route = Router.Route; var IndexRoute = Router.IndexRoute ; var App = React.createClass({ render: function(){ return ( <div> <Header /> <div> {this.props.children} </div> </div> ); } }) React.render(<Router><Route path="/" component={App}> <IndexRoute component={Index}/> <Route path="about" component={About}/> </Route> </Router>, document.getElementById('app')); A: Just upgrade your react router version from 0.0.13 to 1.0.0-rc1(beta) coz the below code will only work for 1.0.0 beta version which is mentioned in change log. React.render(<Router><Route path="/" component={App}> <IndexRoute component={Index}/> <Route path="about" component={About}/> </Route> </Router>, document.getElementById('app')); After upgrading version you have to declare router properly like below. var React = require('react'); var ReactRouter = require('react-router'); var Router = ReactRouter .Router; var Route = ReactRouter .Route; Now router is defined properly. This worked for me..give a try.
{ "language": "en", "url": "https://stackoverflow.com/questions/32812055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing data on db on a specific day and time - nodejs I have a specific requirment for a web application which is build with Nodejs/MongoDb/Express/Angular. Application itself is a application for mentors and has a kind of schema like this: var userSchema = new mongoose.Schema({ email: { type: String, unique: true, required: true }, username: { type: String, unique: true, required: true }, .... status: {type: String, enum: ["online", "offline"]}, schedule: [{ day: String, StartTime: Date, EndTime: Date }] ... }) Every user has its own schedule, for example working Every: Monday ,Wednesday ,Thursday From: 04:00 PM To: 07:00 PM. Now, how can I change the status from Offline to Online as they submited their schedule. I mean from the example above, to change Every: Monday ,Wednesday ,Thursday at the specific time the user status on db from "offline" to "online" ? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/41532732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VSCode uses different System Path's for Python with Run command and Debugger Seemingly out of nowhere my python scripts in VS Code are no longer running correctly. None of the python packages I've installed are importing correctly anymore, getting a ModuleImport error. When I printed sys.path, and sys.version, I found that not only were the directories in path not correct, but the version of Python VS Code was trying to run was not the same as the version of Python the interpreter was set to use. The interpreter I had selected was using Python 3.9.7, but sys.version was printing Python 3.8. Even more strangely, when I ran the same code with the debugger, the directories printed by sys.path were magically correct, and the version of Python being run was suddenly correct again as well. In the end I completely uninstalled and reinstalled Anaconda and all versions of Python on my system, but I'm still running into the same problem after creating a new environment, the only difference now is that the version of python being run is correct, but the path directories are not. Terminal output from Run: Terminal output from Debug: In both cases the correct interpreter is selected, the only difference is using Run or Debug. The only thing I can think of that may relate to the error is that I recently installed Linux on an external hard drive to dual boot from, and I installed Python on that as well. I'm not sure how that would cause this though. A: You could try these: * *Go to VSCode settings and go to extensions, and then find Python. Then find Default Interpreter Path. If the path it says is python, change it to your installation path. *Check your PATH and see if Python is in it. *Reinstalling VSCode or Python. A: It's an issue with the Python Extension update. Use conda run for conda environments for running python files and installing modules. (#18479) changelog(28 February 2022). But it has some problems, I had submitted an issue on GitHub. The debugger can take the correct python interpreter which you have selected in the VSCoe, while the command conda run xxx can not. It will persist in the base instead of the NeoNatal environment. It can not select the sub environment under Anaconda3 envs. Execute sys.executable you will find it. If execute the python script directly in the terminal likes python pythonFileName.py instead of conda run xxx it will be working again. Update: Workaround: * *Set "python.terminal.activateEnvironment" to false in the settings.json. *Downgrade to the previous version of the extension which works fine(avoid conda run). *Try out the following VSIX which has the potential fix: https://github.com/microsoft/vscode-python/suites/5578467772/artifacts/180581906, Use Extension: Install from VSIX command to install the VSIX. Reason: Conda has some problems: conda run -n MY-ENV python FILE.py uses the base interpreter instead of environment interpreter. Running using conda run inside already activated environment should be the same as running it outside conda run does not remove base environment components from $PATH
{ "language": "en", "url": "https://stackoverflow.com/questions/71391476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Missing package property files in war build Littered throughout my project are various property files located in packages that are not being included when the package goal is run from a Maven build. Using the 0.10.2 m2eclipse plugin and the default "package" goal. In the project: src->main->java->mypackage->MyProperties.java src->main->java->mypackage->MyProperties.properties In expanded war directory after the "package" goal is run: target->classes->mypackage->MyProperties.class -- no property file -- I'm trying to get the group to adopt Maven and resolving this issue is going to be a deal maker. Moving the properties files isn't going to be practical. Any help is much appreciated. A: Put your property files where Application/Library resources belong, i.e. in src/main/resources: src/main/resources/mypackage/MyProperties.properties And it will get copied properly. A: Pascal's answer is the correct maven way of doing things. But some developers like to keep resources next to their sources (it's standard procedure in wicket, for example). If you're going to do that, you will have to add your source folder to the resources: <build> <resources> <resource> <directory>src/main/resources</directory> </resource> <resource> <directory>src/main/java</directory> <excludes> <exclude>**/*.java</exclude> </excludes> </resource> </resources> </build>
{ "language": "en", "url": "https://stackoverflow.com/questions/3354564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: RxJava - retrieving entry in Observable in second flatMapSingle We have a vertx verticle which receives an id and uses it see if an entity with the id exist in a database. It contains the following logic: if (itemFound) { e.onNext(item_which_was_found) } else { e.onNext(null); } Another verticle has an Observable which processes a list of id's. It uses rxSend to pass each id in the list to the first verticle to do the database lookup: Observable<Object> observable = ... observable.flatMapSingle(id -> { return rxSend(VERTICLE_1_ADDRESS, id); }) .flatMapSingle ( i -> { // Logic dependent on if item was found ) .subscribe(); With the above, it is easy to handle cases where the entity associated with the id was found in the database, because the first vertcle, in onNext(), returns the entity. The question is for the second case, when no entity exists and first verticle returns onNext(null). In this case, how is it possible to retrieve, in the second flatMapSingle, the item in the observable which is currently being processed (that is, the id which has no associated database entity) ? Or is there a better way to structure the code? Thanks A: You can change your observable definition to: Observable<Object> observable = observable(); observable.flatMapSingle(id -> { return rxSend(VERTICLE_1_ADDRESS, id).flatMap(i -> { // Logic dependent on if item was found // id is visible here }); }).subscribe(); Then the id will be visible to your second lambda.
{ "language": "en", "url": "https://stackoverflow.com/questions/56479534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery AJAX Event is Undefined on Firefox This code works in Webkit browsers, but not Firefox. I think I need to put "event" somewhere in a parenthesis, but not sure how and where...? html <div id="calendar_nav"> <span class="button-prev" role="button" onclick="javascript:reloadweek();" data-semana=<?php echo $weekprev; ?>>&laquo; Previous Week</span> <span class="button-next" role="button" onclick="javascript:reloadweek();" data-semana=<?php echo $weeknext; ?>>Next Week &raquo;</span> </div> jQuery function reloadweek(){ /*console.log(event.target.dataset.semana)*/ var uploading = jQuery('div#uploading').html('<p><img width="60px" src="<?php echo get_template_directory_uri();?>/images/loading.gif"/></p>'); jQuery('#calendar').load("<?php echo get_template_directory_uri();?>/ajaxloader.php #calendar", { 'week': event.target.dataset.semana, }, function() { today() }) } A: Your "onclick" attributes should look like this: <span class="button-prev" role="button" onclick="reloadweek(event);" data-semana=<?php echo $weekprev; ?>>&laquo; Previous Week</span> and then your function needs an "event" parameter: function reloadweek(event){ There's no point in javascript: in "onclick" handler values. You'd really be better off using jQuery to set up your event handlers: jQuery(document).on(".button-prev, .button-next", "click", function(event) { var uploading = jQuery('div#uploading').html('<p><img width="60px" src="<?php echo get_template_directory_uri();?>/images/loading.gif"/></p>'); jQuery('#calendar').load("<?php echo get_template_directory_uri();?>/ajaxloader.php #calendar", { 'week': $(this).data("semana") }, function() { today(); }); }); The value of this in the handler will be bound (by jQuery) to the element that was clicked on. Then you really don't need event at all, though jQuery will make sure it's passed through.
{ "language": "en", "url": "https://stackoverflow.com/questions/31031443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Azure Notification Hub Rest API with iOS Swift 401 Error from device I'm unable to generate a valid Authentication Token using iOS Swift and keep getting a 401 error when trying to send a push notification directly from a iPhone. The documentation on Microsoft Azure's website is incomplete and written in Objective C. After translating to Swift, some parts of it call old functions that have been deprecated. A: I figured it out. The Objective C to Swift translator wasn't working as expected so I just coded it in Objective C and everything works, although the documentation on the Azure website needs to be updated to iOS10.
{ "language": "en", "url": "https://stackoverflow.com/questions/43555746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reusing same connection in signalR while navigating through different pages I have an MVC project, with multiple pages. I have a long running process, which updates the client on its progress. However, this update is sent only to a single client, instead of broadcasting to all. Clients.Client(ConnectionId).sendMessage(msg); In my layout.cshtml, this is how I connect to the hub var serverHub = $.connection.notifier; window.hubReady = $.connection.hub.start(function () { }); The problem is, when I navigate to another page, I no longer receive the messages from signalr, because the connection id has changed. How should I workaround this issue, such that my signalr hub can still send messages to a single client, while the client navigates from page to page. A: You will want to create a server mapping of users to connection id's. See: SignalR 1.0 beta connection factory. You will want to let your users persist past an OnDisconnected event and when they connect with a different connection Id you can continue pumping data down to them. So the thought process could be as follows: * *Page loads, SignalR connection is instantiated *Once connection is fully started call => TryCreateUser (returns a user, whether it existed or it was created). *Long Running process Starts *Client changes pages -> SignalR connection stops *New Page loads, new SignalR connection is instantiated *Once connection is fully started see if you have a cookie, session, or some type of data representing who you are => TryCreateUser(userData) (returns the user you created on the last page). *Data continues pumping down to user. Note: if you take an authentication approach you will have to be authenticated prior to starting a connection and that data cannot change during the lifetime of a SignalR connection, it can only be created/modified while the connection is in the disconnected state.
{ "language": "en", "url": "https://stackoverflow.com/questions/16077519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Facebook post to wall £ shows up as special character I am trying to post a message to the facebook feed / wall / timeline that has a £ symbol in it. I have tried: mb_internal_encoding("UTF-8"); $message = "TEST: £ &pound; &#163;"; and setting: mb_internal_encoding("UTF-8"); mb_http_output( "UTF-8" ); No luck... The PHP document is saved as UTF8. Anyone know how to post a £ symbol to the wall via a php script? The post mechanism is working fine. So one of the values on the array facebook gets is: $message = "TEST: £ &pound; &#163;"; $DataArray["message"] = $message; and the FB command is: $result = $facebook->api("/me/feed", "post", $DataArray); Result is a diamond shape with ? in it. � for the £ symbol the others just write out. A: � This is usually a sign for an invalid UTF-8 character. My bet is that your PHP file is ISO-8859-1 encoded. The pound sign has a different code point in ISO-8859-1 than in UTF-8. When data from the PHP file is used in a UTF-8 context, the pound sign becomes invalid. Save the PHP file with UTF-8 encoding - this can usually be set in the editor's "Save As" dialog. A: Found the reason. I was using ScriptFTP to batch upload files, Filezilla sorted it out. It mus t have been changing the format or something during upload. A: I had a similar problem, but in my case was that my php file was encoded in ANSI, I just needed to change the file encoding to UTF-8 remember to do this when you have special characters if he were invalid so remember to edit these characters after changing the file encoding I have helped you or others xD
{ "language": "en", "url": "https://stackoverflow.com/questions/11677944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Auth Token in Redirect Url as Query String I have a .net core backend using Identity and when a user logs in using a password and email the client sends it up to the API and a auth token is generated, that token is then sent back in the redirect url as a query param so that the subdomian can store it in the local storage and use it to make http requests as this logged in user. Is this secure? The redirect url would look something like: https://sub.domain.com?token=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&user=xxxxxxxxxxxxxxxx
{ "language": "en", "url": "https://stackoverflow.com/questions/67117645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to load a local file without having to ask the user to browse to it first in an AIR Application? I'm writing a small application for myself and instead of using a database I'd like to just use Excel to store the small amount of data I have on my local file system. I want to be able to load that data without having to use the typical FileReference browse() method as it would just be annoying to do every time I use the application. The code below seems to find the file fine as the file.exists method below and most of the other attributes seem to be correct but the file.data is always null. I'm guessing this is a security issue and that's why I'm running into this problem but I thought I'd ask and see if there is in fact a way around this problem. var file:File = new File(fullPath + "\\" + currentFolder + ".txt"); if(file.exists) { var byteArray:ByteArray = file.data; } A: You're close, you just need to combine that with a FileStream object var fileStream:FileStream = new FileStream(); fileStream.open(file, FileMode.READ); var str:String = fileStream.readMultiByte(file.size, File.systemCharset); trace(str); more info here A: If you want to read the content of a file, use the following code: var stream:FileStream = new FileStream(); stream.open("some path here", FileMode.READ); var fileData:String = stream.readUTFBytes(stream.bytesAvailable); trace(fileData); The data property is inherited from FileReference class and it will be populated only after a load call (see this link).
{ "language": "en", "url": "https://stackoverflow.com/questions/6786236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Differernce between alphabets in C? I wanted to know how to you find the difference between alphabets,for ex: difference between a and d is 3, between s and u is 2. I would like to know the methods in both c and java. A: int i = 'd' - 'a'; will have i set to 3 which is the difference
{ "language": "en", "url": "https://stackoverflow.com/questions/28002635", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-6" }
Q: I'm adding columns to my mysql database - Migrating my database to south I have a mysql database. I want to add more columns, so I'm starting to use south. I want to set my database up to use south. How do I do this? I followed the steps at 1054 unknown column django after south migration to no avail NO CHANGES TO MODELS YET (venv)sfo-mpmgr:summertime msmith$ python manage.py convert_to_south livestream Creating migrations directory at '/Users/msmith/Documents/dj/summertime/livestream/migrations'... Creating __init__.py in '/Users/msmith/Documents/dj/summertime/livestream/migrations'... + Added model livestream.Stream Created 0001_initial.py. You can now apply this migration with: ./manage.py migrate livestream - Soft matched migration 0001 to 0001_initial. Running migrations for livestream: - Migrating forwards to 0001_initial. > livestream:0001_initial (faked) App 'livestream' converted. Note that South assumed the application's models matched the database (i.e. you haven't changed it since last syncdb); if you have, you should delete the livestream/migrations directory, revert models.py so it matches the database, and try again. (venv)sfo-mpmgr:summertime msmith$ python manage.py schemamigration livestream --auto Nothing seems to have changed. (venv)sfo-mpmgr:summertime msmith$ python manage.py migrate livestream --fake Running migrations for livestream: - Nothing to migrate. - Loading initial data for livestream. Installed 0 object(s) from 0 fixture(s) (venv)sfo-mpmgr:summertime msmith$ python manage.py migrate livestream Running migrations for livestream: - Nothing to migrate. - Loading initial data for livestream. Installed 0 object(s) from 0 fixture(s) Now I update the Models with the new attribute. (venv)sfo-mpmgr:summertime msmith$ python manage.py schemamigration livestream --auto DatabaseError: (1054, "Unknown column 'livestream_stream.step' in 'field list'") Anyone know how to avoid this error?
{ "language": "en", "url": "https://stackoverflow.com/questions/18261117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Difference between RemoveUntil and PopUntil in Flutter navigation 1)What is the difference between RemoveUntil and PopUntil in Flutter navigator? 2)If have 3 screens A->B->C and now assuming i'm at Screen C and i perform popuntil Screen A,so will this pop Screen A as well or will it pop till Screen B and keep Screen A as it is? A: pushAndRemoveUntil: Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => LoginScreen()), (Route<dynamic> route) => false); This code will route to the login screen and pop all the screens which are in the back stack. popUntil: Navigator.of(context).popUntil(ModalRoute.withName('/widget_name')); This code will pop all the screens till the mentioned screen, here that screen name is widget_name
{ "language": "en", "url": "https://stackoverflow.com/questions/62710395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to output groupby to html table in flask python I have the following code to groupby data in a pandas dataframe and it works fine user_data=user_data.groupby('user searched coin', as_index=False)['predicted coin'].apply(lambda x: ", ".join(f"{k} {v}" for k, v in x.value_counts().items())) however when I try to render it to html in flask with user_data=[user_data.to_html(classes='data')] I get an error that series has not html attribute, I gather that the output from the groupby is not a dataframe. Then I have also tried to transform into a dataframe, now I don't get the error but the output has only one column user_data = pd.DataFrame(user_data) is there any solution for this?
{ "language": "en", "url": "https://stackoverflow.com/questions/68508190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Auto fitting a cell to the size of the content? I'm new to tcpdf, creating my first document. I wonder if there is a way to fit the width of the cell automatically to the content. I currently only see options for fixed size, or taking the whole page width until the end of the line. I'm aware of GetStringWidth() but having the following problems with it * *Why should one bother even for this? Is there a way to just make the cell fit automatically to its contents width? *GetStringWidth() seems to err from time to time, giving shorter results the actual, thus causing the text to be split to the next line. A font is set. A: After learning TCPDF more, this is the conclusion: Cell() and MultiCell() are not intended to be used for just outputting a string and fitting it's length. Instead, Write() and WriteHtml() should be used. Cells exist for the case where you actually want to control the dimentions of the field manually. Nevertheless, in some cases one may want to compute the width of the cell, such that it takes into account the sizes of the text inside. For this purpose exists GetStringWidth(). (Unfortunately for me it err's from time to time. Maybe I'm not aware of something) A: Have an internal "Legacy" application that uses TCPDF to generate a PDF of a checklist. We recently moved from creating a giant string of HTML that described a table, created using the $pdf->writeHTML($myHTMLString); method, to using the MultiCell() methods. However, we ran into an issue where some text in a description cell would need to run on to a second line, this threw off our layout. As a fix, we created an if block based on 2 variables, one for the string width the other for the actual cell width. (We had 2 instances where the cell width might vary). If block example: // Get width of string $lWidth = $pdf->GetStringWidth(strip_tags($clItem['description'])); // Determine width of cell $oadWidth = (.01*$width[0])*186; if ($lWidth < $oadWidth) { $cHeight = 3.5; } else { $cHeight = 7; } We then used the variable created by the if block in the MultiCell() like this $pdf->MultiCell((.01*$width[0])*186, $cHeight, strip_tags($clItem['description']), 1, 'L', 1, 0, '', '', true); We reused the $cHeight variable for the height params in the other sibling cells so each row of cells had a uniform height. You could most likely reuse this method with any of the other right functions that have a height parameter in TCPDF. Thanks to @shealtiel for the original reference to GetStringWidth()
{ "language": "en", "url": "https://stackoverflow.com/questions/16645738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android.R.color.primary_text_light deprecated: What to do now? I am working on a custom android view. I want to draw a text with the standard android text color. Therefore I wanted to use android.R.color.primary_text_light, but the documentation says that it's deprecated and "a text color from your theme" should be used. What does that mean? I just want to use the normal android text color, which is also used when just adding a textview to the layout. A: Android have deprecated it because they want you to use your application theme colors rather then using android native colors. You can find your application theme colors in the following path: project/app/res/values/colors.xml in that file you will have few colors declared already like: <color name="colorPrimary">#2196f3</color> <color name="colorPrimaryDark">#1976d2</color> <color name="colorPrimaryLight">#B3E5FC</color> <color name="colorAccent">#03A9F4</color> <color name="primary_text">#212121</color> <color name="secondary_text">#757575</color> <color name="icons">#FFFFFF</color> <color name="divider">#BDBDBD</color> So have to use these colors now. If you want to change the color value just change the value and you can have your desired color.
{ "language": "en", "url": "https://stackoverflow.com/questions/58214678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL Trigger usage : if column is null set other column null How do I realize the following in MySQL with Triggers: When value of some column is null -> set other column values to null and when value of some column is not null -> set other column values to null table definition: CREATE TABLE variations ( id int(10) NOT NULL, x1 int(10) NOT NULL, x2 int(10), x1_option1 BOOL, x2_option1 BOOL, x1_option2 varchar(10), x2_option2 varchar(10) ); The idea is that we have 2 Elements, x1and x2. While x1is mandatory, x2is optional and can be null. Both, x1 and x2 have two options: x1_option1 , x2_option1, x1_option2 and x2_option2. The first rule should be that when x2 is null, both options for x2 (x2_option1, x2_option2) must also be null. My attempt: CREATE TRIGGER check_null_x2 BEFORE INSERT ON variations FOR EACH ROW BEGIN IF NEW.x2 IS NULL THEN SET NEW.x2_option1 = NULL; SET NEW.x2_option2 = NULL; END IF; END$$ Throws Error: #1064 - 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 '' at line 6 Can you please help me figuring out whats wrong? I just dont understand what '' means. The second rule should be that there can only be one of the two options selected. that means if x2_option1 is NOT NULL, x2_options2 must be NULL. In general i think this can be done the same way as the first rule. My question: how can i do multiple 'IF', 'ELSE IF' etc in one trigger? A: you seem to have ";" set as DELIMETER, which causes the query to execute once it sees a ";". try changing it first: DELIMITER // CREATE TRIGGER check_null_x2 BEFORE INSERT ON variations FOR EACH ROW BEGIN IF NEW.x2 IS NULL THEN SET NEW.x2_option1 = NULL; SET NEW.x2_option2 = NULL; END IF; END;// DELIMITER ; A: This is syntax for trigger: delimiter // CREATE TRIGGER upd_check BEFORE UPDATE ON account FOR EACH ROW BEGIN IF NEW.amount < 0 THEN SET NEW.amount = 0; ELSEIF NEW.amount > 100 THEN SET NEW.amount = 100; END IF; END;// delimiter ; ...and your code is here: DELIMITER // CREATE TRIGGER check_null_x2 BEFORE INSERT ON variations FOR EACH ROW BEGIN IF NEW.x2 IS NULL THEN SET NEW.x2_option1 = NULL; SET NEW.x2_option2 = NULL; END IF; END$$ -- THIS LINE SHOULD BE: "END;//" DELIMITER ; EDIT: The official Documentation says the following: If you use the mysql client program to define a stored program containing semicolon characters, a problem arises. By default, mysql itself recognizes the semicolon as a statement delimiter, so you must redefine the delimiter temporarily to cause mysql to pass the entire stored program definition to the server. To redefine the mysql delimiter, use the delimiter command. The following example shows how to do this for the dorepeat() procedure just shown. The delimiter is changed to // to enable the entire definition to be passed to the server as a single statement, and then restored to ; before invoking the procedure. This enables the ; delimiter used in the procedure body to be passed through to the server rather than being interpreted by mysql itself. A: CREATE TRIGGER `XXXXXX` BEFORE INSERT ON `XXXXXXXXXXX` FOR EACH ROW BEGIN IF ( NEW.aaaaaa IS NULL ) THEN SET NEW.XXXXXX = NULL; SET NEW.YYYYYYYYY = NULL; END IF; END Worked for me....
{ "language": "en", "url": "https://stackoverflow.com/questions/21551150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to set default value in material-UI select box in react? I am using Select box from material-ui I want to show "select the value" option by default selected but after that user is not able to select this option. <FormControl required className={classes.formControl}> <InputLabel htmlFor="circle">Circle</InputLabel> <Select value={circle} onChange={event => handleInput(event, "circle")} input={<Input name="circle" id="circle" />} > <MenuItem value="" disabled> <em>select the value</em> </MenuItem> <MenuItem value={10}>Ten</MenuItem> <MenuItem value={20}>Twenty</MenuItem> <MenuItem value={30}>Thirty</MenuItem> </Select> <FormHelperText>Some important helper text</FormHelperText> </FormControl> Current code on sandbox: https://codesandbox.io/s/xoylmlj1qp I want to make like this: https://jsfiddle.net/wc1mxdto/ Update I changed the state 20 to blank string in circle form: { searchValue: "", circle: '', searchCriteria: "" } now expected output should be dropdown should show "please select value" but currently it showing this A: <FormControl variant="outlined" className={classes.formControl}> <InputLabel id="uni">UNI</InputLabel> <Select key={value} defaultValue={value} labelId="uni" id="uni" name="uni" onBlur={onChange} label="uni" > {unis.map((u, i) => ( <MenuItem value={u.value} key={i}> {u.label} </MenuItem> ))} </Select> </FormControl>; A: Just use the defaultValue attribute of select. You can refer to the Material UI Select API Docs to know more. import React from 'react'; import {useState} from 'react'; import FormControl from '@material-ui/core/FormControl'; import InputLabel from '@material-ui/core/InputLabel'; import Select from '@material-ui/core/Select'; import MenuItem from '@material-ui/core/MenuItem'; const Selector = () => { const [Value, setValue] = useState("1"); // "1" is the default value in this scenario. Replace it with the default value that suits your needs. const handleValueChange = event => { setValue(event.target.value); } return( <FormControl> <InputLabel id="Input label">Select</InputLabel> <Select labelId= "Input label" id= "Select" value= {Value} defaultValue= {Value} onChange= {handleValueChange} > <MenuItem value="1">Item1</MenuItem> <MenuItem value="2">Item2</MenuItem> <MenuItem value="3">Item3</MenuItem> </Select> </FormControl> ) }; export default Selector; A: If you take a look at the Select Api of Material UI here, you could do it easily. * *As explained above, you need to pass the default value in your state variable: const [age, setAge] = React.useState(10);// <--------------(Like this). *Set displayEmpty to true: If true, a value is displayed even if no items are selected. In order to display a meaningful value, a function should be passed to the renderValue prop which returns the value to be displayed when no items are selected. You can only use it when the native prop is false (default). <Select displayEmpty /> A: You need to provide correct MenuItem value in state to be matched on render. Here is the working codesandbox: Default Select Value Material-UI A: You can just pass the displayEmpty into select <Select id="demo-simple-select-outlined" displayEmpty value={select} onChange={handleChange} > and define the menuItem like <MenuItem value=""><Put any default Value which you want to show></MenuItem> A: As React introduced React-Hooks, you just need to pass your default value in React.useState() as React.useState(10). export default function CustomizedSelects() { const classes = useStyles(); const [age, setAge] = React.useState(10);// <--------------(Like this). const handleChange = event => { setAge(event.target.value); }; return ( <form className={classes.root} autoComplete="off"> <FormControl className={classes.margin}> <Select value={age} className={classes.inner} onChange={handleChange} input={<BootstrapInput name="currency" id="currency-customized-select" />} > <MenuItem value={10}>Ten</MenuItem> <MenuItem value={20}>Twenty</MenuItem> <MenuItem value={30}>Thirty</MenuItem> </Select> </FormControl> </form> ); } A: I had a similar issue. In my case, I applied a function directly to onChange so I had something like this: export default function CustomizedSelects() { const classes = useStyles(); const [age, setAge] = React.useState(10); return ( <form className={classes.root} autoComplete="off"> <FormControl className={classes.margin}> <Select value={age} className={classes.inner} onChange={(event) => setAge(event.target.value)} input={<BootstrapInput name="currency" id="currency-customized-select" />} > <MenuItem value={10}>Ten</MenuItem> <MenuItem value={20}>Twenty</MenuItem> <MenuItem value={30}>Thirty</MenuItem> </Select> </FormControl> </form> ); } I also had a separate button to clear select value (or select the default empty value). All was working, the select value was set correctly, except the Select component did not animate to its default form - when no value is selected. I fixed the problem by moving onChange to a handleChange separate function as it is in the code example @B4BIPIN is presenting. I am not an expert in React and still learning and this was a good lesson. I hope this helps ;-) A: Take a list of objects you want to display in the Select dropdown and initialise it using useState. Use the state now to show the value and update the state on the change of the dropdown. const ackList = [ { key: 0, value: "Not acknowledged", }, { key: 1, value: "Acknowledged", }, ]; function AcknowledgementList() { //state to initialise the first from the list const [acknowledge, setAcknowledge] = useState(ackList[1]); //update the state's value on change const handleChange2 = (event) => { setAcknowledge(ackList[event.target.value]); }; return ( <TextField select fullWidth value={acknowledge.key} onChange={handleChange2} variant="outlined" > {ackList.map((ack) => ( <MenuItem key={ack.key} value={ack.key}> {ack.value} </MenuItem> ))} </TextField> ); } A: The problem here is all to do with some pretty poor coding on the part of the MUI folks, where on several components, they have magic strings and really are doing silly things. Let's take a look at the state here: const [age, setAge] = React.useState('3'); You can see that we are having to specify the VALUE as a string. Indeed the data type that the Select control takes is a string | undefined. So the fact we are having to use a number value as a string is the source of confusion. So how does that work? It is all to do with the MenuItem component. Let's take a look: <MenuItem value={1}>First Choice</MenuItem> <MenuItem value={2}>Second Choice</MenuItem> <MenuItem value={3}>Third Choice</MenuItem> You can see that we are indeed having to specify the VALUE of the MenuItem as a number. So in this case, specifying '3' as the State value, as a string, will select the Third Choice on load. You can set the VALUE in the Select control as the state value. Don't forget, when handling the onChange event, that you will need to convert the event.target.value to string.
{ "language": "en", "url": "https://stackoverflow.com/questions/52182673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "42" }
Q: Blazor @bind + @onchange for a select html tag I am trying to bind an enum value to a select tag and handle an @onchange event at the same time, this is the code: <select @bind="Val" @onchange="OnChange"> @foreach(var v in Enum.GetValues<MyEnum>()) { <option value="@v">@v</option> } </select> @code{ MyEnum Val = MyEnum.Default; void OnChange(){ Console.WriteLine("Value changed"); } } But it is telling me that onchange event is already being used in the @bind, so how can I have an onchange event while binding the value. What is the correct event for tag change
{ "language": "en", "url": "https://stackoverflow.com/questions/71380421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ListView Images change back to original settings when scrolled out of view - Android I have a ListView that contains multiple ListView items. The ListView items Layout contains an ImageView. I use this ImageView as a button. When the button is clicked it changes the ImageView from a gray image to a green image. But when I scroll the ImageView out of visible view and then back to it, it returns to its original color. When the ImageView is created it can be either green or gray, it depends on a JSON array. So if an image is green and clicked it turns to gray. Then when its out of visible view and returned to visible view it is green again! How can I make the images maintain their new state? Here is my code, if(p.getJSON().equals("NO")){ imageView.setBackgroundResource(R.drawable.gray); imageView.setTag(0); }//end if equals NO if(p.getJSON().equals("YES")){ imageView.setClickable(false); imageView.setBackgroundResource(R.drawable.green); imageView.setTag(1); }//end if equals yes imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View imageView) { final int status = (Integer) imageView.getTag(); if (status == 0){ imageView.setBackgroundResource(R.drawable.green); imageView.setTag(1); } else{ imageView.setBackgroundResource(R.drawable.gray); imageView.setTag(0); } }//end on click }); A: You need to persist the state for the items that you have modified with the button press and then restore that state when your adapter's getView() is called for that item. There are many ways you can do this: in memory, database, etc. You'll have to pick the method that works best for your purposes. i.e. - item 3 gets clicked and the image changes from grey to green, store something to represent the state of the image (grey vs. green, a boolean would be great for this exact case) and then persist that data somewhere. Then when getView() gets called again for item 3 (it's about to be displayed again) you set the color of the image based on the data you persisted for item 3. You could just modify the value in the original JSONArray that backs the ListView, btw. A: The reason for this behaviour is because you do not persist the state of the items (if they were clicked or not). Each time the list is scrolled, the getView() is called and it executes the following code and the state is reset: if(p.getJSON().equals("NO") ){ imageView.setBackgroundResource(R.drawable.gray); imageView.setTag(0); }//end if equals NO if(p.getJSON().equals("YES")){ imageView.setClickable(false); imageView.setBackgroundResource(R.drawable.green); imageView.setTag(1); }//end if equals yes What is needed is a way to keep track of the state of each item based on its position. So you could confidently tell: item at position k is "YES" or "NO"! You need to keep track of the items which have been clicked so that when getView() is called, you can update the state of the based on its current value (not based on JSON value). 1) Maintain a map of items positions which are checked, and corresponding state value ("YES" or "NO"). 2) If item is clicked, add its (position, new state) to the map. If it is clicked again, update its state inside the map. 3) Use this map and set the state of the item in the getView(), something like: Private field: HashMap<Integer, String> map = new HashMap<Integer, String>(); In your getView(): String state = p.getJSON(); if(map.containsKey(position)) { state = map.get(position); } if(state.equals("NO") ){ imageView.setBackgroundResource(R.drawable.gray); imageView.setTag(0); }//end if equals NO if(state.equals("YES")){ imageView.setClickable(false); imageView.setBackgroundResource(R.drawable.green); imageView.setTag(1); }//end if equals yes final int pos = position; imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View imageView) { final int status = (Integer) imageView.getTag(); if (status == 0){ imageView.setBackgroundResource(R.drawable.green); imageView.setTag(1); map.put(pos, "YES") } else { imageView.setBackgroundResource(R.drawable.gray); imageView.setTag(0); map.put(pos, "NO") } }//end on click }); Note: this is just one of the many ways of getting what you want, however the basic idea should be the same..
{ "language": "en", "url": "https://stackoverflow.com/questions/20232964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set AuthComponent when doing a manual login with AJAX Using CakePHP 2.0, when logging in the normal way, a helpful set of cookies is set and accessible via AuthComponent::user(). However, this does not get set when doing it the AJAX way. The verification works fine, but I would like to figure out how to set AuthComponent without a hard refresh. Maybe I could do without AuthComponent and just store cookies, but I wanted to check to see if there's an easy way to do this before doing all of that work. I've checked the JsHelper and Authentication pages in the CakePHP 2.0 documentation. Any ideas? A: Why dont you create a function in the user around the lines of: public function autologin() { $this->autoRender = false; if ($this->request->is('post')) { if ($this->Auth->login()) { $cuser = $this->Auth->user(); $this->Session->write('Udata', $udata); $fD = array('loggedIn'=>true,'vdata'=>$udata); } else { $fD = array('loggedIn'=>false,'vdata'=>'Your username/password combination was incorrect'); } echo json_encode($fD); } } and call this page with your ajax. with the JSON run some check;
{ "language": "en", "url": "https://stackoverflow.com/questions/16774509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Curl request not working but works fine in POSTMAN I am trying to login to MCA portal ( POST URL : http://www.mca.gov.in/mcafoportal/loginValidateUser.do ) I tried logging in with POSTMAN app on Google Chrome which works fine. However, it doesnt work either in PHP/Python. I am not able to login through PHP/Python Here is the PHP Code : $url="http://www.mca.gov.in/mcafoportal/loginValidateUser.do"; $post_fields = array(); $post_fields['userNamedenc']='hGJfsdnk`1t'; $post_fields['passwordenc']='675894242fa9c66939d9fcf4d5c39d1830f4ddb9'; $post_fields['accessCode'] = "" $str = call_post_mca($url, $post_fields); $str = str_replace("&nbsp;","",$str); $dom = new DOMDocument(); $dom->loadHTML($str); $xpath = new DOMXPath($dom); $input_id = '//input[@id="login_accessCode"]/@value'; $input_val = $xpath->query($input_id)->item(0); $input_val1 = $input_val->nodeValue; $url="http://www.mca.gov.in/mcafoportal/loginValidateUser.do"; $post_fields['userNamedenc']='hGJfsdnk`1t'; $post_fields['passwordenc']='675894242fa9c66939d9fcf4d5c39d1830f4ddb9'; $post_fields['accessCode'] = $input_val1; //New Accesscode function call_post_mca($url, $params) { #$user_agent = getRandomUserAgent(); $user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"; $str = ""; foreach($params as $key=>$value) { $str = $str . "$key=$value" . "&"; } $postData = rtrim($str, "&"); $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); curl_setopt($ch,CURLOPT_HEADER, false); #curl_setopt($ch, CURLOPT_CAINFO, DOC_ROOT . '/includes/cacert.pem'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt($ch,CURLOPT_USERAGENT, $user_agent); curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt ($ch, CURLOPT_REFERER, $url); $cookie= DOC_ROOT . "/cookie.txt"; curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie); curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie); $output=curl_exec($ch); curl_close($ch); return $output; } Any idea what is missing ? A: The site does a redirect, so you need to add CURLOPT_FOLLOWLOCATION => 1 to your options array. When in doubt with cURL, try $status = curl_getinfo($curl); echo json_encode($status, JSON_PRETTY_PRINT); giving : { "url": "http:\/\/www.mca.gov.in\/mcafoportal\/loginValidateUser.do?userNamedenc=hGJfsdnk%601t&passwordenc=675894242fa9c66939d9fcf4d5c39d1830f4ddb9&accessCode=-825374456", "content_type": "text\/plain", "http_code": 302, "header_size": 1560, "request_size": 245, "filetime": -1, "ssl_verify_result": 0, "redirect_count": 0, "total_time": 1.298891, "namelookup_time": 0.526375, "connect_time": 0.999786, "pretransfer_time": 0.999844, "size_upload": 0, "size_download": 0, "speed_download": 0, "speed_upload": 0, "download_content_length": 0, "upload_content_length": -1, "starttransfer_time": 1.298875, "redirect_time": 0, "redirect_url": "http:\/\/www.mca.gov.in\/mcafoportal\/login.do", "primary_ip": "115.114.108.120", "certinfo": [], "primary_port": 80, "local_ip": "192.168.1.54", "local_port": 62524 } As you can see, you got a 302 redirect status, but a redirect_count was 0. After adding the option, i get: { "url": "http:\/\/www.mca.gov.in\/mcafoportal\/login.do", "content_type": "text\/html;charset=ISO-8859-1", "http_code": 200, "header_size": 3131, "request_size": 376, "filetime": -1, "ssl_verify_result": 0, "redirect_count": 1, "total_time": 2.383609, "namelookup_time": 1.7e-5, "connect_time": 1.7e-5, "pretransfer_time": 4.4e-5, "size_upload": 0, "size_download": 42380, "speed_download": 17779, "speed_upload": 0, "download_content_length": 42380, "upload_content_length": -1, "starttransfer_time": 0.30734, "redirect_time": 0.915858, "redirect_url": "", "primary_ip": "14.140.191.120", "certinfo": [], "primary_port": 80, "local_ip": "192.168.1.54", "local_port": 62642 } EDIT url encode the request parameters , and follow redirects $str = urlencode("userNamedenc=hGJfsdnk%601t&passwordenc=675894242fa9c66939d9fcf4d5c39d1830f4ddb9&accessCode=-825374456"); curl_setopt_array( $curl , array ( CURLOPT_URL => "http://www.mca.gov.in/mcafoportal/loginValidateUser.do" , // <- removed parameters here CURLOPT_RETURNTRANSFER => true , CURLOPT_ENCODING => "" , CURLOPT_FOLLOWLOCATION => 1 , CURLOPT_MAXREDIRS => 10 , CURLOPT_TIMEOUT => 30 , CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1 , CURLOPT_CUSTOMREQUEST => "POST" , CURLOPT_POSTFIELDS => $str, // <- added this here CURLOPT_HTTPHEADER => array ( "cache-control: no-cache" ) , ) ); A: The simplest thing you can do, since you already have it working in POSTMAN, is to render out the PHP code in POSTMAN. Here is link about to get PHP code from POSTMAN. Then you can compare the POSTMAN example to your code. <?php $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "http://www.mca.gov.in/mcafoportal/loginValidateUser.do?userNamedenc=hGJfsdnk%601t&passwordenc=675894242fa9c66939d9fcf4d5c39d1830f4ddb9&accessCode=", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_HTTPHEADER => array( "cache-control: no-cache", "postman-token: b54abdc0-17be-f38f-9aba-dbf8f007de99" ), )); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } What is immediately popping out to me is this 'hGJfsdnk`1t'. The backward quote can be an escape character '`'. This could very well be throwing an error where error handling redirects back to the login page. POSTMAN likely has something built in to render out the escape character to 'hGJfsdnk%601t'. Thus, this works in POSTMAN, but not in your code. Here is the status of this request: { "url": "http:\/\/www.mca.gov.in\/mcafoportal\/login.do", "content_type": "text\/html;charset=ISO-8859-1", "http_code": 200, "header_size": 3020, "request_size": 821, "filetime": -1, "ssl_verify_result": 0, "redirect_count": 1, "total_time": 2.920125, "namelookup_time": 8.2e-5, "connect_time": 8.7e-5, "pretransfer_time": 0.000181, "size_upload": 0, "size_download": 42381, "speed_download": 14513, "speed_upload": 0, "download_content_length": -1, "upload_content_length": -1, "starttransfer_time": 0.320995, "redirect_time": 2.084554, "redirect_url": "", "primary_ip": "115.114.108.120", "certinfo": [], "primary_port": 80, "local_ip": "192.168.1.3", "local_port": 45086 } Here is shows the successful login. A: This is honestly one of weird sites I have seen in a long time. First thing was to know how it works. So I decided to use chrome and see what happens when we login with wrong data Observations: * *Blanks username and passwords fields *Generates SHA1 hashes of username and password fields and sets then in userNamedenc and respectively *We can override username and password directly in JavaScript and login to your account just by overriding the details from console. *There are lot of different request which generates cookies but none of them look any useful So the approach to solve the issue was to follow below steps * *Get the login url login.do *Fetch the form details from the response for the access code *Submit the form to loginValidateUser.do The form sends below parameters Now one interesting part of the same is below post data displayCaptcha:true userEnteredCaptcha:strrty If we override the displayCaptcha to false then captcha is no more needed. So a wonderful bypass displayCaptcha: false Next was to code all of the above in PHP, but the site seemed so weird that many of the attempts failed. So finally I realized that we need to take it a bit closer to the browser login and also I felt delays between calls are needed <?php require_once("curl.php"); $curl = new CURL(); $default_headers = Array( "Accept" => "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "Accept-Encoding" => "deflate", "Accept-Language" => "en-US,en;q=0.8", "Cache-Control" => "no-cache", "Connection" => "keep-alive", "DNT" => "1", "Pragma" => "no-cache", "Referer" => "http://www.mca.gov.in/mcafoportal/login.do", "Upgrade-Insecure-Requests" => "1" ); // Get the login page $curl ->followlocation(0) ->cookieejar("") ->verbose(1) ->get("http://www.mca.gov.in/mcafoportal/login.do") ->header($default_headers) ->useragent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36") ->execute(); // Save the postfileds and access code as we would need them later for the POST field $post = $curl->loadInputFieldsFromResponse() ->updatePostParameter(array( "displayCaptcha" => "false", "userNamedenc" => "hGJfsdnk`1t", "passwordenc" => "675894242fa9c66939d9fcf4d5c39d1830f4ddb9", "userName" => "", "Cert" => "")) ->referrer("http://www.mca.gov.in/mcafoportal/login.do") ->removePostParameters( Array("dscBasedLoginFlag", "maxresults", "fe", "query", "SelectCert", "newUserRegistration") ); $postfields = $curl->getPostFields(); var_dump($postfields); // Access some dummy URLs to make it look like browser $curl ->get("http://www.mca.gov.in/mcafoportal/js/global.js")->header($default_headers)->execute()->sleep(2) ->get("http://www.mca.gov.in/mcafoportal/js/loginValidations.js")->header($default_headers)->execute()->sleep(2) ->get("http://www.mca.gov.in/mcafoportal/css/layout.css")->header($default_headers)->execute()->sleep(2) ->get("http://www.mca.gov.in/mcafoportal/img/bullet.png")->header($default_headers)->execute()->sleep(2) ->get("http://www.mca.gov.in/mcafoportal/getCapchaImage.do")->header($default_headers)->execute()->sleep(2); // POST to the login form the postfields saved earlier $curl ->sleep(20) ->header($default_headers) ->postfield($postfields) ->referrer("http://www.mca.gov.in/mcafoportal/login.do") ->post("http://www.mca.gov.in/mcafoportal/loginValidateUser.do") ->execute(false) ->sleep(3) ->get("http://www.mca.gov.in/mcafoportal/login.do") ->header($default_headers) ->execute(true); // Get the response from last GET of login.do $curl->getResponseText($output); //Check if user name is present in the output or not if (stripos($output, "Kiran") > 0) { echo "Hurray!!!! Login succeeded"; } else { echo "Login failed please retry after sometime"; } After running the code it works few times and few times it doesn't. My observations * *Only one login is allowed at a time. So not sure if others were using the login when I was testing *Without delays it would fail most of the time *There is no obvious reason when it fails to login except the site doing something on server side to block the request The reusable curl.php I created and used for chaining methods is below <?php class CURL { protected $ch; protected $postfields; public function getPostFields() { return $this->postfields; } public function newpost() { $this->postfields = array(); return $this; } public function addPostFields($key, $value) { $this->postfields[$key]=$value; return $this; } public function __construct() { $ch = curl_init(); $this->ch = $ch; $this->get()->followlocation()->retuntransfer(); //->connectiontimeout(20)->timeout(10); } function url($url) { curl_setopt($this->ch, CURLOPT_URL, $url); return $this; } function verbose($value = true) { curl_setopt($this->ch, CURLOPT_VERBOSE, $value); return $this; } function post($url='') { if ($url !== '') $this->url($url); curl_setopt($this->ch, CURLOPT_POST, count($this->postfields)); curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($this->postfields)); return $this; } function postfield($fields) { if (is_array($fields)){ $this->postfields = $fields; } return $this; } function close() { curl_close($this->ch); return $this; } function cookieejar($cjar) { curl_setopt($this->ch, CURLOPT_COOKIEJAR, $cjar); return $this; } function cookieefile($cfile) { curl_setopt($this->ch, CURLOPT_COOKIEFILE, $cfile); return $this; } function followlocation($follow = 1) { curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, $follow); return $this; } function loadInputFieldsFromResponse($response ='') { if ($response) $doc = $response; else $doc = $this->lastCurlRes; /* @var $doc DOMDocument */ //simplexml_load_string($data) $this->getResponseDoc($doc); $this->postfields = array(); foreach ($doc->getElementsByTagName('input') as $elem) { /* @var $elem DomNode */ $name = $elem->getAttribute('name'); // if (!$name) // $name = $elem->getAttribute('id'); if ($name) $this->postfields[$name] = $elem->getAttribute("value"); } return $this; } function retuntransfer($transfer=1) { curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, $transfer); return $this; } function connectiontimeout($connectiontimeout) { curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, $connectiontimeout); return $this; } function timeout($timeout) { curl_setopt($this->ch, CURLOPT_TIMEOUT, $timeout); return $this; } function useragent($useragent) { curl_setopt($this->ch, CURLOPT_USERAGENT, $useragent); return $this; } function referrer($referrer) { curl_setopt($this->ch, CURLOPT_REFERER, $referrer); return $this; } function getCURL() { return $this->ch; } protected $lastCurlRes; protected $lastCurlResInfo; function get($url = '') { if ($url !== '') $this->url($url); curl_setopt($this->ch, CURLOPT_POST, 0); curl_setopt($this->ch, CURLOPT_HTTPGET, true); return $this; } function sleep($seconds){ sleep($seconds); return $this; } function execute($output=false) { $this->lastCurlRes = curl_exec($this->ch); if ($output == true) { echo "Response is \n " . $this->lastCurlRes; file_put_contents("out.html", $this->lastCurlRes); } $this->lastCurlResInfo = curl_getinfo($this->ch); $this->postfields = array(); return $this; } function header($headers) { //curl_setopt($this->ch, CURLOPT_HEADER, true); curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers); return $this; } function getResponseText(&$text){ $text = $this->lastCurlRes; return $this; } /* * * @param DOMDocument $doc * * */ function getResponseDoc(&$doc){ $doc = new DOMDocument(); libxml_use_internal_errors(false); libxml_disable_entity_loader(); @$doc->loadHTML($this->lastCurlRes); return $this; } function removePostParameters($keys) { if (!is_array($keys)) $keys = Array($keys); foreach ($keys as $key){ if (array_key_exists($key, $this->postfields)) unset($this->postfields[$key]); } return $this; } function keepPostParameters($keys) { $delete = Array(); foreach ($this->postfields as $key=>$value){ if (!in_array($key, $keys)){ array_push($delete, $key); } } foreach ($delete as $key) { unset($this->postfields[$key]); } return $this; } function updatePostParameter($postarray, $encoded=false) { if (is_array($postarray)) { foreach ($postarray as $key => $value) { if (is_null($value)) unset($this->postfields[$key]); else $this->postfields[$key] = $value; }} elseif (is_string($postarray)) { $parr = preg_split("/&/",$postarray); foreach ($parr as $postvalue) { if (($index = strpos($postvalue, "=")) != false) { $key = substr($postvalue, 0,$index); $value = substr($postvalue, $index + 1); if ($encoded) $this->postfields[$key]=urldecode($value); else $this->postfields[$key]=$value; } else $this->postfields[$postvalue] = ""; } } return $this; } function getResponseXml(){ //SimpleXMLElement('<INPUT/>')->asXML(); } function SSLVerifyPeer($verify=false) { curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $verify); return $this; } } ?> A: @yvesleborg and @tarun-lalwani gave the right hints. You need to take care of the cookies and the redirects. But nevertheless it was not working always for me. I guess the site operator requires some timeout between the two requests. I rewrote your code a little bit to play around with it. mycurl.php: function my_curl_init() { $url="http://www.mca.gov.in/mcafoportal/loginValidateUser.do"; $user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"; $ch = curl_init(); curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); return $ch; } /* * first call in order to get accessCode and sessionCookie */ $ch = my_curl_init(); curl_setopt($ch, CURLOPT_COOKIEJAR, __DIR__ . "/cookie.txt"); // else cookielist is empty $output = curl_exec($ch); file_put_contents(__DIR__ . '/loginValidateUser.html', $output); // save cookie info $cookielist = curl_getinfo($ch, CURLINFO_COOKIELIST); //print_r($cookielist); curl_close($ch); // parse accessCode from output $re = '/\<input.*name="accessCode".*value="([-0-9]+)"/'; preg_match_all($re, $output, $matches, PREG_SET_ORDER, 0); if ($matches) { $accessCode = $matches[0][1]; // debug echo "accessCode: $accessCode" . PHP_EOL; /* * second call in order to login */ $post_fields = array( 'userNamedenc' => 'hGJfsdnk`1t', 'passwordenc' => '675894242fa9c66939d9fcf4d5c39d1830f4ddb9', 'accessCode' => $accessCode ); $cookiedata = preg_split('/\s+/', $cookielist[0]); $session_cookie = $cookiedata[5] . '=' . $cookiedata[6]; // debug echo "sessionCookie: $session_cookie" . PHP_EOL; file_put_contents(__DIR__ . '/cookie2.txt', $session_cookie); /* * !!! pause !!! */ sleep(20); // debug echo "curl -v -L -X POST -b '$session_cookie;' --data 'userNamedenc=hGJfsdnk`1t&passwordenc=675894242fa9c66939d9fcf4d5c39d1830f4ddb9&accessCode=$accessCode' http://www.mca.gov.in/mcafoportal/loginValidateUser.do > loginValidateUser2.html"; $ch = my_curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); curl_setopt($ch, CURLOPT_COOKIE, $session_cookie); $output = curl_exec($ch); file_put_contents(__DIR__ . '/loginValidateUser2.html', $output); curl_close($ch); } The script issues two request to the website. The output of the first one is used to read the accessCode and to store the session cookie. Then after a little break the second one is issued using the accessCode and session information together with the login credentials. I tested it with PHP5.6 from a terminal (php -f mycurl.php). The script debugs all necessary information, outputs a curl command you could use in a terminal and logs the HTML and cookie information to some files in the same folder like the script. Running the script too often doesn't work. The login won't work. So take your time and wait some minutes between your tries. Or change your IP ;) Hope it helps. A: Replication of the Problem I did the same thing in Postman as you did your screenshot but was not able to log in: The only difference I can see is that your request had cookies, which I suspect is why you were able to log in without all the other input fields. And it seems like there are quite a number of input fields: Using Postman So, I used postman intercept to capture all the fields used during a login, including the captcha and access code and I was able to login: Update 1 I've found out that once you've solved a captcha to login, after you've logged out you may login again without displayCaptcha and userEnteredCaptcha in your form data, provided that you use the same cookie as the one you've used to login successfully. You just need to get a valid accessCode from the login page. A: it doesnt work either in PHP/Python that is (as others have already pointed out) because you were using your browser's existing cookie session, which had already solved the captcha. clear your browser cookies, get a fresh cookie session, and DO NOT SOLVE THE CAPTCHA, and Postman won't be able to log in either. Any idea what is missing ? several things, among them, several post login parameters (browserFlag, loginType,__checkbox_dscBasedLoginFlag, and many more), also your encoding loop here is bugged $str = $str . "$key=$value" . "&"; , it pretty much only works as long as both keys and values only contain [a-zA-Z0-9] characters, and since your userNamedenc contains a grave accent character, your encoding loop is insufficient. a fixed loop would be foreach($params as $key=>$value){ $str = $str . urlencode($key)."=".urlencode($value) . "&"; } $str=substr($str,0,-1); , but this is exactly why we have the http_build_query function, that entire loop and the following trim can be replaced with this single line: $str=http_build_query($params); , also, seems you're trying to login without a pre-existing cookie session, that's not going to work. when you do a GET request to the login page, you get a cookie, and a unique captcha, the captcha answer is tied to your cookie session, and needs to be solved before you attempt to login, you also provide no code to deal with the captcha. also, when parsing the "userName" input element, it will default to "Enter Username", which is emtied with javascript and replaced with userNamedenc, you must replicate this in PHP, also, it will have an input element named "dscBasedLoginFlag", which is removed with javascript, you must also do this part in php, also it has an input element named "Cert", which has a default value, but this value is cleared with javascript, do the same in php, and an input element named "newUserRegistration", which is removed with javascript, do that, here's what you should do: make a GET request to the login page, save the cookie session and make sure to provide it for all further requests, and parse out all the login form's elements and add them to your login request (but be careful, there is 2x form inputs, 1 belong to the search bar, only parse the children of the login form, don't mix the 2), and remember to clear/remove the special input tags to emulate the javascript, as described above, then make a GET request to the captcha url, make sure to provide the session cookie, solve the captcha, then make the final login request, with the captcha answer, and userNamedenc and passwordenc and all the other elements parsed out from the login page... that should work. now, solving the captcha programmatically, the captha doesn't look too hard, cracking it probably can be automated, but until someone actually does that, you can use Deathbycaptcha to do it for you, however note that it isn't a free service. here's a fully tested, working example implementation, using my hhb_curl library (from https://github.com/divinity76/hhb_.inc.php/blob/master/hhb_.inc.php ), and the Deathbycaptcha api: <?php declare(strict_types = 1); header ( "content-type: text/plain;charset=utf8" ); require_once ('hhb_.inc.php'); const DEATHBYCATPCHA_USERNAME = '?'; const DEATHBYCAPTCHA_PASSWORD = '?'; $hc = new hhb_curl ( '', true ); $hc->setopt(CURLOPT_TIMEOUT,20);// im on a really slow net atm :( $html = $hc->exec ( 'http://www.mca.gov.in/mcafoportal/login.do' )->getResponseBody (); // cookie session etc $domd = @DOMDocument::loadHTML ( $html ); $inputs = getDOMDocumentFormInputs ( $domd, true ) ['login']; $params = [ ]; foreach ( $inputs as $tmp ) { $params [$tmp->getAttribute ( "name" )] = $tmp->getAttribute ( "value" ); } assert ( isset ( $params ['userNamedenc'] ), 'username input not found??' ); assert ( isset ( $params ['passwordenc'] ), 'passwordenc input not found??' ); $params ['userName'] = ''; // defaults to "Enter Username", cleared with javascript unset ( $params ['dscBasedLoginFlag'] ); // removed with javascript $params ['Cert'] = ''; // cleared to emptystring with javascript unset ( $params ['newUserRegistration'] ); // removed with javascript unset ( $params ['SelectCert'] ); // removed with javascript $params ['userNamedenc'] = 'hGJfsdnk`1t'; $params ['passwordenc'] = '675894242fa9c66939d9fcf4d5c39d1830f4ddb9'; echo 'parsed login parameters: '; var_dump ( $params ); $captchaRaw = $hc->exec ( 'http://www.mca.gov.in/mcafoportal/getCapchaImage.do' )->getResponseBody (); $params ['userEnteredCaptcha'] = solve_captcha2 ( $captchaRaw ); // now actually logging in. $html = $hc->setopt_array ( array ( CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query ( $params ) ) )->exec ( 'http://www.mca.gov.in/mcafoportal/loginValidateUser.do' )->getResponseBody (); var_dump ( $hc->getStdErr (), $hc->getStdOut () ); // printing debug data $domd = @DOMDocument::loadHTML ( $html ); $xp = new DOMXPath ( $domd ); $loginErrors = $xp->query ( '//ul[@class="errorMessage"]' ); if ($loginErrors->length > 0) { echo 'encountered following error(s) logging in: '; foreach ( $loginErrors as $err ) { echo $err->textContent, PHP_EOL; } die (); } echo "logged in successfully!"; /** * solves the captcha manually, by doing: echo ANSWER>captcha.txt * * @param string $raw_image * raw image bytes * @return string answer */ function solve_captcha2(string $raw_image): string { $imagepath = getcwd () . DIRECTORY_SEPARATOR . 'captcha.png'; $answerpath = getcwd () . DIRECTORY_SEPARATOR . 'captcha.txt'; @unlink ( $imagepath ); @unlink ( 'captcha.txt' ); file_put_contents ( $imagepath, $raw_image ); echo 'the captcha is saved in ' . $imagepath . PHP_EOL; echo ' waiting for you to solve it by doing: echo ANSWER>' . $answerpath, PHP_EOL; while ( true ) { sleep ( 1 ); if (file_exists ( $answerpath )) { $answer = trim ( file_get_contents ( $answerpath ) ); echo 'solved: ' . $answer, PHP_EOL; return $answer; } } } function solve_captcha(string $raw_image): string { echo 'solving captcha, hang on, with DEATBYCAPTCHA this usually takes between 10 and 20 seconds.'; { // unfortunately, CURLFile requires a filename, it wont accept a string, so make a file of it $tmpfileh = tmpfile (); fwrite ( $tmpfileh, $raw_image ); // TODO: error checking (incomplete write or whatever) $tmpfile = stream_get_meta_data ( $tmpfileh ) ['uri']; } $hc = new hhb_curl ( '', true ); $hc->setopt_array ( array ( CURLOPT_URL => 'http://api.dbcapi.me/api/captcha', CURLOPT_POSTFIELDS => array ( 'username' => DEATHBYCATPCHA_USERNAME, 'password' => DEATHBYCAPTCHA_PASSWORD, 'captchafile' => new CURLFile ( $tmpfile, 'image/png', 'captcha.png' ) ) ) )->exec (); fclose ( $tmpfileh ); // when tmpfile() is fclosed(), its also implicitly deleted. $statusurl = $hc->getinfo ( CURLINFO_EFFECTIVE_URL ); // status url is given in a http 300x redirect, which hhb_curl auto-follows while ( true ) { // wait for captcha to be solved. sleep ( 10 ); echo '.'; $json = $hc->setopt_array ( array ( CURLOPT_HTTPHEADER => array ( 'Accept: application/json' ), CURLOPT_HTTPGET => true ) )->exec ()->getResponseBody (); $parsed = json_decode ( $json, false ); if (! empty ( $parsed->captcha )) { echo 'captcha solved!: ' . $parsed->captcha, PHP_EOL; return $parsed->captcha; } } } function getDOMDocumentFormInputs(\DOMDocument $domd, bool $getOnlyFirstMatches = false): array { // :DOMNodeList? $forms = $domd->getElementsByTagName ( 'form' ); $parsedForms = array (); $isDescendantOf = function (\DOMNode $decendant, \DOMNode $ele): bool { $parent = $decendant; while ( NULL !== ($parent = $parent->parentNode) ) { if ($parent === $ele) { return true; } } return false; }; // i can't use array_merge on DOMNodeLists :( $merged = function () use (&$domd): array { $ret = array (); foreach ( $domd->getElementsByTagName ( "input" ) as $input ) { $ret [] = $input; } foreach ( $domd->getElementsByTagName ( "textarea" ) as $textarea ) { $ret [] = $textarea; } foreach ( $domd->getElementsByTagName ( "button" ) as $button ) { $ret [] = $button; } return $ret; }; $merged = $merged (); foreach ( $forms as $form ) { $inputs = function () use (&$domd, &$form, &$isDescendantOf, &$merged): array { $ret = array (); foreach ( $merged as $input ) { // hhb_var_dump ( $input->getAttribute ( "name" ), $input->getAttribute ( "id" ) ); if ($input->hasAttribute ( "disabled" )) { // ignore disabled elements? continue; } $name = $input->getAttribute ( "name" ); if ($name === '') { // echo "inputs with no name are ignored when submitted by mainstream browsers (presumably because of specs)... follow suite?", PHP_EOL; continue; } if (! $isDescendantOf ( $input, $form ) && $form->getAttribute ( "id" ) !== '' && $input->getAttribute ( "form" ) !== $form->getAttribute ( "id" )) { // echo "this input does not belong to this form.", PHP_EOL; continue; } if (! array_key_exists ( $name, $ret )) { $ret [$name] = array ( $input ); } else { $ret [$name] [] = $input; } } return $ret; }; $inputs = $inputs (); // sorry about that, Eclipse gets unstable on IIFE syntax. $hasName = true; $name = $form->getAttribute ( "id" ); if ($name === '') { $name = $form->getAttribute ( "name" ); if ($name === '') { $hasName = false; } } if (! $hasName) { $parsedForms [] = array ( $inputs ); } else { if (! array_key_exists ( $name, $parsedForms )) { $parsedForms [$name] = array ( $inputs ); } else { $parsedForms [$name] [] = $tmp; } } } unset ( $form, $tmp, $hasName, $name, $i, $input ); if ($getOnlyFirstMatches) { foreach ( $parsedForms as $key => $val ) { $parsedForms [$key] = $val [0]; } unset ( $key, $val ); foreach ( $parsedForms as $key1 => $val1 ) { foreach ( $val1 as $key2 => $val2 ) { $parsedForms [$key1] [$key2] = $val2 [0]; } } } return $parsedForms; } example usage: in terminal, write php foo.php | tee test.html, after a few seconds it will say something like: the captcha is saved in /home/captcha.png waiting for you to solve it by doing: echo ANSWER>/home/captcha.txt then look at the captcha in /home/captcha.png , solve it, and write in another terminal: echo ANSWER>/home/captcha.txt, now the script will log in, and dump the logged in html in test.html, which you can open in your browser, to confirm that it actually logged in, screenshot when i run it: https://image.prntscr.com/image/_AsB_0J6TLOFSZuvQdjyNg.png also note that i made 2 captcha solver functions, 1 use the deathbycaptcha api, and wont work until you provide a valid and credited deathbycaptcha account on line 5 and 6, which is not free, the other 1, solve_captcha2, asks you to solve the captcha yourself, and tells you where the captcha image is saved (so you can go have a look at it), and what command line argument to write, to provide it with the answer. just replace solve_captcha with solve_captcha2 on line 28, to solve it manually, and vise-versa. the script is fully tested with solve_captcha2, but the deathbycaptcha solver is untested, as my deathbycatpcha account is empty (if you would like to make a donation so i can actually test it, send 7 dollars to paypal account divinity76@gmail.com with a link to this thread, and i will buy the cheapest deathbycaptcha credit pack and actually test it) * *disclaimer: i am not associated with deathbycaptcha in any way (except that i was a customer of theirs a couple of years back), and this post was not sponsored.
{ "language": "en", "url": "https://stackoverflow.com/questions/46377462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Child nodes Appear in Every Parent Nodes Child nodes appear in every parent nodes. Expected result is that child nodes will appear on a specific parent node. There is also an instance where a children node has a children node again. We were advised not to use a library for this one because before, we used ngx tree view but when we use it, we encounter difficulty in filtering the tree view content when we use other search text box. First thing I did is to use FOR loop for the parent nodes. I use IF condition to compare if this parent node has a children(in array of objects). If the IF condition satisfied, this child nodes will be push into an array for THAT SPECIFIC PARENT NODE and also return a boolean variable that will be used in *ngIf. The data passed by this.service.Hierarchy(); is [{text: "Parent1", value: 1, children: Array(5), checked: false}, {text: "Parent2", value: 1, children: Array(0), checked: false}, {text: "Parent3", value: 1, children: Array(0), checked: false}, {text: "Parent4", value: 1, children: Array(0), checked: false},] at .ts file createTree() { let hierarchy= this.service.Hierarchy(); //data passed this.treeComponent = hierarchy; for(let i=0; i<this.treeComponent.length; i++){ //Compare parent if has a children, Example 1 has a children if(this.treeComponent[i].children.length != 0 ){ for(var children of this.treeComponent[i].children){ //use for ngIF this.isChildrenAvailable = true; this.child.push(children); } } }} at .html file <ul *ngFor="let item of treeComponent"> <input type="radio"> {{item.text}} <div *ngIf = "isChildrenAvailable"> <ul *ngFor="let child of child" > <input type="radio"> {{child.text}} </ul> </div> </ul> Expected result: * *Parent 1 Child 1(child of parent 1) Child 2 (child of parent 1) ` * Child Child 1 (children of children 2) *Parent 2 *Parent 3 Actual result: * *Parent 1 Child 1(child of parent 1) Child 2 (child of parent 1) *Parent 2 Child 1(child of parent 1) Child 2 (child of parent 1) *Parent 3 Child 1(child of parent 1) Child 2 (child of parent 1) A: you can simply iterate over the child array in the template, if you need support for endless nesting, you can use recursive components/templates <ul> <li *ngFor="let item of treeComponent"> <input type="radio">{{item.text}} <div *ngIf="item.children.length"> <ul> <li *ngFor="let child of item.children"> <input type="radio">{{child.text}} </li> </ul> </div> </li> </ul>
{ "language": "en", "url": "https://stackoverflow.com/questions/56201674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Move a file from the current users desktop? I was making a installer for some program I made, and I was wondering if I could copy the folder with the contents from the Current Users desktop to another area, how would I do so?Im using: My.Computer.FileSystem.MoveFile("", "") Move the folder "Emailer" (on the desktop) to System files (x86) A: To acces path to the desktop use: Environment.GetFolderPath(Environment.SpecialFolder.Desktop) A: After you've obtained the desktop location (as Garath has pointed out in his answer), check out File.Move in the System.IO namespace. e.g File.Move(path, path2); http://msdn.microsoft.com/en-us/library/system.io.file.move.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/15991020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to access react-spring variables inside a nested tag I have the following code on which I would like to move the line strokeDashoffset={spring.x.interpolate(x => strokeDasharray - x)} inside the <polygon ... tag. function Star(props) { const strokeDasharray = 156 const spring = useSpring( { to: { x: strokeDasharray * (props.is/props.max), points: props.is }, } ) return( <animated.svg viewBox="0 0 45 45" style={{ margin: "0px", width: "45px", height: "45px" }} strokeDashoffset={spring.x.interpolate(x => strokeDasharray - x)} > <polygon fill="#hite" stroke="red" strokeDasharray={strokeDasharray} points="22.5 35.25 8.68704657 42.5118994 11.3250859 27.1309497 0.150171867 16.2381006 15.5935233 13.9940503 22.5 0 29.4064767 13.9940503 44.8498281 16.2381006 33.6749141 27.1309497 36.3129534 42.5118994" /> </animated.svg> ) } I want that, because I would like to add another path inside the svg with other values. When I move it, the animation is gone and the path is fully filled immediately. But why? How can I access the spring.x value inside the polygon instead of just inside the animated.svg? A: It is way easier than I thought: Just use <animated.polygon ... /> instead of <animated.svg .../>
{ "language": "en", "url": "https://stackoverflow.com/questions/65270847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Interaction has already been acknowledged Discord.js This command keeps on returning Interaction has already been acknowledged. How can I solve this? Here's the code I'm currently using: const { SlashCommandBuilder, EmbedBuilder, ButtonStyle, ButtonBuilder, ActionRowBuilder, ActionRow, } = require("discord.js"); module.exports = { data: new SlashCommandBuilder() .setName("highlow") .setDescription(" | Starts a new high or low game!"), async execute(interaction) { const randomNumber = Math.floor(Math.random() * 100) + 1; const hintNumber = Math.floor(Math.random() * 100) + 1; const row = new ActionRowBuilder().addComponents( new ButtonBuilder() .setLabel("High") .setStyle("Secondary") .setCustomId("high"), new ButtonBuilder() .setCustomId("low") .setLabel("Low") .setStyle("Secondary"), new ButtonBuilder() .setCustomId("correct") .setLabel("Same") .setStyle("Secondary") ); const sent = await interaction.reply({ content: `Is my number higher or lower than ${hintNumber}?`, components: [row], fetchReply: true, }); const collector = sent.createMessageComponentCollector({ filter: (i) => i.user.id === interaction.user.id && i.message.id === sent.id, time: 30000, max: 1, }); let won = false; collector.on("collect", async (i) => { await i.deferUpdate({ fetchReply: true }); row.components.forEach((b) => b.setDisabled(true)); if (i.customId === "high") { if (hintNumber > randomNumber) { row.components.forEach((b) => { if (b.customId === "high") b.setStyle("Danger"); }); await interaction.editReply({ content: `Sadge, you got it wrong! It was ${randomNumber}`, components: [row], }); won = false; } else { row.components.forEach((b) => { if (b.customId === "high") b.setStyle("Success"); }); await interaction.editReply({ content: `You guessed the number! It was ${randomNumber}`, components: [row], }); won = true; } } else if (i.customId === "low") { if (hintNumber < randomNumber) { row.components.forEach((b) => { if (b.customId === "low") b.setStyle("Danger"); }); await interaction.editReply({ content: `Sadge, you got it wrong! It was ${randomNumber}`, components: [row], }); won = false; } else { row.components.forEach((b) => { if (b.customId === "low") b.setStyle("Success"); }); await interaction.editReply({ content: `You are right! It was ${randomNumber}`, components: [row], }); won = true; } } else if (i.customId === "correct" && hintNumber === randomNumber) { row.components.forEach((b) => { if (b.customId === "correct") b.setStyle("Success"); }); await interaction.editReply({ content: `You guessed the number! It was ${randomNumber}`, components: [row], }); won = true; } else { await interaction.editReply({ content: `Sadge, you got it wrong! It was ${randomNumber}`, components: [row], }); won = false; } }); collector.on("end", async (collected) => { row.components.forEach((b) => b.setDisabled(true)); if (!won && collected.size === 0) { await interaction.editReply({ content: `You didn't guess the number! It was ${randomNumber}`, components: [row], }); } }); }, }; The error is showing: C:\Users\Matthew\OneDrive\Documents\Ayanokoji\node_modules\@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:293 throw new DiscordAPIError.DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData); ^ DiscordAPIError[40060]: Interaction has already been acknowledged. at SequentialHandler.runRequest (C:\Users\Matthew\OneDrive\Documents\Ayanokoji\node_modules\@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:293:15) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async SequentialHandler.queueRequest (C:\Users\Matthew\OneDrive\Documents\Ayanokoji\node_modules\@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:99:14) at async REST.request (C:\Users\Matthew\OneDrive\Documents\Ayanokoji\node_modules\@discordjs\rest\dist\lib\REST.cjs:52:22) at async ButtonInteraction.deferUpdate (C:\Users\Matthew\OneDrive\Documents\Ayanokoji\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:192:5) at async InteractionCollector.<anonymous> (C:\Users\Matthew\OneDrive\Documents\Ayanokoji\interactions\slash\fun\highlow.js:44:4) { rawError: { message: 'Interaction has already been acknowledged.', code: 40060 }, code: 40060, status: 400, method: 'POST', url: 'https://discord.com/api/v10/interactions/1021755660406374452/aW50ZXJhY3Rpb246MTAyMTc1NTY2MDQwNjM3NDQ1MjpyMjViUU8xSGtzQ1dXZXVXbWh2YmRiczZ5ZldzcVhuYm1hNXdWWFRRSVlUUzk0MXFDV1M2NmRjQWF3MEJXTVo0TmN1UlR3U1QxQnUxVDd1YlZodjdnbnpNRVM5VlVSV1B0aUNSS2ZGZkQ5QURrdlFIenVHaUVZdTRkUmR5YnBVaQ/callback', requestBody: { files: undefined, json: { type: 6 } } } A: On line 44: await i.deferUpdate({ fetchReply: true }); It makes the error because the interaction has already been replied to. The error should go away when you remove this line. You also should replace await interaction.editReply with interaction.followUp on line 51, 60, 71, 80, 90, 96 and 106. And yup I answer your question again.
{ "language": "en", "url": "https://stackoverflow.com/questions/73787113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Navigation Bar and Title in Xcode Simulator I can't get the Navigation Bar Items to show in the app simulator using Xcode 7.2.1. I have my Navigation Controller and my Main Scene. My main scene has a Navigation Item set. This is my setup: But when I run the simulator, there's no title bar. Really frustrating. I've tried changing the status bar and top bar menu options, but to no avail. Any idea how to get them to appear using the Xcode GUI and not programatically? A: Is it possible that you accidentally cleared the "Shows Navigation Bar" setting in the Navigation Controller itself? A: Have you tried deleting your current Navigation Controller in Storyboard and re-embedding your controller in it (or dragging a new Navigation Controller out and setting its default controller by control-dragging to your VC?)
{ "language": "en", "url": "https://stackoverflow.com/questions/35687955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to test libgdx admob on java application if emulator not working? My emulator is not working fine simultaneously I want to test my "libgdx admob" code on my application. Is there any way to test it on desktop application of libgdx? Please help! A: No, there is no way to test the admob code in the desktop version. There are some platform specific things that are not available on the desktop version. This includes the admob view and other Android specific dependencies. I recommend to either try to get the emulator up running, or to find some way to test on a phone. The best is probably to do both.
{ "language": "en", "url": "https://stackoverflow.com/questions/12239488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Meaning of ir as a prefix in Odoo Reading odoo API or source code your would encounter the term ir ( usually as a prefix ), I can't seem to figure out what does it stand for ? for example ir_sequence A: The meaning is Information Repository. A: Although there's no official statement on the matter AFAIK, I tend to think about it as Internal Resource (various resources the system needs to work fine, but not actually meaningful for normal users day-to-day work), just as I think about the res prefix as Resource (which is not internal, it's for normal usage). As example, res.config is to create visual configuration wizards to be presented to a user that may not be the sysadmin (he could be just the sales responsible for example), but many settings are actually stored as ir.config_parameter records, which are only accessible for the sysadmin and are used extensively by Odoo internal code.
{ "language": "en", "url": "https://stackoverflow.com/questions/55476833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to open a listview item on a new page How to display an item on a new page by clicking on the item A: You have to register ItemSelected event handler for you ListView. ListView listViewJson = new ListView(); listViewJson.HasUnevenRows = true; listViewJson.ItemSelected += listViewJson_ItemSelected; In Event Handler, you can get selected item. private void listViewJson_ItemSelected(object sender, SelectedItemChangedEventArgs e) { var item = e.SelectedItem; // Navigate to new page Navigation.PushAsync(new YOUR_PAGE(item)); } And you can develop UI as you want in you new page for displaying a joke. UPDATE You detail page should be like this. I prepared this very roughly. Please make necessary changes. namespace JokesListView { public class JokeDetail : ContentPage { private Joke jk; public JokeDetail(Joke j) { jk = j; Display(); } public void Display() { try { Label lblJoke = new Label(); lblJoke.LineBreakMode = LineBreakMode.WordWrap; lblJoke.Text = jk.joke; Content = lblJoke; } catch (Exception e) { throw e; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/49441114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Dynamic type casting for JsValue field in Scala Play Since I'm writing a function to request data from another API in my Scala code, the response Json has the format like this: "data": { "attributeName": "some String", "attributeValue": false, "attributeSource": "Manual", "attributeValueLabel": null }, "data": { "attributeName": "some String", "attributeValue": "daily", "attributeSource": "Manual", "attributeValueLabel": "Almost Daily" } Note that sometimes the type of attributeValue is String value, some other time it's a Boolean value. So I'm trying to write my own Reads and Writes to read the type dynamically. case class Data(attributeName: Option[String], attributeValue: Option[String], attributeSource: Option[String], attributeValueLabel: Option[String]) object Data{ implicit val readsData: Reads[Data] = { new Reads[Data] { def reads(json: JsValue) = { val attrValue = (json \ "attributeValue").as[] // How to cast to Boolean some time, but some other time is a String here ...... } } } So as you can see in my comment, I'm stuck at the part to cast the (json \ "attributeValue") to String/Boolean, base on the return type of the API. How can I do this? A: You can try to parse it as String first and then as Boolean: val strO = (json \ "attributeValue").asOpt[String] val value: Option[String] = strO match { case str@Some(_) => str case None => (json \ "attributeValue").asOpt[Boolean].map(_.toString) } A: You can use the .orElse function when you are trying to read an attribute in different ways: import play.api.libs.json.{JsPath, Json, Reads} import play.api.libs.functional.syntax._ val json1 = """ |{ | "attributeName": "some String", | "attributeValue": false |} """.stripMargin val json2 = """ |{ | "attributeName": "some String", | "attributeValue": "daily" |} """.stripMargin // I modified you case class to make the example short case class Data(attributeName: String, attributeValue: String) object Data { // No need to define a reads function, just assign the value implicit val readsData: Reads[Data] = ( (JsPath \ "attributeName").read[String] and // Try to read String, then fallback to Boolean (which maps into String) (JsPath \ "attributeValue").read[String].orElse((JsPath \ "attributeValue").read[Boolean].map(_.toString)) )(Data.apply _) } println(Json.parse(json1).as[Data]) println(Json.parse(json2).as[Data]) Output: Data(some String,false) Data(some String,daily)
{ "language": "en", "url": "https://stackoverflow.com/questions/47253553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wrong scroll behaviour when using background-clip When using background-clip: text and -*-text-fill-color: transparent; together with overflow: auto the scrolling is inconsistent in Firefox and it seems to not scroll at all on Chrome (both MacOS). There seem to be rendering issues. I tried changing the background-attachment, adding transform (to trigger GPU) but nothing seemed to work. body { background: #369; color: #fff; } .wrap { height: 50vh; overflow: auto; font: 26px / 1.5 sans-serif; background-image: linear-gradient(180deg, transparent 0, currentColor 30%, currentColor 70%, transparent 100%); background-color: transparent; background-clip: text; -webkit-background-clip: text; -moz-text-fill-color: transparent; -webkit-text-fill-color: transparent; } <div class="wrap"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! </div> Demo: https://jsfiddle.net/wdpmohcL/2/ A: The scroll works if you add background-attachment: local : body { background: #369; color: #fff; } .wrap { height: 50vh; overflow: auto; font: 26px / 1.5 sans-serif; background-image: linear-gradient(180deg, transparent 0, currentColor 30%, currentColor 70%, transparent 100%); background-color: transparent; background-clip: text; background-attachment: local; -webkit-background-clip: text; -moz-text-fill-color: transparent; -webkit-text-fill-color: transparent; } <div class="wrap"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! </div> A: body { background: #369;/*bg color*/ color: #fff; } .wrap { overflow: auto; width: 100%; height: 50vh; display: inline-block; margin: 10px;/*x*/ position: relative; font: 26px / 1.5 sans-serif; -ms-overflow-style: none; /* IE and Edge ,hide scroll bar*/ scrollbar-width: none; /* Firefox ,hide scroll bar*/ } .wrap::-webkit-scrollbar { display: none;/*hide scroll bar*/ } .dwn{ height: 15vh;/*y*/ width: 100%; bottom: 15vh;/*y*/ position: relative; background: linear-gradient( transparent 0%,#369/*use same color as bg*/ 100%); background: -webkit-linear-gradient( transparent 0%,#369/*use same color as bg*/ 100%); } .upn{ height: 15vh;/*y*/ width: 100%; top: 10px;/*x*/ position: absolute; z-index: 100; background: linear-gradient( #369/*use same color as bg*/ 0%, transparent 100%); background: -webkit-linear-gradient( #369/*use same color as bg*/ 0%, transparent 100%); } <div class="tl"> <div class="upn"> </div> <div class="wrap" id="prisonerResponse"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusamus, ipsam, sit! Adipisci, aspernatur minima nobis at distinctio eveniet sunt aliquid, iure laboriosam. Possimus dolore earum delectus ipsa, sequi blanditiis veritatis! </div> <div class="dwn"> </div> </div> (Run it IN FULL PAGE) Here we * *do some stuff to it by using position&display which makes it scrollable as well as dynamically fades in top and bottom *hide scrollbar(it works even without hiding scrollbar!) *since we hide scrollbar hover your mouse over text and scroll *we have made it work in firefox by .dwn,.upn div classes thus hover your mouse over the center of text and scroll down StackBlitz Code-https://stackblitz.com/edit/web-platform-1cfdsj?file=index.html Demo-https://web-platform-1cfdsj.stackblitz.io A: Try using: .wrap { height: 50vh; overflow: auto; font: 26px / 1.5 sans-serif; mask-image: linear-gradient(180deg, transparent 0, currentColor 30%, currentColor 70%, transparent 100%); -webkit-mask-image: linear-gradient(180deg, transparent 0, currentColor 30%, currentColor 70%, transparent 100%); } A: The problem was that background was not fixed relative to the "element's contents". Using: background-attachment: local; will help make the background fixed relative to the element's contents. Add background-attachment: local; to the wrap class.
{ "language": "la", "url": "https://stackoverflow.com/questions/70291008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Retrieving the name of the method from which HTTP call was made using an Interceptor I am using the Spring ClientHttpRequestInterceptor to capture all outgoing HTTP calls from my applications in order to log the data. In addition to the data that I am already collecting in the interceptor, I want to somehow fetch the name of the function from which the HTTP call originated. So, as an example, if a method called getStuffFromUrl is making the HTTP call using the Spring RestTemplate as follows, public String getStuffFromUrl() { ... return restTemplate.exchange(url, HttpMethod.GET,entity, String.class).getBody(); } when I capture this outbound HTTP call in my interceptor, I want to retrieve the name of the method getStuffFromUrl as well. How could I go about doing this? A: If you are allowed to modify your HTTP request, one way would be to add a ad-hoc HTTP header for the method name : public String getStuffFromUrl() { HttpHeaders headers = new HttpHeaders(); headers.add("JavaMethod", "getStuffFromUrl"); entity = new Entity(headers) ... return restTemplate.exchange(url, HttpMethod.GET,entity, String.class).getBody(); } You could then get back the method name and remove the header from within the ClientHttpRequestInterceptor prior the HTTP request is actualy sent out. ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { String javaMethodName="Unknown"; List<String> javaMethodHeader = request.getHeaders().remove("JavaMethod"); if(javaMethodHeader!=null && javaMethodHeader.size()>0) { javaMethodName = javaMethodHeader.get(0); } log.info("Calling method = "+ javaMethodName); execution.execute(request, body); } (provided code not tested)
{ "language": "en", "url": "https://stackoverflow.com/questions/64220282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Specifying Primary Key in JPA I have a class called Coach, that has an attribute of type Person. The person class has an attribute called id. Inside of the Coach table in the database, a field, id, is used as the primary key, which corresponds to the id of the person. How do I specify the @id for the Coach class, using annotations? Well, a coach is a person, so there is a person table that has an id field, first name, and last name. @Entity @Table(name="COACH_TABLE") public class Coach { @OneToOne @JoinColumn(name = "ID") private Person person; } @Entity @Table(name="PERSON_TABLE") public class Person { @Id @Column(name="ID") private int id; } I want to say that the @Id attribute for my Coach class is the id of the Person attribute.
{ "language": "en", "url": "https://stackoverflow.com/questions/19470257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error on compile or run the application on VS2010 & SQL Server 2012 Express I'm getting an error when I try to compile or run the application. Performing a simple tutorial, I worked at first but now when I generate the project F6 or try to run it, I always get the error Error 1 Unable to copy "C:\Projects\DatabaseExampleApp\DatabaseExampleApp\App_Data\northwnd.mdf" to "bin\Debug\App_Data\northwnd.mdf". The process can not access the file 'bin\Debug\App_Data\northwnd.mdf' because it is being used by another process. DatabaseExampleApp The first time when I run the app worked fine I'm using: * *Visual Studio 2010 Professional *SQL Server 2012 Express 64-bits EDIT: after: * *kill the sqlservr.exe (is the file locker) *delete the files myself northwnd.* northwnd_log.* *generate project F6 *run the app work fine But I have a questions: * *how kill or unload the file northwnd.mdf to avoid this problem? The app compile after that but don't run A: You're not showing us your connection string, but I'm assuming you're using some kind of AttachDbFileName=.... approach. My recommendation for this would be: just don't do that. It's messy to fiddle around with .mdf files, specifying them directly by location, you're running into problems when Visual Studio wants to copy that file around - just forget about all that. I would * *create the database on the SQL Server Express instance (CREATE DATABASE ..... in Mgmt Studio) *talk to the database by its logical name - not a physical file name So I would put my database onto the SQL Server Express server instance, and then use a connection string something like this: Server=.\SQLEXPRESS;Database=MyShinyDatabase;Integrated Security=SSPI; No messy file names, Visual Studio won't have to copy around files at runtime or anything, your data is on the server and can be used and administered there - seems like the much cleaner and much nicer approach to me.
{ "language": "en", "url": "https://stackoverflow.com/questions/10237100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to read binary file data using dlang I'm trying to read struct data from specific position in a a binary file. Found out that I can use import std.stdio and its File, however all i seem to find is all about string handling. I have c-code written data on binary files that compose of several different structs and they all, as far as I understand coding lay in a oneliner. In order to find specific struct I need to, like in old c, * *Open file for reading .... (binary read??) *using sizeof and move to startposition of struct data to read *read data (struct.sizeof data) into receivingbuffer and *Close file Documentation for std.stdio.File # read talks about reading entire or up to size but can't find how to read as below c-code line? fseek(filehandle, sizeof(firstStructData), SEEK_SET)); read(filehandle, (char *)nextReceivingBuffer, sizeof(nextReceivingBuffer)) Any ideas or hints? A: Try File.seek and File.rawRead. They work like their C counterparts, but rawRead determines the read count from the size of the output buffer you hand it.
{ "language": "en", "url": "https://stackoverflow.com/questions/41138993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Script for checking which button is clicked dosen't work I have N(1..500) buttons create dynamically and I want know which button is clicked by the user and get the Id. I'm using this jQuery function but it doesn't work: $(':button').click(function() { // reference clicked button via: $(this) var buttonElementId = $(this).attr('id'); alert(buttonElementId); }); A: If they are created dynamically you will need event delegation $(document).on('click', ':button' , function() { // reference clicked button via: $(this) var buttonElementId = $(this).attr('id'); alert(buttonElementId); }); See In jQuery, how to attach events to dynamic html elements? for more info A: For dynamically created elements you should use: $(document).on("click", ":button", function() { // reference clicked button via: $(this) var buttonElementId = $(this).attr('id'); alert(buttonElementId); });
{ "language": "en", "url": "https://stackoverflow.com/questions/25786663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How I can connect Apache server remotely (http://149.4.223.238:8080) through my local machine I am using Eclipse with Tomcat 8.0 and successfully run and deploy web application into Apache server. Now my question is how I can access online apache host address app manager in order to deploy my application on this host Remove Server Address tomcat_users.xml <tomcat-users> <role rolename="admin-gui"/> <role rolename="admin-script"/> <role rolename="manager-gui"/> <role rolename="manager-script"/> <role rolename="manager-jmx"/> <role rolename="manager-status"/> <user username="tom" password="tom123" roles="admin-gui"/> <user username="malik" password="malik123" roles="manager-gui,manager-script,manager-jmx,manager-status"/> </<tomcat-users> I added this to server.xml <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" address="149.4.223.238" redirectPort="8443"/> Context.xml <Context antiResourceLocking="false" privileged="true" > <!-- Remove the comment markers from around the Valve below to limit access to the manager application to clients connecting from localhost --> <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="149\.4\.223\.238|127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" /> </Context> I am searching from last 5-7 hours but still not understand. A: http://149.4.223.238:8080/manager/html It looks like you might not have configured it yet. that link also tell you how to set it up. Also if you remote connect with that machine and access that site through localhost:8080/manager/html that should work too. more details at https://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html A: Your valve configuration is restricting access to IPs in the server itself, the public one and the loopback addresses <Valve className="org.apache.catalina.valves.RemoteAddrValve" allow="149\.4\.223\.238|127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" /> So, if you want to allow access from your public IP (be careful with that, it's a security hole) you should include it on the regexp. As an option, you can access it through an ssh tunnel (can be done with putty too) ssh -L 8080:localhost:8080 some_user@149.4.223.238 Now it should be accessible from localhost:8080.
{ "language": "en", "url": "https://stackoverflow.com/questions/52721237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SwiftUI View does not update The content of CardView inside the ForEach of CardNavigatorView is correctly updated thanks to an async download task (inside CardView) that downloads an image, and the Image() is displayed correctly, but I detected that the frame around CardView in CardNavigatorView is not updated accordingly causing the Text("test") to appear in the middle of the CardView image, instead of being pushed down by the CardView frame if it was updated correctly, to encircle the image. The border(Color.red, width:2) helped me to conclude this as it appears as if it was empty. Any suggestion please ? struct CardNavigatorView: View { @ObservedObject var model: CardNavigatorViewModel @State private var offset: CGFloat = 0 let spacing: CGFloat = 10 var body: some View { GeometryReader { geometry in return ScrollView(.horizontal, showsIndicators: true) { HStack(spacing: self.spacing) { ForEach(self.model.cardSource.cards, id:\.hashString) { card in CardView(card: card) .frame(width: geometry.size.width).border(Color.red, width: 2) } } } .content.offset(x: self.offset) .frame(width: geometry.size.width, alignment: .leading) } Text("Test") } } CardView is declared as following struct CardView: View { @ObservedObject var card: Card @EnvironmentObject var userData: UserData var body: some View { GeometryReader { geometry in VStack { ZStack(alignment: .topTrailing) { ImageViewContainer(imageUrl: self.card.imagesURL[0]) .frame(width:geometry.size.width) .scaledToFill() .clipped() NameView(name: self.card.name) .frame(width:geometry.size.width) Button(action:{ self.userData.toggleFav(card:self.card) }) { ZStack{ Image("fav_icon").renderingMode(Image.TemplateRenderingMode?.init(Image.TemplateRenderingMode.original)) .resizable() .aspectRatio(contentMode:.fit) .frame(width:25).opacity(self.card.isFav ? 1 : 0).offset(x:-10, y:10) Image("not_fav_icon").renderingMode(Image.TemplateRenderingMode?.init(Image.TemplateRenderingMode.original)) .resizable() .aspectRatio(contentMode:.fit) .frame(width:25).opacity(self.card.isFav ? 0 : 1).offset(x:-10, y:10) } } }.border(Color.green, width: 3) Text("\(self.card.description)") Text("Note : \(self.card.ratingString)") }.onAppear{self.userData.setUserSettingsTo(card: self.card)} } } } A: Solution found. For people wondering what was wrong: I guess that the GeometryReader in CardView gets the size of the ScrollView of the parent CardNavigatorView, which is in turn considered as empty. Since GeometryReader closures allows to expand outside of its border, I got the effect I tried to explain. The tip is to provide a frame(width:geometry.size.width) modifier to the CardView instance! (to be tuned up to your need)
{ "language": "en", "url": "https://stackoverflow.com/questions/60048369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook share throwing connection error when sharing Every article on the following website fails when attempting to share the page via the share link in our social media widget. for example: the following page, http://news.gc.ca/web/article-en.do?mthd=index&crtr.page=1&nid=957389 when shared via the following link: Returns an Error: Connection error in the share preview window. Response headers for this request are: Cache-Control: private, no-cache, no-store, must-revalidate Content-Encoding: gzip Content-Type: text/html Date: Wed, 01 Apr 2015 14:22:20 GMT Expires: Sat, 01 Jan 2000 00:00:00 GMT Pragma: no-cache Strict-Transport-Security: max-age=15552000; preload Vary: Accept-Encoding X-Content-Type-Options: nosniff X-FB-Debug: iYvCJSRJJqVdVXyIubD1kVq6teZBILIBRrCACZW9hI/Ms+B2qsquq52KyU5820UTfLmuXTis3LbRoL2bMlCVBw== X-Frame-Options: DENY X-XSS-Protection: 0 X-Firefox-Spdy: 3.1 200 OK running the above URL through the OpenGraph object debugger returns: Error parsing input URL, no data was cached, or no data was scraped. and the scraper sees the following for the URL: Document returned no data We need to determine the cause of this since none of our content can be shared from our site at the moment. Any ideas, tips greatly appreciated!
{ "language": "en", "url": "https://stackoverflow.com/questions/29394290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: non-recursive JavaScript JSON parser I have a very large JSON string that I need to parse with in-browser JavaScript. Right now, in a few browsers, I run out of stack space. Unfortunately, my JSON can contain user strings, so I can't use eval or otherwise let the browser parse it. I've looked at a few of the standard JavaScript JSON parsers, and they are recursive. Wondering if anyone knows of any JSON parser that is safe and non-recursive. I'd be willing for it to have fewer features -- I just have a giant array of objects. Alternatively, if someone knows of one that might be easy to modify, that would be a big help too. EDIT: On closer inspection the stack overflow is thrown by eval() used inside the parser. So, it must be recursive. A: If eval throws stackoverflow, you can use this http://code.google.com/p/json-sans-eval/ A JSON parser that doesn't use eval() at all. A: I have written json parsers that are not recursive in several languages, but until now not in javascript. Instead of being recursive, this uses a local array named stack. In actionscript this was substantially faster and more memory efficient than recursion, and I assume javascript would be similar. This implementation uses eval only for quoted strings with backslash escapes, as both an optimization and simplification. That could easily be replaced with the string handling from any other parser. The escape handling code is long and not related to recursion. This implementation is not strict in (at least) the following ways. It treats 8 bit characters as whitespace. It allows leading "+" and "0" in numbers. It allows trailing "," in arrays and objects. It ignores input after the first result. So "[+09,]2" returns [9] and ignores "2". function parseJSON( inJSON ) { var result; var parent; var string; var depth = 0; var stack = new Array(); var state = 0; var began , place = 0 , limit = inJSON.length; var letter; while ( place < limit ) { letter = inJSON.charCodeAt( place++ ); if ( letter <= 0x20 || letter >= 0x7F ) { // whitespace or control } else if ( letter === 0x22 ) { // " string var slash = 0; var plain = true; began = place - 1; while ( place < limit ) { letter = inJSON.charCodeAt( place++ ); if ( slash !== 0 ) { slash = 0; } else if ( letter === 0x5C ) { // \ escape slash = 1; plain = false; } else if ( letter === 0x22 ) { // " string if ( plain ) { result = inJSON.substring( began + 1 , place - 1 ); } else { string = inJSON.substring( began , place ); result = eval( string ); // eval to unescape } break; } } } else if ( letter === 0x7B ) { // { object stack[depth++] = state; stack[depth++] = parent; parent = new Object(); result = undefined; state = letter; } else if ( letter === 0x7D ) { // } object if ( state === 0x3A ) { parent[stack[--depth]] = result; state = stack[--depth]; } if ( state === 0x7B ) { result = parent; parent = stack[--depth]; state = stack[--depth]; } else { // error got } expected state { result = undefined; break; } } else if ( letter === 0x5B ) { // [ array stack[depth++] = state; stack[depth++] = parent; parent = new Array(); result = undefined; state = letter; } else if ( letter === 0x5D ) { // ] array if ( state === 0x5B ) { if ( undefined !== result ) parent.push( result ); result = parent; parent = stack[--depth]; state = stack[--depth]; } else { // error got ] expected state [ result = undefined; break; } } else if ( letter === 0x2C ) { // , delimiter if ( undefined === result ) { // error got , expected previous value break; } else if ( state === 0x3A ) { parent[stack[--depth]] = result; state = stack[--depth]; result = undefined; } else if ( state === 0x5B ) { parent.push( result ); result = undefined; } else { // error got , expected state [ or : result = undefined; break; } } else if ( letter === 0x3A ) { // : assignment if ( state === 0x7B ) { // could verify result is string stack[depth++] = state; stack[depth++] = result; state = letter; result = undefined; } else { // error got : expected state { result = undefined; break; } } else { if ( ( letter >= 0x30 && letter <= 0x39 ) || letter === 0x2B || letter === 0x2D || letter === 0x2E ) { var exponent = -2; var real = ( letter === 0x2E ); var digits = ( letter >= 0x30 && letter <= 0x39 ) ? 1 : 0; began = place - 1; while ( place < limit ) { letter = inJSON.charCodeAt( place++ ); if ( letter >= 0x30 && letter <= 0x39 ) { // digit digits += 1; } else if ( letter === 0x2E ) { // . if ( real ) break; else real = true; } else if ( letter === 0x45 || letter === 0x65 ) { // e E if ( exponent > began || 0 === digits ) break; else exponent = place - 1; real = true; } else if ( letter === 0x2B || letter === 0x2D ) { // + - if ( place != exponent + 2 ) break; } else { break; } } place -= 1; string = inJSON.substring( began , place ); if ( 0 === digits ) break; // error expected digits if ( real ) result = parseFloat( string ); else result = parseInt( string , 10 ); } else if ( letter === 0x6E && 'ull' === inJSON.substr( place , 3 ) ) { result = null; place += 3; } else if ( letter === 0x74 && 'rue' === inJSON.substr( place , 3 ) ) { result = true; place += 3; } else if ( letter === 0x66 && 'alse' === inJSON.substr( place , 4 ) ) { result = false; place += 4; } else { // error unrecognized literal result = undefined; break; } } if ( 0 === depth ) break; } return result; } A: I recommend you to divide JSON string in chunks, and bring them on demand. May be using AJAX too, you can have a recipe that just fit your needs. Using a "divide and conquer" mechanism, I think you can still use common JSON parsing methods. Hope that helps, A: JSON parsing in browser is usually done with just eval, but preceding the eval with a regular expression "lint", that is supposed to make it safe to evaluate the JSON. There is an example on this on wikipedia: * *http://en.wikipedia.org/wiki/JSON#Security_issues
{ "language": "en", "url": "https://stackoverflow.com/questions/3557497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: PHP recursion issue My idea is simple: if child->indent, if parent->make bold. Lets say p0 is the parent of p1 and p2, p3 and p4 are the childs of p1. p5 is the independent page like p0. So what i wanna get is p0 (bold font) [3px]p1(bold font) [ 6px ]p3 [ 6px ]p4 [3px]p2 p5 (bold font) The problem is, I can't figure out. how to realize my idea. Tried given functions. No success. It works but indents only first level childs. My recursive php function looks like that function generateOptions($parent, $level, $padding, $db) { $result=$db->query("SELECT id, name FROM menu WHERE parent='$parent' AND showinmenu!='0'"); if($level == 0) {$padding=''; $optstyle='bold';} else {$optstyle='std'; $padding='&nbsp;';} while($data=$result->fetch_row()){ echo generateOption($optstyle.'option', $data, $padding); generateOptions($data[0], $level++, $padding, $db); } } function generateOption($type,$data, $padding){ switch($type){ case 'boldoption': return '<option class="bold" value="'.$data[0].'">'.$padding.$data[1]."</option>\n"; break; case 'stdoption': return '<option class="std" value="'.$data[0].'">'.$padding.$data[1]."</option>\n"; break; } } And here is the screenshot of my db table. http://prntscr.com/39461 The final working result function generateOptions($parent, $level, $padding, $db) { $result=$db->query("SELECT id, name FROM menu WHERE parent='$parent' AND showinmenu!='0'"); $spacer = '&nbsp;&nbsp;'; $padding = str_repeat($spacer, $level); while($data=$result->fetch_row()){ $children_html = generateOptions($data[0], $level+1, $padding, $db); $optstyle = empty($children_html) ? 'std' : 'bold'; $html .= generateOption($optstyle.'option', $level, $data, $padding); $html .= $children_html; } return $html; } function generateOption($type, $level, $data, $padding){ $bgcolor=array('0'=>'#f66e02','1'=>'#FF9C4D', '2'=>'#FF9C4D'); $fontcolor=array('0'=>'#fff','1'=>'#000', '2'=>'#000'); switch($type){ case 'boldoption': return '<option class="bold" style="background-color:'.$bgcolor[$level].'; color:'.$fontcolor[$level].'" value="'.$data[0].'">'.$padding.$data[1]."</option>\n"; break; case 'stdoption': return '<option class="std" value="'.$data[0].'">'.$padding.$data[1]."</option>\n"; break; } } A: Your indentation problem you can easily solve by multiplying the $level by the number of pixels for a simple indent (3px in your case). For the bold problem you need a different approach as in your current code, you don't know if the item has any children. The solution to that would be to first get the children in a variable, then add the bold style if any exist, echo the item and only then process the children. Personally I would first get all data from the database in one pass, then build the hierarchical structure and then use a different function to generate the html. See for example this question for more details. Edit: Based on your updated question; you can easily optimize it and get rid of the query in the while loop (I'd still go for the option in the previous paragraph by the way...): * *Don't echo anything, just return a string from your function *Get rid of the query in the while function *Swap the echo and the function call lines The result in your function would be something like: .... $html = ''; while (...) { $children_html = generateOptions($data[0], $level+1, $padding, $db); $optstyle = empty($children_html) ? 'std' : 'bold'; $html .= generateOption($optstyle.'option', $data, $padding); $html .= $children_html; } return $html; and just do a echo generateOptions(...) where you called the function before. A: It looks like you might need to be adding more &nbps;'s to your padding where you're just assigning it to one space. else {$optstyle='std'; $padding='&nbsp;';} to else {$optstyle='std'; $padding .='&nbsp;';} A: You are trying to map a flat data structure (list) into a tree visually. Before you can do this in a simple manner, you need to gather the date that is influencing the display to the list. E.g. you could add a level per entry (1, 2 or 3), which looks like that being your recursive structure already! Then you pass the modified list to the display routine, that only needs to decide based on the level how to display the entry, for each level: * *font-weight: bold; *padding-left: 3px; font-weight: bold; *padding-left: 6px; The easiest thing to achieve that is to assing a class attribute to the elements parent HTML tag like level-1, level-2 etc.. You already have a $level variable, but I see an error, you increment it all the time, but you only need to pass the value: generateOptions($data[0], $level+1, $padding, $db); It might be that this already solves your issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to add token authentication in the headers with interceptor and the token can be null? I have Application Angular13 with authentication OAuth and I try to add this token for all services. But I don't manage undefined token. I have tried several techniques for calling the token but I always end up with an error, I want to be able to use non-authenticate services anyway @Injectable({ providedIn: 'root', }) export class TokenInterceptorService implements HttpInterceptor { constructor(private authService: AuthService) {} intercept( request: HttpRequest<any>, next: HttpHandler ): Observable<HttpEvent<any>> { const {token} = this.authService.decodedAccessToken; if (token) { request = request.clone({ setHeaders: { Authorization: `Bearer ${token}`, }, }); } return next.handle(request).pipe( catchError((err) => { console.error(err); const error = err.error.message || err.statusText; return throwError(error); }) ); } } i add this on ngModel providers: [{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptorService, multi: true, },], try this const token = this.authService.decodedAccessToken; // or this typeof token != 'undefined' && token // no condition Authorization: `Bearer ${this.authService.decodedAccessToken}`, // and on error 401 this.authService.logout(); // return next.handle(request): angular-oauth2-oidc.mjs:1398 error loading discovery document TypeError: Cannot destructure property 'token' of 'this.authService.decodedAccessToken' as it is undefined. /// or core.mjs:6509 ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of null (reading 'message') /// or status: 401 I currently have blank pages or incomplete loading A: Try this: const token = this.authService.decodedAccessToken?.token || null;
{ "language": "en", "url": "https://stackoverflow.com/questions/73802773", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Load multiple models within same function of controller I have two functions in my model as class Jobseeker_model extends CI_Model { public function __construct() { parent::__construct(); $this->load->database(); } public function result_getall($id) { $this->db->select('*'); $this->db->from('tbl_jobseeker'); $this->db->where('tbl_jobseeker.User_id',$id); $this->db->join('tbl_work_exp', 'tbl_jobseeker.User_id = tbl_work_exp.User_id','left'); $query = $this->db->get(); return $query->row(); } public function select($id) { $this->db->select('*'); $this->db->from('tbl_qualification'); $this->db->where('tbl_qualification.User_id',$id); $query = $this->db->get(); return $query->result(); } } And in my controller I have a function as public function display() { $id = $this->session->userdata('user_id'); $data['row'] = $this->jobseeker_model->result_getall($id); $res['a'] = $this->jobseeker_model->select($id); $this->load->view('jobseeker_display.php', $data,$res); } It is not possible to display the view page.. I could pass two variables into my view page.right? A: You can pass your any number of variables/arrays using a single array. In Controller: public function display() { $id = $this->session->userdata('user_id'); $data['var1'] = $this->jobseeker_model->result_getall($id); $data['var2'] = $this->jobseeker_model->select($id); $this->load->view('jobseeker_display.php', $data); } In View: `$var1` and `$var2` will be available. A: You can pass your two variable using single srray public function display() { $id = $this->session->userdata('user_id'); $data['row'] = $this->jobseeker_model->result_getall($id); $data['a'] = $this->jobseeker_model->select($id); $this->load->view('jobseeker_display.php', $data); } Views foreach($a as $data){ // your code } echo $row->column_name; A: Try this public function display() { $id = $this->session->userdata('user_id'); $data['row'] = $this->jobseeker_model->result_getall($id); $data['a'] = $this->jobseeker_model->select($id); $this->load->view('jobseeker_display.php', $data); }
{ "language": "en", "url": "https://stackoverflow.com/questions/32477243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: WPF VisualTreeHelper.HitTest using multiple threads In my application, there is a transparent InkCanvas on top of a Viewport3D object. The Viewport3D shows a large 3D mesh. The user will sketch on the InkCanvas in order to select a portion of the 3D model that the Viewport3D is rendering. The user is allowed to draw circles on the InkCanvas. When the user sketches, I iterate over all the points that fall inside of the drawn circle and I use the VisualTreeHelper.HitTest function to perform raycasting and determine which vertices of the Viewport3D mesh coincide with the sketch. The problem is that VisualTreeHelper.HitTest is very slow. In case I used a Parallel.For I still would not be able to perform multiple raycastings on the Viewport3D in parallel (due to the fact that the owning thread of the Viewport3D object is the UI thread and I'd have to use Viewport3D's Dispatcher.Invoke function which will defeat the purpose of having a Parallel.For in the first place.) Is there a way to speed this up using multiple threads? Better yet, is there an alternative solution? A: After a lot of searching, I think what I want is impossible in the WPF framework. I switched to OpenTK for that purpose and implemented the raycasting myself. Now I have a WPF-mimick in OpenTK with a much better performance. The code is available here if anyone is interested.
{ "language": "en", "url": "https://stackoverflow.com/questions/30004430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to link to official PHP documentation in phpDocumentor 2? I use the phpDocumentor 2 to describe few methods. I want to link to the official PHP documentation of a native function. I can write something like this: /** * @see http://php.net/manual/en/function.ucfirst.php ucfirst */ These don’t work: /** * @see ucfirst * @see \ucfirst */ Is there a better way? I am looking for something like this: /** * @the-official-documentation-for ucfirst */ A: You have some issue with your syntax in the documentation. You should use @link instead of @see. /** * @see http://php.net/manual/en/function.ucfirst.php ucfirst */ Change your documentation code to /** * @link http://php.net/manual/en/function.ucfirst.php ucfirst */ I have tested it and is working on my editor i.e. phpStorm Note: It only works in the functions and class names. You cannot use it on comments.
{ "language": "en", "url": "https://stackoverflow.com/questions/41436377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Node.js with Socket.io on multiple pages? I am building an app with Node.js that will have multiple pages and will be setup like so: * *Page1 : Default home *Page2 : Connects to RabbitMQ and gets data then pushes it to the client via Socket.io. *Page3: Same thing as Page2 except it pushes different data and subscribes to different data on RabbitMQ. Is it possible to have Page2 subscribe to RabbitMQ and use Socket.io if Page1 does not? Also will Page2 and Page3 conflict with each other since they are both using socket.io and RabbitMQ? I have the RabbitMQ and Socket.io code working in a stand-alone app but am confused on how to do this in an app with multiple pages/routes. (I am using Express for the routing.) I'm very new to Node.js so any help would be appreciated. A: Got it solved. Was thinking about it incorrectly. When NodeJs starts (or on the first subscriber) the system should connect to RabbitMQ and emit events on Socket.io regardless of the page the user is on. It's the page that determines what topic the user wants to listen to via the connect code to socket.io. This way there is only one instance the of the RabbitMQ code ever running and the server can emit to anyone interested. And this way there is no conflict.
{ "language": "en", "url": "https://stackoverflow.com/questions/28357240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent navigation from one state to another state in angularjs? I need to intercept when user clicks on browser back button from a specific view to navigate it to home view rather than the default back page. Any ideas on how to do this? I have states defined as below. I can't allow to navigate from the state 'paymentsubmitted' to 'payment' $stateProvider .state('home', { url: '/' , templateUrl: 'search', controller: 'payCtrl' }) .state('details', { url: '/details/{id:int}', templateUrl: 'details', controller: 'payDetailsCtrl' }) .state('payment', { url: '/payment', templateUrl: 'Payment', controller: 'payPaymentCtrl' }) .state('paymentsubmitted', { url: '/paymentsubmitted', templateUrl: 'PaymentSubmitted', controller: 'payPaymentCtrl' }); I tried to use $locationChangeStart but next and current are looking at absolute urls. How can I have it look at the states that are defined? Thank you! $rootScope.$on('$locationChangeStart', function (event, next, current) { if (current == '') { } });
{ "language": "en", "url": "https://stackoverflow.com/questions/37932089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selenium WebDriver simulate mousemove event with movementX and movementY other than zero I want to test my web application using selenium webdriver and I can't get mousemove event invoked with movementX or movementY other than 0. I've tried using Class: Selenium::WebDriver::ActionBuilder: driver.action.move_to(element).move_by(1,1).perform() And javascript hacks like this. Is there any other way to invoke/induce MouseEvent of type mousemove taking into account that movementX and movementY is important? A: Selenium-webdrivers #move_to accepts right and down offsets for the element you're moving to. When using capybara with selenium-webdriver, assuming you have found the element you want to move the mouse to, you should be able to do page.driver.browser.action.move_to(element.native, 1, 1).perform Note: this will only work with the selenium driver, not with Poltergeist, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/40914303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hide bubble in Amcharts Is there anyway to hide bubble in bubble chart of Amcharts. I have a requirement where I need to hide bubble on click on a button. I checked the documentation, where I couldn't able to find anything. can anyone guide me how to do that
{ "language": "en", "url": "https://stackoverflow.com/questions/50589725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get JSON response for each df row Imagine you have the following df: d = {'KvK': [72941014, 76912027, 75090058], 'line amount#2': [0.0, 0.05, .05], 'ExclBTW': [0.5, 0.18, .05]} df = pd.DataFrame(data=d) df KvK line am ExclBTW APIOutput 0 72941014 0.00 0.50 https://api.kvk.nl/api/v2/search/companies?use... 1 76912027 0.05 0.18 https://api.kvk.nl/api/v2/search/companies?use... 2 75090058 0.05 0.05 https://api.kvk.nl/api/v2/search/companies?use... Now I added the APIOutput column: df['APIOutput'] = df['KvK'].apply(lambda x: f"https://api.kvk.nl/api/v2/search/companies?user_key=l7xxd3eea0c598a645a7fa69dbb&q={x}") I want to get all the JSON responses from the APIOutput into one column, apioutput1. I've tried the following code; df['apioutput1'] = requests.get.apply(lambda x: f"df['APIOutput']{x}", verify=False) However the above does not work.. Desired output: KvK lineam ExclBTW APIOutput apioutput1 0 72941014 0.00 0.50 https://api.kvk.nl/api/v2/search/companies?use... JSON 1 76912027 0.05 0.18 https://api.kvk.nl/api/v2/search/companies?use... JSON 2 75090058 0.05 0.05 https://api.kvk.nl/api/v2/search/companies?use... JSON how to achieve the above? Please help A: Call apply on the series, just like you did when filling in the APIOutput column. df['apioutput1'] = df['APIOutput'].apply(lambda url: requests.get(url, verify=False)) A: Use .apply to call requests.get on every row df['apioutput1'] = df['APIOutput'].apply(lambda x: requests.get(x, verify=False) )
{ "language": "en", "url": "https://stackoverflow.com/questions/67371534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call child function from parent class For example i have class A { void Afunction(); }; and i have #include "A.h" class B: public A { void Function(); }; #include "B.h" class C { void UpdateStuff(); void CreateStuff(); B* Stuff; } I need call CreateStuff(); from Afunction(); but I can't just #include "C.h" Is there another way to do this ? A: You can call child function using a pointer or a reference of Parent class that points or references the child object. For example: #include <iostream> struct A { virtual void Function() //Defination { std::cout << "Super_class: A\n"; } virtual ~A() {} }; struct B { virtual void Function() { std::cout << "Child_class\n"; } }; int main() { A *obj1 = new B; obj1->Function(); B obj2; obj2.A::Function(); //Calling to Parent class function(A) obj2.Function(); //Calling to Child class function(B) } A: You're unable to achieve that with your current code design. Class A does not inherit from Class C and Afunction() doesn't get passed a reference to Class C. You can either make A inherit C like you have with B inheriting A or you can pass a reference to the function like so class A { void Afunction(C* CObject); }; Furthermore you also can't call child class functions from parent class functions when talking about inheritance. Inheritance works from Top down not from the bottom up. For example class A { void Afunction(); }; class B : public A { void Afunction() { A::Afunction(); // This is valid } } This is not valid code. class A { void Afunction() { B::Afunction(); // This is not valid as A::Afunction() does not inherit from B::Afunction() } }; class B : public A { void Afunction(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/64533800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Callstack and event loop when running asynchronous queries in JavaScript I am new to JS so please forgive my lack of understanding. Suppose I work with MongoDB and I want to fetch details from a particular database in an asynchronous manner. I would love to understand how this happens in JavaScript because the language is defined as a single threaded. for example to execute this line asynchronously: myCursor = db.inventory.find( {} ) I have read about the subject a lot and I understand that some asynchronous functions like setTimeOut are executed by Web API'S. Will each asynchronous function be the responsibility of the web APIs? Many thanks A: So you asked: "Why does asynchronous behavior reduce the amount of threads?" - Note: Don't confuse threading with using multicore, Its totally deferent concept , But of course thread can take advantage of multicore system, But now Lets think we have a single core CPU. Threading A thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, (Basically small unit of execution). For I/O operation (like making a network call) take time but program need to wait and wasting valuable computation power by doing nothing, So historically we use thread that execute a task independently, Its has some drawback, One of is memory concussion (Because Its need to clone register, stack, counter), this is a deferent topic. Also thread are so expensive to switch context... So we know that thread are expensive, What if we can reduce thread count ? Asynchronous The idea is to use Event, and execute via a library ( Also known: runtime, executor etc...), without the program blocking to wait for results. Its cheep and efficient for I/O intensive tasks. Even, It can use a single thread to do all async stuff!
{ "language": "en", "url": "https://stackoverflow.com/questions/67678526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set visual studio setup and deployment release location for multiple projects I have several different services in separate VS solutions that I want to create a single image setup file in a particular location. I can set the Releases (Setup) tab as shown: However, if I set more than 1 solution to create a setup file (with different names) in this location they overwrite each other. I'd like to know how to set them all to write their setup files into the same release location? A: Release Location is by default set to <ISProjectDataFolder> which is same location as the .ism or Installshield project file however you may change it to where setup.exe or installer project output is supposed to produced. In one installshield project you can set only one Release Location so, it is not clear how and where you set location for others? Do you have multiple installshield projects if yes, then you should name each projects outout file a different name so they do not overwrite existing files. See this screenshot
{ "language": "en", "url": "https://stackoverflow.com/questions/48420889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: convert gstreamer pipeline to python code Im trying to convert gstreamer pipeline to python code using gi library. This is the pipeline which is running successfully in terminal: gst-launch-1.0 rtspsrc location="rtsp://admin:123456@192.168.0.150:554/H264?ch=1&subtype=0&proto=Onvif" latency=300 ! rtph264depay ! h264parse ! nvv4l2decoder drop-frame-interval=1 ! nvvideoconvert ! video/x-raw,width=1920,height=1080,formate=I420 ! queue ! nveglglessink window-x=0 window-y=0 window-width=1080 window-height=720 but while running the same pipeline using python code, there is no output window displaying rtsp stream and also no error on the terminal. The terminal simply stuck until i press ctrl+c. This is the code that im using to run the gstreamer command: import gi gi.require_version("Gst", "1.0") from gi.repository import Gst, GObject def main(device): GObject.threads_init() Gst.init(None) pipeline = Gst.Pipeline() source = Gst.ElementFactory.make("rtspsrc", "video-source") source.set_property("location", device) source.set_property("latency", 300) pipeline.add(source) depay = Gst.ElementFactory.make("rtph264depay", "depay") pipeline.add(depay) source.link(depay) parse = Gst.ElementFactory.make("h264parse", "parse") pipeline.add(parse) depay.link(parse) decoder = Gst.ElementFactory.make("nvv4l2decoder", "decoder") decoder.set_property("drop-frame-interval", 2) pipeline.add(decoder) parse.link(decoder) convert = Gst.ElementFactory.make("nvvideoconvert", "convert") pipeline.add(convert) decoder.link(convert) caps = Gst.Caps.from_string("video/x-raw,width=1920,height=1080,formate=I420") filter = Gst.ElementFactory.make("capsfilter", "filter") filter.set_property("caps", caps) pipeline.add(filter) convert.link(filter) queue = Gst.ElementFactory.make("queue", "queue") pipeline.add(queue) filter.link(queue) sink = Gst.ElementFactory.make("nveglglessink", "video-sink") sink.set_property("window-x", 0) sink.set_property("window-y", 0) sink.set_property("window-width", 1280) sink.set_property("window-height", 720) pipeline.add(sink) queue.link(sink) loop = GObject.MainLoop() pipeline.set_state(Gst.State.PLAYING) try: loop.run() except: pass pipeline.set_state(Gst.State.NULL) if __name__ == "__main__": main("rtsp://admin:123456@192.168.0.150:554/H264?ch=1&subtype=0&proto=Onvif") Does anyone know what is the mistake? Thank you! A: The reason it doesn't work is because rtspsrc's source pad is a so-called "Sometimes pad". The link here explains it quite well, but basically you cannot know upfront how many pads will become available on the rtspsrc, since this depends on the SDP provided by the RTSP server. As such, you should listen to the "pad-added" signal of the rtspsrc, where you can link the rest of your pipeline to the source pad that just showed up in the callback. So summarised: def main(device): GObject.threads_init() Gst.init(None) pipeline = Gst.Pipeline() source = Gst.ElementFactory.make("rtspsrc", "video-source") source.set_property("location", device) source.set_property("latency", 300) source.connect("pad-added", on_rtspsrc_pad_added) pipeline.add(source) # We will add/link the rest of the pipeline later loop = GObject.MainLoop() pipeline.set_state(Gst.State.PLAYING) try: loop.run() except: pass pipeline.set_state(Gst.State.NULL) def on_rtspsrc_pad_added(rtspsrc, pad, *user_data): # Create the rest of your pipeline here and link it depay = Gst.ElementFactory.make("rtph264depay", "depay") pipeline.add(depay) rtspsrc.link(depay) # and so on ....
{ "language": "en", "url": "https://stackoverflow.com/questions/60230807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Group rows in Pandas dataframe, apply custom function and store results in a new dataframe as rows I have a pandas dataframe df_org with three columns - Index (integer), Titles (string) and Dates (date). I have a method process_title(text), which takes a string as input and tokenize, remove stop words and lemmatize the input string and returns the words as a list. from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords stop_words = set(stopwords.words('english')) lemmatizer = WordNetLemmatizer() def process_title(text): tokens = word_tokenize(text.lower()) try: tokens.remove("google") tokens.remove("search") tokens.remove("-") except: pass lemm_tokens = list(map(lemmatizer.lemmatize,tokens)) without_stop = [word for word in lemm_tokens if word not in stop_words] return without_stop I want a new dataframe which contains three columns - Word(string), Frequency(integer), Date(date). The Word column contain words(single word) from the list returned by process_title(text), the Frequency column contains the frequency of that word appearing on a given date and Date column contains the date. --------------------------------------- | Word | Frequency | Date | --------------------------------------- | computer | 1 |2021-08-01| | science | 1 |2021-08-01| | something| 5 |2021-08-02| ..... How can I group the df_org dataframe along date and create the new dataframe? Changes can be made to the process_title(text) method without compromising the end requirement. A: You can use the DataFrame.explode method, followed by groupby and size: I am going to just use a simple .str.split instead of your function, as I don't know where word_tokenize comes from. In [1]: import pandas as pd In [2]: df = pd.DataFrame({'title': ['Hello World', 'Foo Bar'], 'date': ['2021-01-12T20:00', '2021-02-10T22:00']}) In [3]: df['words'] = df['title'].apply(lambda s: process_title(str(s))) In [4]: df Out[4]: title date words 0 Hello World 2021-01-12T20:00 [Hello, World] 1 Foo Bar 2021-02-10T22:00 [Foo, Bar] In [5]: exploded = df.explode('words') In [6]: exploded Out[6]: title date words 0 Hello World 2021-01-12T20:00 Hello 0 Hello World 2021-01-12T20:00 World 1 Foo Bar 2021-02-10T22:00 Foo 1 Foo Bar 2021-02-10T22:00 Bar In [7]: exploded.groupby(['date', 'words']).size() Out[7]: date words 2021-01-12T20:00 Hello 1 World 1 2021-02-10T22:00 Bar 1 Foo 1 dtype: int64
{ "language": "en", "url": "https://stackoverflow.com/questions/68974288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Enum unbinds from the model on ajax call I am reading an enum value from the db then bind it to the model. When i post the form with ajax, somehow the enum is unbound or the model property in null or zero but it display properly on the view. I have posted code below. Im using entityframework and mvc3 //model code constructor public CarModel(Car car) { State=(CarState)car.State; //car.State comes in as an int //etc setting other variables } //CarState property public CarState {get;set;} //model code @Html.DisplayFor(m=>m.CarState) //Controller code() Save(CarModel car) { //I have code that saves the changes } The minute i get to "car", CarState has no value. A: It's not quite clear how you are passing this value to the controller action. You have only shown some @Html.DisplayFor(m=>m.CarState) but obviously this only displays a label in the view. It doesn't send anything back to the server. If you want to send some value back you will have to use an input field inside the form. For example: @Html.EditorFor(m => m.CarState) or use a HiddenFor field if you don't want the user to edit it. In any case you need to send that value to the server if you expect the model binder to be able to retrieve it. The model binder is not a magician. He cannot invent values. He binds values to your model from the Request.
{ "language": "en", "url": "https://stackoverflow.com/questions/11116239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ¿How to find request's parameters @ debug mode? Excuse my writing, but English is not my native tongue. This is my situation: I'm checking source code of a web application base on Java. Well, when I want a parameter of request variable, I call request.getParameter(key). But there is an missing parameter, and I executed the application in debug mode, thus, I can look for the parameter. But I don't find the parameters anywhere. Can somebody help me? I use NetBeans IDE for development. Thank you! A: Check getParameterMap from Request object http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterMap() if it isn't there you need to check whether your parameter is passed from browser - you can check network tab in Chrome development tools
{ "language": "en", "url": "https://stackoverflow.com/questions/29333445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JSP Spring-MVC Reusing Controller Logic psuedo: @RequestMapping("/news/feed/featurednews/{feedname}") public List<NewsModel> getFeed(String feedname, @RequestParam("start", optional) Integer startIndex) { return feedService.getFeaturedNewsByName(feedname); } @RequestMapping("/news/{newsPageName}") public String goToNewsPage(Model m, String newsPageName) { m.addAttribute("stories", feedService.getFeaturedNewsByName(newsPageName)); return getGenericNewsViewName(); } as you can see I'm reusing the service that gets the feed, is that the best I can do here, or can I reuse the getFeed() method? A: It's perfectly fine to write @RequestMapping("/news/feed/featurednews/{feedname}") public List<NewsModel> getFeed(String feedname, @RequestParam("start", optional) Integer startIndex) { return feedService.getFeaturedNewsByName(feedname); } @RequestMapping("/news/{newsPageName}") public String goToNewsPage(Model m, String newsPageName) { m.addAttribute("stories", this.getFeed(newsPageName, 0)); return getGenericNewsViewName(); } The Controller by itself is a plain Java class, you just tell the Spring request dispatcher on where to map requests to using the annotations (which doesn't affect any normal method call).
{ "language": "en", "url": "https://stackoverflow.com/questions/3102248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: HtmlAgilityPack select "p" nodes that don't have child "p" How can I efficiently select all nodes of type x that are not children of a node of type x? Example with type as p: <p id="top1"> <ul> <li>Text</li> <li>Text</li> <li>Text</li> </ul> <div> <p id="sub"> <p id="sub_sub"> </p> </p> </div> </p> <div> <div> <p id="top2"> </p> </div> </div> The select should only return nodes with ids top1 and top2 A: Like this: elem.Descendants().Where(e => !e.Descendants("p").Any())
{ "language": "en", "url": "https://stackoverflow.com/questions/6699880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Replacing "۔ "with in python I am working in python2.7 with urdu text. what i am doing is reading a text file and replacing "۔" with "end of senetence marker" it is replacing in file but it is placing this in start. i want to add markers at the place of "-" that is at the end of sentences. My code is here: import codecs import re import sys import io fil = codecs.open("aa.txt","r",encoding="utf-8") fil1 = codecs.open("a.txt","w",encoding="utf-8") for line in fil: for ch in line: ch = ch.replace(u'۔','</s><s>') fil1.write(ch) my original data is: میرا نام احمد ہے۔ میں پڑھتا ہو۔ my file after trying to replace is: kindly help me or suggest me what can i do. A: string.replace(s, old, new[, maxreplace]) Function parameters * *s: The string to search and replace from. *old: The old sub-string you wish to replace. *new: The new sub-string you wish to put in-place of the old one. *maxreplace: The maximum number of times you wish to replace the sub-string. And your function: ch = ch.replace(u'۔','</s><s>') Where is the string you whant to make change as a parameter? I did not understand what is u for there Try this: ch = ch.replace(ch,'۔','</s><s>') And maybe the program reads from right to left but writes from left to right.
{ "language": "en", "url": "https://stackoverflow.com/questions/47121058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Control raspberry pi via website in React.js? I've written a nodejs application and put it on my raspberry pi. That's all good. However, I would now like to control my nodejs application via a web browser interface / website built in React. How would I do this? The website would be on the internet, but would need to have somehow access to my raspberry pi computer and modify things there. A: I think there are two ways of doing this : * *Use your raspberry pi as a web server too : install Nginx/Apache for example (they are web servers) and give them your React app. *Use a external hosting, like OVH for example, and give them your React app too. I don't know if you know how to do a React website, but there are plenties of tutorials on web, like this one. The goal here is to create an API relation between your NodeJS application and your website. The NodeJS server has to be listening on a port (8080 for example) and specific URLs which corresponds to commands (/api/reboot will reboot the app for example). And in your website, you just have to call those URLs after a button is pushed (a 'Reboot' button for example, will send a POST request to http://raspberrypi:8080/api/reboot). Basically, link every command you want to execute with your NodeJS application to an url and link it in your website to an action. If you want to securise the transmission (so nobody can reboot your app), just include some password and HTTPS :) See ya ! A: Here is the link: MyExample Also recommending to add module child-process to use execute command like this: var exec = require('child_process').exec; execute('sudo reboot'); use this when receiving socket function execute(command) { var cmd = exec(command, function(error, stdout, stderr){ console.log("error: ", error); }); } With this u can make client side with "terminal" (text holder) and on button click client would send info to RPI with Your command in text holder.
{ "language": "en", "url": "https://stackoverflow.com/questions/41271604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Using OLEDB parameters in .NET when connecting to an AS400/DB2 I have been pulling my hair out trying to figure out what I can't get parameters to work in my query. I have the code written in VB.NET trying to do a query to an AS/400. I have IBM Access for Windows installed and I am able to get queries to work, just not with parameters. Any time I include a parameter in my query (ex. @MyParm) it doesn't work. It's like it doesn't replace the parameter with the value it should be. Here's my code: I get the following error: SQL0206: Column @MyParm not in specified tables Here's my code: Dim da As New OleDbDataAdapter Dim dt As New DataTable da.SelectCommand = New OleDbCommand da.SelectCommand.Connection = con da.SelectCommand.CommandText = "SELECT * FROM MyTable WHERE Col1 = @MyParm" With da.SelectCommand.Parameters .Add("@MyParm", OleDbType.Integer, 9) .Item("@MyParm").Value = 5 End With ' I get the error here of course da.Fill(dt) I can replace @MyParm with a literal of 5 and it works fine. What am I missing here? I do this with SQL Server all the time, but this is the first time I am attempting it on an AS400. A: You're right, same question as AS400 SQL query with Parameter, which contains the solution. A: Just a note: Host Integration Server 2006 supports named parameters.
{ "language": "en", "url": "https://stackoverflow.com/questions/2511442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is there a way to initialize object, call its method, then pass it as function argument, in just the function call scope? Is there a way to initialize an object, call a few of its method (it is not possible to just construct the object to be in the needed state), then pass it as an argument to a function, and possibly one-liner, just in the calling scope? Something like this: #include <iostream> #include <sstream> void log(const std::ostringstream& obj) { std::cout<<obj.str(); //Do something meaningful with obj that doesn't modify it } void gol(const std::string& obj) { std::cout<<obj; //Do something meaningful with obj that doesn't modify it } int main() { log(std::ostringstream oss << "Foo" << 123 << 'B'); gol(std::string str .append("Foo").append(std::to_string(123)).append("Bar")); } By "in the calling scope", I mean that the object "oss" is automatically destroyed after "log" returns. The same goes for "str". I could do it like this: int main() { { std::ostringstream oss; oss << "Foo" << 123 << 'B'; log(oss); } { std::string str; str.append("Foo").append(std::to_string(123)).append("Bar")); gol(str); } } But then it's not really one-liner anymore. A: You can write it like this: #include <iostream> #include <sstream> void log(const std::ostringstream& obj) { std::cout<<obj.str(); //Do something meaningful with obj that doesn't modify it } void gol(const std::string& obj) { std::cout<<obj; //Do something meaningful with obj that doesn't modify it } int main() { log(std::ostringstream{} << "Foo" << 123 << 'B'); gol(std::string{}.append("Foo").append(std::to_string(123)).append("Bar")); } Though, I am not aware of a way to give it a name, call methods, and pass it to another function, all in the same expression. In general, trying to squeeze as much code into a single line is not something that is actually desirable.
{ "language": "en", "url": "https://stackoverflow.com/questions/72559640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 404 errors when calling an asp.net MVC 3 controller with an big URL list I've an action that I've to put in a GET request. The URL is build live, and looks like this: https://my-domain.com/MyController/MyAction?MyParameter=8259%2C8318%2C8201%2C8188%2C7155%2C6894%2C8221%2C8187%2C7030%2C8214%2C7489%2C8145%2C8223%2C8208%2C8273%2C8257%2C8292%2C6931%2C7072%2C7007%2C8195%2C8235%2C7493%2C7525%2C7492%2C8262%2C7491%2C7013%2C8157%2C7180%2C7181%2C7182%2C7183%2C7421%2C7422%2C7500%2C7501%2C8238%2C8239%2C8240%2C8241%2C7710%2C7711%2C7712%2C7713%2C8068%2C8432%2C7358%2C7008%2C8135%2C8307%2C8163%2C8164%2C8132%2C8182%2C8183%2C8081%2C8083%2C8109%2C8110%2C7681%2C7682%2C7683%2C7593%2C7594%2C7595%2C7546%2C7547%2C7548%2C7577%2C7578%2C7581%2C8300%2C8301%2C8302%2C8282%2C8283%2C8284%2C8311%2C8312%2C8313%2C8217%2C8218%2C8244%2C8245%2C8479%2C8482%2C8398%2C8399%2C8400%2C8401%2C8404%2C8407%2C8392%2C8394%2C6959%2C6960%2C6961%2C7041%2C7042%2C7043%2C8227%2C8228%2C8229%2C7638%2C7708%2C7118%2C8288%2C6897%2C6898%2C6899%2C6900%2C6901%2C6902%2C6842%2C6843%2C6844%2C6845%2C6846%2C6847%2C7361%2C7362%2C7363%2C7364%2C7365%2C7366%2C8165%2C8166%2C8167%2C8168%2C8169%2C8170%2C8247%2C8248%2C8249%2C8250%2C8251%2C8252%2C8099%2C8100%2C6903%2C6904%2C6905%2C6906%2C6907%2C6908%2C7704%2C8291%2C8253%2C7709%2C8277%2C7372%2C7282%2C7552%2C8205%2C7341%2C8264%2C7384%2C7701%2C7432%2C7625%2C7169%2C6912%2C8095%2C7481%2C8452%2C7062%2C7664%2C8088%2C8209%2C8278%2C6986%2C6978%2C7128%2C7440%2C6987%2C8224%2C8225%2C8178%2C8179%2C6889%2C6890%2C8191%2C8093%2C8230%2C7317%2C6895%2C8211%2C8226%2C8285%2C7266%2C7321%2C7445%2C7672%2C7453%2C7476%2C7533%2C6967%2C8054%2C7377%2C7188%2C8323%2C8105%2C7276%2C8202%2C8072%2C7689%2C8434%2C7075%2C7257%2C7379%2C6864%2C7570%2C8146%2C8147%2C8148%2C8149%2C7018%2C7019%2C7020%2C7021%2C8031%2C7044%2C7278%2C7486%2C8409%2C7707%2C8438%2C7378%2C7265%2C7176%2C7199%2C7706%2C7632%2C6998%2C7584%2C8171%2C7399%2C7125%2C6836%2C7535%2C7528%2C6968%2C7327%2C8319%2C8098%2C7543%2C6852%2C7103%2C6882%2C8426%2C8114%2C6957%2C6952%2C7527%2C6956%2C6953%2C8196%2C6989%2C7246%2C8272%2C8320%2C8324%2C6979%2C8315%2C8293%2C8294%2C8322%2C8204%2C7203%2C7326%2C7355%2C7087%2C7009%2C7498%2C7700%2C8113%2C8274%2C8325%2C8321%2C8116%2C7211%2C7252%2C7332%2C7023%2C7074%2C6977%2C7603%2C8096%2C7063%2C7014%2C7416%2C8190%2C8310%2C7032%2C7129%2C7136%2C7131%2C7187%2C7170%2C7159%2C7532%2C7651%2C7262%2C7670%2C7402%2C7403%2C7245%2C7235%2C7601%2C7316%2C7545%2C7343%2C7376%2C7665%2C7688%2C7374%2C7375%2C8041%2C7404%2C7409%2C7419%2C8422%2C7461%2C7438%2C7443%2C7487%2C7464%2C7515%2C7514%2C7512%2C7523%2C7598%2C8176%2C7544%2C7620%2C7652%2C7690%2C8330%2C8335%2C8418%2C8417%2C8421%2C8442%2C8458%2C8492%2C8457%2C8474%2C8483 And I get a 404 error. If I replace the %2C by the original ,I got the same problem, just with a little more parameters. If I make the same request with less parameters, it works. I already have this: <system.web> <httpRuntime maxUrlLength="2097151" maxQueryStringLength="2097151" relaxedUrlToFileSystemMapping="true"/> </system.web> Because previously I was having telling me that I was having a maxQueryStringLength set too big. A: No matter how large you set the maxQueryStringLength, there's a limit in the browsers. For example some browsers support a request length of only 2048 characters. Yours is longer (2440 characters). The only thing you could do is to use POST instead of GET to send such large data because POST requests doesn't have such limitation. So you generate an HTML <form> element with method="post" and action pointing to the url and a hidden field inside it containing this data and then submit this form. A: In fact, I was blocked by an IIS limit: the maxUrl size and max query size(which is measured in octet: <system.webServer> <security> <requestFiltering> <requestLimits maxUrl="1048576" maxQueryString="1048576" /> </requestFiltering> </security> </system.webServer> This resolved my problem
{ "language": "en", "url": "https://stackoverflow.com/questions/12564308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: getting the actual bytes in a Socket (raw?) Ok im pretty new in this networking stuff in .net especially in sockets. I've already "made" a proxy application and tried using it with my own local website (using wampserver) i selected few pictures that are around 60~k bytes of size yet i receive in my proxy counter around 15k "bytes", I have the feeling this is the packets cause i'm using Socket.Send & Socket.Receive. Any help would do :) A: Your problem is one of message framing. The Available property only reports the bytes that have arrived so far - not the complete HTTP request or response. If this is just a learning exercise, then I recommend using another protocol. HTTP has one of the most complex message framing systems of any protocol. If this is intended for production, then you'll have to implement (at least partial) HTTP parsing to handle the message framing, and I also recommend a change to asynchronous socket methods rather than synchronous. A better solution is to just implement a web application that uses WebRequest to handle client requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/4377934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CRUD with external REST service as Model in Loopback A couple quick questions: * *I would like to use an external REST API service (e.g. AgileCRM). With their service, I would like to use the REST Connector within a model that allows me to CRUD AgileCRM's API. Is this possible? If so, what model should be the base (e.g. PersistedModel, Model, etc)? *I would like to merge data from AgileCRM and a PersistedModel (e.g. MySQL). Should I do this via relationships OR inheritance? If inheritance, which should be the parent model? It would be ideal to use all data from AgileCRM (represented as a model in LB, if possible) and add information from a local MySQL database. *Have you any thoughts on wrapping an API service (e.g. AgileCRM) as a connector type (e.g. REST Connector for AgileCRM, based on REST Connector)? AgileCRM has many features but their CRUD methods operate slightly different from how LB interacts with data sources. A: This is a really old question, sorry it never got answered, but it's also very broad is some portions. I would recommend asking shorter, more specific questions, and making multiple StackOverflow questions for them. That said, here's some brief answers for people reading this entry: * *Yes, this is possible. Check out the REST connector. *I would probably use multiple parent models that are internal and then a single exposed REST model (not "persisted") that collates that data together. *Sure, you could do that. Writing a connector isn't too difficult, check out our docs on building a connector.
{ "language": "en", "url": "https://stackoverflow.com/questions/30291570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Loading data from database in the background to tableview JavaFX when I use the scrolling mouse The database has more than 10k rows of data. Everyone will be processed (translated) before it is displayed. That is, one column will be loaded on the rigid and the other is compared with the dictionary and displayed if there is another table in the database. Therefore, there is a lot of data I load of 50 pieces in use scrolling mouse. In order not slowed to the program it plans to do it so that when you use the scroll created a new thread and just charge in the background. I mean mainly about how to place it in the case of multi-threading. Maybe you have some advice or sample code. Thanks in advance A: To solve this task you should to use javafx.concurrent.Task , Example. And simple handle your scroll event, on scroll populate table with additional values.
{ "language": "en", "url": "https://stackoverflow.com/questions/39634081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Downloading Java JDK through Script I have been using the following to download JDK 8u112 via a script. wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u112-b15/jdk-8u112-linux-x64.tar.gz Recently, it throws ERROR 404: Not found and when you go to the link, it shows the same text in Downloading Java JDK on Linux via wget is shown license page instead I've also tried http://download.oracle.com/otn/java/jdk/8u112-b15/jdk-8u112-linux-x64.tar.gz but it throws 401 Authorization Error. Is there a new work around on this? A: It seems like the most recent version of jdk can be downloaded by wget but not the files in the archives. As such, I'm using casper.js script to login to Oracle and to download. Following is my script to download Japanese version of jdk8u121. The current script will only attempt to download but will fail on redirect. I'm using download.sh bash script to scan the log to get the url with session parameter and using wget to do the actual download. You'll need to replace <username> and <password> with valid ones to login to Oracle site. Change values of jdkTag and jdkFileLink to get the jdk version you want to download. oraclejdk.js var casper = require('casper').create({ verbose: true, logLevel: 'info', // debug pageSettings: { userAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36", loadImages: false, loadPlugins: false } }); // login info var loginUrl='http://www.oracle.com/webapps/redirect/signon?nexturl=https://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html'; var username='<username>'; var password='<password>'; // accept license page info var jdkUrl='http://www.oracle.com/technetwork/'; var jdkTag='jdk-8u121-oth-JPR'; // download jdk info var jdkFileLink='jdk-8u121-oth-JPRXXXjdk-8u121-linux-x64.tar.gz'; // open login page casper.start(loginUrl); casper.thenEvaluate(function(username, password) { // this.capture('loginPage.png', {top:0, left:0, width:600, height:800}); document.querySelector("#sso_username").value = username; document.querySelector("#ssopassword").value = password; doLogin(document.LoginForm); }, { username: username, password: password }); // login to oracle site casper.then(function() { this.waitForUrl(jdkUrl, function() { // this.capture('jdkPage.png', {top:0, left:0, width:1200, height:800}); this.evaluate(function(jdkTag) { disableDownloadAnchors(document, false, jdkTag); hideAgreementDiv(document, jdkTag); writeSessionCookie('oraclelicense', 'accept-securebackup-cookie'); }, { jdkTag: jdkTag }); }, null, null, 5000); }); // accept license casper.then(function() { this.waitFor(function checkLink() { return this.evaluate(function(jdkTag) { return (document.getElementById('agreementDiv' + jdkTag).getAttribute('style') === 'visibility: hidden;'); }, { jdkTag: jdkTag }); }, function then() { // this.capture('acceptedLicense.png', {top:0, left:0, width:1200, height:800}); downlink = this.evaluate(function(jdkFileLink) { var jdkElement = document.getElementById(jdkFileLink); if (jdkElement) { var jdkLink = jdkElement.getAttribute("href"); jdkElement.click(); return jdkLink; } }, { jdkFileLink: jdkFileLink }); }, null, 5000); }); casper.run(); download.sh #!/bin/bash url=$(casperjs --web-security=no oraclejdk.js |grep "http://download.oracle.com/otn/java/jdk" $() | sed -e 's/^.*: //') jdk=$(echo "${url}" | sed -e 's/^.*jdk-/jdk/' |sed -e 's/?.*//') wget -O "${jdk}" "${url}" A: This is not a direct answer to your question...but Here is how i get URL to latest jdk download URL #!/bin/bash jdkwebinstallerDownloadPage="https://www.oracle.com"$(curl -s https://www.oracle.com/technetwork/java/javase/downloads/index.html | unix2dos | grep "<a name=\"JDK8\"" | sed 's/^.*\<a name=\"JDK8\" href=//g' | sed -r 's/>.*//g' | sed s/\"//g) ## Above yields https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html jdkinstallerDownloadURL=$(curl -s $jdkwebinstallerDownloadPage | grep windows | grep downloads | grep x64 | grep jdk | grep -v demos | sed -r 's/^.*https/https/g' | sed -r 's/\".*//g') ## yields https://download.oracle.com/otn/java/jdk/8u221-b11/230deb18db3e4014bb8e3e8324f81b43/jdk-8u221-windows-x64.exe I am now looking to how to download from this url using wget...given that i have cedentials to login into oracle's login webpage which is https://login.oracle.com/mysso/signon.jsp
{ "language": "en", "url": "https://stackoverflow.com/questions/44162061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Parse incomplete ellipses from DXF files I am developing a DXF parser by using the dxflib library. I have a problem parsing ellipses. When I parse an ellipse I receive the following data: struct DL_EllipseData { /*! X Coordinate of center point. */ double cx; /*! Y Coordinate of center point. */ double cy; /*! X coordinate of the endpoint of the major axis. */ double mx; /*! Y coordinate of the endpoint of the major axis. */ double my; /*! Ratio of minor axis to major axis. */ double ratio; /*! Startangle of ellipse in rad. */ double angle1; /*! Endangle of ellipse in rad. */ double angle2; }; The problem is that when angle1 != 0 AND angle2 != 2* Math.PI the ellipse is open and I am not able to compute the arc path that represents that geometry. For example considering the following ellipse: These are its properties: As you can see the angles are: angle1 = 0.81855 // 46 degrees angle2 = 2.38934 // 136 degrees but the picture of the ellipse (I took from autocad seems to have quite different angles). Following the section of the DXF file that represents the ellipse: 0 ELLIPSE 5 A7 330 1F 100 AcDbEntity 8 DL-Wall 48 25.0 370 -3 100 AcDbEllipse 10 906.6576677029225 20 906.657675539829 30 0.0 11 -641.4561777354752 21 641.4561777354752 31 0.0 210 0.0 220 0.0 230 1.0 40 0.9999999999999978 41 0.8185500151218715 42 2.389346341916759 How I have to compute the proper angles (and also start end end point of the arc segment)? A: /// <summary> /// Static method to detemine the WPF end point of the arc. /// </summary> /// <param name="arc">The DXF ArcEntity object to evaluate</param> /// <returns>Point with values of the arc end point.</returns> public static Point calcEndPoint(Arc arc) { double x = (Math.Cos(arc.endAngle * (Math.PI / 180)) * arc.radius) + arc.center.X; double y = arc.center.Y - (Math.Sin(arc.endAngle * (Math.PI / 180)) * arc.radius); return new Point(x, y); } /// <summary> /// Static method to detemine the WPF start point of the arc. /// </summary> /// <param name="arc">The DXF ArcEntity object to evaluate</param> /// <returns>Point with values of the arc start point.</returns> public static Point calcStartPoint(Arc arc) { double x = (Math.Cos(arc.startAngle * (Math.PI / 180)) * arc.radius) + arc.center.X; double y = arc.center.Y - (Math.Sin(arc.startAngle * (Math.PI / 180)) * arc.radius); return new Point(x, y); } public static bool checkArcSize(Arc arc) { double angleDiff = arc.endAngle - arc.startAngle; return !((angleDiff > 0 && angleDiff <= 180) || angleDiff <= -180); } Using System.Windows.Media.Path, PathFigure, ArcSegment: PathFigure figure = new PathFigure(); figure.StartPoint = calcStartPoint([your arc struct]); ArcSegment arc = new ArcSegment(); arc.Point = calcEndPoints([your arc struct]); arc.RotationAngle = Math.Abs(endAngle - startAngle); arc.Size = new Size(radius, radius); arc.IsLargeArc = checkArcSize([your arc struct]); figure.Segments.Add(arc); You will need to adjust each of the helper functions to use your struct as well as any C++ vs C# differences in syntax. I believe that these helper functions will bridge the gap between what the DXF spec gives you and what is required to draw the Arc in WPF.
{ "language": "en", "url": "https://stackoverflow.com/questions/31137778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I change a FL_Window's caption other than in a constructor argument? MainWindow::MainWindow(int w, int h, const string& c) : Fl_Window(w, h, c.c_str()) // Don't call constructor over here { script.load_file(WIN_CONFIG_SCRIPT); int width = script.get_global_int("width"); int height = script.get_global_int("height"); const char* caption = script.get_global_string("caption").c_str(); /** CALL CONSTRUCTOR NOW **/ //NOTE: I don't know a way to change an FLTK Fl_Window's Caption after //initialising it. Toolbar* toolbar = new Toolbar(0, 0, this->w(),30); toolbar->add_button("Hello"); toolbar->add_button("World!"); end(); } How do I initialize the base class inside the constructor? Alternatively, how do I change an FLTK Fl_Window's caption after initialising it? Is there any other way out of this mess? A: How do I initialize the base class inside the constructor? You may not. The base part of the instance must be initialised before the derived part of the instance or any of its members. How do I change an FLTK Fl_Window's caption after initialising it? The documentation says you can call: label("my caption") What's wrong with that? Any other way out of this mess? No. Also, you should upgrade to FLTK 2.
{ "language": "en", "url": "https://stackoverflow.com/questions/8805472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: django channels str doesnt suppoer buffer API I am trying to work with django and channels with the help of https://blog.heroku.com/archives/2016/3/17/in_deep_with_django_channels_the_future_of_real_time_apps_in_django however this code doesn't seem compatible with python 3.4 on my ws_connect: @channel_session def ws_connect(message): prefix, label = message['path'].strip('/').split('/') room = Room.objects.get(label=label) Group('chat-' + label).add(message.reply_channel) message.channel_session['room'] = room.label I get the following error when trying to connect to the socket. prefix, label = message['path'].strip('/').split('/') TypeError: Type str doesn't support the buffer API I only just started working with python 3.4 and have no idea why this breaks A: It looks like message['path'] is a bytes object rather than a string, and trying to apply strip() to a bytes object yields that rather cryptic error message. Instead, try message['path'].decode() to convert it to a string, then do your stripping and splitting. See also Python 3.0 urllib.parse error "Type str doesn't support the buffer API"
{ "language": "en", "url": "https://stackoverflow.com/questions/36113651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alignment in 64bit machine is not 8 Bytes I am trying to find out alignment on my 64bit machine(Win10 on Intel iCore7). I thought of this experiment: void check_alignment(char c1, char c2 ) { printf("delta=%d\n", (int)&c2 - (int)&c1); // prints 4 instead of 8 } void main(){ check_alignment('a','b'); } I was expecting delta=8. Since it's 64bit machine char c1 and char c2 should be stored on multiples of 8. Isn't that right? Even if we assume compiler has done optimization to have them stored in less space, why not just store them back to back delta=1? Why 4 byte alignment? I repeated the above experiment with float types, and still gives delta=4 void check_alignment(float f1, float f2 ) { printf("delta=%d\n", (int)&c2 - (int)&c1); // prints 4 } void main(){ check_alignment(1.0,1.1); } A: Firstly, if your platform is 64-bit, then why are you casting your pointer values to int? Is int 64-bit wide on your platform? If not, your subtraction is likely to produce a meaningless result. Use intptr_t or ptrdiff_t for that purpose, not int. Secondly, in a typical implementation a 1-byte type will typically be aligned at 1-byte boundary, regardless of whether your platform is 64-bit or not. To see a 8-byte alignment you'd need a 8-byte type. And in order to see how it is aligned you have to inspect the physical value of the address (i.e. whether it is divisible by 1, 2, 4, 8 etc.), not analyze how far apart two variables are spaced. Thirdly, how far apart c1 and c2 are in memory has little to do with alignment requirements of char type. It is determined by how char values are passed (or stored locally) on your platform. In your case they are apparently allocated 4-byte storage cells each. That's perfectly fine. Nobody every promised you that two unrelated objects with 1-byte alignment will be packed next to each other as tightly as possible. If you want to determine alignment by measuring how far from each other two objects are stored, declare an array. Do not try to measure the distance between two independent objects - this is meaningless. A: To determine the greatest fundamental alignment in your C implementation, use: #include <stdio.h> #include <stddef.h> int main(void) { printf("%zd bytes\n", _Alignof(max_align_t)); } To determine the alignment requirement of any particular type, replace max_align_t above with that type. Alignment is not purely a function of the processor or other hardware. Hardware might support aligned or unaligned accesses with different performance effects, and some instructions might support unaligned access while others do not. A particular C implementation might choose to require or not require certain alignment in combination with choosing to use or not use various instructions. Additionally, on some hardware, whether unaligned access is supported is configurable by the operating system.
{ "language": "en", "url": "https://stackoverflow.com/questions/51622751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to use PhpUnit/DbUnit with a real Doctrine EntityManager for functional testing I'm using PhpUnit/DbUnit to create a set of 5 to 10 fixture records. I use in-memory sqlite. I successfully can use a Doctrine\DBAL\Connection to access it, so I can use methods like ->insert( $tableName, $data ); for my tests. Now I want to consume the Doctrine EntityManager so I can create an entity and call ->persist(). In unit-testing I used to mock the EntityManager and asserted an expectation to call persist. But for functional-testing I want to check the final result written to the DB, even go further and re-use the result of the writing. I therefore need to create a real EntityManager but consuming the DbUnit connection. I've seen that creting a new EntityManager takes 3 arguments, but still the creator is protected: /** * Creates a new EntityManager that operates on the given database connection * and uses the given Configuration and EventManager implementations. * * @param \Doctrine\DBAL\Connection $conn * @param \Doctrine\ORM\Configuration $config * @param \Doctrine\Common\EventManager $eventManager */ protected function __construct(Connection $conn, Configuration $config, EventManager $eventManager) { [...] I don't know if I'm expected to create a subclass, or maybe use an already subclassed EntityManager or how should I proceed. So question: How can I setup a real Doctrine\ORM\EntityManager within a PhpUnit/DbUnit test class using the low level Doctrine\Dbal\Connection that is already bound to the DbUnit connection? Note: I'm inside a symfony3 project, so mapping files are in the expected places of symfony.
{ "language": "en", "url": "https://stackoverflow.com/questions/52864751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get p-values for random effects in glmer I want to analyze when the claims of a protest are directed at the state, based on action and country level characteristics, using glmer. So, I would like to obtain p-values of both the fixed and random effects. My model looks like this: targets <- glmer(state ~ ENV + HLH + HRI + LAB + SMO + Capital + (1 + rile + parties + rep + rep2 + gdppc + election| Country), data = df, family = binomial) The output only gives me the Variance & Std.Dev. of the random effects, as well as the correlations among them, which makes sense for most multilevel analyses but not for my purposes. Is there any way I can get something like the estimates and the p-values for the random effects? If this cannot be done with R, is there any other statistical software that would give such an output? UPDATE: Following the suggestions here, I have moved this question to Cross Validated: https://stats.stackexchange.com/questions/381208/r-how-to-get-estimates-and-p-values-for-random-effects-in-glmer A: library(lme4) library(lattice) xyplot(incidence/size ~ period|herd, cbpp, type=c('g','p','l'), layout=c(3,5), index.cond = function(x,y)max(y)) gm1 <- glmer(cbind(incidence, size - incidence) ~ period + (1 | herd), data = cbpp, family = binomial) summary(gm1)
{ "language": "en", "url": "https://stackoverflow.com/questions/53685637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JSON in HTML escaping I'm including JSON in an HTML tag, considering the only possible input characters for the JSON will be "':{},[a-z][0-9] is it possible for JSON or HTML to be broken with my approach? What should I be wary of when using JSON across HTML and Javascript? <input type="hidden" value="<?=htmlspecialchars(json_encode($myArray));?>" /> A: in the definition of json, one of the posible values its a string. which can contain <, > among other things you can use a base64 enconding to avoid this. A: JSON can contain nearly any character in its strings. As you are using it in an attribute, escape_quotesaddslashes should be enough, that depends on your (X)HTML version. htmlspecialchars is OK anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/11090308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generate a Random Number That Evenly Divides into Another in C# I am making a quiz that quizzes a user on basic arithmetic skills. The problem I have is that I don't want to be able to generate a division question that allows real numbers. I want all answers to have integer answers. How can I randomly generate a number between p and q that evenly divides into n? A: The idea is to generate two integers a and n, and then return a and c = a * n. The answerer should guess what is n and beware of division by zero! Something like this will do: public KeyValuePair<int, int> GenerateIntDivisibleNoPair(int p, int q) { if (p <= 0 || q <= 0 || q <= p) throw Exception(); //for simplification of idea Random rand = new Random(); int a = rand.Next(p, q + 1); //cannot be zero! note: maxValue put as q + 1 to include q int n = rand.Next(p, q + 1); //cannot be zero! note: maxValue put as q + 1 to include q return new KeyValuePair<int, int>(a, a * n); } You use it like this: KeyValuePair<int, int> val = GenerateIntDivisibleNoPair(1, 101); Console.WriteLine("What is " + val.Value.ToString() + " divide by " + val.Key.ToString() + "?"); A: I would have a Random declared somewhere with global access: public static Random Rnd { get; set; } Then when you want a number that divides by another you keep generating a number until you get one that divides by your Divisor: if(Rnd == null) { Rnd = new Random(); } int Min = p; //Can be any number int Max = q; //Can be any number if(Min > Max) //Assert that Min is lower than Max { int Temp = Max; Max = Min; Min = Temp; } int Divisor = n; //Can be any number int NextRandom = Rnd.Next(Min, Max + 1); //Add 1 to Max, because Next always returns one less than the value of Max. while(NextRandom % Divisor != 0) { NextRandom = Rnd.Next(Min, Max + 1); //Add 1 to Max, because Next always returns one less than the value of Max. } The check uses the modulus function %. This function gives you the remainder of an integer divide. This means that if the NextRandom % Divisor is 0, then the Divisor divides evenly into NextRandom. This can be turned into a method like so: public static int GetRandomMultiple(int divisor, int min, int max) { if (Rnd == null) { Rnd = new Random(); } if(min > max) //Assert that min is lower than max { int Temp = max; max = min; min = Temp; } int NextRandom = Rnd.Next(min, max + 1); //Add 1 to Max, because Next always returns one less than the value of Max. while (NextRandom % divisor != 0) { NextRandom = Rnd.Next(min, max + 1); //Add 1 to Max, because Next always returns one less than the value of Max. } return NextRandom; } Then you can call it with the variables you mentioned like so: int Number = GetRandomMultiple(n, p, q); Note: I add one to the value of Max because of the 'Next' method. I think it's a bug in .Net. The value of Max is never returned, only Min..Max - 1. Adding one compensates for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/35571589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Sum negative and positive values separately I am attempting to sum up positive and negative values separately in XSL v1.0. I have XML like this: <Billing_Statements> <Statement_Details> <Invoice_Details> <Meter_Details> <Consumption>XX</Consumption> </Meter_Details> <Meter_Details> <Consumption>XX</Consumption> </Meter_Details> </Invoice_Details> <Invoice_Details> <Meter_Details> <Consumption>XX</Consumption> </Meter_Details> <Meter_Details> <Consumption>XX</Consumption> </Meter_Details> </Invoice_Details> </Statement_Details> </Billing_Statements> Where XX can be a positive or a negative value. I need to output first the sum of the positive values and then the sum of the negative values for all Invoice_Detail nodes for each Statement_Details. At the moment I have tried: <xsl:value-of select="sum(Invoice_Details/Meter_Details[Consumption &lt; 0])" /> and many variations of this and they all return a sum of 0 no matter what. When collecting all the other information from the Meter_Details nodes my for-each section works perfectly as this: <xsl:for-each select="Invoice_Details/Meter_Details[Consumption &lt; 0]"> And selects only nodes with negative or positive values. Why does this not work for the sum()? I'm certainly struggling with XSL here and would love any help I can get. A: Use: sum(*/*/*[. >=0]) and sum(*/*/*[not(. >=0)]) Here is a complete transformation that uses these two relative XPath expressions: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="Statement_Details"> Statement <xsl:value-of select="position()"/> <xsl:apply-templates/> </xsl:template> <xsl:template match="Invoice_Details"> Invoice <xsl:value-of select="position()"/> Positive: <xsl:value-of select="sum(*/*[. >=0])"/> Negative: <xsl:value-of select="sum(*/*[not(. >=0)])"/> </xsl:template> </xsl:stylesheet> When this transformation is applied on the following XML document (having the wanted structure): <Billing_Statements> <Statement_Details> <Invoice_Details> <Meter_Details> <Consumption>-3</Consumption> </Meter_Details> <Meter_Details> <Consumption>5</Consumption> </Meter_Details> </Invoice_Details> <Invoice_Details> <Meter_Details> <Consumption>8</Consumption> </Meter_Details> <Meter_Details> <Consumption>-12</Consumption> </Meter_Details> </Invoice_Details> <Invoice_Details> <Meter_Details> <Consumption>22</Consumption> </Meter_Details> <Meter_Details> <Consumption>3</Consumption> </Meter_Details> </Invoice_Details> <Invoice_Details> <Meter_Details> <Consumption>4</Consumption> </Meter_Details> <Meter_Details> <Consumption>-5</Consumption> </Meter_Details> </Invoice_Details> </Statement_Details> <Statement_Details> <Invoice_Details> <Meter_Details> <Consumption>-13</Consumption> </Meter_Details> <Meter_Details> <Consumption>25</Consumption> </Meter_Details> </Invoice_Details> <Invoice_Details> <Meter_Details> <Consumption>77</Consumption> </Meter_Details> <Meter_Details> <Consumption>-15</Consumption> </Meter_Details> </Invoice_Details> <Invoice_Details> <Meter_Details> <Consumption>31</Consumption> </Meter_Details> <Meter_Details> <Consumption>-3</Consumption> </Meter_Details> </Invoice_Details> <Invoice_Details> <Meter_Details> <Consumption>-87</Consumption> </Meter_Details> <Meter_Details> <Consumption>54</Consumption> </Meter_Details> </Invoice_Details> </Statement_Details> </Billing_Statements> the wanted, correct result is produced: Statement 1 Invoice 1 Positive: 5 Negative: -3 Invoice 2 Positive: 8 Negative: -12 Invoice 3 Positive: 25 Negative: 0 Invoice 4 Positive: 4 Negative: -5 Statement 2 Invoice 1 Positive: 25 Negative: -13 Invoice 2 Positive: 77 Negative: -15 Invoice 3 Positive: 31 Negative: -3 Invoice 4 Positive: 54 Negative: -87
{ "language": "en", "url": "https://stackoverflow.com/questions/15491152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can you sign hyperledger-sawtooth transactions using metamask keys? Hyperledger sawtooth uses secp256k1 ECDSA to sign transactions: https://sawtooth.hyperledger.org/docs/core/releases/1.2.5/_autogen/txn_submit_tutorial.html?highlight=transaction%20sign And aparently ethereum uses the same type of signature: https://hackernoon.com/a-closer-look-at-ethereum-signatures-5784c14abecc Thus, it would seem that because Metamask is used with Ethereum it would also work with sawtooth. However, I haven't found examples of this, and although I've tried signing transactions with web3.js and ethers.js with Metamask those signatures get rejected by Sawtooth. A: It's possible, this is an example I made using web3:0.20.7: https://github.com/le99/sawtooth-with-metamask-signatures/blob/master/src/App.js The important function is onClick() import './App.css'; import React, { useState } from 'react'; var ethUtil = require('ethereumjs-util') const secp256k1 = require('secp256k1') const CryptoJS = require('crypto-js'); const axios = require('axios').default; const cbor = require('cbor') const Web3 = require('web3'); //https://github.com/ethereum/web3.js/blob/0.20.7/DOCUMENTATION.md // let web3 = new Web3(Web3.givenProvider || "ws://localhost:8545"); let web3; if (typeof window.web3 !== 'undefined') { web3 = new Web3(window.web3.currentProvider); } else { // set the provider you want from Web3.providers web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); } const hash = (x) => CryptoJS.SHA512(x).toString(CryptoJS.enc.Hex) // https://stackoverflow.com/questions/33914764/how-to-read-a-binary-file-with-filereader-in-order-to-hash-it-with-sha-256-in-cr function arrayBufferToWordArray(ab) { var i8a = new Uint8Array(ab); var a = []; for (var i = 0; i < i8a.length; i += 4) { a.push(i8a[i] << 24 | i8a[i + 1] << 16 | i8a[i + 2] << 8 | i8a[i + 3]); } return CryptoJS.lib.WordArray.create(a, i8a.length); } async function onClick(){ const ethereum = window.ethereum; var from = web3.eth.accounts[0] // var msgHash = ethUtil.keccak256(Buffer.from('An amazing message, for use with MetaMask!')) var msgHash = Buffer.from('8144a6fa26be252b86456491fbcd43c1de7e022241845ffea1c3df066f7cfede', 'hex'); console.log(from); let signature1 = await new Promise((resolve, reject)=>{ web3.eth.sign(from, msgHash, function (err, result) { if (err) return reject(err) return resolve(result) }) }); const rpk3 = secp256k1.ecdsaRecover(Uint8Array.from(Buffer.from(signature1.slice(2, -2), 'hex')), parseInt(signature1.slice(-2), 16) - 27, Uint8Array.from(msgHash)); let publicKey = Buffer.from(rpk3, 'hex').toString('hex') console.log(msgHash.toString('hex')); console.log(signature1); console.log(publicKey); console.log(); const INT_KEY_FAMILY = 'intkey' const INT_KEY_NAMESPACE = hash(INT_KEY_FAMILY).substring(0, 6) const address = INT_KEY_NAMESPACE + hash('foo').slice(-64) console.log('address:',address); const payload = { Verb: 'set', Name: 'foo', Value: 41 } console.log('public:', publicKey); const payloadBytes = cbor.encode(payload) const protobuf = require('sawtooth-sdk/protobuf') const transactionHeaderBytes = protobuf.TransactionHeader.encode({ familyName: 'intkey', familyVersion: '1.0', inputs: [address], outputs: [address], signerPublicKey: publicKey, // In this example, we're signing the batch with the same private key, // but the batch can be signed by another party, in which case, the // public key will need to be associated with that key. batcherPublicKey: publicKey, // In this example, there are no dependencies. This list should include // an previous transaction header signatures that must be applied for // this transaction to successfully commit. // For example, // dependencies: ['540a6803971d1880ec73a96cb97815a95d374cbad5d865925e5aa0432fcf1931539afe10310c122c5eaae15df61236079abbf4f258889359c4d175516934484a'], dependencies: [], payloadSha512: CryptoJS.SHA512(arrayBufferToWordArray(payloadBytes)).toString(CryptoJS.enc.Hex), nonce:"hey4" }).finish() let sss=CryptoJS.SHA256(arrayBufferToWordArray(transactionHeaderBytes)).toString(CryptoJS.enc.Hex); let dataHash=Uint8Array.from(Buffer.from(sss, 'hex')); let signature = await new Promise((resolve, reject)=>{ web3.eth.sign(from, dataHash, function (err, result) { if (err) return reject(err) return resolve(result) }) }); signature = signature.slice(2, -2) console.log('sha1:', CryptoJS.SHA512(arrayBufferToWordArray(transactionHeaderBytes)).toString(CryptoJS.enc.Hex)) console.log('signature1:', signature) const transaction = protobuf.Transaction.create({ header: transactionHeaderBytes, headerSignature: signature, payload: payloadBytes }) //-------------------------------------- //Optional //If sending to sign outside const txnListBytes = protobuf.TransactionList.encode({transactions:[ transaction ]}).finish() //const txnBytes2 = transaction.finish() let transactions = protobuf.TransactionList.decode(txnListBytes).transactions; //---------------------------------------- //transactions = [transaction] const batchHeaderBytes = protobuf.BatchHeader.encode({ signerPublicKey: publicKey, transactionIds: transactions.map((txn) => txn.headerSignature), }).finish() // sss=CryptoJS.SHA256(arrayBufferToWordArray(batchHeaderBytes)).toString(CryptoJS.enc.Hex); dataHash=Uint8Array.from(Buffer.from(sss, 'hex')); signature = await new Promise((resolve, reject)=>{ web3.eth.sign(from, dataHash, function (err, result) { if (err) return reject(err) return resolve(result) }) }); signature = signature.slice(2, -2) const batch = protobuf.Batch.create({ header: batchHeaderBytes, headerSignature: signature, transactions: transactions }) const batchListBytes = protobuf.BatchList.encode({ batches: [batch] }).finish() console.log(Buffer.from(batchListBytes).toString('hex')); console.log('batchListBytes has the batch bytes that ca be sent to sawtooth') // axios.post(`${HOST}/batches`, batchListBytes, { // headers: {'Content-Type': 'application/octet-stream'} // }) // .then((response) => { // console.log(response.data); // }) // .catch((err)=>{ // console.log(err); // }); } The example is based on: https://sawtooth.hyperledger.org/docs/core/releases/1.2.6/_autogen/sdk_submit_tutorial_js.html There is a lot of low level stuff, hyperledger and Metamask represent signatures slightly differently. Also most libraries for Metamask automatically wrap the data (https://web3js.readthedocs.io/en/v1.2.11/web3-eth-accounts.html#sign), they then hash it using keccak256, and that hash is what is finnally signed with secp256k1, which is not what you need for Sawtooth. An example where no wraping or intermediaries are used to sign is: https://github.com/danfinlay/js-eth-personal-sign-examples/blob/master/index.js
{ "language": "en", "url": "https://stackoverflow.com/questions/64582064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Binary search tree successor How can I change the following function to let me return the successor of an integer k to a level between h1 and h2? h1 and h2 are ranges for example h1 = 0 and h2=3, I want the successor of k who is at depths between 0 and 3 //BST declaration struct node { int key; struct node *left;//pointer to left struct node *right;// pointer to right }; struct node *successor(struct node *T, int k, int h1, int h2) { struct node *z = T; struct node *y = NULL;//successor candidate if(T!=NULL) { while(z!=NULL && z->key!=NULL) { if(k > z->key) z = z->right;//If k is greater than the root then I move to the right else if(k < z->key) { y = z;//updates the successor of his father z = z->left;//If k is less than the root then I move to the left } } if(z!=NULL && z->right!=NULL) y = bstMinimum(z->right); } return y; } //find the minimum of the right tree struct node *bstMinimum(struct node *A) { while(A!=NULL && A->left!=NULL) { A=A->left; } return A; }
{ "language": "en", "url": "https://stackoverflow.com/questions/32468544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to share to git a Dynamic Web Project in Eclipse I make a new Dynamic Web Project, and then go team->share Project. Eclipse advises against using a repository in the same place so I do as I am told and create one somewhere else. After doing this WEB-INF and WEB-INF/lib and also "Java Resources/src" end up with "?" decorators on them. Is this bad ?, should I have done this differently ?. A: Can you use "egit". It is the git provider for eclipse A: As stated in the user manual for EGit, the question mark next to a file denotes it is untracked by the GIT repository, and will not be version controlled until explicitly added.
{ "language": "en", "url": "https://stackoverflow.com/questions/21893588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sum the values for different keys with id same in javascript I would like to know how to sum more than one key values of object for same id in javascript for same id, how to sum price and total in my obj I have tried the code below var obj = [{ id: "1", price: 100, total: 200 }, { id: "1", price: 100, total: 200 }, { id: "2", price: 10, total: 200 }] let newobj = obj.reduce((a, c) => { let filtered = a.filter(el => el.id === c.id); if (filtered.length > 0) { a[a.indexOf(filtered[0])].price += +c.price; } else { a.push(c); } return a; }, []); console.log(newobj); Expected Output: result=[{ id: "1", price: 200, total: 400 },{ id: "2", price: 10, total: 200 }] A: Instead of Array#filter, you could use Array#find and take the object directly without later having a look up for the index. If found just add both wanted properties price and total. If you like not to mutate the original data, you could take a copy of the object for pushing. a.push({ ...c }); var array = [{ id: "1", price: 100, total: 200 }, { id: "1", price: 100, total: 200 }, { id: "2", price: 10, total: 200 }], result = array.reduce((a, c) => { let found = a.find(el => el.id === c.id); if (found) { found.price += c.price; found.total += c.total; } else { a.push(c); } return a; }, []); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; } A: All you have to do is add the totals as you did the price var obj = [{ id: "1", price: 100, total: 200 }, { id: "1", price: 100, total: 200 }, { id: "2", price: 10, total: 200 }] let newobj = obj.reduce((a, c) => { let filtered = a.filter(el => el.id === c.id); if (filtered.length > 0) { a[a.indexOf(filtered[0])].price += +c.price; a[a.indexOf(filtered[0])].total += +c.total; /* <-- new */ } else { a.push(c); } return a; }, []); console.log(newobj); A: You could do like this with help of spread operator var obj = [{ id: "1", price: 100, total: 200 },{ id: "1", price: 100, total: 200 },{ id: "2", price: 10, total: 200}] let newobj = Object.values(obj.reduce((acc,i) => { acc[i.id] = acc[i.id] ? {...acc[i.id],price:acc[i.id]['price']+i.price,total:acc[i.id]['total']+i.total} : i; return acc; }, {})); console.log(newobj)
{ "language": "en", "url": "https://stackoverflow.com/questions/59855649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: reading value from a file in batch script We can set the value of a variable (say, "upper_bound") in a batch file in the following way: SET upper_bound=3 But is there any way to read this value '3' from a input.txt file which will just contain value 3? A: Like this: SET/P upper_bound=<input.txt
{ "language": "en", "url": "https://stackoverflow.com/questions/40289122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Data only shown when application starts I have two problems. First, I managed to connect a DB which I created in visual studio and connected it to the form, but the changes are shown only when the form is started from the .exe file. Could someone explain to me why? Second, know I want to connect a second WinForm to the same DB, but I could not find the correct way of doing it. Thank you! enter image description here string cn_string = Properties.Settings.Default.TenantListConnectionString; SqlConnection cn_connection = new SqlConnection(cn_string); if (cn_connection.State != ConnectionState.Open) { cn_connection.Open(); } string sql_Text = "SELECT * FROM tbl_Tenants"; DataTable tbl = new DataTable(); SqlDataAdapter adapter = new SqlDataAdapter(sql_Text, cn_connection); adapter.Fill(tbl); listBox1.DisplayMember = "Tenant Name"; listBox1.ValueMember = "Room Number"; listBox1.DataSource = tbl;
{ "language": "en", "url": "https://stackoverflow.com/questions/59254638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bash, searching in all pdf files I want a script that would find my everything what I want in all of my pdf files. So I wrote this #!/bin/bash for file in */*.pdf; do printf "$file\n" echo "--------------------------------------------" pdftotext $file - | grep -i "$1" echo "--------------------------------------------" printf "\n\n" done But there are some problems. Firstly I'd like to see only those files that grep find something in, also I noticed that PdfToText throws a help messeges when it encounters a filename with white spaces A: Quite a few issues here. * *Your script will spew errors if filenames include a percent sign, since printf "$file" will interpret its first argument as a format. Use printf '%s' "$file" instead. *You haven't quoted the filename argument when you run pdftotext, which is likely why it throws its help message -- pdftext foo bar.pdf - looks like two arguments, not one filename. pdftotext "$file" instead. (As a rule, always quote your variables in bash.) *If you want to show output only for matching files, you need to evaluate a condition before you print the filename. I don't know how pdftotext behaves exactly, but assuming it doesn't produce a bunch of stderr, the following might work: #!/usr/bin/env bash line=$(printf '%032s' 0); line=${line//0/-} for file in */*.pdf; do output="$(pdftotext "$file" - | grep -i "$1")" if [ -n "$output" ]; then printf "%s\n$line\n%s\n$line\n\n" "$file" "$output" fi done Note: I haven't tested this. You might want to expand the printf with the $line references for readability if this format appears complex or obtuse.
{ "language": "en", "url": "https://stackoverflow.com/questions/35069650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inline for a constructor I am trying to completely understand what inline does but I get confused when it comes to constructors. So far I understood that inlining a function will put the function in the place it is called: class X { public: X() {} inline void Y() { std::cout << "hello" << std::endl; } }; int main() { X x; x.Y; //so instead of this it will be: "std::cout << "hello" << std::endl;" } But what will this do (how does this get replaced?): class X { public: //or inline if the compilers feeling friendly for this example __forceinline X() {} } A: The meaning of inline is just to inform the compiler that the finction in question will be defined in this translation as well as possibly other translation units. The compiler uses this information for two purposes: * *It won't define the function in the translation unit as an externally visible, unique symbol, i.e., you won't get an error about the symbol being defined multiple times. *It may change its view on whether it wants to call a function to access the finctionality or just expand the code where it is used. Whether it actually will inline the code will depend on what the compiler can inline, what it thinks may be reasonable to inline, and possibly on the phase of the moon. There is no difference with respect to what sort of function is being inlined. That is, whether it is a constructor, a member function, a normal function, etc. BTW, member functions defined inside the class definition are implicitly declared inline. There is no need to mention it explicitly. __forecedinline seems to be a compiler extension and assuming it does what it says is probably a bad idea as compilers are a lot better at deciding on what should be inlined than humans.
{ "language": "en", "url": "https://stackoverflow.com/questions/18036359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Segmentation Fault 11, Xcode 8.2.1, Swift 3 I'm trying to create an archive of my application, but I'm getting a segmentation fault when building for an iOS Device. I do not encounter this issue when building for the simulator. So far, I have: * *Cleaned my project *Cleaned my build folder *Deleted my derived data folder *Installed Mac OS Sierra *Installed additional Xcode tools after updating to Sierra *Restarted Xcode/computer multiple times The error typically looks like this: Call parameter type does not match function signature! 0 swift 0x000000010f4ab3ad PrintStackTraceSignalHandler(void*) + 45 1 swift 0x000000010f4aab56 SignalHandler(int) + 790 2 libsystem_platform.dylib 0x00007fffb1b28bba _sigtramp + 26 3 libsystem_platform.dylib 0x000000011033a000 _sigtramp + 1585517664 4 swift 0x000000010f3038e8 llvm::TypeFinder::incorporateValue(llvm::Value const*) + 296 5 swift 0x000000010f3032fa llvm::TypeFinder::run(llvm::Module const&, bool) + 682 6 swift 0x000000010f1c827e (anonymous namespace)::TypePrinting::incorporateTypes(llvm::Module const&) + 30 7 swift 0x000000010f1c9bdb printAsOperandImpl(llvm::Value const&, llvm::raw_ostream&, bool, llvm::ModuleSlotTracker&) + 171 8 swift 0x000000010f30c633 (anonymous namespace)::VerifierSupport::Write(llvm::Value const*) + 67 9 swift 0x000000010f31616e (anonymous namespace)::Verifier::VerifyCallSite(llvm::CallSite) + 590 10 swift 0x000000010f318ef3 (anonymous namespace)::Verifier::visitCallInst(llvm::CallInst&) + 35 11 swift 0x000000010f329ac1 (anonymous namespace)::VerifierLegacyPass::runOnFunction(llvm::Function&) + 1649 12 swift 0x000000010f2e089d llvm::FPPassManager::runOnFunction(llvm::Function&) + 973 13 swift 0x000000010f2e02ab llvm::FPPassManager::runOnModule(llvm::Module&) + 43 14 swift 0x000000010f2e977a llvm::legacy::PassManager::run(llvm::Module&) + 1514 15 swift 0x000000010c605901 performLLVM(swift::IRGenOptions&, swift::DiagnosticEngine&, llvm::sys::SmartMutex<false>*, llvm::GlobalVariable*, llvm::Module*, llvm::TargetMachine*, llvm::StringRef) + 5921 16 swift 0x000000010c6038c1 performIRGeneration(swift::IRGenOptions&, swift::ModuleDecl*, swift::SILModule*, llvm::StringRef, llvm::LLVMContext&, swift::SourceFile*, unsigned int) + 2625 17 swift 0x000000010c4b8f31 performCompile(swift::CompilerInstance&, swift::CompilerInvocation&, llvm::ArrayRef<char const*>, int&, swift::FrontendObserver*) + 23777 18 swift 0x000000010c4b12b3 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 17859 19 swift 0x000000010c46d5cf main + 8239 20 libdyld.dylib 0x00007fffb191b255 start + 1 In the stack dump, there's this line: 2. Running pass 'Module Verifier' on function '@_TZFC12MyAppName23MyClassNameg13nextImagePathV10Foundation3URL' I think this indicates the error is being thrown when compiling the static computed variable nextImagePath, which returns a URL to a file path. Internally, this relies on a few other computed variables and a method nextFilePathForDirectoryAtURL. Altogether, the code looks like this: /* * This is the offending computed variable. */ static var nextImagePath: URL { return nextFilePathForDirectoryAtURL(imageDirectory, withExtension: "jpg"); } /* * The method called by above variable. It looks through all the * files in a directory, finds the one with the highest index, * and returns a new path by incrementing the highest index by 1. */ fileprivate static func nextFilePathForDirectoryAtURL(_ url: URL, withExtension ext: String) -> URL { guard let files = try? FileManager.default.contentsOfDirectory( at: url, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) else { fatalError("Could not create next file path for directory at url: \(url)"); } var maxFileNumber = 0; for file in files { let fileName = file.deletingPathExtension().lastPathComponent; guard let fileNumber = Int(fileName), file.pathExtension.lowercased() == ext.lowercased() else { continue } maxFileNumber = max(maxFileNumber, fileNumber); } return url.appendingPathComponent("\(maxFileNumber + 1).\(ext)"); } /* * Some supporting computed variables for constructing directories. */ fileprivate static var libraryDirectory: URL { guard let url = try? FileManager.default.url( for: .libraryDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else { fatalError("Could not create library directory url."); } return url; } fileprivate static var documentSetDirectory: URL { let directory = libraryDirectory.appendingPathComponent("MemberDocumentSets"); try? FileManager.default.createDirectory( at: directory, withIntermediateDirectories: true, attributes: nil); return directory; } fileprivate static var imageDirectory: URL { let directory = documentSetDirectory.appendingPathComponent("Images"); try? FileManager.default.createDirectory( at: directory, withIntermediateDirectories: true, attributes: nil); return directory; } I'm not really sure why this error is occurring, or why it doesn't happen when building for the simulator. I've been trying to find answers for about 5 hours now with no luck, so I'd thought post. Any help is greatly appreciated. Thanks! A: Welp, after many hours, I was able to deduce that the error was caused by the documentSetDirectory computed variable. Apparently, the compiler was not happy about converting the result of a try statement into an optional. Instead, I had to wrap the statement in a do catch block. The following code fixed my problem: fileprivate static var documentSetDirectory: URL { let directory = libraryDirectory.appendingPathComponent("MemberDocumentSets"); do { try FileManager.default.createDirectory( at: directory, withIntermediateDirectories: true, attributes: nil); } catch { /* * Do nothing. So why have a catch block at all? Because: for some reason * this prevents the compiler from spitting up. Apparently it didn't like * converting the `try` to an optional here. Weirdly, I'm still doing the * optional conversion elsewhere in this same class without issue (see * computed variables below). * * ¯\_(ツ)_/¯ */ } return directory; } fileprivate static var imageDirectory: URL { let directory = documentSetDirectory.appendingPathComponent("Images"); try? FileManager.default.createDirectory( at: directory, withIntermediateDirectories: true, attributes: nil); return directory; } Evidently, this must be a bug with the compiler. I created an empty project and copied the original code, but it compiled without issue and I was unable to find any project setting differences that caused the same error. In any case, I'm glad to have found a solution, and hopefully it'll save some time for a few poor souls in the future.
{ "language": "en", "url": "https://stackoverflow.com/questions/42239781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to open a file upon button click PySimpleGui my goal is to create a button and when the button is pressed to open txt file. I have already created button in the layout but I can't figure out how to make a txt file open upon button click. This is python and I'm using PySimpleGui as framework. The txt file is very long(~600k lines) so ideally it will be in another popup Couldn't find anything in the documentation nor the cookbook A: To browse a txt file * *Using sg.FileBrowse to select file and send filename to previous element sg.Input *Set option file_types=(("TXT Files", "*.txt"), ("ALL Files", "*.*")) of sg.FileBrowse to filter txt files. Read txt file by * *open(filename, 'rt', 'utf-8') as f *read all text from f Create another popup window with element sg.Multiline with text read from txt file. from pathlib import Path import PySimpleGUI as sg def popup_text(filename, text): layout = [ [sg.Multiline(text, size=(80, 25)),], ] win = sg.Window(filename, layout, modal=True, finalize=True) while True: event, values = win.read() if event == sg.WINDOW_CLOSED: break win.close() sg.theme("DarkBlue3") sg.set_options(font=("Microsoft JhengHei", 16)) layout = [ [ sg.Input(key='-INPUT-'), sg.FileBrowse(file_types=(("TXT Files", "*.txt"), ("ALL Files", "*.*"))), sg.Button("Open"), ] ] window = sg.Window('Title', layout) while True: event, values = window.read() if event == sg.WINDOW_CLOSED: break elif event == 'Open': filename = values['-INPUT-'] if Path(filename).is_file(): try: with open(filename, "rt", encoding='utf-8') as f: text = f.read() popup_text(filename, text) except Exception as e: print("Error: ", e) window.close() May get problem if txt file with different encoding. A: On linux you have an environment variable called editor like this EDITOR=/usr/bin/micro You can get that env using os file_editor = os.getenv("EDITOR", default = "paht/to/default/editor") Then you can spawn a process os.spawnlp(os.P_WAIT, file_editor, '', '/path/to/file') This essentially be a popup. Windows probably uses a different env name Leaving the above because this is essentially what this does: os.system('c:/tmp/sample.txt') The above snippet is a one liner to do basically what I mentioned above A: I don't know what is your platform. Anyway, opening a file will involve: * *choosing a file to be opened (from your formulation, I understand that in your case it's a given file with a known path; otherwise you'd need to use, e.g., sg.FileBrowse()); and *executing a command to open the file using a default or a specified reader or editor. I use the following function (working in MacOS and Windows) to execute a command: import platform import shlex import subprocess def execute_command(command: str): """ Starts a subprocess to execute the given shell command. Uses shlex.split() to split the command into arguments the right way. Logs errors/exceptions (if any) and returns the output of the command. :param command: Shell command to be executed. :type command: str :return: Output of the executed command (out as returned by subprocess.Popen()). :rtype: str """ proc = None out, err = None, None try: if platform.system().lower() == 'windows': command = shlex.split(command) proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) out, err = proc.communicate(timeout=20) except subprocess.TimeoutExpired: if proc: proc.kill() out, err = proc.communicate() except Exception as e: if e: print(e) if err: print(err) return out and call it this way to open the file using the default editor: command = f'\"{filename}\"' if platform.system().lower() == 'windows' else \ f'open \"{filename}\"' execute_command(command) You can tweak command to open the file in an editor of your choice the same way as you would do in CLI. This is quite a universal solution for various commands. There are shorter solutions for sure :) Reference: https://docs.python.org/3/library/subprocess.html
{ "language": "en", "url": "https://stackoverflow.com/questions/67065794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: App is crashing due to connections left open. Should I close them in the DAL, or in the domain repositories? I have an ASP.NET MVC application that was running fine in dev & test but is crashing under load. The culprit is failure to close the OdbcConnections that I'm using in a custom DAL. The underlying database is Oracle. Entity Framework was not an option at the time this project started so we have a custom DAL to centralize all access to the Oracle database. The DAL is just a POCO that wraps the connection and has a couple of helper methods to wrap QueryReader and ExecuteNonQuery for convenience. The DAL is used by a set of domain repositories (over a dozen) that in turn build domain models by querying the DAL. My question: Where should I close the connection in this scenario? For example, in the DAL I have a method that gets the connection based on the environment in which the app is hosted: public OdbcConnection GetConnection() { // environment check happens, then return return new OdbcConnection(myConnectionString); } Then I have methods like this in the DAL: public OdbcCommand CreateCommand(string queryText) { return new OdbcCommand(queryText); } public OdbcDataReader QueryReader(string queryText) { var connection = GetConnection(); connection.Open(); try { var command = connection.CreateCommand(); command.CommandText = queryText; command.CommandType = CommandType.Text; return QueryReader(command); } finally { connection.Close(); } } public OdbcDataReader QueryReader(OdbcCommand command) { var connection = GetConnection(); connection.Open; try { command.Connection = connection; command.Prepare(); return command.ExecuteReader(); } finally { connection.Close(); } } (the try/finally blocks were added as a first attempt to stop the errors, but closing the connection here breaks all the repositories, as seen below) Then my repository methods look something like this: (_dal is a protected object loaded by the repository's base class) public IEnumerable<SomeDomainObject> GetMyDomainObjects() { var query = "select abc from xyz where foo = ?"; var command = _dal.CreateCommand(query); var reader = _dal.QueryReader(command); if (reader.HasRows) // fails here if I close connection in QueryReader() { var list = new IList<MyDomainObject>(); while (reader.Read()) { // build the domain object and append it to the list } } else { // error handling here } } Note: The crashes occurred because I didn't have the try/finally to close the connection as early as possible, so I've added them in since then. But now the finally clause closes the connection underlying the OdbcDataReader so that when the reader is being processed by the domain, it can't read any data because the connection is closed. ISSUE: If I close the connection in the DAL then it is closed before the reader can iterate. Should I manually open and close the connection in each repository method, i.e. inside GetMyDomainObjects should I open the connection (via _dal.GetConnection()) and then have a try/finally that will close the connection? In every repository method? Or is there a way to manage this connection centrally, i.e. via IDispose on the DAL, and then just dispose of the DAL itself at the end of the method instead of exposing the underlying connection to the repository method? Any and all help much appreciated. Thank you! Edit Here is the error message that is coming up in the ELMAH log: System.Data.Odbc.OdbcException: ERROR [HY000] [Oracle][ODBC][Ora]ORA-12537: TNS:connection closed ERROR [IM006] [Microsoft][ODBC Driver Manager] Driver's SQLSetConnectAttr failed ERROR [HY000] [Oracle][ODBC][Ora]ORA-12537: TNS:connection closed Also, this application is replacing an old legacy classic ASP site that connects to the same database. When I roll back to the legacy site the database connection works correctly. So it isn't the Oracle connection itself I don't think. A: Change your second function definition as follows: public OdbcDataReader QueryReader(OdbcCommand command) { var connection = GetConnection(); connection.Open; try { command.Connection = connection; command.Prepare(); return command.ExecuteReader(CommandBehavior.CloseConnection); } finally { //connection.Close(); } } I believe the solution is self explanatory.
{ "language": "en", "url": "https://stackoverflow.com/questions/37815873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Re-opening stdout and stdin file descriptors after closing them I'm writing a function, which, given an argument, will either redirect the stdout to a file or read the stdin from a file. To do this I close the file descriptor associated with the stdout or stdin, so that when I open the file it opens under the descriptor that I just closed. This works, but the problem is that once this is done, I need to restore the stdout and stdin to what they should really be. What I can do for stdout is open("/dev/tty",O_WRONLY); But I'm not sure why this works, and more importantly I don't know of an equivalent statement for stdin. So I have, for stdout close(1); if (creat(filePath, O_RDWR) == -1) { exit(1); } and for stdin close(0); if (open(filePath, O_RDONLY) == -1) { exit(1); } A: You should use dup() and dup2() to clone a file descriptor. int stdin_copy = dup(0); int stdout_copy = dup(1); close(0); close(1); int file1 = open(...); int file2 = open(...); < do your work. file1 and file2 must be 0 and 1, because open always returns lowest unused fd > close(file1); close(file2); dup2(stdin_copy, 0); dup2(stdout_copy, 1); close(stdin_copy); close(stdout_copy); However, there's a minor detail you might want to be careful with (from man dup): The two descriptors do not share file descriptor flags (the close-on-execflag). The close-on-exec flag (FD_CLOEXEC; see fcntl(2)) for the duplicate descriptor is off. If this is a problem, you might have to restore the close-on-exec flag, possibly using dup3() instead of dup2() to avoid race conditions. Also, be aware that if your program is multi-threaded, other threads may accidentally write/read to your remapped stdin/stdout. A: I think you can "save" the descriptors before redirecting: int save_in, save_out; save_in = dup(STDIN_FILENO); save_out = dup(STDOUT_FILENO); Later on you can use dup2 to restore them: /* Time passes, STDIN_FILENO isn't what it used to be. */ dup2(save_in, STDIN_FILENO); I am not doing any error checking in that example - you should. A: You could create a child process, and set up the redirection inside the child only. Then wait for the child to terminate, and continue working in the parent process. That way you don't have to worry about reversing your redirection at all. Just look for examples of code using fork() and wait ().
{ "language": "en", "url": "https://stackoverflow.com/questions/9084099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: Remove planes if boolean = true not working I'm trying to remove my planes when the user inputs that they have landed. This doesn't work. Can anyone see any problems with my code to why it does not work. Here is my code: Plane static boolean isLanded; public boolean isLanded() { return isLanded; } public void setLanded(boolean isLanded) { this.isLanded = isLanded; } PlaneStore public void removeLandedPlanes(PlaneStore store) { if(Plane.isLanded = true) { airlineMap.remove(store); } } MainApp case 3: System.out.println("Remove Landed Planes."); airlineMap.removeLandedPlanes(airlineMap); airlineMap.print(); break; HashMap declaration in PlaneStore HashMap<String, TreeMap<String, Plane>> airlineMap; public PlaneStore() { airlineMap = new HashMap<String, TreeMap<String, Plane>>(); } And then in main PlaneStore airlineMap = new PlaneStore(); What this seems to have done is make every plane object to have isLanded to false. A: if(Plane.isLanded = true) Note that this is assigning the value true to Plane.isLanded. You want to use the comparison operator == instead of =. if(Plane.isLanded == true) And since this is a boolean already, you should actually leave out the == true completely: if(Plane.isLanded) A: You are assigning to Plane.isLanded, not testing for equality if(Plane.isLanded = true) should be if(Plane.isLanded == true) You could avoid this altogether with simply if (Plane.isLanded) or put the constant term on the left if (true == Plane.isLanded) which would not have compiled had you made your initial mistake of = instead of ==
{ "language": "en", "url": "https://stackoverflow.com/questions/13860033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how can I display UIImage from image url The code below works fine if I give statically but imgDescView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[NSString stringWithFormat:@"http://4cing.com/mobile_app/uploads/pageicon/6.jpg"]]]]; Same code - I am passing the image url name dynamically it's not working imgDescView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[NSString stringWithFormat:@"%@",[imagename objectAtIndex:0]]]]; A: NSMutableArray *imagename = [[NSMutableArray alloc] initWithObjects:@"http://4cing.com/mobile_app/uploads/pageicon/6.jpg", nil]; UIImageView *imgDescView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0, 200, 200)]; imgDescView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:[NSString stringWithFormat:@"%@",[imagename objectAtIndex:0]]]]]; it is working ... i think u r not creating array properly. A: You need to verify the NSArray contents. Log out the objects of the array: NSLog(@"imagename = %@",[imagename description]); Also, a side-note - might want to think about loading that image dynamically. I wrote a class that makes this pretty painless: https://stackoverflow.com/a/9786513/585320 The answer is geared toward using in TableViews (where lag would really hurt performance), but you can (and I do) use this for any web image loading. This keeps the UI fluid and is very fast. A: Hi create url in this manner [NSURL URLWithString:[[NSString stringWithFormat:@"%@",[imagename objectAtIndex:0]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] i think it will work and will resolve ur problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/15519277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's wrong with following google ecommerce analytics code I have waited for more than 72 hours but ecommerce data is not tracked. Tracking is enabled in the analytics account. <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-xxxxx-1']); _gaq.push(['_setDomainName', '.welcome.com']); _gaq.push(['_trackPageview']); _gaq.push(['_trackPageLoadTime']); _gaq.push(['_addTrans', '650', // order ID - required 'bags', // affiliation or store name '19.99', // total - required '0', '4.0', // shipping 'Anchorage', // city 'Alaska', // state or province 'USA' ]); //Add each items in the order _gaq.push(['_addItem', '650', // order ID - necessary to associate item with transaction '29', // SKU/code - required 'bags set of 4', // product name 'Cleaning Supplies', // category or variation '15.99', // unit price - required '1' ); //Now submit the transaction _gaq.push(['_trackTrans']); //submits transaction to the Analytics server (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> A: I think you are missing a closing bracket: //Add each items in the order _gaq.push(['_addItem', '650', // order ID - necessary to associate item with transaction '29', // SKU/code - required 'bags set of 4', // product name 'Cleaning Supplies', // category or variation '15.99', // unit price - required '1' ]); //right here, missing closing bracket
{ "language": "en", "url": "https://stackoverflow.com/questions/6221933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why numeric enums can be assigned to any number in typescript? I want to know why numeric enums can be assigned to any number. what's different between numeric enums and string-based enums? enum TYPES { False = 0, True = 1, UnKnow = 2, } type IType = { type: TYPES } const demo1: IType = { type: 9 // works, hope error: Type 9 is not assignable to type TYPES } enum COLORS { GREEN = 'green', RED = 'red', YELLOW = 'yellow', } type IColor = { color: COLORS; } const demo2: IColor = { color: 'blue' // error: Type '"blue"' is not assignable to type 'COLORS'.ts(2322) }
{ "language": "en", "url": "https://stackoverflow.com/questions/57051076", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get the six week sunday's weekno in SQL server 2008 r2? I want to get the six week sundays weekno using the SQL Server 2008.For example i have the November month, date 18, year 2012. The WeekNo of the November month 18 th date is "47". A: Try this: SELECT DATEPART(week,'18-nov-2012')
{ "language": "en", "url": "https://stackoverflow.com/questions/13639005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can i put my searchbox and navbar at the same line? I'm trying to make my search box in the same line with the "home, about, contact..." stuff but it doesn't seem to worrk, i guess my CSS just not enough to make that, can anyone help me to make them stand in the same line? Thank you so much! This is css: .container{ background-color: #A3318A; } .container ul{ display: inline block; } .container ul li { display: inline; padding:15px; font-size: 1.5rem; color: white; } This is my html: <!DOCTYPE html> <html> <head> <title></title> <link rel="stylesheet" href="style.css"> <script src="https://kit.fontawesome.com/48a972c999.js" crossorigin="anonymous"></script> </head> <body> <div class="container"> <ul> <li>Home</li> <li>About</li> <li>News</li> <li>Contact</li> </ul> <form> <input class="input" type="text" placeholder="Search here..."> <i class="fas fa-search"></i> </form> </div> </body> </html> A: Make form with display: inline-block: .container form, /* added */ .container ul{ display: inline-block; /* fixed */ }
{ "language": "en", "url": "https://stackoverflow.com/questions/68463019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Notification Builder action not working on API 31 (Android 12) I'm stuck while dealing with this api 31. i made a chat app. When I create an action button to receive a phone call it works on android below API 31 or below Android 12, but it doesn't work on Android 12 (only work if the notification is not has action). maybe someone here can help me in finding a solution to this problem? FirebaseService.java @Override public void onMessageReceived(@NonNull RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); boolean cancelNotification = false; Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); Map<String, String> params = remoteMessage.getData(); JSONObject data = new JSONObject(params); PendingIntent pendingIntent; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) { pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_MUTABLE); } else { pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); } String channel_id = getNotificationData(data, "channel"); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channel_id) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(getNotificationData(data, "title")) .setContentText(getNotificationData(data, "body")) .setAutoCancel(true) .setContentIntent(pendingIntent); if(channel_id.equals("cll2") && getNotificationData(data, "call_action").equals("open")){ playCallSound(this); if(WindowUtil.isAppOnBackground(this) || isScreenOff()){ ArrayList<String> par = new ArrayList<>(); par.add("call_channel"); par.add("call_type"); par.add("call_token"); par.add("call_peer"); String callType = getNotificationData(data, "call_type"); if(callType.equals("3") || callType.equals("4")){ par.add("call_group_name"); par.add("call_group_caller"); } Intent receiveCallAction = new Intent(this, CallReceiver.class); receiveCallAction.putExtra("action", "ANSWER"); Intent cancelCallAction = new Intent(this, CallReceiver.class); cancelCallAction.putExtra("action", "DECLINE"); for (String s : par) { receiveCallAction.putExtra(s, getNotificationData(data, s)); cancelCallAction.putExtra(s, getNotificationData(data, s)); } notificationBuilder.setOngoing(true); receiveCallAction.setAction("RECEIVE_CALL"); cancelCallAction.setAction("CANCEL_CALL"); PendingIntent receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_UPDATE_CURRENT); notificationBuilder .addAction(R.drawable.ic_baseline_call_24_green, "Answer", receiveCallPendingIntent) .addAction(R.drawable.ic_baseline_call_red_24, "Decline", cancelCallPendingIntent); }else{ cancelNotification = true; } }if(channel_id.equals("cll2") && getNotificationData(data, "call_action").equals("end_timeout")){ stopRinging(); }else if(channel_id.equals("ntf1")){ if(UserUtil.IS_CHAT_ACTIVITY){ cancelNotification = true; } if(!cancelNotification){ playNotificationSound(this); } } if(!cancelNotification){ NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE); NotificationChannel channel = new NotificationChannel(channel_id, getString(R.string.app_name), NotificationManager.IMPORTANCE_HIGH); channel.enableLights(true); channel.enableVibration(true); mNotificationManager.createNotificationChannel(channel); } mNotificationManager.notify(1000, notificationBuilder.build()); } } CallReceiver.java (Broadcast Receiver) @Override public void onReceive(Context context, Intent intent) { if (intent != null && intent.getExtras() != null) { String action = intent.getStringExtra("action"); // Perform the action performClickAction(context, action, intent.getExtras()); // Close the notification after the click action is performed. NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.cancel(1000); // Stop the ringtone stopRinging(); } } on my AndroidManifest.xml <service android:name=".services.FirebaseService" android:exported="true"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service> <receiver android:name=".receiver.CallReceiver" android:exported="false" android:enabled="true"> <intent-filter> <action android:name="CALL_RECEIVER" /> </intent-filter> </receiver> Thank you A: i solve this problem by this code PendingIntent receiveCallPendingIntent; PendingIntent cancelCallPendingIntent; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) { receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); }else{ receiveCallPendingIntent = PendingIntent.getBroadcast(this, 1200, receiveCallAction, PendingIntent.FLAG_UPDATE_CURRENT); cancelCallPendingIntent = PendingIntent.getBroadcast(this, 1201, cancelCallAction, PendingIntent.FLAG_UPDATE_CURRENT); } also add this permission for force Android 12^ (AndroidManifest.xml) <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /><receiver android:name=".receiver.CallReceiver" android:exported="false" android:enabled="true" android:permission="android.permission.RECEIVE_BOOT_COMPLETED" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </receiver>
{ "language": "en", "url": "https://stackoverflow.com/questions/74733208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }