text
stringlengths
15
59.8k
meta
dict
Q: Unable to create scheduled event using AWS SAM I have a SAM template.yaml like below: AWSTemplateFormatVersion: '2010-09-09' Transform: 'AWS::Serverless-2016-10-31' Resources: GathererFunction: Type: 'AWS::Serverless::Function' Properties: Handler: main.handler Runtime: nodejs14.x Events: GathererDataSchedule: Type: Schedule Properties: Schedule: 'rate(1 minute)' GathererBucket: Type: AWS::S3::Bucket Properties: BucketName: gatherer-bucket I run sam validate and it comes back fine. I try to run sam deploy and the deployment fails when creating the schedule. Error says: ScheduleExpression is not valid. (Service: AmazonCloudWatchEvents; Status Code: 400; error code: ValidationException; I've also tried Schedule: rate('1 minute') and Schedule: rate(1 minute) Where am I going wrong? A: For me this template is deploying fine using the SAM cli. May you try to update your SAM cli? And also check if you have permissions to create Eventbridge events?
{ "language": "en", "url": "https://stackoverflow.com/questions/70808158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set values to an object of type NSObject after adding it to an NSMutableArray I created a class named as Tutoral which is a sub class of NSObject, and it has following synthesized properties Title and Url.Then in my viewcontroller I created an instance of the Tutorial class.I also Created an NSMutableArray object and initialised. I added my tutorial object instance to the array. Then I set the properties such as Title = "mytitle" and Url = "myurl". In another place I fetched the tutorial object instance from the array and NSLog its Title and Url property values.It shows "mytitle" and "myurl" respectively. My confusion is that why tutorial object instance which is inside the arry shows its property values. The tutorial object properties are set after that object is added to the array. Follwing are my tested code. NSMutableArray *newTutorials = [[NSMutableArray alloc] initWithCapacity:0]; Tutorial *tutorial = [[Tutorial alloc] init]; [newTutorials addObject:tutorial]; tutorial.title = @"mytitle"; tutorial.url = @"myurl"; Tutorial *objNew = [newTutorials objectAtIndex:0]; NSLog(@"Title %@",objNew.title); NSLog(@"Url %@",objNew.url); A: When you add an object to an array, the array just keeps a reference to that object (a pointer). It doesn't create a copy of that object. So, in the code example above, you're always dealing with the same instance of Tutorial: * *First, you create a new Tutorial with alloc and init, and store a reference to it with the tutorial pointer. *Then you add it to your array. Your array retains the object, which means it keeps a reference to it. *Then you set the title and url properties of your existing object. *Then you grab another reference to the same object, and call it objNew. You get this reference by asking the array for a pointer to its first object. *You then print the properties of the object. A: When the following line of code executed, [newTutorials addObject:tutorial]; What it does is , it add the address (reference) of tutorial object which you created in the previous line to the array newTutorials. Your confusion is this : " You haven't set the values for the tutorial object inside the array but why is it displaying mytitle and myurl when you NSLoged the propeties of tutorials?" The answer is simple "You've not stored the tutorial object inside the array but you have stored a reference to the tutorial object" Since when you've stored the reference and you've done the following to tutorial object : tutorial.title = @"mytitle"; tutorial.url = @"myurl"; When you try to print the properties of the reference stored in the array, it prints mytitle and myurl because that is what you've assigned to the actual object's properties.
{ "language": "en", "url": "https://stackoverflow.com/questions/21521469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gradle Android plugin generate R files for different product flavors? I am trying to merge my free app and paid app. The productFlavors of Android's new build system seem to be a perfect fit for my problem. I have the freeApp flavor working great, however when I build the paidApp flavor the R file that is being generated is in a package structure that is defined in the freeApp. Here is a snippet from by gradle.build file: productFlavors { freeApp { versionCode 201308020 versionName "2.0.13_free" packageName "com.flyingspheres.android" } paidApp { versionCode 201305110 versionName "2.0.10_paid" packageName "com.flyingspheres.android.inventory" } I always believed the R file's location is defined by the package name in the manifest. I verified that the manifest file is generating correctly. The problem is that the R file for both flavors is located in the same location. Gradle demands that a manifest lives within the main source tree so whatever version of the manifest I put in the main source tree that is where the R.java file will be generated at. Assuming that I get the R files to generate in the correct location for each flavor; how are the import statements for the R file supposed to be managed so that each flavor references the correct R file? Here is a screen shot of my project structure: Each AndroidManifest.xml file is a full and complete manifest - according to the documentation the manifest in the main tree should completely overwrite the product flavor version. Although, that is clearly not happening, because the activity that should be launched and the content providers aren't being overwritten. Any insights to what I'm doing wrong would be most appreciated. This has to be a very common situation that anyone overriding the packageName would run into. I've been trying to figure it out for about a week now and can't seem to get there on my own. Thanks, -Aaron A: Under android's gradle plugin 0.7.3, the generated R.java file is only made for the src/main's package name. It contains all the resources for the different flavors, it just puts them into one generated R.java file. I heard this from an IO talk. What's your package name in the src/main/AndroidManifest.xml? My guess is that it's com.flyingspheres.android Try importing R in your classes which need to access resources programatically using your src/main's package name. E.g. import com.flyingspheres.android.R;
{ "language": "en", "url": "https://stackoverflow.com/questions/19736212", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Best website for Programming Language Icons I was wondering to find icon packs for all programming language icons. Can anyone suggest which one is good website where I can find all icons (Either official or based on some similar theme) related to any programming language. A: Well after lots of surfing I found a good webpage for programming language icons. Programming Language Icons. Thank you guys! A: I use FontAwesome for all types of icons. There are various websites another is Flaticon A: There is Devicon a set of icons representing programming languages, designing, and development tools. You can use it as a font or directly copy/paste the SVG code into your project.
{ "language": "en", "url": "https://stackoverflow.com/questions/61593631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Using SUMIF with INDIRECT Values are in another sheet which is named as cell value"A3" =SUMIF(INDIRECT(" ' "&A3&" '$B:$B"),D$2,INDIRECT(" ' "&A3&" '!$M:$M")) do you see anything wrong with this formula ? doesn't work #REF! is the response. A: By enclosing A3 in ampersands you are referencing cell A3 in the current sheet. What you want is: =SUMIF(INDIRECT("'A3'!$B:$B"),D$2,INDIRECT("'A3'!$M:$M")) On second look, if you are intending to reference a sheet that is named what you have in cell A3 then you don't need the apostrophes around the cell reference: =SUMIF(INDIRECT(A3&"!$B:$B"),D$2,INDIRECT(A3&"!$M:$M"))
{ "language": "en", "url": "https://stackoverflow.com/questions/43202949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: installation path for sqlite database I am trying to access a database using python. The src folder is: ptbl/ ├── dialogue.py ├── elem_H.py ├── elems.db ├── __init__.py ├── __main__.py ├── main.py ├── menubar.ui └── menu.py with elem_H.py access elems.db database as: sqlfile = "elems.db" conn = sqlite3.connect(sqlfile) Ofcourse, when I am running it from terminal, inside src dir(ptbl), everything works fine. But, when I am outside the src dir,its giving error: sqlite3.OperationalError: no such table: Overview and same, if I install it using autotools. For elems.db to be worked,I have to run it from a folder where elems.db is present. How can I make it installed in a path? A: Mixing python and SQLite files in one single directory is not a good pratice at all. You should fix it and extract elems.db from your libraries directory. Moreover, as Lutz Horn said in comments, you should make it configurable and not trust that your database file will be always located in the exact same place. But anyway, to fix your issue without updating these two points, you have to take care of the elem_H.py location. You know elems.db is next to it, so you can do: import os.path sqlfile = os.path.join(os.path.dirname(__file__), "elems.db") * *__file__ store the relative path to your file from the place where you run command. *os.path.dirname remove the filename from the given path. *os.path.join will concat the computed path and your filename.
{ "language": "en", "url": "https://stackoverflow.com/questions/40806068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django - Can I create a global variable that can be accessed/manipulated from different functions in different files? I'm trying to figure out a way I can avoid passing so many arguments to functions in my app. I'm using different databases for each table, so joining is not possible, so I need to create a primary key dictionary that has the objects I need for subsequent functions. I do this to make only two queries. My example is below. Please note how I have to pass in the people_ref reference dictionary to each deform function. What I would like to do is set some sort of global people_ref variable that can be accessed from anywhere. That way I could just dump the People.in_bulk() response to the global pool, and then access it directly from inside the deform functions without having to pass in the reference. Is there a way to do that? What I want to call: >>> myapp.models.make_crazy_books([1,2,3]) From myapp/models.py: import itertools from django.db import models from myapp.utils import deform class People(models.Model): born = model.DateField() class Book(models.Model): author = models.ForeignKey(People, related_name='author_set') editor = models.ForeignKey(People, related_name='editor_set') last_edition = model.DateField() def make_crazy_books(book_ids): book_list = Book.objects.using("db1").filter(id__in=book_ids) #Query here, db1 people_list = ((b.author_id, b.editor_id) for b in book_list) people_ids = set(itertools.chain(*people_list)) people_ref = People.objects.using("db2").in_bulk(people_ids) #Query here, db2 #Would like to not have to send people_ref to each function book_list = deform.deform_edition(book_list, people_ref) book_list = deform.deform_author(book_list, people_ref) """ ... do some other deforming functions """ return book_list From mayapp/utils/deform.py: def deform_edition(book_list, people_ref): for book in book_list: author = people_ref[book.author_id] #Change to global lookup? b.last_edition = author.born return book_list def deform_author(book_list, people_ref): for book in book_list: editor = people_ref[book.editor_id] #Change to global lookup? b.author = editor return book_list I would try using Django's caching functionality, but with multiple threads running, the cached reference dictionary can be read/overwritten by other simultaneous requests. EDIT: Perhaps local-memory caching would work since it's thread safe? A: Generally, sharing data between a group of related functions is what OOP is for - define a class that contains the functions (as methods), then instantiate the class with the particular data. In this case though there is a class already associated with the data - it's a QuerySet of People objects. So you could define a custom QuerySet subclass for People that contains the deform methods - unfortunately in Django to get that to work you also need to define a custom Manager, overriding get_query_set to return your QuerySet subclass.
{ "language": "en", "url": "https://stackoverflow.com/questions/10520862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Procedure running slow in first attempt after migration SQLSERVER 2005 to 2012 Recently we have migrated SQLServer 2005 to 2012 and seen huge slowness in stored procedures execution.it's taking long time in first attempt but as on expected time in second attempt. I was under impression this may be due to caching but I have used "dbcc freeproccache" but When I'm executing all procedures again they are taking expected time, I don't have seen any performance issue on first attempt to nth times after executing "dbcc freeproccache". To improve the performance I already did following things which are not working for me. * *Rebuild the indexes. *Updated historic stats using 100% sampling data.
{ "language": "en", "url": "https://stackoverflow.com/questions/42221735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with bootstrap sub-menu hovering I am currently using a sub-menu implementation in twitter bootstrap. The lines of code are as follows - <ul class="dropdown-menu toggle-drop-down"> <li style="left: 100px; position: absolute; top: -18px;"> <img src="@{'/public/images/modal_arrow.png'}"> </li> <li> <a href="/editSystemNotification/${notification.id}">Edit</a> </li> <li class="dropdown-submenu"> <a class="sendSettings" href="/editSystemNotification/${notification.id}">Send</a> </li> </ul> Javascript code: - var subList = "<ul class=\"sublist-remove dropdown-menu\"><li><a tabindex='-1' href=\"#\"><i class=\"fa fa-mail-forward\"></i> Send Mail</a></li><li><a href=\"#\"><i class=\"fa fa-hand-o-up\"></i> Notify</a></li></ul>"; $(".sendSettings").hover(function(e) { console.log("hello world"); $('.sublist-remove').remove(); e.stopPropagation(); $(this).parent().append(subList); }); But when I am trying to hover on the submenu section, I can find the main dropdown element is being hovered on and hence its giving a flickering effect. And I am not able to click on the sub-menu. Please help with the issue as in where have I gone wrong? A: I suppose you are using Bootstrap 2? Submenus are removed in Bootstrap 3. An example of working submenus in Bootstrap 3 can be found at http://www.bootply.com/86684
{ "language": "en", "url": "https://stackoverflow.com/questions/20949957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Changing result from line 2 to line 1 I have a vb.net application that is made to acquire a result from a webpage to my alertbox. The webpage's result however is on the second line and is spaced. I can only see half the text which is inside the alertbox since it's on line 2. How do i change it so that the result goes to line 1? The webpage result is like this: 1 2 Success: 127.0.0.1 works However I want it to show up on my alertbox like this: 1 Success: 127.0.0.1 works I've fixed the spacing so far, but I can't fix the lines. Here's the code: Dim Website2 As New WebClient Dim WebsiteIW As String = Website2.DownloadString("http://webpage.com/" + FlatTextBox1.Text) If WebsiteIW.Length > 37 Then WebsiteIW = WebsiteIW.Substring(0, 37) While WebsiteIW.Contains(" ") WebsiteIW = WebsiteIW.Replace(" ", "") End While FlatAlertBox1.Text = WebsiteIW A: Instead of While WebsiteIW.Contains(" ") WebsiteIW = WebsiteIW.Replace(" ", "") End While Use WebsiteIW = WebsiteIW.trim It's a lot faster, and will get rid of an stray newline characters.
{ "language": "en", "url": "https://stackoverflow.com/questions/27347454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get x left ,x right ,y top, y bottom from pdf.js we are using pdf.js in order to drag drop image inside pdf and I want send coordinate to Aspose.PDF how i can get x left ,x right ,y top, y bottom instead of only (x,y) var pdfY = maxPDFy - param.posizioneY - offsetY; y = (pdfY * maxHTMLy) / maxPDFy; x = ((param.posizioneX * maxHTMLx) / maxPDFx) + paramContainerWidth; https://codepen.io/ValerioEmanuele/pen/pGRZqe
{ "language": "en", "url": "https://stackoverflow.com/questions/73933241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: imageStore() operation on dimensions beyond buffer size I have compute shader in which I have uimage2d buffer and imageStore() operations on that buffer. I want to know what would be behaviour if i write to locations beyond the size of buffer. Would be there some wrap effect ? Or behaviour depends on driver ? Or will it undefined and anything can happen? A: According to the specification, an access to a texel which doesn't exist has no effect. See OpenGL 4.6 API Core Profile Specification - 8.26. TEXTURE IMAGE LOADS AND STORES; page 193: If the individual texel identified for an image load, store, or atomic operation doesn’t exist, the access is treated as invalid. Invalid image loads will return zero. Invalid image stores will have no effect. Invalid image atomics will not update any texture bound to the image unit and will return zero. An access is considered invalid if: [...] * *the selected texel doesn’t exist
{ "language": "en", "url": "https://stackoverflow.com/questions/55092280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Loop the included array currently im building a filter and in this filter there is an array with dynamic values. Im just one step away from finishing it but i dont get the right loop done. I already tried it with something like forEach but all the ways i tried it didnt work. Here is the code: map(p => (!this.personTypeFilter) ? p:p.filter(((i:any) => this.getPersonTypesBezeichnung(i.personentyp)?.toLowerCase().includes(this.personTypeFilter.forEach((x:any) => { return console.log(this.personTypeFilter[x]))))) This way makes my code to explode So the filter need to include all values step by step with a for loop or something like that //EDIT The goal of this situation is to filter a whole array for Example you have multiple checkboxes which will be pushed to an list after clicking the single checkboxes. Now i want to filter every single value of this list, so i thought about looping it with forEach. The correction solution instead was map. A: Instead of a complex for loop or forEach you can just use a simple map. Just handle it similiar to a for loop, the map will go for all your elements in your array like below. map(p => (!this.personTypeFilter.map((x:any) => x)) ? p:p.filter(((i:any) => this.getPersonTypesBezeichnung(i.personentyp).includes(this.personTypeFilter.map((x:any) => x).join(', '))))),
{ "language": "en", "url": "https://stackoverflow.com/questions/69310571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Does hapijs have something like overload protection? What will a hapi server do if it is overloaded and is there something like toobusy-js to prevent a fallout of the server by shortcutting some requests with errors. A: Yes it's embedded in the framework, look at load on connections settings. You have 3 options : * *maxHeapUsedBytes - maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). *maxRssBytes - maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). *maxEventLoopDelay - maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). ` And you must not forget to set a sample interval (time between 2 checks) on server.load config: * *sampleInterval - the frequency of sampling in milliseconds. Defaults to 0 (no sampling). Example : server configuration : { "load": { "sampleInterval": 1000 } } connection configuration : { "load": { "maxHeapUsedBytes": 1073741824, "maxRssBytes": 1610612736, "maxEventLoopDelay": 5000 } }
{ "language": "en", "url": "https://stackoverflow.com/questions/31817534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I remove or alter spaces between images in an inline heading in CSS? Here is my code. I haven't finished formatting anything under the heading yet. But I'm trying to get the h2(the one with images) centered and without spaces. I've tried messing with font spaces in parent and removing padding but nothing seems to be working. I only want to do this in CSS. Code: body { background-color: blue; } div { background-color: white; padding: 25px; } h1 { text-align: center; } h2 img { display: inline; height: 100px; margin-left: 100px; } <body> <div> <h1> Float, Float, Float! </h1> <div class="nospace"> <h2> <img src="dragon_float.jpg"> <img src="rootbeer_float.jpg"> <img src="dog_tubing.jpg"> <img src="money.jpg"> </h2> </div> </div> </body> A: It seems like a minor tweak will get what you want. First, there's space between the images because you put spaces between the images. Any whitespace between the HTML elements will be rendered as a space, so remove the line breaks: <img src="dragon_float.jpg"><img src="rootbeer_float.jpg"><img src="dog_tubing.jpg"><img src="money.jpg"> Second, add h2 to the style that centers, and remove the left margin on h2: h1, h2 { text-align: center; } h2 img { display: inline; height: 100px; //margin-left:100px; } That's all that's needed. A: Maybe use: h2 img { display: inline-block; float: left; height: 100px; margin-left:100px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/39780865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make Dialog in landscape or portrait orintation Hy, i have got some trooubles in my dialog. If i want to use it on portrait orientation it behaves ok, but if its in landscape orinetation o can use only 4 seekbars. A: Wrap your entire layout in a <ScrollView>, it just gets truncated because the screen isn't 'high' enough. If you layout would be bigger in height, the first screen would be cut off too.
{ "language": "en", "url": "https://stackoverflow.com/questions/18752089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: N * N matrix by Java This is what I written: import javax.swing.JOptionPane; public class JavaTest{ public static void main(String[] args){ String numberString = JOptionPane.showInputDialog(null, "Enter number here: ", null, JOptionPane.INFORMATION_MESSAGE); int number = Integer.parseInt(numberString); printMatrix(number); } public static void printMatrix(int n){ int[][] myList = new int[n][n]; String output = ""; for (int row = 1; row <= n; row++){ for (int col = 1; col <= n; col++){ myList[row][col] = (int) (Math.random() * 2); } } for (int row = 1; row <= n; row++){ for (int col = 1; col <= n; col++){ if (col == n){ output += "\n" + myList[row][col]; } else{ output += myList[row][col] + " "; } } } if (n < 0){ JOptionPane.showMessageDialog(null, "Invalid input!"); } else{ JOptionPane.showMessageDialog(null, output); } } } I run it and enter 3 in a dialog box, and the eclipse IDE shows that Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at JavaTest.printMatrix(JavaTest.java:17) at JavaTest.main(JavaTest.java:8) I guess at line 17 and 8 the program goes wrong but I don't know how to improve it. What can I do to improve my code? Thanks! A: You're looping from 1 to n: for (int row = 1; row <= n; row++){ for (int col = 1; col <= n; col++){ Indexes begin at 0, not at 1. The loops should be from 0 to n-1: for (int row = 0; row < n; row++){ for (int col = 0; col < n; col++){ (This same error may likely be in other places than just the first line that threw the exception.)
{ "language": "en", "url": "https://stackoverflow.com/questions/29068538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: win32 main loop interval issue C++ I'm making a keylogger that logs key strokes (duh..). Now when I've implemented the basic keylogger in C++, I wanted to add a new feature to the application: I want it to mail the logs to my email. So far so good, I found this open source email client that fits perfect for my needs. The only problem I have is to make the application send the logs in intervals of x minutes. int main(int argc, char *argv[]) { //stealth(); hHook = SetWindowsHookEx(WH_KEYBOARD_LL, MyLowLevelKeyBoardProc, NULL, 0); if(hHook == NULL) { cout << "Hook failed" << endl; } MSG message; while(GetMessage(&message, NULL, 0, 0)) { TranslateMessage(&message); DispatchMessage(&message); } return 0; } Somehow I need to implement somekind of counter which will at some point use a function send();. Anyone got any idea how to modify the MSG loop to execute the funktion send(); each and every 5 minutes? A: Take a look at the SetTimer function, I think it does exactly what you need. Before event loop you should call this function with desired interval and you have to pass to it a callback function. Alternatively you can use another function CreateTimerQueueTimer VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) { } UINT timer = SetTimer(NULL, 0, 500, &TimerProc); MSG message; while(GetMessage(&message, NULL, 0, 0)) { TranslateMessage(&message); DispatchMessage(&message); } KillTimer(NULL, timerId); A: Make a new thread to sleep x milis and then send in a while(!interrupted) loop. As you may know, accessing the same data for read and write from 2 separate threads simultaneously will cause an error. http://msdn.microsoft.com/en-us/library/kdzttdcb(v=vs.80).aspx To avoid that you can use critical section http://msdn.microsoft.com/en-us/library/windows/desktop/ms686908(v=vs.85).aspx Or just make your thread to sleep and turn a boolean value to true meaning 'yes we waited enough' and your main function always send data when that boolean is true then set it back to false. edit: I believe this is the simplier way to archieve this while(!interrupted) { // Your thread will do this. sleep(60000); maysend = true; } [...] if(maysend) { // Your main function will contain this send(); maysend = false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/16480834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can my appengine app send mail using the senderid of domain that installed the app Say I have an appengine app called foo at foo.appspot.com and my email i.e. adminfoo(at)gmail.com is it's adminstrator. Now, I want to sell this service to blah.com. blah.com has a google app account and 'adds' the foo application and sets the url http://foo.blah.com to point to it. Now, using the new namespace manager, I carve out separate data for blah.com but when blah.com wants to send out email currently the only way it is possible is either * *sender is admin i.e. adminfoo (at) gmail.com *or foo.appspot.com has to add someone(@)blah.com as a developer Is there any other way? What happens if one has 1,000's of customers ? Also, the docs state that the email sender can be 'the currently logged in user'. So, if someone(at)blah.com were to 'login' using the google login and 'stay logged in to the app' than can the app send email on behalf of someone(at)blah.com with someone(at)blah.com being the sender? A: The other way is that your app can send email as anything@appid.appspotmail.com, where 'appid' is its App ID. As you say, you can also send email as the logged in user - but only on requests made by that user - so sending mail as them from the Task Queue is out. A: You might want to look into an 3rd party E-Mail provider. We use http://postmarkapp.com/ for our AppEngine projets (via huTools.postmark) and we love it.
{ "language": "en", "url": "https://stackoverflow.com/questions/4066542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: A script to update linked sheet from google doc I have linked part of a sheet in google doc (as linked object). Now, whenever I change the sheet data, I can click a button in google doc and the data is reflected in the google doc linked sheet too (this is all built in google doc stuff). What I want to do is the other side of this. I am able to see a bunch of data in one place (google doc) based on the sheets I have linked. I would like to update the data in the google doc, and "upload" it to the linked google sheets. I am trying to write a script to do that. But cannot seem to find any method to access linked sheets. I found this slides API page that can does the sheet -> slide syncing. I am looking at the document API page, but I scanning through add... and get... methods, I don't see to find any way to get linked objects. Is it represented as NamedRange? If so, how do I access it? There was another similar question, but without any satisfactory answer. If you can share some pointers to get started, I would appreciate it. Edit: Here is an example doc (and a spreadsheet contained their in) to explain the situation clearer. Test document for updating spreadsheet - Google Docs A: You can find the Table elements in your Document via findElement(elementType). If that's the only Table in your Document, as in the sample you shared, this is immediate. Once you retrieve the Table, you can loop through its rows and cells and come up with a 2D array with the values from the table: function getTableValues() { const doc = DocumentApp.getActiveDocument(); const body = doc.getBody(); const table = body.findElement(DocumentApp.ElementType.TABLE).getElement(); let tableValues = [[]]; for (let i = 0; i < table.getNumRows(); i++) { const tableRow = table.getRow(i); for (let j = 0; j < tableRow.getNumCells(); j++) { const tableCell = tableRow.getCell(j); const text = tableCell.getText(); tableValues[i].push(text); } if (i == table.getNumRows() - 1) break; tableValues.push([]); } return tableValues; } Once you've done that, you just need to copy it to your spreadsheet via setValues(values): function copyToSheet(tableValues, spreadsheetId) { const sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName("Sheet1"); sheet.getRange(1, 1, tableValues.length, tableValues[0].length).setValues(tableValues); } Calling both of these in the same function, you would get this: function main() { const tableValues = getTableValues(); const spreadsheetId = "{your-spreadsheet-id}"; copyToSheet(tableValues, spreadsheetId); } Note: * *getActiveDocument() is used to retrieve the Document, so this assumes the script is bound to your Document. If that's not the case, use openById(id) or openByUrl(url) instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/63726480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AWS Database not connecting with Jenkins I am running a python program called MyCode.py that uses pymysql to connect to a AWS database and pull from it. When I run it in Jenkins using in the shell, the python packages are successfully installed however the pymysql connection fails to connect and times out after MyCode.py is called. When I run MyCode.py through my Mac OSx terminal, it runs perfectly and can successfully pull from the database. Any idea if the code I use to call my python script disrupts pymysql from connecting? Jenkins shell script: ls -la virtualenv FullTests . FullTests/bin/activate pip install pandas pip install pymysql pip install logger pip install requests ls -la python FullTests.py deactivate MyCode.py (Snippet) conn = pymysql.connect(host='production-cluster.cluster123-east-1.rds.amazonaws.com', port=3306, user='reader', passwd='somepassword, db='metrics', connect_timeout=10) cur = conn.cursor() cur.callproc('metrics.GetReaderData') result = cur.fetchall() return result
{ "language": "en", "url": "https://stackoverflow.com/questions/44961187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby and Swig: TypeError: can't convert nil into String As a follow up of the question: Ruby with Swig: NameError: uninitialized constant I'm trying to use Qxt library (namely QxtGlobalShortcut) in the ruby. As suggested on: How can I call C++ functions from within ruby I created swig wrapper, however when trying to use generated library I'm stuck with error: irb(main):005:0> shortcut = QxtGlobalShortcut::QxtGlobalShortcut.new ui TypeError: can't convert nil into String from (irb):5:in `initialize' from (irb):5:in `new' from (irb):5 from /usr/bin/irb:12:in `<main>' My full irb session output: $ irb irb(main):001:0> require 'Qt4' => true irb(main):002:0> require 'QxtGlobalShortcut' => true irb(main):003:0> app = Qt::Application.new ARGV => #<Qt::Application:0x00000002e02598 objectName="irb"> irb(main):004:0> ui = Qt::Widget.new => #<Qt::Widget:0x00000002f9e2a8 objectName="", x=0, y=0, width=640, height=480> irb(main):005:0> shortcut = QxtGlobalShortcut::QxtGlobalShortcut.new ui TypeError: can't convert nil into String from (irb):5:in `initialize' from (irb):5:in `new' from (irb):5 from /usr/bin/irb:12:in `<main>' I used following to generate the wrapper in swig: As qxtglobalshortcut.h contents were not parsable by Swig, I created the simplified version (containg all the API that I need to use) with the contents: #ifndef QXTGLOBALSHORTCUT_H #define QXTGLOBALSHORTCUT_H #include "qxtglobal.h" #include <QObject> #include <QKeySequence> class QxtGlobalShortcut : public QObject { public: explicit QxtGlobalShortcut(QObject* parent); explicit QxtGlobalShortcut(const QKeySequence& shortcut, QObject* parent = 0); virtual ~QxtGlobalShortcut(); QKeySequence shortcut() const; bool setShortcut(const QKeySequence& shortcut); bool isEnabled() const; }; #endif // QXTGLOBALSHORTCUT_H The rest is pretty much standard: $ cat QxtGlobalShortcut.i %module QxtGlobalShortcut %{ /* Includes the header in the wrapper code */ #include "/usr/include/QxtGui/QxtGlobalShortcut" %} /* Parse the header file to generate wrappers */ %include "qxtglobalshortcut.h" $ cat extconf.sh require 'mkmf' dir_config('QxtCore') dir_config('QxtGui') dir_config('QtCore') dir_config('QtGui') create_makefile('QxtGlobalShortcut') $ cat wrapper.sh swig -c++ -ruby QxtGlobalShortcut.i ruby extconf.rb --with-QxtCore-include=/usr/include/QxtCore/ --with-QxtGui-include=/usr/include/QxtGui/ --with-QtCore-include=/usr/include/QtCore/ --with-QtGui-include=/usr/include/QtGui/ make sudo make install For the swig generated output, see: QxtGlobalShortcut_wrap.cxx. Any idea how to fix it? Thanks. UPDATE: Providing the irb output based on @PascalHurni extended logging diff: $ irb irb(main):001:0> require 'Qt4' => true irb(main):002:0> require 'QxtGlobalShortcut' => true irb(main):003:0> app = Qt::Application.new ARGV => #<Qt::Application:0x00000001d79d98 objectName="irb"> irb(main):004:0> ui = Qt::Widget.new => #<Qt::Widget:0x00000001f16818 objectName="", x=0, y=0, width=640, height=480> irb(main):005:0> shortcut = QxtGlobalShortcut::QxtGlobalShortcut.new ui _wrap_new_QxtGlobalShortcut ENTERING with 0 arguments TypeError: can't convert nil into String from (irb):5:in `initialize' from (irb):5:in `new' from (irb):5 from /usr/bin/irb:12:in `<main>' Moreover, I see there seems to be problem with argc, therefor posting make output (not sure if that helps): creating Makefile g++ -I. -I/usr/include/x86_64-linux -I/usr/include/ruby/backward -I/usr/include -I. -I/usr/include/QtGui/ -I/usr/include/QtCore/ -I/usr/include/QxtGui/ -I/usr/include/QxtCore/ -fPIC -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -mtune=generic -fPIC -m64 -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -mtune=generic -o QxtGlobalShortcut_wrap.o -c QxtGlobalShortcut_wrap.cxx QxtGlobalShortcut_wrap.cxx: In function ‘void SWIG_Ruby_define_class(swig_type_info*)’: QxtGlobalShortcut_wrap.cxx:1517:9: warning: variable ‘klass’ set but not used [-Wunused-but-set-variable] QxtGlobalShortcut_wrap.cxx: In function ‘void SWIG_InitializeModule(void*)’: QxtGlobalShortcut_wrap.cxx:2206:21: warning: statement has no effect [-Wunused-value] QxtGlobalShortcut_wrap.cxx: In function ‘VALUE _wrap_new_QxtGlobalShortcut(int, VALUE*, VALUE)’: QxtGlobalShortcut_wrap.cxx:1973:75: warning: ‘argc’ is used uninitialized in this function [-Wuninitialized] rm -f QxtGlobalShortcut.so g++ -shared -o QxtGlobalShortcut.so QxtGlobalShortcut_wrap.o -L. -L/usr/lib64 -L. -Wl,-z,relro -rdynamic -Wl,-export-dynamic -m64 -lruby -lpthread -lrt -ldl -lcrypt -lm -lc /usr/bin/mkdir -p /usr/local/lib64/ruby/site_ruby /usr/bin/install -c -m 0755 QxtGlobalShortcut.so /usr/local/lib64/ruby/site_ruby Any ideas? UPDATE 2: Providing the irb output based on @PascalHurni extended logging diff (version 2): $ irb irb(main):001:0> require 'Qt4' => true irb(main):002:0> require 'QxtGlobalShortcut' => true irb(main):003:0> app = Qt::Application.new ARGV => #<Qt::Application:0x000000017b4e30 objectName="irb"> irb(main):004:0> ui = Qt::Widget.new => #<Qt::Widget:0x00000001952940 objectName="", x=0, y=0, width=640, height=480> irb(main):005:0> shortcut = QxtGlobalShortcut::QxtGlobalShortcut.new ui _wrap_new_QxtGlobalShortcut ENTERING with 1 arguments _wrap_new_QxtGlobalShortcut before ptr convert for _wrap_new_QxtGlobalShortcut__SWIG_0 TYPE=12 TypeError: can't convert nil into String from (irb):5:in `initialize' from (irb):5:in `new' from (irb):5 from /usr/bin/irb:12:in `<main>' A: This one is more tricky. I don't see any reference to a string, so the TypeError is really weird. Nonetheless, you may patch the generated .cxx file with this gist https://gist.github.com/phurni/5081001 . As you see it simply adds a bunch of printf() to trace the call to #initialize. You may follow this pattern to track it down, maybe editing your question with some more info, or the updated irb session (showing the trace). UPDATE To make it short, it seems that the Qxt lib you generate and the Qt ruby lib you use are not generated by the same version of SWIG. This wouldn't be a problem for separated libs, but because your Qxt lib will interop with the Qt lib (you pass the ui argument which is a Qt wrapped object to your own Qxt wrapped object), both MUST be wrapped by the same version (at least the minor?) of SWIG. Back to technical detail: The exception raised comes from the call of SWIG_ConvertPtron line 1984 which in turn calls SWIG_Ruby_MangleStr. This function tries to get an instance variable @__swigtype__ on the passed argument which is ui in your code. This is to be able to type check (on the C++ side) the passed argument. It seems that this variable is nil (because it comes from Qt wrapped differently without using such a variable), and the code in SWIG_Ruby_MangleStr WANTS to convert it to a String. Conclusion: I don't know a way to determine which version of SWIG wrapped an existing lib, if you find one, you may get the one that wrapped the Qt lib and use that version to wrap your Qxt lib. The other way is to generate the Qt libs with a known version of SWIG and do the same for your Qxt lib.
{ "language": "en", "url": "https://stackoverflow.com/questions/15197131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Inkscape's export to PDF can't create PDF file I'm running the following line of PHP code to have Inkscape create a PDF from an SVG. $command = 'inkscape -z -f ' . $temp_destination . ' -A ' . $temp_pdf . ' -T'; exec($command, $output, $return_var); When this is run though no PDF file is created. So then I try and run the same command in Terminal under the user that PHP runs under (_www I'm using MAMP PRO) sudo -u _www inkscape -z -f /path/to/tmp.svg -A /path/to/tmp.pdf -T ...and I get a lot of these errors below, even though the PDF is created now. error retrieving current directory: getcwd: cannot access parent directories: Permission denied How can I get this command be able to create the PDF file?
{ "language": "en", "url": "https://stackoverflow.com/questions/22361638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to move cursor and click item using firefox addon script like imacros I do believe there is no way to use simple javascript to move mouse and click item/url. I have searched a lot about this, and most answer I found, it's not possible for security reason. But How about using firefox addon script? I do believe it's possible, because imacros does that, even better they can record and replay it. But I can find how they do that, Can anybody give me some clue how to move mouse cursor using addon script? Thanks for all your help. A: The best way to do that that doesn't involve the headache of making sure that everything is positioned exactly correctly is using Selenium IDE. Selenium provides a very robust browser automation toolkit, and the IDE version is fairly easy to use although it may require some tweaking. You can download the Firefox plugin here, under Selenium IDE.
{ "language": "en", "url": "https://stackoverflow.com/questions/15322390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My contents are left aligned in IE 7? I have a outer div which is working correctly in chrome, firefox but not in IE.. I have some contents inside outer div.. to make it center aligned or middle of page i gave this width:970px; height:630px; to outer div... so that i got the contents at the center in chrome and Mozilla... but in the case of IE 7.. in IE its left aligned.. here is my css.... <style type="text/css"> body, html { font-family:helvetica,arial,sans-serif; font-size:90%; } div.outer { display: block; margin-left: auto; margin-right: auto; width:970px; height:630px; position:relative; } </style> here is my full code: <head><title>home</title> </head><body class='claro'><div class='outer' style="border:1px solid black;"> <div id="dottedBorderhome"> </div> <div id="dragIconhome"> </div> <div class="claro" id="menuDiv2" onclick="setWidgetproperty(this.id,'x','navMenu2');" onmousedown="setMenuBarProperty('navMenu2');" onmouseup="setDocStyle(this.id)" style="border: 1px dotted white; left: auto; position: absolute; top: 17px;"> <!-- here one menu bar will come --> </div> <div class="claro" id="divlabel43" onclick="setWidgetproperty(this.id,null,'divlabel43')" onmouseup="setDocStyle(this.id)" style="left: 50px; position: absolute; top: 92px; text-align: right; font-family: Times; font-size: 15pt; font-weight: bold;" > <label id="label43" onclick="setLblProperty(this.id)" onmouseover="editName('divlabel43',this.id,'label')"> Worklist Manager </label> </div> <div class="claro" id="htmlTableDiv9" onmouseup="setDocStyle(this.id)" style="left: auto; position: absolute; top: 130px; height:70px; width:150px;"> <!-- here its contains table --> </div> <div class="claro" id="divImage2" onclick="setWidgetproperty(this.id,'xy','image2')" onmouseup="setDocStyle(this.id)" style="left: auto; position: absolute; top: 70px;"> <img class="images" id="image2" name="Search-icon2.png" onclick="setImgProperty(this.id)" src="images/uploads/Search-icon2.png" style="height: 50px; width: 58px;"> </div> <div class="claro" id="menuDiv1" onclick="setWidgetproperty(this.id,'x','navMenu1');" onmousedown="setMenuBarProperty('navMenu1');" onmouseup="setDocStyle(this.id)" style="border:1px dotted white; left: auto; position: absolute; top: 640px;"> <!-- here another menu bar --> </div> <div id="CWPWORKLIST__1" onclick="setWidgetproperty(this.id,'xy','inner__CWPWORKLIST__1')" ondblclick="editDataGridResponseMapping(this.id)" onmouseup="setDocStyle(this.id)" style="left:auto; position:absolute; top:340px; height: 296px; width: 921px;"> <!-- here another table--> </div> </div></body> A: As Sven suggested, https://stackoverflow.com/questions/4742877/center-align-div-in-internet-explorer likely holds your answer. Either you've got non-valid HTML that is putting IE7 in quirks mode, or you're missing the doctype. A: Try this <style type="text/css"> body, html { font-family:helvetica,arial,sans-serif; font-size:90%; } div.outer { display: block; margin:0 auto; width:970px; height:630px; position:relative; } </style> A: Use code with proper doc type. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
{ "language": "en", "url": "https://stackoverflow.com/questions/13986792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Links from static html in Grails My app renders html, created by external program and placed in a folder outside the app (so that it wouldn't disappear after redeployment), and this html contains links to other files in that folder. I can change the links, but how to get them work? This is how the html is rendered now: def url = createLink(controller: 'job', action: 'renderResults', params: [resultsPath:resultsPath]) render(contentType: 'text/html', text: "<script>window.location.href='$url'</script>") .. def renderResults (String resultsPath){ def htmlContent = new File(resultsPath).text render (text: htmlContent, contentType:"text/html", encoding:"UTF-8") } This one does not work (suppose renderImage is ok) <a href="${createLink(controller : 'job', action:'renderImage', params: [imagePath:'C:/Users/../image.jpg'])}">Link</a> even if I try to render html in a gsp view: def url = createLink(controller: 'job', action: 'renderResults', params:[resultsPath:resultsPath]) render(view:"index/results", text: "<script>window.location.href='$url'</script>") with only {$text} in results.gsp. All this may seem crazy, so please don't hesitate to tell me about that - I'm just a newbie. UPD: My question is somewhat vague, so I'll try sum it up: is there any way to create a link from an html to some resource located outside the app? Dynamic grails links do not work in html - I guess, because it is not a view. And simple static links (like "/home/images/test.img", "../../images/test.img") inevitably lead somewhere into app folder.
{ "language": "en", "url": "https://stackoverflow.com/questions/26531267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PCL: Why so much dynamic allocation and raw pointers I've been working with PCL lately, in conjunction with ROS, and have been looking through some of their examples. I am by no means an expert at c++, but I was under the impression that good style avoids raw pointers/dynamic allocation as much as possible. In addition, that shared pointers are on a as necessary protocol since they necessitate a reference manager. I feel like the PCL tutorials are filled to the brim with these kinds of things, dynamic allocation and shared pointers, examples: link1 link2 link3. I'm just curious if/why this is necessary, if only to understand the c++ better.
{ "language": "en", "url": "https://stackoverflow.com/questions/69376403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to do a Inner-Join in JPA Criteria? I'm using Netbeans to program a webservice REST that returns a JSON response, I am also using JPA Criteria to create the querys. I have two Entities that looks like this: public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "id_user") private Integer idUser; @Size(max = 45) @Column(name = "username") private String username; @Size(max = 45) @Column(name = "password") private String password; @Size(max = 45) @Column(name = "email") private String email; @OneToMany(mappedBy = "idUser") private Collection<Comment> commentCollection; public class Comment implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "id_comment") private Integer idComment; @Column(name = "id_thesis") private Integer idThesis; @Size(max = 250) @Column(name = "comment") private String comment; @Column(name = "cdate") @Temporal(TemporalType.DATE) private Date cdate; @JoinColumn(name = "id_user", referencedColumnName = "id_user") @ManyToOne private User idUser; } Both entities with sets and gets. I want to do a query like this: SELECT * FROM Comments c INNER JOIN User u WHERE c.id_user = u.id_user; but in the JPA Criteria language, I've had many problems trying to make it work but i don't get it yet. This is the code that I'm using for the join AbstractFacade.java public Join<User, Comment> getCommentInfo() { CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); CriteriaQuery q = cb.createQuery(); Root<User> r = q.from(User.class); Join<User, Comment> j = r.join("commentCollection", JoinType.INNER); Query query = getEntityManager().createQuery(q); return (Join<User, Comment>) query.getResultList(); } UserFacadeREST.java @GET @Path("test") @Produces({"application/json"}) public Join<User, Comment> getCommentInfoREST() { return getCommentInfo(); } This error is shown when I test the method: java.util.Vector cannot be cast to javax.persistence.criteria.Join Please help me with that, I do not know if the sentence join is wrong or how to solve the cast properly. Edit: I add the next lines to the getCommentInfo() method to see the content of the list. q.select(j.get("username")); List results = query.getResultList(); Iterator iter = results.iterator(); while (iter.hasNext()){ System.out.println(iter.next()); } Error: The attribute [username] is not present in the managed type [EntityTypeImpl@1000979996:Comment. A: In the case of getResultList(), the javadocs state that it returns an java.util.List (see here: http://docs.oracle.com/javaee/5/api/javax/persistence/Query.html#getResultList%28%29 ), that Vector implements. The result type, aka what's in the list, depends on the criteria projection or, in a JPQL Query, of the from statement. In your case, because you don't do projection, I think it should return a List<User>. For your information, and if you are using JPA 2.0, you can also use TypedQuery which could avoid that (ugly !) cast : http://www.javabeat.net/typedquery-jpa-2/
{ "language": "en", "url": "https://stackoverflow.com/questions/25089809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recursive backtracker mazegenerator is not very recursive i am making a Recursive backtracker mazegenerator in Java. but it keep going ArrayIndexOutOfBoundsException, and is not very recursive please if someone would look at my code and tell me what i am doing wrong. thanks in advance. public class RecursiveBacktrackerMazeGenerator { boolean[][] labMap = new boolean[16][24]; char [][] mazeMap = new char [16][24]; Random random = new Random(); int minRandomInt1 = random.nextInt(23); int minRandomInt2 = random.nextInt(15); int height; int width; public RecursiveBacktrackerMazeGenerator() { for (int i = 0; i <= 15; i++) { Arrays.fill(labMap[i],true); } width = minRandomInt1; height = minRandomInt2; Maze(); for (int i = 0; i < 16; i++) { for (int j = 0; j < 24; j++) { if (labMap[i][j] == false){ mazeMap[i][j] = ' '; } else if (labMap[i][j] == true){ mazeMap[i][j] = 'X'; } System.out.print(mazeMap[i][j]); } System.out.println(); } } private void Maze() { labMap[height][width] = true; try { while ((height>=2&& height<=13 && width>=2 && width<=21) && (labMap[height - 1][width] == true && labMap[height - 2][width] == true) || (labMap[height + 1][width] == true && labMap[height + 2][width] == true) || (labMap[height][width - 1] == true && labMap[height][width - 2] == true) || (labMap[height][width + 1] == true && labMap[height][width + 2] == true)) { int minRandomInt = random.nextInt(37); //width = minRandomInt1; //height = minRandomInt2; if (minRandomInt >= 0 && minRandomInt <= 9) { if (height>=2) if (labMap[height - 1][width] == true && labMap[height - 2][width] == true){ if (width != 23 && width != 0) { labMap[height - 1][width] = false; labMap[height - 2][width] = false; height = height - 2; } } } else if (minRandomInt > 9 && minRandomInt <= 19) { if (height <= 13) { if (labMap[height + 1][width] == true && labMap[height + 2][width] == true) { if (width != 23 && width != 0) { labMap[height + 1][width] = false; labMap[height + 2][width] = false; height = height + 2; } } } } else if (minRandomInt > 19 && minRandomInt <= 28) { if (width <= 21 ) { if (labMap[height][width + 1] == true && labMap[height][width + 2] == true) { if (height != 0 && height != 15) { labMap[height][width + 1] = false; labMap[height][width + 2] = false; width = width + 2; } } } } else if (minRandomInt > 28 && minRandomInt <= 37) { if (width >= 2) { if (labMap[height][width - 1] == true && labMap[height][width - 2] == true) { if (height != 0 && height != 15) { labMap[height][width - 1] = false; labMap[height][width - 2] = false; width = width - 2; } } } } } if (height <= 14) { if (labMap[height + 1][width] == false) { height++; Maze(); } } else if (height >=1){ if(labMap[height -1][width] == false) { height--; Maze(); } } else if (width>=1){ if (labMap[height][width-1] == false) { width--; Maze(); } } else if (width <= 22) { if (labMap[height][width + 1] == false) { width++; Maze(); } } } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e); System.out.println("width = "+ width); System.out.println("height = " + height); } } } A: Your while loop's parentheses are kind of messed up, I changed it to this and it works, and is more readable: while ( ((height>=2) && (height<=13) && (width>=2) && (width<=21)) && ( (labMap[height - 1][width] && labMap[height - 2][width] ) || (labMap[height + 1][width] && labMap[height + 2][width] ) || (labMap[height][width - 1] && labMap[height][width - 2] ) || (labMap[height][width + 1] && labMap[height][width + 2] ))) {
{ "language": "en", "url": "https://stackoverflow.com/questions/36041286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: spectral structure of sinusoidal model let us consider following code function [ x ] = generate1(N,m,A3) f1 = 100; f2 = 200; T = 1./f1; t = (0:(N*T/m):(N*T))'; %' wn = randn(length(t),1); %zero mean variance 1 x = 20.*sin(2.*pi.*f1.*t) + 30.*cos(2.*pi.*f2.*t) + A3.*wn; %[pks,locs] = findpeaks(x); %plot(x); end as i know peaks in Fourier domain represent at this frequency,which are present in signal,for example let us take plot of Fourier transform of this signal let us run this signal y=generate1(3,500,1); and plot plot(abs(fft(y))) but clearly it does not shows me peaks at frequency given in signal,what is problem?please help me,generally it is stationary signal,that why this graph should show me exact picture but it does not do,why? EDITED : y1=generate1(3,500,0); A: function [ x, fs ] = generate1(N,m,A3) f1 = 100; f2 = 200; T = 1./f1; t = (0:(N*T/m):(N*T))'; %' wn = randn(length(t),1); %zero mean variance 1 x = 20.*sin(2.*pi.*f1.*t) + 30.*cos(2.*pi.*f2.*t) + A3.*wn; %[pks,locs] = findpeaks(x); %plot(x); fs = 1/(t(2)-t(1)); end and see absfft = abs(fft(y)); plot(fs/2*linspace(0,1,length(absfft)/2+1),2*absfft(1:end/2+1)) or plot(linspace(-fs/2,fs/2,length(absfft)),fftshift(absfft)) the x-axis in your plot is from 0 to fs/2 and then from -fs/2 to 0
{ "language": "en", "url": "https://stackoverflow.com/questions/20918899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculating Holidays in Javascript As a learning exercise I took the question here: calculate holidays in Javascript, and with a suggested approach, took it upon myself to develop a solution with ES6 array methods. The previous stack post that is linked above suggested an object approach, but the answer did not include any code. I decided to use an array approach, and offer a complete coding example. The older post with 8K views, did not offer an array approach, and the OP already had an answer so I created a new question and self-answered. I'm still learning, so I invite the pro's to improve upon this! I ran some performance tests and the if/then approach is faster, but this code works. Also as you can see I was not able to chain the .findIndex(), but that just results in another variable and another line of code. One note of caution, some ES6 array methods are not supported in older browsers. Anyway, I hope this helps. A: function check_holiday4(ds) { const [m, d, y] = ds.split('/'); const h = [ // keys are formatted as month,week,day ["0,1", "New Year's Day"], ["0,3,1", "Martin Luther King, Jr. Day"], ["0,20", (function() { if (((y - 1937) % 4) == 0) return 'Inauguration Day' })()], ["1,14", "Valentine's Day"], ["1,3,1", "President's Day"], ["2,2,0", "Daylight Savings Time Begins"], ["3,3,3", "Administrative Professionals Day"], ["4,2,0", "Mother's Day"], ["4,5,1", "Memorial Day"], ["5,14", "Flag Day"], ["5,3,0", "Father's Day"], ["5,3,6", "Armed Forces Day"], ["6,4", "Independence Day"], ["6,4,0", "Parents Day"], ["8,1,1", "Labor Day"], ["9,2,1", "Columbus Day"], ["9,31", "Halloween"], ["10,11", "Veterans Day"], ["10,1,0", "Daylight Savings Time Ends"], ["10,1,2", "Election Day"], ["10,4,4", "Thanksgiving Day"], ["11,25", "Christmas Day"] ]; const f = (a, n, d) => (d + 6 - new Date(...a, 7).getDay()) % 7 + n * 7 - 6; const dim = (y, m) => new Date(y, m + 1, 0).getDate(); const hc = (y, m) => h.filter(v => v[0].startsWith(m)).map((val, i) => { const [vm, vn, vdw] = val[0].split(','); let cd = f([y, vm], vn, +vdw); cd = (cd > dim(y, vm)) ? cd - 7 : (val[0].split(',').length === 2) ? vn : cd; val[0] = (+vm + 1) + "/" + cd + "/" + y; return [val[0], val[1]]; }); const ha = hc(y, m - 1); return ha[ha.findIndex(sa => sa[0] === ds)][1]; } console.log(check_holiday4(new Date("10/31/2019").toLocaleDateString())); // "Halloween" console.log(check_holiday4(new Date("5/31/2021").toLocaleDateString())); // "Memorial Day"
{ "language": "en", "url": "https://stackoverflow.com/questions/58511847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How make a Comparator for alphabetics chars with an differrent order that the alphabetic order My problem is that I want to compare some character not using the alphabetic sort. Here is my order relation : A < B < T < Q < C < D < E < F ... How can I create a Comparator for this? Must I write all the cases like this: if (char1.equals(char2)) { return 0; } else if (char1.equals("A")) { return -1; } else if (char1.equals("B") && char2.equals("A")) { return 1; } else if (char1.equals("T") && (char2.equals("B") || char2.equals("A"))) { return 1; } else if (char1.equals("Q") && (char2.equals("T") || char2.equals("B") || char2 .equals("A"))) { return 1; } else if (char1.equals("C") && (char2.equals("Q") || char2.equals("T") || char2.equals("B") || char2.equals("A"))) { return 1; } else if (char1.equals("D") && (char2.equals("C") || char2.equals("Q") || char2.equals("T") || char2.equals("B") || char2 .equals("A"))) { return 1; } else if (char1.equals("E") && (char2.equals("D") || char2.equals("C") || char2.equals("Q") || char2.equals("T") || char2.equals("B") || char2.equals("A"))) { return 1; } else if (char1.equals("F") && (char2.equals("E") || char2.equals("D") || char2.equals("C") || char2.equals("Q") || char2.equals("T") || char2.equals("B") || char2 .equals("A"))) { return 1; } A: If you want to compare Strings using your custom character ordering, create a RuleBasedCollator, e.g. String myRules = "< a, A < b, B < t, T < q, Q < c, C < d, D < e, E < f, F < g, G" + "< h, H < i, I < j, J < k, K < l, L < m, M < n, N < o, O < p, P" + "< r, R < s, S < u, U < v, V < w, W < x, X < y, Y < z, Z"; RuleBasedCollator myCollator = new RuleBasedCollator(myRules); String[] test = { "a", "B", "c", "D", "q", "T", "cc", "cB", "cq", "cT" }; Arrays.sort(test, myCollator); System.out.println(Arrays.toString(test)); Output [a, B, T, q, c, cB, cT, cq, cc, D] A: Store the characters in the order you want in an array char[] or list (List) Compare based on the index of the character in the list/array list.indexOf(char1) - list.indexOf(char2); A: There is a very easy solution: First put your chars in a List: char[] arrayChars= {'A','B','T', ... }; List<Character> sortedChars= new ArrayList<Character>(); for (char c : arrayChars) { // Arrays.asList won't work sortedChars.add(c); } And then compare the indexes: int compare(char a,char b) { return sortedChars.indexOf(a) - sortedChars.indexOf(b); } A: I'd do it like this import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; public class Compare { public static void main(String[] args) { final List<Character> reference = new ArrayList<Character>( Arrays.asList(new Character[] {'A','B','T','Q','C','D','E','F'})); Character[] toBeSorted = {'A','B','C','D','E','F','Q','T'}; Comparator<Character> myComparator = new Comparator<Character>() { public int compare(Character o1, Character o2) { Integer i1 = reference.indexOf(o1); Integer i2 = reference.indexOf(o2); return i1.compareTo(i2); } }; Arrays.sort(toBeSorted, myComparator); System.out.println(Arrays.asList(toBeSorted)); } } A: the integers (N) carry a what is called a natural order. So you simply put your stuff in a list indexed by integers, following the order you want to implement. Then when the time comes to compare 2 chars, you compare their indexes and that's it ! A: Finally, I use String but it works fine with that : public class IndiceRepetitionComparator implements Comparator<String> { List<String> relationOrdre = Arrays.asList("A", "B", "T", "Q", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "R", "S", "U", "V", "W", "X", "Y", "Z"); @Override public int compare(String indiceRepetition1, String indiceRepetition2) { // même objet if (indiceRepetition1 == indiceRepetition2) { return 0; } if (indiceRepetition1 == null) { return -1; } if (indiceRepetition2 == null) { return -1; } return (relationOrdre.indexOf(indiceRepetition1) - relationOrdre.indexOf(indiceRepetition2) > 0) ? 1 : -1; } } Thank you for your help
{ "language": "en", "url": "https://stackoverflow.com/questions/38332406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Realtime auto calculate total value form I'm planning to create a realtime automatic calculating form that gathers the price of products in all (or some) collection and sums up some elements (of course the value is in integer, for example extra fee, modification, ...). It's Shopify platform, I have created a script that takes the price of a particular product when selected from a dropdown list. I can't make it do the calculation with some elements also being chosen by the select option. The idea came from this instruction: http://www.javascript-coder.com/javascript-form/javascript-calculator-script.phtml Here is the code: the code take price of product works well on my shopify web but when I put it in this code snippet, it doesn't work. $(function(){ $('select[name="Menu"]').change(function(){ var textId= $(this).data('text'); var price = $( "option:selected" , this).data('price'); $('#'+textId).val(price); }); }); $.fn.fonkTopla = function() { var total = 0; this.each(function() { var deger = fonkDeger($(this).val()); total += deger; }); return total; }; function fonkDeger(veri) { return (veri != '') ? parseInt(veri) : 0; } $(document).ready(function(){ $('input[name^="inptxt1"]').bind('keyup', function() { $('#total').html( $('input[name^="inptxt1"]').fonkTopla()); }); }); function getPrice() { //Assume form with id="theform" var theForm = document.forms["calculate"]; //Get a reference to the TextBox var price = theForm.elements["inptxt1"]; var howmany =0; //If the textbox is not blank if(inptxt1.value!="") { howmany = parseInt(inptxt1.value); } return howmany; } var filling_prices= new Array(); filling_prices["Selection"]=0; filling_prices["Fee1"]=3; filling_prices["Fee2"]=10; //This function finds the filling price based on the //drop down selection function getFillingPrice() { var optFillingPrice=0; //Get a reference to the form id="calculate" var theForm = document.forms["calculate"]; //Get a reference to the select id="filling" var selectedFilling = theForm.elements["filling"]; //set cakeFilling Price equal to value user chose //For example filling_prices["Lemon".value] would be equal to 5 optFillingPrice = filling_prices[selectedFilling.value]; //finally we return cakeFillingPrice return optFillingPrice; } function getTotal() { //Here we get the total price by calling our function //Each function returns a number so by calling them we add the values they return together var lastPrice = getPrice() + getFillingPrice() //display the result document.getElementById('totalP').innerHTML = "Total Price is: "+lastPrice; } <form action="" id="calculate"> <select name="Menu" data-text="inptxt1"> <option value="0" data-price="0">-- Select --</option> <option value="10" data-price="10">10$</option> <option value="20" data-price="20">20$</option> <!-- this one takes price of product in Shopify collection{% for product in collections.all.products %} <option value="{{ product.id }}" data-price="{{ product.price | ceil }}">{{ product.name}}</option> {% endfor %}--> </select> <input type="text" name="inptxt1" id="inptxt1" readonly/> <select id="filling" name='filling' onchange="calculateTotal()"> <option value="Selection">-- Select --</option> <option value="Fee1">Extra fee 1</option> <option value="Fee2">Extra fee 2</option> </select> Total: <div id="totalP"></div> </form>
{ "language": "en", "url": "https://stackoverflow.com/questions/38849628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I connect a VM to an ad-hoc network? I need to connect a VM to an ad-hoc network because I have Ubuntu Server running on my VM and I need to access it from other devices on the ad-hoc network. My VM is running on VMware Workstation 15 Player. What could I do to connect the VM to the ad-hoc network hosted on the host computer. A: There is two ways to do that. The first one is to connect your host machine to Ad-Hoc using its driver. The second way is to passthrough Wi-Fi adapter to the VM and connect to Ad-Hoc using driver installed there.
{ "language": "en", "url": "https://stackoverflow.com/questions/61837002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WSDL.exe - How do I generate cs file I have local wsdl-file, and related xsd-files and I want to generate a cs-file. Now i succeded in generate cs-file with the following command: All is fine!! A: Start "Developer Command Prompt for VS 2019" and run th following command: wsdl.exe C:\file.wsdl C:\file1.xsd C:\file2.xsd c:\file3.xsd c:\file4.xsd
{ "language": "en", "url": "https://stackoverflow.com/questions/62717778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why can't I the properties of properties when looping an object? Let's say I have this object: const people = { frodo: { name: 'Frodo', age: 33 }, aragorn: { name: 'Aragorn', age: 87 }, legolas: { name: 'Legolas', age: 2931 } } And let's say I want to loop over the properties of that object, like this: for (var person in people) { console.log(person.name); } I get undefined for any property of the person I tried to access. Why does this happen, and what's the correct way to loop the properties of that object and still be able to access their own properties? A: The for ... in loop iterates over the keys (properties) of an object. So for (var person in people) { console.log(people[person].name); } will get you the desired result. The variable person will receive the values "frodo", "aragorn" and "legolas" during the execution of the loop which are the keys (properties) of your person object. A: You take the keys of the object with for ... in statement. Then you need it as property accessor fopr the object. const people = { frodo: { name: 'Frodo', age: 33 }, aragorn: { name: 'Aragorn', age: 87 }, legolas: { name: 'Legolas', age: 2931 } } for (var person in people) { console.log(people[person].name); } A: You need to look at what person is within your code: const people = { frodo: { name: 'Frodo', age: 33 }, aragorn: { name: 'Aragorn', age: 87 }, legolas: { name: 'Legolas', age: 2931 } } for(person in people) console.log(person); It's the name of the object, not the object itself. To access it you need to specify where the object is located: const people = { frodo: { name: 'Frodo', age: 33 }, aragorn: { name: 'Aragorn', age: 87 }, legolas: { name: 'Legolas', age: 2931 } } for(person in people) { console.log( people[person].age, people[person].name, people[person] ); } A: for .. in returns every key in the object. You can get the person by using the key. const people = { frodo: { name: 'Frodo', age: 33 }, aragorn: { name: 'Aragorn', age: 87 }, legolas: { name: 'Legolas', age: 2931 } } for(var key in people) { var person = people[key] console.log(person.name) }
{ "language": "en", "url": "https://stackoverflow.com/questions/52654835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you create a custom project type (from my plugin) without opening Eclipse? I have created a plugin for Eclipse. With the help of this plugin, I am creating a new type of project, let's say XTypeProject. The creation of this XTypeProject is similar to any other type of project you create in Eclipse. File -> New -> YourProjectType I just want to know whether there is any way I can create a simple XTypeProject in Eclipse through some external mechanism, anything, and this project created through an external mechanism has to be similar to the project I create using Eclipse. Can Maven help me in this? Or is there any other way to do that? A: Here are my findings :- * *I went through the advice of Amos M. Carpenter and searched for the source code of the plugin that I have written. *After that, I did a debug (Plugin Debug) and searched for the methods that are called when we create a project from the Eclipse menu. *I took a note of all those class files and their methods that are called and the information/parameters they need for further processing. *I initiated the same call through ANT and was able to do what I wanted. Thank you for the support. P.S - I can't share my Plugin details as it is written for an organisation.
{ "language": "en", "url": "https://stackoverflow.com/questions/30908320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: convert degrees decimal minutes to decimal degrees How can convert degrees decimal minutes to decimal degrees on NMEA 0183 standard GPS trackers send position as degrees decimal minutes and need to convert. Inputs : 5546.263 /*(mean = 55° 46.263'N)*/ 3739.712 /*(mean = 37° 39.712'E)*/ Outputs : 55.771050 37.661867 Some inputs have a zero at first , like as above (3739.712 came from GPS device like 03739.712) I try to it my self but have problem on first step :) first problem is how degrees decimal minutes can convert to decimal degrees A: I don't know PHP, but if you can split the (string?) "5546.263" into 55 and 46.263 (degrees and decimal minutes), you can convert to decimal degrees with 55 + (46.263 / 60). In other words, it is degrees + (minutes / 60).
{ "language": "en", "url": "https://stackoverflow.com/questions/19456843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Avoid line break in R Markdown output I'm wondering how I can get all of the elements from my output on one single line, as the space for it is clearly there. Preamble of the file: ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ```
{ "language": "en", "url": "https://stackoverflow.com/questions/73926240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to collecting yii tabular input form? I made yii tabular input form, but every i submit this form its data can't save to database. it is my view: <div class="row" id="email_usul0" style="display:none;"> <?php echo $form->labelEx($modeljenis, 'email_usulan'); //email usulan jika yang dipilih bagian ?> <?php echo $form->textField($modeljenis, "email_usulan[0]", array('style' => 'width: 330px;')); ?> <?php echo $form->error($modeljenis, 'email_usulan'); ?> </div> <div class="row" id="nipnip0" style="display:none;"> <?php echo $form->labelEx($modeljenis, 'nip_baru'); //email usulan jika yang dipilih pegawai (tidak autocomplete, diisi eselon 3 ?> <?php echo $form->textField($modeljenis, "nip_baru[0]", array('style' => 'width: 330px;')); ?> <?php echo $form->error($modeljenis, 'nip_baru'); ?> </div> It is my controller for save post data: public function actionEmail() { $model = new EmailForm(); $modeljenis = array(); $modeljenis = new JenisEmailForm(); if (isset($_POST['EmailForm'])) { $model->attributes = $_POST['EmailForm']; $model->memo = CUploadedFile::getInstance($model, 'memo'); if ($model->validate()) { $email = new Email; $email->nama = 'NAME'; $email->email_kirim = $model->email_kirim; $model->memo->saveAs($path); foreach($_POST['JenisEmailForm'] as $i=>$modele) { if(isset($_POST['JenisEmailForm'][$i])){ $modeljenis[$i]->attributes=$modele; $email->jenis_email = $modeljenis[$i]->jenis_email; $email->save(); } } } } $this->render('email', array('model' => $model,'modeljenis' => $modeljenis, )); } It can't save data to the mysql. Thanks in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/24848250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android Navigation Drawer: open deep fragment from notification first sorry for my rusty English ! This is a doubt I have had for some time now and although my skills on Android have been getting better I haven't found an elegant solution for this issue: Lets say an application uses the Navigation Drawer pattern and has three levels of navigation: Home -> Posts -> Post details When I open the App from the launcher I add the Home Fragment. From here the user can navigate all the way down to a given "post" using fragment transactions. Now imagine there is some kind of notification that is letting me know something happened on a specific post: How would you create a "synthetic" back-stack when opening the app from the notification ? What I mean is: 1- Open the app from the notification 2- The app opens on Post Details 3- Back navigation has to be > Posts > Home Thanks a lot in advance ! A: without any line of code its hard to say how you are setting these Fragments , but you may need addToBackStack method or consider @Override onBackPressed properly. assuming notification is yours you can set id or whatever you need inside PendingIntent extras Bundle, obtain inside OnCreate method and then create a stack
{ "language": "en", "url": "https://stackoverflow.com/questions/43053827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: rake db:migrate does nothing I'm following this tutorial, and I'm having a problem when running rake db:migrate In db/migrate I have the create_post.rb file: class CreatePosts < ActiveRecord::Migration def change create_table :posts do |t| t.string :title t.text :text t.timestamps end end end But it does not create the table. My database.yml file is: development: adapter: mysql2 encoding: utf8 database: blog_development pool: 5 username: root password: socket: /tmp/mysql.sock The output from rake db:migrate seems ok. I'm using phpMyAdmin to handle the database, which is correctly created manually by me. What am I doing wrong? A: If you are connecting to the right database everything seems fine to me.. I had a similar problem a few weeks ago and the accepted answer of this question fixed my issue. Here are the steps to run: rake db:drop:all rake db:create:all rake db:migrate I hope it will fix your problem. WARNING: this will erase your database. A: Could you please tell which OS you got? Delete the line: socket: /tmp/mysql.sock and run: db:migrate Give the output of: db:migrate:status If this is not working for you, you could also try to add: host: 127.0.0.1 to your database.yml file A: If nothing stated above works please do check your schema.rb for migration contents. If migration contents are already there then just do the below command in production: rails db:schema:load RAILS_ENV=production.
{ "language": "en", "url": "https://stackoverflow.com/questions/22686452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add a rule blocking the IP address through the API Windows Firewall Delphi Good afternoon. Nobody faced with the addition of a Windows Firewall rules in Delphi? I need to restrict incoming and outgoing connections from specific IP addresses. This code throws me an application at startup with an error: Exception EVariantInvalidOpError in module Project1.exe at 00033E74. Invalid variant operation. Does anyone have what error? procedure TForm1.FormCreate(Sender: TObject); Const NET_FW_IP_PROTOCOL_TCP = 6; NET_FW_IP_PROTOCOL_UDP = 17; NET_FW_ACTION_ALLOW = 1; NET_FW_RULE_DIR_in = 1; var CurrentProfiles : OleVariant; fwPolicy2 : OleVariant; RulesObject : OleVariant; NewRule : OleVariant; txtAddress : OleVariant; NET_FW_ACTION_ : OleVariant; NET_FW_RULE_DIRECTION_: OleVariant; begin // Create the FwPolicy2 object. fwPolicy2 := CreateOleObject('HNetCfg.FwPolicy2'); RulesObject := fwPolicy2.Rules; CurrentProfiles := fwPolicy2.CurrentProfileTypes; txtaddress.text:='192.168.1.33'; //Create a Rule Object. NewRule := CreateOleObject('HNetCfg.FWRule'); newrule.Name:= 'BrutalNT: IP Access Block ' + txtAddress.Text; newrule.Description := 'Block Incoming Connections from IP Address.'; newrule.Action := 1; newrule.Direction := NET_FW_RULE_DIR_IN; newrule.Enabled := true; newrule.InterfaceTypes := 'All'; newrule.RemoteAddresses := txtAddress.Text; //Add a new rule RulesObject.Add(NewRule); end; A: You are using txtAddress : OleVariant but without any structure behind. So you cannot use something like txtAddress.text, because there is nothing where this can be mapped. Simply change the type to string, there is no need for txtAddress to be of type OleVariant. procedure TForm1.FormCreate(Sender: TObject); Const NET_FW_IP_PROTOCOL_TCP = 6; NET_FW_IP_PROTOCOL_UDP = 17; NET_FW_ACTION_BLOCK = 0; NET_FW_ACTION_ALLOW = 1; NET_FW_RULE_DIR_IN = 1; var CurrentProfiles : OleVariant; fwPolicy2 : OleVariant; RulesObject : OleVariant; NewRule : OleVariant; txtAddress : string; // OleVariant; begin // Create the FwPolicy2 object. fwPolicy2 := CreateOleObject('HNetCfg.FwPolicy2'); RulesObject := fwPolicy2.Rules; CurrentProfiles := fwPolicy2.CurrentProfileTypes; txtaddress{.text}:='192.168.1.33'; //Create a Rule Object. NewRule := CreateOleObject('HNetCfg.FWRule'); Newrule.Name := 'BrutalNT: IP Access Block ' + txtAddress{.Text}; Newrule.Description := 'Block Incoming Connections from IP Address.'; Newrule.Action := NET_FW_ACTION_BLOCK{1}; Newrule.Direction := NET_FW_RULE_DIR_IN; Newrule.Enabled := true; Newrule.InterfaceTypes := 'All'; Newrule.RemoteAddresses := txtAddress{.Text}; //Add a new rule RulesObject.Add(NewRule); end; BTW If you want to block you have to set NewRule.Action := 0; (NET_FW_ACTION_BLOCK)
{ "language": "en", "url": "https://stackoverflow.com/questions/25281216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Stata: Ado package not found I am looking to install the user-written 'esttab' of stata package 'st0085_2.pkg'. Normally I would type the following to do this: net install st0085_2.pkg In this case it outputs: checking st0085_2 consistency and verifying not already installed... installing into c:\ado\plus\... file c:\ado\plus\next.trk already exists r(602) So I changed the ado directory path and install the ado to somewhere else (I cant delete next.trk without admin approval): net set ado "U:\Documents\Stata\AMIE\ado" net install st0085_2.pkg The installation is successful but still the esttab command is unrecognized and I try and find where the ado is and it outputs that it has not yet been installed. I don't see how STATA can say the ado-file already exists when downloading but when retrieving the package is not found? unless they are looking in different directories but even when I ado set a new path (I have tried many combinations) it still cannot find the package. This is extra frustrating as I have used esttab on other computers. A: While I doubt the original poster is still around, the answer may be interesting to others encountering the same situation. The problem OP encounters here is that he does not have the correct rights to modify/delete the next.trk file in the default ado folder. Usually this happens when you do not have admin rights on a (heavily) locked-down server. One solution is to copy the files directly: however, this can be rather tricky if the server is really locked down, or you have programs with unspecified dependencies. The alternative is to change your ado folder. OP took the correct first step by altering the location of net install through net set ado "somefoldername". However, they missed the second step, which tells Stata "somefoldername" is part of the adopath. This is done through adopath ++ "somefoldername". If I'm not mistaken, this only stays active as long as Stata is open. To make this "permanent", that line of code should be added to the profile.do dofile, which runs automatically at Stata startup. See the Stata FAQ for more information on the profile.do file.
{ "language": "en", "url": "https://stackoverflow.com/questions/43287524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Sencha localStorage.getItem() returns null in model In my model, I have the following code: Ext.define('Proximity.model.CandidateblocklistModel', { extend: 'Ext.data.Model', requires: ['Ext.data.proxy.LocalStorage'], config: { store:'Proximity.store.CandidateblockStore', fields: [ { name: 'id', type: 'id' }, { name: 'name', type: 'string' }, { name: 'img', type: 'string' }, { name: 'designation', type: 'string' }, { name: 'summary', type: 'string' }, { name: 'experience', type: 'string' }, { name: 'industry', type: 'string' }, { name: 'functionnml', type: 'string' }, { name: 'role', type: 'string' } ], proxy : { type : 'ajax', url : Proximity.util.Config.getBaseUrl() + '/index.php/candidate/getcandidateblock', withCredentials: false, useDefaultXhrHeader: false, extraParams: { "id": localStorage.getItem('id') }, reader : { filters: [ Ext.create('Ext.util.Filter', { property: 'name' }) ] } } } }); The id in the local storage is already set before calling this model. I can see the id in localStorage by inspect element in Chrome, and I did get the value of it in other section. But I only can't get it in my model when I am trying to use it in proxy. I want to get data from my web service based on the value of the localStorage. Code in my proxy: extraParams: { "id": localStorage.getItem('id') }, I want to get the id from localStorage here. Please help me. A: I think the following code works proxy : { type : 'ajax', url : Proximity.util.Config.getBaseUrl() + '/index.php/candidate/getcandidatebest', withCredentials: false, useDefaultXhrHeader: false, extraParams: { id: localStorage.getItem('id') }, reader : { filters: [ Ext.create('Ext.util.Filter', { property: 'ind_id', property: 'fun_id', property: 'role_id', property: 'id' }) ] } } and then use the filtering facility of store to pass the localstorage value. To do that give filter permission remoteFilter: true, this. A: Ahh i found an awesome trick. Instate of setting extraParams in your Model, set it in the store of the same model. My new code is as follows. Ext.define('Proximity.model.RecruiterbestlistModel', { extend: 'Ext.data.Model', config: { store:'Proximity.store.RecruiterbestStore', fields: [ { name: 'id', type: 'int' }, { name: 'name', type: 'string' }, { name: 'img', type: 'string' }, { name: 'company', type: 'string' }, { name: 'summary', type: 'string' }, { name: 'address', type: 'string' }, { name: 'industry', type: 'string' }, { name: 'functionnml', type: 'string' }, { name: 'role', type: 'string' } ], proxy : { type : 'ajax', url : Proximity.util.Config.getBaseUrl() + '/index.php/recruiter/getrecruiterbest/', withCredentials: false, useDefaultXhrHeader: false, reader : { filters: [ Ext.create('Ext.util.Filter', { property: 'ind_id', property: 'fun_id', property: 'role_id' }) ] } } } }); Look i have removed the code extraParams: { "id": localStorage.getItem('id') }, from Model. And in my store i have added listeners: { beforeload: function(store){ this.getProxy().setExtraParams({ id: localStorage.getItem('id') }); return true; }, So my new store code is as follows Ext.define('Proximity.store.RecruiterbestStore', { extend: 'Ext.data.Store', alias: 'store.recruiterbeststore', config: { model: 'Proximity.model.RecruiterbestlistModel', autoLoad: true, remoteFilter: true, storeId: 'recruiterbeststore' }, listeners: { beforeload: function(store){ this.getProxy().setExtraParams({ id: localStorage.getItem('id') }); return true; } } }); And its solved my problem. But now i am having another issue. after running sencha app build native(using cordova bild), again i am having same issue, the extraParam are not added to proxy request. Please help me to solve this.
{ "language": "en", "url": "https://stackoverflow.com/questions/25462897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: KML complex schema I'm new to Kml and i'm searching for a way to define a more complex kml schema that can contain: a defined region, and inside the region all the countries of the region with their coordinates. So the schema has to contain a complex element and not a simple one. Currently i have this structure for country. But i don't know how can i make one for region. <Schema parent="Placemark" name="S_country"> <SimpleField type="wstring" name="CNTRY_NAME"> </SimpleField> </SimpleField> <SimpleField type="wstring" name="CURR_TYPE"> </SimpleField> <SimpleField type="wstring" name="CURR_CODE"> </SimpleField> </Schema> It is possible to have complex elements inside the schema? Thank you! A: Try reading this. It's the least thing you can do other than doing your own research. Advance KML 1: Easy Note Advance KML 2: Google Tutorial
{ "language": "en", "url": "https://stackoverflow.com/questions/6829292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: dtrace impact, monitoring processes (OS X)? I'm trying to find a efficient way to programmatically monitor, from user mode, what processes are started on my computer (OS X Yosemite). Since NSWorkspaceDidLaunchApplicationNotification only works for apps and kqueues (NOTE_EXIT) only allows one to monitor a specific process, dtrace probes seemed to be the way to go. I've played around with both /usr/bin/execsnoop and /usr/bin/newproc.d (and stripped down versions, that just install a single probe (syscall::posix_spawn:return) and do nothing else (e.g. no prints)). These do great job getting me the info I need, but when I start an app that kicks off multiple processes/quickly execs multiple commands (e.g. VMWare Fusion) - the probe(s) seem to noticeably impact the system. Specifically kernel_task consistently spikes to 50%+ CPU usage for a few seconds and the OS UI (mouse, etc) noticeable slows/lags...if the dtrace probes are not installed, this behavior is never observed. So a few questions: 1) any way to avoid this perf issue? (dtrace #pragmas?) 2) are dtrace probes cumulative? (if I install dtrace probes do I need to manually uninstall them, or does ctl+C clear/disable them?) 3) any way to see what dtrace probes are currently installed? I'm not attached to using dtrace - but am not aware of another (non-polling) way to get the pid/process name of things that are started on OS X :/ A: * *I am extremely surprised to see a measurable impact after enabling a single probe; does even dtrace -n syscall::posix_spawn:return cause a problem? If so, are you running short of memory? DTrace does require a (by default) modest amount and its initialisation may be pushing you over the edge. Do you see the problem with anything besides Fusion? It appears to suffer from performance problems of its own on Yosemite. *Probes are shared between consumers. If there is only one running consumer (e.g. dtrace) then all DTrace probes will be removed when it exits. If two consumers have enabled the same probe then it will remain active until the last consumer exits. *Maybe. Someone with access to the OS X source code could modify this script.
{ "language": "en", "url": "https://stackoverflow.com/questions/27794574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Project on update/create (set values from another object en masse) in LINQ2DB? When using LINQ2DB for my application I tried to use entity-DTO mapping using Expression<Func<Entity, DTO>> and vice versa like described here: https://github.com/linq2db/linq2db/issues/1283#issuecomment-413509043 This works great for projecting using a select, but what do I do when I need to update/insert a new record? I've skimmed over Update and Set extension methods but couldn't find anything. What I am trying to achieve is basically expression-based two-way mapping between an entity class and a DTO, kinda like AutoMapper's projection for EF but manually written per-DTO, in the form of two expressions for two-way conversion. Sadly I am not an expert in expression trees and LINQ to SQL translation, so would appreciate if anyone suggests something that works like this: Expression<Func<SomeDTO, SomeEntityTable>> projectExpr = x => new SomeEntity { ID = x.ID, Name = x.Name, // ... }; // this is just so that I can write two mapping expressions per DTO and don't ever repeat them, for stuff like CRUD // ... using var db = ConnectionFactory.Instance.GetMainDB(); await db.SomeEntityTable .Where(e => e.ID == dto.ID) .Set(dto, projectExpr) // dto is of SomeDTO type here; this will set ONLY the values that are written in the expression .Set(e => e.LastEditedAt, DateTime.Now()) // able to append some more stuff after .UpdateAsync(); // similar for insert operation, using the same expression A: These extension methods should provide needed mapping: using var db = ConnectionFactory.Instance.GetMainDB(); await db.SomeEntityTable .Where(e => e.ID == dto.ID) .AsUpdatable() .Set(dto, projectExpr) // new extension method .Set(e => e.LastEditedAt, DateTime.Now()) .UpdateAsync(); await db.SomeEntityTable .AsValueInsertable() .Values(dto, projectExpr) // new extension method .Value(e => e.LastEditedAt, DateTime.Now()) .InsertAsync(); And implementation: public static class InsertUpdateExtensions { private static MethodInfo _withIUpdatable = Methods.LinqToDB.Update.SetUpdatableExpression; private static MethodInfo _withIValueInsertable = Methods.LinqToDB.Insert.VI.ValueExpression; public static IUpdatable<TEntity> Set<TEntity, TDto>( this IUpdatable<TEntity> updatable, TDto obj, Expression<Func<TDto, TEntity>> projection) { var body = projection.GetBody(Expression.Constant(obj)); var entityParam = Expression.Parameter(typeof(TEntity), "e"); var pairs = EnumeratePairs(body, entityParam); foreach (var pair in pairs) { updatable = (IUpdatable<TEntity>)_withIUpdatable.MakeGenericMethod(typeof(TEntity), pair.Item1.Type) .Invoke(null, new object?[] { updatable, Expression.Lambda(pair.Item1, entityParam), Expression.Lambda(pair.Item2) })!; } return updatable; } public static IValueInsertable<TEntity> Values<TEntity, TDto>( this IValueInsertable<TEntity> insertable, TDto obj, Expression<Func<TDto, TEntity>> projection) { var body = projection.GetBody(Expression.Constant(obj)); var entityParam = Expression.Parameter(typeof(TEntity), "e"); var pairs = EnumeratePairs(body, entityParam); foreach (var pair in pairs) { insertable = (IValueInsertable<TEntity>)_withIValueInsertable.MakeGenericMethod(typeof(TEntity), pair.Item1.Type) .Invoke(null, new object?[] { insertable, Expression.Lambda(pair.Item1, entityParam), Expression.Lambda(pair.Item2) })!; } return insertable; } private static IEnumerable<Tuple<Expression, Expression>> EnumeratePairs(Expression projection, Expression entityPath) { switch (projection.NodeType) { case ExpressionType.MemberInit: { var mi = (MemberInitExpression)projection; foreach (var b in mi.Bindings) { if (b.BindingType == MemberBindingType.Assignment) { var assignment = (MemberAssignment)b; foreach (var p in EnumeratePairs(Expression.MakeMemberAccess(entityPath, assignment.Member), assignment.Expression)) { yield return p; } } } break; } case ExpressionType.New: { var ne = (NewExpression)projection; if (ne.Members != null) { for (var index = 0; index < ne.Arguments.Count; index++) { var expr = ne.Arguments[index]; var member = ne.Members[index]; foreach (var p in EnumeratePairs(Expression.MakeMemberAccess(entityPath, member), expr)) { yield return p; } } } break; } case ExpressionType.MemberAccess: { yield return Tuple.Create(projection, entityPath); break; } default: throw new NotImplementedException(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/74786123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Line-breaking widget layout for Android I'm trying to create an activity that presents some data to the user. The data is such that it can be divided into 'words', each being a widget, and sequence of 'words' would form the data ('sentence'?), the ViewGroup widget containing the words. As space required for all 'words' in a 'sentence' would exceed the available horizontal space on the display, I would like to wrap these 'sentences' as you would a normal piece of text. The following code: public class WrapTest extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout l = new LinearLayout(this); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); LinearLayout.LayoutParams mlp = new LinearLayout.LayoutParams( new ViewGroup.MarginLayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)); mlp.setMargins(0, 0, 2, 0); for (int i = 0; i < 10; i++) { TextView t = new TextView(this); t.setText("Hello"); t.setBackgroundColor(Color.RED); t.setSingleLine(true); l.addView(t, mlp); } setContentView(l, lp); } } yields something like the left picture, but I would want a layout presenting the same widgets like in the right one. Is there such a layout or combination of layouts and parameters, or do I have to implement my own ViewGroup for this? A: I made my own layout that does what I want, but it is quite limited at the moment. Comments and improvement suggestions are of course welcome. The activity: package se.fnord.xmms2.predicate; import se.fnord.android.layout.PredicateLayout; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.widget.TextView; public class Predicate extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); PredicateLayout l = new PredicateLayout(this); for (int i = 0; i < 10; i++) { TextView t = new TextView(this); t.setText("Hello"); t.setBackgroundColor(Color.RED); t.setSingleLine(true); l.addView(t, new PredicateLayout.LayoutParams(2, 0)); } setContentView(l); } } Or in an XML layout: <se.fnord.android.layout.PredicateLayout android:id="@+id/predicate_layout" android:layout_width="fill_parent" android:layout_height="wrap_content" /> And the Layout: package se.fnord.android.layout; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * ViewGroup that arranges child views in a similar way to text, with them laid * out one line at a time and "wrapping" to the next line as needed. * * Code licensed under CC-by-SA * * @author Henrik Gustafsson * @see http://stackoverflow.com/questions/549451/line-breaking-widget-layout-for-android * @license http://creativecommons.org/licenses/by-sa/2.5/ * */ public class PredicateLayout extends ViewGroup { private int line_height; public PredicateLayout(Context context) { super(context); } public PredicateLayout(Context context, AttributeSet attrs){ super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { assert(MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED); final int width = MeasureSpec.getSize(widthMeasureSpec); // The next line is WRONG!!! Doesn't take into account requested MeasureSpec mode! int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); final int count = getChildCount(); int line_height = 0; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); child.measure( MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(height, MeasureSpec.UNSPECIFIED)); final int childw = child.getMeasuredWidth(); line_height = Math.max(line_height, child.getMeasuredHeight() + lp.height); if (xpos + childw > width) { xpos = getPaddingLeft(); ypos += line_height; } xpos += childw + lp.width; } } this.line_height = line_height; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED){ height = ypos + line_height; } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST){ if (ypos + line_height < height){ height = ypos + line_height; } } setMeasuredDimension(width, height); } @Override protected LayoutParams generateDefaultLayoutParams() { return new LayoutParams(1, 1); // default of 1px spacing } @Override protected boolean checkLayoutParams(LayoutParams p) { return (p instanceof LayoutParams); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); final int width = r - l; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final int childw = child.getMeasuredWidth(); final int childh = child.getMeasuredHeight(); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (xpos + childw > width) { xpos = getPaddingLeft(); ypos += line_height; } child.layout(xpos, ypos, xpos + childw, ypos + childh); xpos += childw + lp.width; } } } } With the result: A: There is a problem with the first Answer: child.measure( MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST)); In a ListView, for example, the list items are passed a heightMeasureSpec of 0 (UNSPECIFIED) and so, here, the MeasureSpec of size 0 (AT_MOST) is passed to all of the children. This means that the whole PredicateLayout is invisible (height 0). As a quick fix, I changed the child height MeasureSpec like this: int childHeightMeasureSpec; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); } else { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } and then child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), childHeightMeasureSpec); which seems to work for me although does not handle EXACT mode which would be much more tricky. A: Since May 2016 there is new layout called FlexboxLayout from Google, which is highly configurable for purpose you want. FlexboxLayout is in Google GitHub repository at https://github.com/google/flexbox-layout at this moment. You can use it in your project by adding dependency to your build.gradle file: dependencies { implementation 'com.google.android.flexbox:flexbox:3.0.0' } More about FlexboxLayout usage and all the attributes you can find in repository readme or in Mark Allison articles here: https://blog.stylingandroid.com/flexboxlayout-part-1/ https://blog.stylingandroid.com/flexboxlayout-part2/ https://blog.stylingandroid.com/flexboxlayout-part-3/ A: I implemented something very similar to this, but using what I think is a little more standard way to handle spacing and padding. Please let me know what you guys think, and feel free to reuse without attribution: package com.asolutions.widget; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import com.asolutions.widget.R; public class RowLayout extends ViewGroup { public static final int DEFAULT_HORIZONTAL_SPACING = 5; public static final int DEFAULT_VERTICAL_SPACING = 5; private final int horizontalSpacing; private final int verticalSpacing; private List<RowMeasurement> currentRows = Collections.emptyList(); public RowLayout(Context context, AttributeSet attrs) { super(context, attrs); TypedArray styledAttributes = context.obtainStyledAttributes(attrs, R.styleable.RowLayout); horizontalSpacing = styledAttributes.getDimensionPixelSize(R.styleable.RowLayout_android_horizontalSpacing, DEFAULT_HORIZONTAL_SPACING); verticalSpacing = styledAttributes.getDimensionPixelSize(R.styleable.RowLayout_android_verticalSpacing, DEFAULT_VERTICAL_SPACING); styledAttributes.recycle(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); final int maxInternalWidth = MeasureSpec.getSize(widthMeasureSpec) - getHorizontalPadding(); final int maxInternalHeight = MeasureSpec.getSize(heightMeasureSpec) - getVerticalPadding(); List<RowMeasurement> rows = new ArrayList<RowMeasurement>(); RowMeasurement currentRow = new RowMeasurement(maxInternalWidth, widthMode); rows.add(currentRow); for (View child : getLayoutChildren()) { LayoutParams childLayoutParams = child.getLayoutParams(); int childWidthSpec = createChildMeasureSpec(childLayoutParams.width, maxInternalWidth, widthMode); int childHeightSpec = createChildMeasureSpec(childLayoutParams.height, maxInternalHeight, heightMode); child.measure(childWidthSpec, childHeightSpec); int childWidth = child.getMeasuredWidth(); int childHeight = child.getMeasuredHeight(); if (currentRow.wouldExceedMax(childWidth)) { currentRow = new RowMeasurement(maxInternalWidth, widthMode); rows.add(currentRow); } currentRow.addChildDimensions(childWidth, childHeight); } int longestRowWidth = 0; int totalRowHeight = 0; for (int index = 0; index < rows.size(); index++) { RowMeasurement row = rows.get(index); totalRowHeight += row.getHeight(); if (index < rows.size() - 1) { totalRowHeight += verticalSpacing; } longestRowWidth = Math.max(longestRowWidth, row.getWidth()); } setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? MeasureSpec.getSize(widthMeasureSpec) : longestRowWidth + getHorizontalPadding(), heightMode == MeasureSpec.EXACTLY ? MeasureSpec.getSize(heightMeasureSpec) : totalRowHeight + getVerticalPadding()); currentRows = Collections.unmodifiableList(rows); } private int createChildMeasureSpec(int childLayoutParam, int max, int parentMode) { int spec; if (childLayoutParam == LayoutParams.FILL_PARENT) { spec = MeasureSpec.makeMeasureSpec(max, MeasureSpec.EXACTLY); } else if (childLayoutParam == LayoutParams.WRAP_CONTENT) { spec = MeasureSpec.makeMeasureSpec(max, parentMode == MeasureSpec.UNSPECIFIED ? MeasureSpec.UNSPECIFIED : MeasureSpec.AT_MOST); } else { spec = MeasureSpec.makeMeasureSpec(childLayoutParam, MeasureSpec.EXACTLY); } return spec; } @Override protected void onLayout(boolean changed, int leftPosition, int topPosition, int rightPosition, int bottomPosition) { final int widthOffset = getMeasuredWidth() - getPaddingRight(); int x = getPaddingLeft(); int y = getPaddingTop(); Iterator<RowMeasurement> rowIterator = currentRows.iterator(); RowMeasurement currentRow = rowIterator.next(); for (View child : getLayoutChildren()) { final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); if (x + childWidth > widthOffset) { x = getPaddingLeft(); y += currentRow.height + verticalSpacing; if (rowIterator.hasNext()) { currentRow = rowIterator.next(); } } child.layout(x, y, x + childWidth, y + childHeight); x += childWidth + horizontalSpacing; } } private List<View> getLayoutChildren() { List<View> children = new ArrayList<View>(); for (int index = 0; index < getChildCount(); index++) { View child = getChildAt(index); if (child.getVisibility() != View.GONE) { children.add(child); } } return children; } protected int getVerticalPadding() { return getPaddingTop() + getPaddingBottom(); } protected int getHorizontalPadding() { return getPaddingLeft() + getPaddingRight(); } private final class RowMeasurement { private final int maxWidth; private final int widthMode; private int width; private int height; public RowMeasurement(int maxWidth, int widthMode) { this.maxWidth = maxWidth; this.widthMode = widthMode; } public int getHeight() { return height; } public int getWidth() { return width; } public boolean wouldExceedMax(int childWidth) { return widthMode == MeasureSpec.UNSPECIFIED ? false : getNewWidth(childWidth) > maxWidth; } public void addChildDimensions(int childWidth, int childHeight) { width = getNewWidth(childWidth); height = Math.max(height, childHeight); } private int getNewWidth(int childWidth) { return width == 0 ? childWidth : width + horizontalSpacing + childWidth; } } } This also requires an entry under /res/values/attrs.xml, which you can create if it's not already there. <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="RowLayout"> <attr name="android:verticalSpacing" /> <attr name="android:horizontalSpacing" /> </declare-styleable> </resources> Usage in an xml layout looks like this: <?xml version="1.0" encoding="utf-8"?> <com.asolutions.widget.RowLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:padding="10dp" android:horizontalSpacing="10dp" android:verticalSpacing="20dp"> <FrameLayout android:layout_width="30px" android:layout_height="40px" android:background="#F00"/> <FrameLayout android:layout_width="60px" android:layout_height="40px" android:background="#F00"/> <FrameLayout android:layout_width="70px" android:layout_height="20px" android:background="#F00"/> <FrameLayout android:layout_width="20px" android:layout_height="60px" android:background="#F00"/> <FrameLayout android:layout_width="10px" android:layout_height="40px" android:background="#F00"/> <FrameLayout android:layout_width="40px" android:layout_height="40px" android:background="#F00"/> <FrameLayout android:layout_width="40px" android:layout_height="40px" android:background="#F00"/> <FrameLayout android:layout_width="40px" android:layout_height="40px" android:background="#F00"/> </com.asolutions.widget.RowLayout> A: My slightly modified version based on posted here previously: * *It works in Eclipse layout editor *It centers all the items horizontally import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; public class FlowLayout extends ViewGroup { private int line_height; public static class LayoutParams extends ViewGroup.LayoutParams { public final int horizontal_spacing; public final int vertical_spacing; /** * @param horizontal_spacing Pixels between items, horizontally * @param vertical_spacing Pixels between items, vertically */ public LayoutParams(int horizontal_spacing, int vertical_spacing, ViewGroup.LayoutParams viewGroupLayout) { super(viewGroupLayout); this.horizontal_spacing = horizontal_spacing; this.vertical_spacing = vertical_spacing; } /** * @param horizontal_spacing Pixels between items, horizontally * @param vertical_spacing Pixels between items, vertically */ public LayoutParams(int horizontal_spacing, int vertical_spacing) { super(0, 0); this.horizontal_spacing = horizontal_spacing; this.vertical_spacing = vertical_spacing; } } public FlowLayout(Context context) { super(context); } public FlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { assert (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED); final int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); final int count = getChildCount(); int line_height = 0; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); int childHeightMeasureSpec; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); } else { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), childHeightMeasureSpec); final int childw = child.getMeasuredWidth(); line_height = Math.max(line_height, child.getMeasuredHeight() + lp.vertical_spacing); if (xpos + childw > width) { xpos = getPaddingLeft(); ypos += line_height; } xpos += childw + lp.horizontal_spacing; } } this.line_height = line_height; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) { height = ypos + line_height; } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { if (ypos + line_height < height) { height = ypos + line_height; } } setMeasuredDimension(width, height); } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(1, 1); // default of 1px spacing } @Override protected android.view.ViewGroup.LayoutParams generateLayoutParams( android.view.ViewGroup.LayoutParams p) { return new LayoutParams(1, 1, p); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { if (p instanceof LayoutParams) { return true; } return false; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); final int width = r - l; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); int lastHorizontalSpacing = 0; int rowStartIdx = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final int childw = child.getMeasuredWidth(); final int childh = child.getMeasuredHeight(); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (xpos + childw > width) { final int freeSpace = width - xpos + lastHorizontalSpacing; xpos = getPaddingLeft() + freeSpace / 2; for (int j = rowStartIdx; j < i; ++j) { final View drawChild = getChildAt(j); drawChild.layout(xpos, ypos, xpos + drawChild.getMeasuredWidth(), ypos + drawChild.getMeasuredHeight()); xpos += drawChild.getMeasuredWidth() + ((LayoutParams)drawChild.getLayoutParams()).horizontal_spacing; } lastHorizontalSpacing = 0; xpos = getPaddingLeft(); ypos += line_height; rowStartIdx = i; } child.layout(xpos, ypos, xpos + childw, ypos + childh); xpos += childw + lp.horizontal_spacing; lastHorizontalSpacing = lp.horizontal_spacing; } } if (rowStartIdx < count) { final int freeSpace = width - xpos + lastHorizontalSpacing; xpos = getPaddingLeft() + freeSpace / 2; for (int j = rowStartIdx; j < count; ++j) { final View drawChild = getChildAt(j); drawChild.layout(xpos, ypos, xpos + drawChild.getMeasuredWidth(), ypos + drawChild.getMeasuredHeight()); xpos += drawChild.getMeasuredWidth() + ((LayoutParams)drawChild.getLayoutParams()).horizontal_spacing; } } } } A: I have updated this sample to fix a bug, now, each line can have a different height ! import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * ViewGroup that arranges child views in a similar way to text, with them laid * out one line at a time and "wrapping" to the next line as needed. * * Code licensed under CC-by-SA * * @author Henrik Gustafsson * @see http://stackoverflow.com/questions/549451/line-breaking-widget-layout-for-android * @license http://creativecommons.org/licenses/by-sa/2.5/ * * Updated by Aurélien Guillard * Each line can have a different height * */ public class FlowLayout extends ViewGroup { public static class LayoutParams extends ViewGroup.LayoutParams { public final int horizontal_spacing; public final int vertical_spacing; /** * @param horizontal_spacing Pixels between items, horizontally * @param vertical_spacing Pixels between items, vertically */ public LayoutParams(int horizontal_spacing, int vertical_spacing) { super(0, 0); this.horizontal_spacing = horizontal_spacing; this.vertical_spacing = vertical_spacing; } } public FlowLayout(Context context) { super(context); } public FlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { assert (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED); final int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); final int count = getChildCount(); int line_height = 0; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); int childHeightMeasureSpec; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); } else { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final LayoutParams lp = (LayoutParams) child.getLayoutParams(); child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), childHeightMeasureSpec); final int childw = child.getMeasuredWidth(); if (xpos + childw > width) { xpos = getPaddingLeft(); ypos += line_height; } xpos += childw + lp.horizontal_spacing; line_height = child.getMeasuredHeight() + lp.vertical_spacing; } } if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) { height = ypos + line_height; } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { if (ypos + line_height < height) { height = ypos + line_height; } } setMeasuredDimension(width, height); } @Override protected ViewGroup.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(1, 1); // default of 1px spacing } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { if (p instanceof LayoutParams) { return true; } return false; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); final int width = r - l; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); int lineHeight = 0; for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final int childw = child.getMeasuredWidth(); final int childh = child.getMeasuredHeight(); final LayoutParams lp = (LayoutParams) child.getLayoutParams(); if (xpos + childw > width) { xpos = getPaddingLeft(); ypos += lineHeight; } lineHeight = child.getMeasuredHeight() + lp.vertical_spacing; child.layout(xpos, ypos, xpos + childw, ypos + childh); xpos += childw + lp.horizontal_spacing; } } } } A: The android-flowlayout project by ApmeM support line breaks, too. A: Here is my simplified, code-only version: package com.superliminal.android.util; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * A view container with layout behavior like that of the Swing FlowLayout. * Originally from http://nishantvnair.wordpress.com/2010/09/28/flowlayout-in-android/ itself derived from * http://stackoverflow.com/questions/549451/line-breaking-widget-layout-for-android * * @author Melinda Green */ public class FlowLayout extends ViewGroup { private final static int PAD_H = 2, PAD_V = 2; // Space between child views. private int mHeight; public FlowLayout(Context context) { super(context); } public FlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { assert (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED); final int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); final int count = getChildCount(); int xpos = getPaddingLeft(); int ypos = getPaddingTop(); int childHeightMeasureSpec; if(MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); else childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); mHeight = 0; for(int i = 0; i < count; i++) { final View child = getChildAt(i); if(child.getVisibility() != GONE) { child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), childHeightMeasureSpec); final int childw = child.getMeasuredWidth(); mHeight = Math.max(mHeight, child.getMeasuredHeight() + PAD_V); if(xpos + childw > width) { xpos = getPaddingLeft(); ypos += mHeight; } xpos += childw + PAD_H; } } if(MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) { height = ypos + mHeight; } else if(MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { if(ypos + mHeight < height) { height = ypos + mHeight; } } height += 5; // Fudge to avoid clipping bottom of last row. setMeasuredDimension(width, height); } // end onMeasure() @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int width = r - l; int xpos = getPaddingLeft(); int ypos = getPaddingTop(); for(int i = 0; i < getChildCount(); i++) { final View child = getChildAt(i); if(child.getVisibility() != GONE) { final int childw = child.getMeasuredWidth(); final int childh = child.getMeasuredHeight(); if(xpos + childw > width) { xpos = getPaddingLeft(); ypos += mHeight; } child.layout(xpos, ypos, xpos + childw, ypos + childh); xpos += childw + PAD_H; } } } // end onLayout() } A: Some of the different answers here would give me a ClassCastException in the Exclipse layout editor. In my case, I wanted to use ViewGroup.MarginLayoutParams rather than making my own. Either way, make sure to return the instance of LayoutParams that your custom layout class needs in generateLayoutParams. This is what mine looks like, just replace MarginLayoutParams with the one your ViewGroup needs: @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof MarginLayoutParams; } It looks like this method gets called to to assign a LayoutParams object for each child in the ViewGroup. A: LinearLayout row = new LinearLayout(this); //get the size of the screen Display display = getWindowManager().getDefaultDisplay(); this.screenWidth = display.getWidth(); // deprecated for(int i=0; i<this.users.length; i++) { row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); this.tag_button = new Button(this); this.tag_button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 70)); //get the size of the button text Paint mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setTextSize(tag_button.getTextSize()); mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL)); float size = mPaint.measureText(tag_button.getText().toString(), 0, tag_button.getText().toString().length()); size = size+28; this.totalTextWidth += size; if(totalTextWidth < screenWidth) { row.addView(tag_button); } else { this.tags.addView(row); row = new LinearLayout(this); row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); row.addView(tag_button); this.totalTextWidth = size; } } A: I adapted some of the ode above and implemented a flow layout which centers all child views, horizontal and vertical. It fits my needs. public class CenteredFlowLayout extends ViewGroup { private int lineHeight; private int centricHeightPadding; private final int halfGap; public static final List<View> LINE_CHILDREN = new ArrayList<View>(); public static class LayoutParams extends ViewGroup.LayoutParams { public final int horizontalSpacing; public final int verticalSpacing; public LayoutParams(int horizontalSpacing, int verticalSpacing) { super(0, 0); this.horizontalSpacing = horizontalSpacing; this.verticalSpacing = verticalSpacing; } } public CenteredFlowLayout(Context context) { super(context); halfGap = getResources().getDimensionPixelSize(R.dimen.half_gap); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); final int maxHeight = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom(); final int count = getChildCount(); int lineHeight = 0; int xAxis = getPaddingLeft(); int yAxis = getPaddingTop(); int childHeightMeasureSpec; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST); } else { childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { final CentricFlowLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams(); child.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST), childHeightMeasureSpec); final int childMeasuredWidth = child.getMeasuredWidth(); lineHeight = Math.max(lineHeight, child.getMeasuredHeight() + lp.verticalSpacing); if (xAxis + childMeasuredWidth > width) { xAxis = getPaddingLeft(); yAxis += lineHeight; } else if (i + 1 == count) { yAxis += lineHeight; } xAxis += childMeasuredWidth + lp.horizontalSpacing; } } this.lineHeight = lineHeight; if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) { height = yAxis + lineHeight; } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) { if (yAxis + lineHeight < height) { height = yAxis + lineHeight; } } if (maxHeight == 0) { maxHeight = height + getPaddingTop(); } centricHeightPadding = (maxHeight - height) / 2; setMeasuredDimension(width, disableCenterVertical ? height + getPaddingTop() : maxHeight); } @Override protected CentricFlowLayout.LayoutParams generateDefaultLayoutParams() { return new CentricFlowLayout.LayoutParams(halfGap, halfGap); } @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { if (p instanceof LayoutParams) { return true; } return false; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int count = getChildCount(); final int width = r - l; int yAxis = centricHeightPadding + getPaddingTop() + getPaddingBottom(); View child; int measuredWidth; int lineWidth = getPaddingLeft() + getPaddingRight(); CentricFlowLayout.LayoutParams lp; int offset; LINE_CHILDREN.clear(); for (int i = 0; i < count; i++) { child = getChildAt(i); lp = (LayoutParams) child.getLayoutParams(); if (GONE != child.getVisibility()) { measuredWidth = child.getMeasuredWidth(); if (lineWidth + measuredWidth + lp.horizontalSpacing > width) { offset = (width - lineWidth) / 2; layoutHorizontalCentricLine(LINE_CHILDREN, offset, yAxis); lineWidth = getPaddingLeft() + getPaddingRight() + measuredWidth + lp.horizontalSpacing; yAxis += lineHeight; LINE_CHILDREN.clear(); LINE_CHILDREN.add(child); } else { lineWidth += measuredWidth + lp.horizontalSpacing; LINE_CHILDREN.add(child); } } } offset = (width - lineWidth) / 2; layoutHorizontalCentricLine(LINE_CHILDREN, offset, yAxis); } private void layoutHorizontalCentricLine(final List<View> children, final int offset, final int yAxis) { int xAxis = getPaddingLeft() + getPaddingRight() + offset; for (View child : children) { final int measuredWidth = child.getMeasuredWidth(); final int measuredHeight = child.getMeasuredHeight(); final CentricFlowLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams(); child.layout(xAxis, yAxis, xAxis + measuredWidth, yAxis + measuredHeight); xAxis += measuredWidth + lp.horizontalSpacing; } } } A: try : dependencies { implementation'com.google.android:flexbox:0.3.2' } A: Try setting both of lp's LayoutParams to be WRAP_CONTENT. Setting mlp to be WRAP_CONTENT, WRAP_CONTENT ensures that your TextView(s) t are just wide and tall enough enough to hold "Hello" or whatever String you put in them. I think l may not be aware of how wide your t's are. The setSingleLine(true) may be contributing too.
{ "language": "en", "url": "https://stackoverflow.com/questions/549451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "100" }
Q: Macros That Write Macros - Compile Error When I compile the following code, SBCL complains that g!-unit-value and g!-unit are undefined. I'm not sure how to debug this. As far as I can tell, flatten is failing. When flatten reaches the unquoted part of defunits, it seems like the entire part is being treated as an atom. Does that sound correct? The following uses code from the book Let over Lambda: Paul Graham Utilities (defun symb (&rest args) (values (intern (apply #'mkstr args)))) (defun mkstr (&rest args) (with-output-to-string (s) (dolist (a args) (princ a s)))) (defun group (source n) (if (zerop n) (error "zero length")) (labels ((rec (source acc) (let ((rest (nthcdr n source))) (if (consp rest) (rec rest (cons (subseq source 0 n) acc)) (nreverse (cons source acc)))))) (if source (rec source nil) nil))) (defun flatten (x) (labels ((rec (x acc) (cond ((null x) acc) ((atom x) (cons x acc)) (t (rec (car x) (rec (cdr x) acc)))))) (rec x nil))) Let Over Lambda Utilities - Chapter 3 (defmacro defmacro/g! (name args &rest body) (let ((g!-symbols (remove-duplicates (remove-if-not #'g!-symbol-p (flatten body))))) `(defmacro ,name ,args (let ,(mapcar (lambda (g!-symbol) `(,g!-symbol (gensym ,(subseq (symbol-name g!-symbol) 2)))) g!-symbols) ,@body)))) (defun g!-symbol-p (symbol-to-test) (and (symbolp symbol-to-test) (> (length (symbol-name symbol-to-test)) 2) (string= (symbol-name symbol-to-test) "G!" :start1 0 :end1 2))) (defmacro defmacro! (name args &rest body) (let* ((o!-symbols (remove-if-not #'o!-symbol-p args)) (g!-symbols (mapcar #'o!-symbol-to-g!-symbol o!-symbols))) `(defmacro/g! ,name ,args `(let ,(mapcar #'list (list ,@g!-symbols) (list ,@o!-symbols)) ,(progn ,@body))))) (defun o!-symbol-p (symbol-to-test) (and (symbolp symbol-to-test) (> (length (symbol-name symbol-to-test)) 2) (string= (symbol-name symbol-to-test) "O!" :start1 0 :end1 2))) (defun o!-symbol-to-g!-symbol (o!-symbol) (symb "G!" (subseq (symbol-name o!-symbol) 2))) Let Over Lambda - Chapter 5 (defun defunits-chaining (u units prev) (if (member u prev) (error "~{ ~a~^ depends on~}" (cons u prev))) (let ((spec (find u units :key #'car))) (if (null spec) (error "Unknown unit ~a" u) (let ((chain (second spec))) (if (listp chain) (* (car chain) (defunits-chaining (second chain) units (cons u prev))) chain))))) (defmacro! defunits (quantity base-unit &rest units) `(defmacro ,(symb 'unit-of- quantity) (,g!-unit-value ,g!-unit) `(* ,,g!-unit-value ,(case ,g!-unit ((,base-unit) 1) ,@(mapcar (lambda (x) `((,(car x)) ,(defunits-chaining (car x) (cons `(,base-unit 1) (group units 2)) nil))) (group units 2)))))) A: For anyone else who is trying to get defmacro! to work on SBCL, a temporary solution to this problem is to grope inside the unquote structure during the flatten procedure recursively flatten its contents: (defun flatten (x) (labels ((flatten-recursively (x flattening-list) (cond ((null x) flattening-list) ((eq (type-of x) 'SB-IMPL::COMMA) (flatten-recursively (sb-impl::comma-expr x) flattening-list)) ((atom x) (cons x flattening-list)) (t (flatten-recursively (car x) (flatten-recursively (cdr x) flattening-list)))))) (flatten-recursively x nil))) But this is horribly platform dependant. If I find a better way, I'll post it. A: In case anyone's still interested in this one, here are my three cents. My objection to the above modification of flatten is that it might be more naturally useful as it were originally, while the problem with representations of unquote is rather endemic to defmacro/g!. I came up with a not-too-pretty modification of defmacro/g! using features to decide what to do. Namely, when dealing with non-SBCL implementations (#-sbcl) we proceed as before, while in the case of SBCL (#+sbcl) we dig into the sb-impl::comma structure, use its expr attribute when necessary and use equalp in remove-duplicates, as we are now dealing with structures, not symbols. Here's the code: (defmacro defmacro/g! (name args &rest body) (let ((syms (remove-duplicates (remove-if-not #-sbcl #'g!-symbol-p #+sbcl #'(lambda (s) (and (sb-impl::comma-p s) (g!-symbol-p (sb-impl::comma-expr s)))) (flatten body)) :test #-sbcl #'eql #+sbcl #'equalp))) `(defmacro ,name ,args (let ,(mapcar (lambda (s) `(#-sbcl ,s #+sbcl ,(sb-impl::comma-expr s) (gensym ,(subseq #-sbcl (symbol-name s) #+sbcl (symbol-name (sb-impl::comma-expr s)) 2)))) syms) ,@body)))) It works with SBCL. I have yet to test it thoroughly on other implementations. A: This is kind of tricky: Problem: you assume that backquote/comma expressions are plain lists. You need to ask yourself this question: What is the representation of a backquote/comma expression? Is it a list? Actually the full representation is unspecified. See here: CLHS: Section 2.4.6.1 Notes about Backquote We are using SBCL. See this: * (setf *print-pretty* nil) NIL * '`(a ,b) (SB-INT:QUASIQUOTE (A #S(SB-IMPL::COMMA :EXPR B :KIND 0))) So a comma expression is represented by a structure of type SB-IMPL::COMMA. The SBCL developers thought that this representation helps when such backquote lists need to be printed by the pretty printer. Since your flatten treats structures as atoms, it won't look inside... But this is the specific representation of SBCL. Clozure CL does something else and LispWorks again does something else. Clozure CL: ? '`(a ,b) (LIST* 'A (LIST B)) LispWorks: CL-USER 87 > '`(a ,b) (SYSTEM::BQ-LIST (QUOTE A) B) Debugging Since you found out that somehow flatten was involved, the next debugging steps are: First: trace the function flatten and see with which data it is called and what it returns. Since we are not sure what the data actually is, one can INSPECT it. A debugging example using SBCL: * (defun flatten (x) (inspect x) (labels ((rec (x acc) (cond ((null x) acc) ((atom x) (cons x acc)) (t (rec (car x) (rec (cdr x) acc)))))) (rec x nil))) STYLE-WARNING: redefining COMMON-LISP-USER::FLATTEN in DEFUN FLATTEN Above calls INSPECT on the argument data. In Common Lisp, the Inspector usually is something where one can interactively inspect data structures. As an example we are calling flatten with a backquote expression: * (flatten '`(a ,b)) The object is a proper list of length 2. 0. 0: SB-INT:QUASIQUOTE 1. 1: (A ,B) We are in the interactive Inspector. The commands now available: > help help for INSPECT: Q, E - Quit the inspector. <integer> - Inspect the numbered slot. R - Redisplay current inspected object. U - Move upward/backward to previous inspected object. ?, H, Help - Show this help. <other> - Evaluate the input as an expression. Within the inspector, the special variable SB-EXT:*INSPECTED* is bound to the current inspected object, so that it can be referred to in evaluated expressions. So the command 1 walks into the data structure, here a list. > 1 The object is a proper list of length 2. 0. 0: A 1. 1: ,B Walk in further: > 1 The object is a STRUCTURE-OBJECT of type SB-IMPL::COMMA. 0. EXPR: B 1. KIND: 0 Here the Inspector tells us that the object is a structure of a certain type. That's what we wanted to know. We now leave the Inspector using the command q and the flatten function continues and returns a value: > q (SB-INT:QUASIQUOTE A ,B)
{ "language": "en", "url": "https://stackoverflow.com/questions/33724300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Instrumenting (logging) Scala expressions (UPD after @krivachy.akos ) How to debug expressions in Scala? You don't have an opportunity to set a breakpoint and see local variables in most cases because inside the expression there are no variables. And usually there are no statements to which you can set a breakpoint. One old way of debugging is to have the code instrumented. This gives an indispensable information about the internal processing of expressions. However, in a typical logging implementation there are no direct ways of intercepting expressions. In particular, a typical logger have methods with Unit return type: def debug(msg: =>String) {...} To use the logger one have to rewrite concise expression in a way to be able to call logger: Example 1: if you have some boolean-based rules with complex conditions and multiple evaluation paths: val x = if(condition1(a,b)) Some(production1(a,b)) else if(condition2(c,d)) Some(production2(a,b)) else None then it is hard to make sure it works as desired. ( It's not always possible to avoid complex rules altogether. And representation rules in OOP-style is not always good.) Then a typical instrumentation would require introduction of some intermediate variables and blocks of code: debug("a="+a) debug("b="+b) val x = if(condition1(a,b)) { debug("rule1 hit") val production = production1(a,b) debug("rule1 result: "+production) Some(production) } else { debug("rule1 doesn't hit") debug("c="+c) debug("d="+d) if(condition2(c,d)){ debug("rule2 hit") Some(production2(a,b)) } else None } Example 2: def f(list:List[Int]) = list. map(_*2). flatMap(t => (0 until t). map(_+1) ) Instrumentation will lead to some intermediate variables: def f(list:List[Int]) = { val twiced = list.map(_*2) debug(s"twiced = $twiced") val result = twiced.flatMap(t => { val widened = (0 until t).map(_+1) debug(s"widened = $widened") widened }) debug(s"result = $result") result } Very ugly, I suppose. And this instrumentation takes more space than the code itself. The main reason, I think, is that the logger is incompatible with an expression evaluation style. Is there a way to log expression values in a more concise way? A: I recently found a nice way of logging the value of an expression: trait Logging { protected val loggerName = getClass.getName protected lazy val logger = LoggerFactory.getLogger(loggerName) implicit class RichExpressionForLogging[T](expr: T){ def infoE (msg: T ⇒ String):T = {if (logger.isInfoEnabled ) logger.info (msg(expr)); expr} def traceE(msg: T ⇒ String):T = {if (logger.isTraceEnabled) logger.trace(msg(expr)); expr} def debugE(msg: T ⇒ String):T = {if (logger.isDebugEnabled) logger.debug(msg(expr)); expr} def infoL (msg: String):T = {if (logger.isInfoEnabled ) logger.info (msg+expr); expr} def traceL(msg: String):T = {if (logger.isTraceEnabled) logger.trace(msg+expr); expr} def debugL(msg: String):T = {if (logger.isDebugEnabled) logger.debug(msg+expr); expr} } } Here how it is used: Example 1 (rules): val x = if(condition1(a.debugL("a="),b.debugL("b="))) Some(production1(a,b).debugL("rule1=")) else if(condition2(c,d)) Some(production2(a,b).debugL("rule2=")) else None Example 2: def f(list:List[Int]) = list. map(_*2). debugE(s"res1="+_). flatMap(t => (0 until t). map(_+1). debugE(s"res2="+_)). debugE(s"res="+_) It can also be used everywhere in expressions: if((a<0).debugE(s"a=$a<0="+_)) for{ a <- f(list).debugE("f(list)="+_) b <- a.debugL("a=") } yield b.debugL("b=") Of course you should mix-in Logging trait to your class. This kind of instrumentation doesn't hide the logic of the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/20141681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android RecyclerView with Filterable interface I'm trying to implement RecyclerView with Filterable interface in order to Filter my list from Toolbar's SearcView Widget. But My Problem is that I can't Update my list with new Data. notifyDataSetChanged() in publishResults method does nothing, I don't know why. Only the count of elements is changed. Here is my implementation of Recycler Adapter with Filterable Interface: public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ShoppingListHolder> implements Filterable { private Context context; private ArrayList<ShoppingListModel> shoppingList, filteredShoppingList; private ListFilter listFilter; public RecyclerAdapter(Context context, ArrayList<ShoppingListModel> shoppingList) { this.context = context; this.shoppingList = shoppingList; this.filteredShoppingList = shoppingList; } @Override public ShoppingListHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.shopping_listitem_layout_new, viewGroup, false); return new ShoppingListHolder(itemView); } @Override public int getItemCount() { return this.filteredShoppingList.size(); } @Override public void onBindViewHolder(ShoppingListHolder shoppingListHolder, int position) { final ShoppingListModel list = this.filteredShoppingList.get(position); shoppingListHolder.titleView.setText(list.getTitle()); if(list.getAlarmDate() == null || list.getAlarmDate().isEmpty()) shoppingListHolder.reminderView.setText("--/--/--"); else shoppingListHolder.reminderView.setText(list.getAlarmDate()); ArrayList<ListItemModel> listItems = DBManager.getShoppingListItems(DBHelper.SHOPPING_LIST_ITEM_PARENT_ID + " = " + list.getId()); double maxItems = listItems.size(); double checkedCount = 0; shoppingListHolder.itemContainer.removeAllViews(); for (int i = 0; i < listItems.size(); i++) { ListItemModel item = listItems.get(i); ShoppingListItemView listItem = new ShoppingListItemView(context, item, i + 1, list.getColor()); shoppingListHolder.itemContainer.addView(listItem); if (item.isChecked() == ListItemModel.ListItemState.Checked.ordinal()) { checkedCount++; } } if(checkedCount == 0){ shoppingListHolder.progressPercentageView.setText("0%"); }else{ shoppingListHolder.progressPercentageView.setText((int)(checkedCount / maxItems * 100) + "%"); } shoppingListHolder.progressBar.setMax((int) maxItems); shoppingListHolder.progressBar.setProgress((int) checkedCount); shoppingListHolder.rippleView.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() { @Override public void onComplete(RippleView rippleView) { Intent shoppingList = new Intent(context, ShoppingListItemActivity.class); Bundle extras = new Bundle(); extras.putLong(ShoppingListModel.SHOPPING_LIST_MODEL_KEY, list.getId()); shoppingList.putExtras(extras); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { context.startActivity(shoppingList, ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context).toBundle()); }else{ context.startActivity(shoppingList); } } }); } class ShoppingListHolder extends RecyclerView.ViewHolder { CardView cardView; RippleView rippleView; TextView titleView; TextView reminderView; ImageView locationPin; LinearLayout itemContainer; TextView progressPercentageView; ProgressBar progressBar; public ShoppingListHolder(View itemView) { super(itemView); rippleView = (RippleView) itemView.findViewById(R.id.card_view_ripple); cardView = (CardView) itemView.findViewById(R.id.card_view); titleView = (TextView) itemView.findViewById(R.id.title); reminderView = (TextView) itemView.findViewById(R.id.reminder); locationPin = (ImageView) itemView.findViewById(R.id.location_pin); itemContainer = (LinearLayout) itemView.findViewById(R.id.item_container); progressPercentageView = (TextView) itemView.findViewById(R.id.progress_percentage_label); progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar); } } @Override public Filter getFilter() { if (listFilter == null) { listFilter = new ListFilter(); } return listFilter; } private class ListFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults filterResults = new FilterResults(); ArrayList<ShoppingListModel> tempList; if (constraint != null && constraint.length() > 0) { tempList = DBManager.getShoppingList(DBHelper.SHOPPING_LIST_TITLE + " like '%" + constraint + "%' or " + DBHelper.SHOPPING_LIST_TAGS + " like '%" + constraint + "%'"); filterResults.count = tempList.size(); filterResults.values = tempList; } else { tempList = DBManager.getShoppingList(null); filterResults.count = tempList.size(); filterResults.values = tempList; } return filterResults; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { filteredShoppingList.clear(); filteredShoppingList.addAll((ArrayList<ShoppingListModel>) results.values); notifyDataSetChanged(); } } } Thanks people for help in advance. A: I would suggest in stead of adding the array list after you clear you instead do this @Override protected void publishResults(CharSequence constraint, FilterResults results) { filteredShoppingList = (ArrayList<ShoppingListModel>)filterResults.values; if (filterResults.count > 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/32889520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to insert records into the table by joining the reference table CREATE TABLE ref_table ( ref_id NUMBER(10), code VARCHAR2(50), val VARCHAR2(50), constraint pk_ref_table primary key(ref_id) ); insert into ref_table values(1,'maker','E_maker'); insert into ref_table values(2,'checker','E_checker'); insert into ref_table values(3,'sme','E_sme'); create table data_table ( id NUMBER(10), e_id VARCHAR2(50), maker VARCHAR2(100), checker VARCHAR2(100), sme VARCHAR2(100) ); INSERT INTO data_table VALUES ( 1, 11, 'owner_fn,owner_ln;owner_fn_2,owner_ln_2', 'owner_checker', 'sme1,sme_ln1;sme2,sme_ln2' ); CREATE TABLE org_table ( e_id NUMBER(10), ref_id NUMBER(10), CONSTRAINT pk_org_table PRIMARY KEY ( e_id ), CONSTRAINT fk_org_table_ref_id FOREIGN KEY ( ref_id ) REFERENCES ref_table ( ref_id ) ); ref_table -> This table is for the reference data. data_table -> This is the table that contains the actual data. org_table -> This is the table which I need to insert the data from data_table and ref_table. My attempt: MERGE INTO org_table ot USING ( SELECT e_id, regexp_substr(maker, '[^;]+', 1, level) maker, regexp_substr(checker, '[^;]+', 1, level) checker, regexp_substr(sme, '[^;]+', 1, level) sme FROM data_table CONNECT BY e_id = PRIOR e_id AND PRIOR sys_guid() IS NOT NULL AND level <= regexp_count(maker, ';') + 1 AND level <= regexp_count(checker, ';') + 1 AND level <= regexp_count(sme, ';') + 1 ORDER BY E_ID ) S on ( ot.e_id = s.e_id ) WHEN NOT MATCHED THEN INSERT ( e_id, ref_id ) VALUES ( s.e_id, s.ref_id ); Tool used : SQL Developer version 20.4 Problem that I am facing: SELECT e_id, regexp_substr(maker, '[^;]+', 1, level) maker, regexp_substr(checker, '[^;]+', 1, level) checker, regexp_substr(sme, '[^;]+', 1, level) sme FROM data_table CONNECT BY e_id = PRIOR e_id AND PRIOR sys_guid() IS NOT NULL AND level <= regexp_count(maker, ';') + 1 AND level <= regexp_count(checker, ';') + 1 AND level <= regexp_count(sme, ';') + 1 ORDER BY E_ID This query should give me the below result like whenever in the columns maker, checker or some contains ; then it should insert a new record for the same e_id but this is not inserting into the new line. And then, I want to insert the record into the org_table with e_id from data_table and ref_id from ref_table and the output should be like from the ref_table 1 is for maker column, 2 is for checker column and 3 is for some. Expected Output: +------+--------+--+ | e_id | ref_id | | +------+--------+--+ | 11 | 1 | | | 11 | 1 | | | 11 | 2 | | | 11 | 3 | | | 11 | 3 | | +------+--------+--+ 1 - It came twice because there were two maker for the same e_id. So, from ref_table 1 is the id for the maker. 2 - It came only once because there was one checker for the same e_id. So, from ref_table 2 is the id for the checker. 3 - It came twice because there was two some for the same e_id. So, from ref_table 3 is the id for the sme. How I will be able to join the columns from ref_table and data_table column value to get the desired result.
{ "language": "en", "url": "https://stackoverflow.com/questions/70757562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to add a button click event in a custom element I want to add a click event to the button with id: hamb-btn, where when clicked it will add a new class in the div class = "nav-link show" element. like that is an example of adding the class if the hamb button is pressed. its my code... note: i use webpack. import { html, css, LitElement } from 'lit-element'; class SinDrawer extends LitElement { static get styles() { return css` nav { display: flex; padding: 8px; background-color: var(--main-color); } `; } constructor() { super(); } render() { return html` <nav> <div class="nav-brand"> <a href="#/home"> <img src="./icons/icon_512.png" alt="sr-brand" height="50" title="Sinfor-Resto"> </a> </div> <div class="nav-link"> <a href="#/home" class="nav-anchor">Beranda</a> <a href="#/favorite" class="nav-anchor">Favorite</a> <a href="#/about" class="nav-anchor">Tentang</a> </div> <button id="hamb-btn" onclick="">&#9776;</button> </nav> `; } } customElements.define('sin-drawer', SinDrawer); A: You can always use classMap or styleMap directives for the dynamic styling in the Lit Component. More information available at Dynamic classes and styles. import { html, css, LitElement } from 'lit-element'; import { classMap } from 'lit/directives/class-map.js'; class SinDrawer extends LitElement { static get styles() { return css` nav { display: flex; padding: 8px; background-color: var(--main-color); } `; } static get properties() { return { _show: { state: true }, }; } constructor() { super(); this._show = false; } show() { this._show = !this._show; } render() { return html` <nav> <div class="nav-brand"> <a href="#/home"> <img src="./icons/icon_512.png" alt="sr-brand" height="50" title="Sinfor-Resto" /> </a> </div> <div class="nav-link ${classMap({ show: this._show })}"> <a href="#/home" class="nav-anchor">Beranda</a> <a href="#/favorite" class="nav-anchor">Favorite</a> <a href="#/about" class="nav-anchor">Tentang</a> </div> <button id="hamb-btn" @click=${this.show}>&#9776;</button> </nav> `; } } customElements.define('sin-drawer', SinDrawer); A: This can be done in 3 simple steps. * *Add a property ‘newClass’ as follows and initialise this.newClass as “” in constructor. static get properties(){ return{ newClass: String } } *Add ‘newClass’ to the div as follows <div class="nav-link ${this.newClass}"> *On click of the button, this.newClass will contain the new class name. <button id="hamb-btn" @click=${e=>this.newClass =”newClassName”}>&#9776;</button> Since this.newClass is added to properties of the element, it will rerender the DOM and update the div with class=”nav-link newClassName”
{ "language": "en", "url": "https://stackoverflow.com/questions/67657664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: not able to restore large database more than 15GB using power shell I'm using the following script to restore the database which has size more than 15 GB and it requires more than 100GB of space for mdf and ldf. However I have the enough space on the drive and I'm able to restore it manually through SSMS. But when I'm using PowerShell script I'm getting this error. I'm using sql server 2012 in my machine. This script is able to restore database with less size and I'm using the SMO for restoring. Please help me in this. Any other code base is also appreciated. Exception calling "SqlRestore" with "1" argument(s): "Restore failed for Server 'localhost'. " At D:\CI\RestoreDb.ps1:65 char:9 + $smoRestore.SqlRestore($server) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : FailedOperationException function Invoke-DatabaseRestore { param ([String]$SQLServer="(local)", $BackupPath,[String]$DataBaseName, [String]$BackupFileFilter = "") $server = New-Object ( "Microsoft.SqlServer.Management.Smo.Server" ) $SQLServer if ($server.Databases[$DataBaseName] -ne $null) { $server.KillDatabase($DataBaseName) #$server.databases[$DataBaseName].drop() } # Get-ChildItem $BackupPath -Filter $BackupFileFilter | select fullname | % { $backupFile = $_.FullName #we will query the database name from the backup header later #$server = New-Object ( "Microsoft.SqlServer.Management.Smo.Server" ) $SQLServer $backupDevice = New-Object( "Microsoft.SqlServer.Management.Smo.BackupDeviceItem" ) ($BackupPath, "File") $smoRestore = new-object( "Microsoft.SqlServer.Management.Smo.Restore" ) $backupDevice| FL * #Get default log and data file locations $DataPath ="D:\MSSQL\Data" $LogPath = "D:\MSSQL\Log" if(!(Test-Path($DataPath+"\"+$DataBaseName))) { New-Item -Name $DataBaseName -Path $DataPath -ItemType Directory -Force } if(!(Test-Path($LogPath+"\"+$DataBaseName))) { New-Item -Name $DataBaseName -Path $LogPath -ItemType Directory -Force } $DataPath = $DataPath+"\"+$DataBaseName $LogPath = $LogPath+"\"+$DataBaseName #restore settings $smoRestore.NoRecovery = $false; $smoRestore.ReplaceDatabase = $true; $smoRestore.Action = "Database" $smoRestore.PercentCompleteNotification = 10; $smoRestore.Devices.Add($backupDevice) #get database name from backup file $smoRestoreDetails = $smoRestore.ReadBackupHeader($server) #give a new database name $smoRestore.Database = $DataBaseName # $smoRestoreDetails.Rows[0]["DatabaseName"] #Relocate each file in the restore to the default directory $smoRestoreFiles = $smoRestore.ReadFileList($server) foreach ($File in $smoRestoreFiles) { #Create relocate file object so that we can restore the database to a different path $smoRestoreFile = New-Object( "Microsoft.SqlServer.Management.Smo.RelocateFile" ) #the logical file names should be the logical filename stored in the backup media $smoRestoreFile.LogicalFileName = $File.LogicalName $smoRestoreFile.PhysicalFileName = $( if($File.Type -eq "L") {$LogPath} else {$DataPath} ) + "\" + [System.IO.Path]::GetFileName($File.PhysicalName) $smoRestore.RelocateFiles.Add($smoRestoreFile) } #restore database $smoRestore.SqlRestore($server) } #load assemblies [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null $SqlInstance = 'HYDHTC233832D' $DatabaseName = "xyz" $BackupPath = "D:\xyz.bak" Invoke-DatabaseRestore -SQLServer $SqlInstance -BackupPath $BackupPath -DataBaseName $DatabaseName A: Here the problem was connection timeout due to large database. Adding $conn.StatementTimeout = 10000 solved me the issue :) Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/36977391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it alright to use target="_blank" in HTML5? I recall reading somewhere that in HTML5 it was no longer okay to use target="_blank" in HTML5, but I can't find it now. Is it alright to continue to use target="_blank"? I know it's generally considered a bad idea, but it's by the easiest way to open a new window for something like a PDF, and it also doesn't require you to rely on JavaScript. A: It is ok to use target="_blank"; This was done away with in XHTML because targeting new windows will always bring up the pop-up alert in most browsers. XHTML will always show an error with the target attribute in a validate. HTML 5 brought it back because we still use it. It's our friend and we can't let go. Never let go. A: Most web developers use target="_blank" only to open links in new tab. If you use target="_blank" only to open links in a new tab, then it is vulnerable to an attacker. When you open a link in a new tab ( target="_blank" ), the page that opens in a new tab can access the initial tab and change its location using the window.opener property. Javascript code: window.opener.location.replace(malicious URL) Prevention: rel="nofollow noopener noreferrer" More about the attribute values. A: While target is still acceptable in HTML5 it is not preferred. To link to a PDF file use the download attribute instead of the target attribute. Here is an example: <a href="files/invoice.pdf" download>Invoice</a> If the original file name is coded for unique file storage you can specify a user-friendly download name by assigning a value to the download attribute: <a href="files/j24oHPqJiUR2ftK0oeNH.pdf" download="invoice.pdf">Invoice</a> Keep in mind that while most modern browsers support this feature some may not. See caniuse.com for more info. A: It sure is! http://www.w3.org/TR/2010/WD-html5-20100624/text-level-semantics.html#the-a-element A: It looks like target="_blank" is still alright. It is listed as a browsing context keyword in the latest HTML5 draft. A: Though the target="_blank" is acceptable in HTML5, I personally try never to use it (even for opening PDFs in a new window). HTML should define meaning and content. Ask yourself, “would the meaning of the a element change if the target attribute were removed?” If not, the code should not go in the HTML. (Actually I’m surprised the W3C kept it… I guess they really just can’t let go.) Browser behavior, specifically, interactive behavior with the user, should be implemented with client-side scripting languages like JavaScript. Since you want the browser to behave in a particular way, i.e., opening a new window, you should use JS. But as you mentioned, this behavior requires the browser to rely on JS. (Though if your site degrades gracefully, or enhances progressively, or whatever, then it should still be okay. The users with JS disabled won’t miss much.) That being said, neither of these is the right answer. Out there somewhere is the opinion that how a link opens should ultimately be decided by the end user. Take this example. You’re surfing Wikipedia, getting deeper and deeper into a rabbit hole. You come across a link in your reading. Let’s say you want to skim the linked page real quick before coming back. You might open it in a new tab, and then close it when you’re done (because hitting the ‘back’ button and waiting for page reload takes too long). Or, what if it looks interesting and you want to save it for later? Maybe you should open it in a new background tab instead, and keep reading the current page. Or, maybe you decide you’re done reading this page, so you’ll just follow the link in the current tab. The point is, you have your own workflow, and you’d like your browser to behave accordingly. You might get pretty frustrated if it made these kinds of decisions for you. THAT being said, web developers should make it absolutely clear where their links go, what types and/or formats of sources they reference, and what they do. Tooltips can be your friend (unless you're using a tablet or phone; in that case, specify these on the mobile site). We all know how much it sucks to be taken somewhere we weren't expecting or make something happen we didn't mean to. A: it's by the easiest way to open a new window for something like a PDF It's also the easiest way to annoy non-Windows users. PDF open just fine in browsers on other platforms. Opening a new window also messes up the navigation history and complicates matter on smaller platforms like smartphones. Do NOT open new windows for things like PDF just because older versions of Windows were broken. A: I think target attribute is deprecated for the <link> element, not <a>, that's probably why you heard it's not supposed to be used anymore. A: You can do it in the following way with jquery, this will open it in a new window: <input type="button" id="idboton" value="google" name="boton" /> <script type="text/javascript"> $('#idboton').click(function(){ window.open('https://www.google.com.co'); }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/4198788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "171" }
Q: Why the icons / images looks blur (not clear) on tablet , but looks fine on phone in android? I was working on android app based on phone. However, recently the app need to support the tablet. The design was based on 1920 * 1080, I put all images/ icons into the xxhdpi folder and for lower resolution I just let android to help me rescale it. The problem is , it works well on phone(1280 * 800 5"), but when I use tablet to check it (say , galaxy tab 2 which resolution is only 1280 * 800 10.1" and 1024 * 600) but it looks like very blur . How to fix it ? Thanks for helping. Added <supports-screens android:resizeable="true" android:smallScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:normalScreens="true" android:anyDensity="true"/> already but still the same Update: I also find that the dp is too small for the tablet <style name="AppBaseTheme" parent="@style/Theme.AppCompat.Light"> <!-- API 11 theme customizations can go here. --> <item name="android:actionBarSize">60dp</item> </style> I was using a custom actionBarSize , it works nice on phone, but the 60dp is too small for tablet, how can I fix it as well? Thanks A: Well, I don't think you following the guidelines when you're using images. The android documentation doesn't say anything about screen resolutions when dealing with images, it rather focuses on pixel density when referring image resources (usually drawables) which is explained here. Remember that you can have two types of images (as far as I know): * *Image resources (usually drawables) *Image assets When using drawables you have to focus on pixel density rather than screen resolution because as you have just found out a small (or regular) screen device can have exactly the same resolution as a large screen device, to top it off, sometimes a normal screen device (handset) can have a higher resolution than a large screen device (tablet) where obviously in this case the handset has a much higher pixel density. So, you need to follow their guidelines take a medium pixel density (mdpi) device as the baseline to design your image resources as follows...taking a 96px image as an example... * *for a medium density device (mdpi) provide an image with 96px in the drawable folder...this is your baseline *then, target a high pixel density(hdpi) device by multiplying your baseline image by 1.5...that is, 96x1.5 = 144px...place this image inside the drawable-hdpi folder with exactly the same name *a x-large pixel density device image would be the baseline image multiplied by 2 (96x2=192px). This goes inside the drawable-xhdpi folder *for an xx-large picel density (xxhdpi) device multiply the baseline image by 3 (96x3=288) and place it inside the drawable-xxhdpi folder Notice in the link provided that you don't need to provide an image for a device with a low pixel density since Android scales it down from mdpi without any problems... Note: Android also supports low-density (LDPI) screens, but you normally don't need to create custom assets at this size because Android effectively down-scales your HDPI assets by 1/2 to match the expected size. In your case, whats happening is that your Galaxy tablet has a lower pixel density and Android down-scales the image from a xxhdpi to whatever density the tablet has (hdpi or xhdpi)....so, it your image is a 512px image Android would down-scale it to 341px for xhdpi or 256px for an hdpi device. If you follow these guidelines and focus on pixel density, you should be fine. However, for images in the assets folder there's no much you can do apart from using the ScaleType enum or using stretchable 9-patch images Hope this helps Update Actually, according to this link, the Galaxy Tab 2 has mdpi screen, which means your image will be scale down three times from xxhdpi. You should provide the same images with different sizes inside the appropriate drawable-x folders A: I know its a way too late but recently I faced the same issue about the way app launcher icons looks on a tablet and they are blurry. I'm sure that AOS honestly chooses mdpi drawables for tablets with mdpi display density and thats the problem. So I solved this by placing smartphones icons to a tablet resources dirs as following (left column - usual smartphone drawables-density and the right - tablet dirs): drawable-xhdpi -> drawable-large-mdpi (these are 96x96px) drawable-xxhdpi -> drawable-large-hdpi (these are 144x144px) drawable-xxxhdpi -> drawable-large-xhdpi (these are 192x192px) drawable-xxxhdpi -> drawable-xlarge (these are 192x192px) I'm not sure if last two has to be 288x288 px but since I don't have such icons in the project I guess 192x192 should be enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/25234621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: React Native navigation is not working I am trying to navigate between two screen using react-native navigation https://reactnavigation.org/. It is working from index.js to EnableNotification.js but it is not working from EnableNotification.js to CreateMessage.js EnableNotification.js /** * https://github.com/facebook/react-native * @flow */ import React, { Component } from "react"; import { View, Text, Image, Button, StyleSheet } from "react-native"; import { StackNavigator } from "react-navigation"; import styles from "./Styles"; import * as strings from "./Strings"; import CreateMessage from "./CreateMessage"; export default class EnableNotificationScreen extends Component { render() { const { navigate } = this.props.navigation; return ( <View style={styles.container}> <Image source={require("./img/enable_notification.png")} /> <Text style={styles.textStyle}> {strings.enable_notification} </Text> <View style={{ width: 240, marginTop: 30 }}> <Button title="ENABLE NOTIFICATION" color="#FE434C" onPress={() => navigate("CreateMessage")} style={{ borderRadius: 40 }} /> </View> <Text style={{ textAlign: "center", marginTop: 10 }} > NOT NOW </Text> </View> ); } } const ScheduledApp = StackNavigator({ CreateMessage: { screen: CreateMessage, navigationOptions: { header: { visible: false } } } }); CreateMessage.js import React, { Component } from "react"; import { View, Text, Image, Button, StyleSheet } from "react-native"; export default class CreateMessage extends Component { render() { return <View><Text>Hello World!</Text></View>; } } A: First : index.android.js or index.ios.js import React, { Component } from 'react'; import { AppRegistry, Navigator } from 'react-native'; import Index from './app/Index'; import CreateMessage from './app/CreateMessage'; import EnableNotification from './app/EnableNotification'; render() { return ( <Navigator initialRoute={{screen: 'Index'}} renderScene={(route, nav) => {return this.renderScene(route, nav)}} /> ) } renderScene(route,nav) { switch (route.screen) { case "Index": return <Index navigator={nav} /> case "EnableNotification": return <EnableNotification navigator={nav} /> case "CreateMessage": return <CreateMessage navigator={nav} /> } } After that : index.js goEnableNotification() { this.props.navigator.push({ screen: 'EnableNotification' }); } Finally : EnableNotification.js goCreateMessage() { this.props.navigator.push({ screen: 'CreateMessage' }); } If you want to go back, do a function goBack : goBack() { this.props.navigator.pop(); } I hope this will help you ! A: This worked for me - CreateMessage component needs to be part of the navigation stack in order to navigate there through this.props.navigator.navigate(<name>)
{ "language": "en", "url": "https://stackoverflow.com/questions/43614479", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a non-wrapping text-span inside a TextView? I'm trying to make a non-wrapping text span inside a TextView in my Android app. What I've tried so far is to implement a TextAppearanceSpan and set the style of that span to: <style name="TextAppearance.NonWrappingElement"> <item name="android:maxLines">1</item> <item name="android:singleLine">true</item> <item name="android:lines">1</item> <item name="android:ellipsize">end</item> </style> ...however, the text in the TextView is still wrapping..
{ "language": "en", "url": "https://stackoverflow.com/questions/44417230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does client send an authentication token back to the user in OpenID connect? I'm learning about OpenID connect and OAuth2.0 and i think there is something missing, what the client will do after receiving the ID token from the authorization server? Ok it now has a JWT that contains information about the user, but when the user wants to send a request to the client to do whatever he wants to do, he should attach a token with his request, right? so, when the client will generate this token? as far as i know, if a server uses HTTP as its protocol, it can't send data to the user if the user didn't issue a request, so it shouldn't be able to send that token without a request from the user. Did i miss something? I tried to search about this stuff, and I didn't find anything useful. A: Ok it now has a JWT that contains information about the user, but when the user wants to send a request to the client to do whatever he wants to do, he should attach a token with his request, right? Should say "but when the client wants to send a request to the server ..." if a server uses HTTP as its protocol, it can't send data to the user if the user didn't issue a request, so it shouldn't be able to send that token without a request from the user. The token will have been provided to the client during sign-on process. To summarise the process: * *Client enters credentials (e.g. username and password) and sends those to a login endpoint. *The login server will generate a JWT and return to client. *Client receives a JWT and caches it locally at the client end ready to be sent to the server on subsequent requests. *On all subsequent requests to the server the client will attach the cached JWT in the authorization headers of the http request. *The server will validate the token to ensure client is authenticated.
{ "language": "en", "url": "https://stackoverflow.com/questions/75309418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you rename a variable in R? If I have a variable x <- "foo" and another variable y <- 1:5 is there a way I can rename y to foo while keeping it equal to 1:5? A: You could use comment() so that foo was an attribute of y. For example, try: x <- "foo" y <- 1:5 comment(y) <- x str(y) attr(y, "comment")
{ "language": "en", "url": "https://stackoverflow.com/questions/30804564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Azure Mobile service(push notification) I am working on Azure mobile service push notification and I am trying to send push notification on particular registration id. I have following script, can somebody tell me how can I update this JavaScript so it works fine: exports.post = function(request, response) { var push = request.service.push; var token="APA91bG7pOV2jLiSiSujNS4Gg_Q##################"; var mes = "Hellooooo"; var payload = '{"data":{"message" : "Testing"}}'; push.gcm.send(null,payload,{ success: function(pushResponse) { console.log("Sent push:", pushResponse, payload); request.respond(); }, error: function (pushResponse) { console.log("Error Sending push:", pushResponse); request.respond(500, { error: pushResponse }); } }); };
{ "language": "en", "url": "https://stackoverflow.com/questions/35860971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Server: find and remove dups in a table I am not familiar with SQL programming, I understand there were posts about removing dups before but this is a little more complicated and I haven't found a solution online. The requirement: I have a table Positions with columns A, B, C, total, date. * *Two rows are regarded as dups only when the values of A, B, C all match. *once dups are found, choose the row whose date is not empty and update the value of total of that row by summing up the total of all dups rows; *remove the other dups except for the row chosen in the above step. The chosen SQL is SQL Server. please help. John A: Can try as follows to update the table. update POSITIONS as a set total = (select sum(total) from positions as b where a.col1 = b.col1 and a.col2 = b.col2 and a.col3 = b.col3) WHERE a.date is not null If you don't want the total of row with date to be included in the sum, then you have to tweek the query accordingly. The following assumptions were made as your question is not very clear. 1) There will be only one row with non empty date 2) No need to update if all the dates available are empty Next time, try to include as much info as possible with your question for us to guide better. Regards. A: First, you calculate SUM total value Group by A,B,C Where date not null. Then, you update total = SUM (calculated step one). Last, you select DISTINCT A,B,C,total Try this code: UPDATE POSITIONS AS P SET total = (SELECT SUM(total) FROM POSITIONS WHERE A = P.A AND B = P.B AND C = P.C) WHERE date IS NOT NULL SELECT DISTINCT A,B,C,total FROM POSITIONS WHERE date IS NOT NULL A: WITH CTE_Position AS ( SELECT 'Test' AS A, 1 AS B, 1 AS C, 5 AS Total, CONVERT(DATE, '05/10/2018') AS [Date] UNION ALL SELECT 'Test' AS A, 1 AS B, 2 AS C, 6 AS Total, NULL AS [Date] UNION ALL SELECT 'Test' AS A, 2 AS B, 3 AS C, 5 AS Total, CONVERT(DATE, '05/10/2018') AS [Date] UNION ALL SELECT 'Test' AS A, 2 AS B, 4 AS C, 6 AS Total, NULL AS [Date] UNION ALL SELECT 'Test' AS A, 3 AS B, 5 AS C, 5 AS Total, CONVERT(DATE, '05/10/2018') AS [Date] UNION ALL SELECT 'Test' AS A, 3 AS B, 6 AS C, 6 AS Total, NULL AS [Date] UNION ALL SELECT 'Test' AS A, 4 AS B, 7 AS C, 5 AS Total, CONVERT(DATE, '05/10/2018') AS [Date] ) SELECT p1.A, p1.B, p1.C ,Total = (CASE WHEN SUM(p2.Total) IS NULL OR SUM(p2.Total) = 0 THEN SUM(p1.Total) ELSE SUM(p1.Total + p2.Total) END) ,p1.[Date] FROM CTE_Position p1 LEFT JOIN CTE_Position p2 ON p1.A = p2.A AND p1.B = p2.B AND p2.[Date] IS NULL WHERE p1.[Date] IS NOT NULL GROUP BY p1.A, p1.B, p1.C, p1.[DATE]
{ "language": "en", "url": "https://stackoverflow.com/questions/33293626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress Feed URL redirecting to Login Page I am trying to read wordpress feed url into php This is link of Wordpress Feed URL When we click on this url it redirects to login page where as it should have shown the contents of feed. Below is my php code to read this feed url <?php $xmlDoc = new DOMDocument(); libxml_use_internal_errors(true); $xmlDoc->loadHTMLFile("https://intranet.saniservice.com/feed/rss2"); libxml_use_internal_errors(false); print_r($xmlDoc); ?> When this code is executed it returns data but that data is of login page which we see when we click on feed url, I am not sure how can i stop this feed from redirecting to login page.
{ "language": "en", "url": "https://stackoverflow.com/questions/44148211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AWS EC2 PHP SDK SSL error Im trying to set an auto start and stop on my EC2 using PHP script. When im trying to run the script it turns out error like below, Fatal error: Uncaught exception 'Guzzle\Http\Exception\CurlException' with message '[curl] 60: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed [url] https://ec2.ap-southeast-1a.amazonaws.com/' .... .... i've reinstalled the ca-certificates in my centos server. but the error persist. Below are the specification details, PHP5.3. aws php sdk 2.8 centos 6.5 Anyone encounter this error before?
{ "language": "en", "url": "https://stackoverflow.com/questions/30831849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Web Audio: Make event occur at exact moment? I am trying to make something where sound samples are chosen randomly at intervals so that the song evolves and is different each time it's listened to. HTML Audio was not sufficient for this, because the timing was imprecise, so I am experimenting with Web Audio, but it seems quite complicated. For now, I just want to know how to make a new audio file play at 16 seconds exactly, or 32 seconds, etc. I came across something like this playSound.start(audioContext.currentTime + numb); But as of now I cannot make it work. var audioContext = new audioContextCheck(); function audioFileLoader(fileDirectory) { var soundObj = {}; soundObj.fileDirectory = fileDirectory; var getSound = new XMLHttpRequest(); getSound.open("GET", soundObj.fileDirectory, true); getSound.responseType = "arraybuffer"; getSound.onload = function() { audioContext.decodeAudioData(getSound.response, function(buffer) { soundObj.soundToPlay = buffer; }); } getSound.send(); soundObj.play = function(volumeVal, pitchVal) { var volume = audioContext.createGain(); volume.gain.value = volumeVal; var playSound = audioContext.createBufferSource(); playSound.playbackRate.value = pitchVal; playSound.buffer = soundObj.soundToPlay; playSound.connect(volume); volume.connect(audioContext.destination) playSound.start(audioContext.currentTime) } return soundObj; }; var harp1 = audioFileLoader("IRELAND/harp1.ogg"); var harp2 = audioFileLoader("IRELAND/harp2.ogg"); function keyPressed() { harp1.play(.5, 2); harp2.start(audioContext.currentTime + 7.5); } window.addEventListener("keydown", keyPressed, false); You see I am trying to make harp2.ogg play immediately when harp1.ogg finishes. Eventually I want to be able to choose the next file randomly, but for now I just need to know how to make it happen at all. How can I make harp2.ogg play exactly at 7.5 seconds after harp1.ogg begins (or better yet, is there a way to trigger it when harp2 ends (without a gap in audio)?) Help appreciated, thanks! A: WebAudio should be able to start audio very precisely using start(time), down to the nearest sample time. If it doesn't, it's because the audio data from decodeAudioData doesn't contain the data you expected, or it's a bug in your browser. A: Looks like when you call keyPressed, you want to trigger both songs to start playing. One immediately, and the other in 7.5 seconds. * *The function to play the songs is soundObj.play and it needs to take an additional argument, which is the audioContext time to play the song. Something like: soundObj.play = function(volumeVal, pitchVal, startTime) {...} *The function keyPressed() block should look something like this: harp1.play(.5, 2, 0); harp2.start(1, 1, audioContext.currentTime + 7.5); audioContext.resume(); audioContext.resume() starts the actual audio (or rather starts the audio graph timing so it does things you've scheduled)
{ "language": "en", "url": "https://stackoverflow.com/questions/41758946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Command works in console, not in code Just killed 5 hours on this, giving up for the moment. This command works fine from a non-elevated command prompt (Permissions pregranted on the key so no issues): REG ADD "HKCR\CLSID\{323CA680-C24D-4099-B94D-446DD2D7249E}\ShellFolder" /v Attributes /d 0xA0900100 /t REG_DWORD /f But the c# version doesn't produce any changes to the regkey: (Same machine as above with same regkey permissions incase anyone asks): System.Diagnostics.Process.Start("CMD", "/C REG ADD \"HKCR\\CLSID\\{323CA680-C24D-4099-B94D-446DD2D7249E}\\ShellFolder\" /v Attributes /d 0xA0900100 /t REG_DWORD /f"); I've tried several variations, none of them work. 3 other developers I deal with are baffled the command doesn't work, and nobody can figure out why. Any ideas? A: Your command is well formed, and it isn't an escape code issue. Likely you are hitting a UAC / privilege issue. If you really want to go down this path rather than using the .NET registry API, I recommend you try the explicit form of creating a ProcessStartInfo and use Verb "runas" to get elevated privs. processStartInfo.UseShellExecute = true; processStartInfo.Verb = "runas"; The sure way to find out is to redirect IO and see what the process / shell is saying. processStartInfo.RedirectStandardInput = true; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; var child = Process.Start(processStartInfo); You'll need to read from stderr / stdout (start a thread, or just for this case do it synchronously) var sb = new StringBuilder(); while ((nRead = child.StandardError.Read(buffer, 0, BUFSIZE)) > 0) for (int n = 0; n < nRead; n++) sb.Append(buffer[n]); Console.WriteLine(sb.ToString()); A: Try using the Registry class. Even if you - for whatever reason - must use Process.Start it will help you debug your issue. string key = @"HKCR\CLSID\{323CA680-C24D-4099-B94D-446DD2D7249E}\ShellFolder"; string valueName = "Attributes"; string value ="0xA0900100"; Microsoft.Win32.Registry.SetValue(key, valueName, value, Microsoft.Win32.RegistryValueKind.String);
{ "language": "en", "url": "https://stackoverflow.com/questions/26437234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using MouseOver and MouseOut Hi guys im working on my first website and im trying to implement a sliding menu using jquery. This is what a got so far : <a href="javascript:void(0);"onmouseover="ShowBox();" onmouseout="HideBox();"">Show box<a> <script type="text/javascript"> function ShowBox() { $("#SlideMenu").slideDown(); } function HideBox() { $("#SlideMenu").slideUp(); } </script> When i MouseOver the control my menu slides down but slides back up automatically. What I would like is to let the user the time to select and option from the menu and if he doesn't, i would like the menu to close as soon as the mouse leaves the control. Any idea why this isn't working ? Thanks in advance. A: Do your stuff without the inline JS, and remember to close the <a> element and use a ready function <a id="test">Show box</a> <script type="text/javascript"> $(document).ready(function() { $("#test").on({ mouseenter: function() { $("#SlideMenu").slideDown(); }, mouseleave: function() { $("#SlideMenu").slideUp(); }, click: function(e) { e.preventDefault(); } }); }); </script> FIDDLE A: As you're using jQuery I believe it would be beneficial for you to use something similar to: $("#box").hover( function() { //.stop() to prevent propagation $(this).stop().animate({"bottom": "200px"}, "fast"); }, function() { $(this).stop().animate({"bottom": "0px"}, "fast"); } ); What this will mean is that whilst the mouse is over the menu, the menu will stay in its open position. When the mouse exits the menu it will close. Obviously change the id, and animation CSS values to suit your needs :)! Here is a working example: http://jsfiddle.net/V3PYs/1/ A: Really there is no problem here - the script is doing exactly what you told it to. However, from what I understand, what you want is for the menu to stay open when you leave the "trigger" element if the user's mouse is now over the menu. Try this: <script type="text/javascript"> var timeout=250;//timeout in milliseconds to wait before hiding the menu var menuMouseout; $(document).ready(function() { $("#trigger").hover(function(){ $("#SlideMenu").slideDown(); }, function(){ menuMouseout=setTimeout("$('#SlideMenu').slideUp();", timeout); }); $("#SlideMenu").hover(function(){ clearTimeout(menuMouseout); }, function(){ menuMouseout=setTimeout("$('#SlideMenu').slideUp();", timeout); }); }); </script> This way, the user is left some time after mousing out of the trigger element to get to the menu. You might need to fiddle with the timeout, but this should work. I tested this and it seems to be working. Just be sure, if necessary, to wrap this in $(document).ready to make sure all elements are loaded and ready. Demo: http://www.dstrout.net/pub/menu.htm A: If you're using jQuery this would be the proper way to go about it: <a href="#" id="showBoxHref">Show box</a> <script type="text/javascript"> $("#showBoxHref").hover(function() { $(this).slideDown(); }, function() { $(this).slideUp(); }); </script> (just copy/paste this in and it should work)
{ "language": "en", "url": "https://stackoverflow.com/questions/10508282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: checking type of reference in generics java I am currently building a game in java(turn based RPG) and am facing a problem in inventory UI. Perhaps my problem is well known or has a simple solution, but having never had any training, I will still ask the question. While displaying the inventory after selecting an item I check if that item implements the SpecificItemWorker interface , that is, acts on a specific GameObject that has to be passed in to its takeAction() method. While selecting that object which has to be passed, I display all the possible candidate objects for the user to select. For example, suppose the user selects a UpgradeParchment that acts on any object that implements Upgradable interface. Here, I initiate a ItemSelector that displays all the items in the inventory that implements Upgradable. However with a different class , the interface that the object needs to implement in order to be a possible candidate will differ.(Note that some objects act on the game environment rather than on a specific object, but we are not considering that case here.).Now instead of hard-coding the possible interfaces in a switch case statement , i want it to be dynamic.I tried to use generics, but it does not allow to check if an object is an instanceof of the Type parameter. The following code gives a compile error: package ui; import objects.Collectable; public class ItemSelector<T> { public void test(Collectable ob) { if (ob instanceof T) {// compile error // do work } } } Does anyone know how this can be achieved?Thanks for any help. Looking for a speedy reply, Thanks. EDIT : The parameter in the testAction() method will be of type Collectable as in my inventory class, there is only a list of Collectable objects.Similarly, in my test method , I have updated the types.Although it is a minor change, sorry for any inconvenience.Collectable is also an interface. A: Due to runtime type erasure, you need to provide what's called a type token to the class: public class ItemSelector<T> { private final Class<T> clazz; public ItemSelector(Class<T> clazz) { this.clazz = clazz; } public void test(GameObject ob) { if (clazz.isInstance(ob)) {// use token to check type // do work } } } This requires a class object to be passed to the constructor, usually by passing a class literal, eg MyClass.class A: There is a way to check the type with class.getTypeName(). I assume the SpecificItemWorker is a game object as shown in the code. package stackoverflow.question39718130; public class SpecificItemWorker extends GameObject { } package stackoverflow.question39718130; public class ItemSelector<T> { private T t; public ItemSelector(final T t) { this.t = t; } public T getT() { return t; } public void test(final GameObject ob) { /*if (ob instanceof T) {// compile error // do work }*/ if (t.getClass().getTypeName() == ob.getClass().getTypeName()) { System.out.println("Grab item."); } else { System.err.println("No item found."); } } } There is a test example to pass the GameObject. package stackoverflow.question39718130; public class GameObjectTest { public static void main(final String[] args) { specificItemWorkerTest(); } public static void specificItemWorkerTest() { final GameObject specificItemWorker = new SpecificItemWorker(); final ItemSelector<GameObject> selector = new ItemSelector<>(specificItemWorker); selector.test(specificItemWorker); } } I hope I understood you right with the SpecificItemWorker. Please let me know if this fits to your solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/39718130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add custom comparatorClass class in Solr I am newbie in Solr. I want to add a custom comparatorClass in Solr. I also need to use fields - term and count in my custom class which I have defined in my schema.xml. Structure of indexing document : "docs": [ { "count": 98, "term": "age", }, { "count": 6, "term": "age assan", }, { "count": 5, "term": "age but", }, { "count": 10, "term": "age salman", }] I have stored ngrams with term and their count but solr gives frequency by own that I don't need. I want my count frequency which I have defined for each term. And that term and count, I need to use and want to sort with frequency(count) and then edit distance which I need to implement by creating own class in comparator class or there is something else which helps me. Please share.. How can I do this. Any help please. Thanks. A: You should be able to do this without implementing a custom similarity class. The first requirement is (from your description) a straight forward sort on the count value, while the latter can be implemented by sorting on the value from the strdist() function. You can also multiply or weight these values against each other in a single sort statement by using several functions. If you really, really need to build your own scorer (which I don't think you need to do from your description) - these are usually written to explore other ranking algorithms than tf/idf, bm25 etc. for larger corpuses, a search on Google gives you many resources with pre-made, easy to adopt solutions. I particularly want to point out "This is the Nuclear Option" in Build Your Own Custom Lucene Query and Scorer: Unless you just want the educational experience, building a custom Lucene Query should be the “nuclear option” for search relevancy. It’s very fiddly and there are many ins-and-outs. If you’re actually considering this to solve a real problem, you’ve already gone down the following paths [...]
{ "language": "en", "url": "https://stackoverflow.com/questions/27597412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: naming uploaded image after username? I am developing using CodeIgniter framework. I have an image upload folder which permission is set to 755. My host is using suPHP so site users are able to upload to it. I just noticed that when user uploads an image, the IMAGE file permission is 666. I am naming the images using usernames so it would be quite easy for someone to guess that someone with username ‘hello’ would have an image stored in that directory named ‘hello.jpg’ or ‘hello.png’ Is this unsafe? Could a malicious visitor do something like erase or replace a member’s image from that image upload directory? Do I have to name the image something random and then store that random image name into that user’s db table row so I know which image name matches which user? A: You should always validate any user input of course, but you could in this case simply check that the current user's username matches the name being used as the filename (assuming you authenticate the users prior to allowing them to upload), and ensure they have no means to specify the filename via anything they input. In short, authenticate, and name your files using known user info', server-side data only.
{ "language": "en", "url": "https://stackoverflow.com/questions/13250126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to control 1000+ flash app instances? I have a flash app running on 1200 machines on a local network. Currently, the app polls the php server every 10 seconds, and is returned a 14 byte string with the state. If the state is new, the app changes mode and gets new data from the server. 1200 machines polling every 10 seconds to pick up ~8 state changes per day seems like an awful lot of network traffic for this. There is other traffic on the network (streaming video, web surfing etc). When the network load gets high, some of the machines loose the ability to communicate with the server and hang. When I run 400 machines I don't run into this problem. Looks like a scalability problem. What would you recommend for lightweight communication between server and 1200 clients? Remoting with AMFast? XML Sockets? Something else entirely? Thanks very much! A: Socket communication, and having the server send a message to the clients when the state changes, instead of the clients polling the server, seems like the way to go here. Almost a textbook example for sockets vs polling, I would say. In applications for public web, socket communication in Flash can sometimes be troublesome because of firewall settings and using other ports than 80 and so on, but in your internal system, it should work fine. A: Do you need the state to be a 14 Byte string (14 Bytes is 112-bits which would support 5.19 x 10^33 different status'), are there really that many states that you need to communicate? How many states do you need to convey?
{ "language": "en", "url": "https://stackoverflow.com/questions/9639047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RestKit Object mapping issue I have this JSON response that I can't figure out how to map. It looks like this: { "responseError": null, "displayMenuList": { "MenuList": [ { "ID": "3223", "Name": "Main", "AddressURL": "www.mysite.com", "DisplayType": "True", "ImageURL": "main.png", "NotSplitBUser": "True", "ParentCategoryId": "3223", "PrivateUser": "True", "SortOrder": 1, "SplitBUser": "True", "TargetURL": "_self" }, { "ID": "3307", "Name": "Contact", "AddressURL": "www.mysite.com", "DisplayType": "True", "ImageURL": "service.png", "NotSplitBUser": "True", "ParentCategoryId": "3224", "PrivateUser": "True", "SortOrder": 0, "SplitBUser": "True", "TargetURL": "_self" }, { "ID": "3298", "Name": "Call Us", "AddressURL": "www.mysite.com", "DisplayType": "True", "ImageURL": "service.png", "NotSplitBUser": "True", "ParentCategoryId": "3224", "PrivateUser": "True", "SortOrder": 1, "SplitBUser": "True", "TargetURL": "_self" }, { "ID": "3224", "Name": "Service", "AddressURL": "www.mysite.com", "DisplayType": "True", "ImageURL": "service.png", "NotSplitBUser": "True", "ParentCategoryId": "3224", "PrivateUser": "True", "SortOrder": 2, "SplitBUser": "True", "TargetURL": "_self" } ] }, "responseCurrentBillState": null, "responseGetPcrfSubBuckets": null, "userData": { "abroadInd": null, "accountType": "B", "customerId": "", "fullName": "Juan", "subscriberNumber": "" } } I just can't figure out how to map those objects, I've created object called RKSideMenu, also an object called RKUserData they look like this: @interface RKSideMenu : NSObject @property (copy, nonatomic) NSString *addressURL; @property (copy, nonatomic) NSString *displayType; @property (copy, nonatomic) NSNumber *id_number; @property (copy, nonatomic) NSString *imageURL; @property (copy, nonatomic) NSString *name; @property (assign, nonatomic) BOOL splitBUser; + (NSDictionary*)getAttributes; @end @implementation RKSideMenu + (NSDictionary*)getAttributes { return [NSDictionary dictionaryWithObjects:@[@"addressURL", @"displayType", @"id_number", @"imageURL", @"name", @"splitBUser"] forKeys:@[@"AddressURL", @"DisplayType", @"ID", @"ImageURL", @"Name", @"SplitBUser"]]; } @end @interface RKUserData : NSObject @property (copy, nonatomic) NSString *abroadInd; @property (copy, nonatomic) NSString *accountType; @property (copy, nonatomic) NSString *customerID; @property (copy, nonatomic) NSString *fullName; @property (copy, nonatomic) NSString *subscriberNumber; + (NSDictionary*)getAttributes; @end @implementation RKUserData + (NSDictionary*)getAttributes { return [NSDictionary dictionaryWithObjects:@[@"abroadInd", @"accountType", @"customerID", @"fullName;", @"subscriberNumber"] forKeys:@[@"abroadInd", @"accountType", @"customerId", @"fullName;", @"subscriberNumber"]]; } @end I started mapping with those two methods, but than I stuck and don't know what to do. I look at https://github.com/RestKit/RestKit/wiki/Object-mapping, but still couldn't get it right. RKObjectMapping *sideMenuMapping = [RKObjectMapping mappingForClass:[RKSideMenu class]]; [sideMenuMapping addAttributeMappingsFromDictionary:[RKSideMenu getAttributes]]; RKObjectMapping *userDataMapping = [RKObjectMapping mappingForClass:[RKUserData class]]; [userDataMapping addAttributeMappingsFromDictionary:[RKUserData getAttributes]]; Thanks in advance! Edit: Json on top replaced with real json from server. A: So what you need to do in order to setup your mapping is first of all define the base url of your API, like so: AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"URL_TO_YOUR_API"]]; RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client]; Then you need to set a response descriptor for the url that outputs the json above: [[RKObjectManager sharedManager] addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:sideMenuMapping method:RKRequestMethodAny pathPattern:@"/mainScreenData" keyPath:@"displayMenuList.MenuList" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]]; "RKRequestMethodAny" should be replaced by the Request Method you are using e.g. "RKRequestMethodGET". Then you just retrieve the objects by calling: [[RKObjectManager sharedManager] getObjectsAtPath:@"/mainScreenData" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { NSArray *sideMenuList = [NSMutableArray arrayWithArray:[mappingResult array]]; } failure:^(RKObjectRequestOperation *operation, NSError *error) { NSLog(@"%@",[error localizedDescription]); }]; I would highly recommend you having a look at the demos that are supplied by RestKit. That makes the whole process a lot clearer. Cheers, Sebastian
{ "language": "en", "url": "https://stackoverflow.com/questions/21019913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scope of "use module" and associated linking error I am trying to navigate my way around fortran 90 and I have this toy example using which I would like to ask a question module foo implicit none contains subroutine foobar() print *,'foobar' end subroutine foobar end module foo Then the main program - program test use foo real a,b,c a = 10. b= 10. c= 10. print *,'hello world' call abc(a,b,c) end program test subroutine abc(a,b,c) call def(a,b,c) end subroutine abc subroutine def(a,b,c) call foobar() print *,'def' end subroutine def If I do not include the 'use foo' statement in subroutine def I get a linking error while linking test.o and foo.o-undefined reference. Why is that ? By declaring use foo at the 'main' level do the subroutines also not get access to the symbol foo ? I would guess not based on the compiler error. So this means the only way to move forward is to include the use foo statement in every subroutine. What is the motivation behind this ?
{ "language": "en", "url": "https://stackoverflow.com/questions/45197745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to sort an array of numbers which has separator in between? I have an array of numbers each with numbers in both side but a separator between both numbers.For example: $selectTableRows= array("1_6", "3_4", "10_1", "2_2", "5_7"); I need to sort the array depending on the numbers after the separator "_".Thus, the result should be like, 10_1 , 2_2 , 3_4 , 1_6 , 5_7 Need help in php. Thank You A: The solution using usort and explode functions: $selectTableRows = array("1_6", "3_4", "10_1", "2_2", "5_7"); usort($selectTableRows, function ($a, $b){ return explode('_', $a)[1] - explode('_', $b)[1]; }); print_r($selectTableRows); The output: Array ( [0] => 10_1 [1] => 2_2 [2] => 3_4 [3] => 1_6 [4] => 5_7 )
{ "language": "en", "url": "https://stackoverflow.com/questions/42563315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SAP HANA data provider for Microsoft ado.net I need to connect my C# web application with SAP HANA database using Entity Framework 6. I've got this documentation: obsolete link (possibly, Microsoft Entity Framework Support (SAP HANA Data Provider for Microsoft ADO.NET) may correspond.) This document explains how to use SAP HANA data provider for Microsoft ado.net. But I unable to find from where could I download SAP HANA data provider for Microsoft ado.net. Could any one provide me a link for the same? A: You can get the ado.net driver (+ python, java, etc..) from this address: https://tools.hana.ondemand.com/#hanatools A: It is part of the SAP HANA client package. Go to https://service.sap.com/hana, login, then click "Software download", and select your edition. Proceed with "SAP HANA Client 1.00", not with the proposed "Studio".
{ "language": "en", "url": "https://stackoverflow.com/questions/36861019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Why data types was changed while calling the apply function in Pandas? While using the apply function to process a DataFrame, the data type of columns was changed unexpectedly. What should I do to prevent this? For example: In [1]: import pandas as pd In [2]: from pandas import DataFrame In [3]: tmp = DataFrame({'item':[1,2,3]}) In [4]: tmp['score'] = 0.0 In [5]: tmp.dtypes Out[5]: item int64 score float64 dtype: object In [6]: tmp Out[6]: item score 0 1 0.0 1 2 0.0 2 3 0.0 In [7]: def Test(x): ...: return x ...: In [8]: tmp = tmp.apply(Test,axis=1) In [9]: tmp.dtypes Out[9]: item float64 score float64 dtype: object The data type of tmp['item'] was changed into float. How to maintain the original data type of it? A: This is happening because .apply essentially iterates over rows (when axis=1) and applies the function to a Series that represents each row. Since Series must contain the same data type, a Series made from a row of mixed int and float types will properly promote ints to float: In [4]: def test(x): return x In [5]: tmp.iloc[0] Out[5]: item 1.0 score 0.0 Name: 0, dtype: float64 In [6]: tmp.apply(test, axis=1) Out[6]: item score 0 1.0 0.0 1 2.0 0.0 2 3.0 0.0 Note what happens when we select a column, though: In [7]: tmp.iloc[:,0] Out[7]: 0 1 1 2 2 3 Name: item, dtype: int64 In [8]: tmp.apply(test, axis=0) Out[8]: item score 0 1 0.0 1 2 0.0 2 3 0.0
{ "language": "en", "url": "https://stackoverflow.com/questions/40315792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compute the maximum-coverage path in an Occupancy Grid I am implementing a basic robot which uses a SLAM algorithm to produce an occupancy grid of it's environment. It is very simple with no probabilistic aspect, simply an enum to represent Empty, Occupied, Unexplored, Unreachable etc. I was wondering if there is a well known algorithm to find the shortest path necessary to visit all of the grid cells once (it's a Vacuum cleaner!). Is this the Travelling Salesman Problem? I have researched a couple of solutions based on Graphs, for example finding Hamiltonian Cycles, but i wondered if there was anything which efficiently worked on Grids directly. The grid will be around 250x250 cells. Thanks! A: Just thought id add my solution to this unanswered question - Most algorithms I tried out were just too computationally complex. I settled on an approximation of the maximum-coverage path which was quite efficiently computed using the reverse wavefront algorithm. Using this algorithm I was able to construct a maximum-coverage path of a 250x250 array of grid cells in around 5 seconds, which was certainly acceptable in my scenario.
{ "language": "en", "url": "https://stackoverflow.com/questions/9886656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Check if the image and file type exist inside directory This is my code: $file = 'images/img_' . $post->_id . '.jpg'; // images/img_1.jpg if (file_exists($file) && is_file($file)) { //show the image echo '<img src="' . $file . '" class="img-responsive" />'; } else { // show default image echo '<img src="images/default.gif" class="img-responsive" />'; } What this basicly does is to check if the an image (eg img_1.jpg) exist in my images folder and display it, if not it shows a default image. This works fine, the only problem, as you probably 've seen, is that it checks only the .jpg files and not *.gif or *.png too (the file could also be img_1.gif or img_1.png, right? ) . How can I make sure that it will check against all valid file types too and show the file with the correct format? A: You could loop through an array of file extensions and check them i've made a sample script to show what i mean listed below $array = array('.jpg','.png','.gif'); foreach($array as $key => $value){ $file = 'images/img_' . $post->_id . $value; // images/img_1.jpg if (file_exists($file) && is_file($file)) { $filefound = '<img src="' . $file . '" class="img-responsive" />'; } } if(isset($filefound)){ echo $filefound; }else{ echo '<img src="images/default.gif" class="img-responsive" />'; } A: The most efficient way to do this is probably to store the extension in the database, that way you're not scanning your file system for matches. However, you could also use the glob();; function and check if results has anything. $result = glob('images/img_' . $post->_id . '.*'); If you want to further narrow down your extension types you can do that like this: $result = glob('images/img_' . $post->_id . '.{jpg,jpeg,png,gif}', GLOB_BRACE) New code might look something like this (untested but you get the idea): $result = glob('images/img_' . $post->_id . '.{jpg,jpeg,png,gif}', GLOB_BRACE); if(!empty($result)) { //show the image echo '<img src="' . $result[0]. '" class="img-responsive" />'; } else { // show default image echo '<img src="images/default.gif" class="img-responsive" />'; } A: It is obvious that your script will check only for .jpg not for others because you have written statically the file extension. $file = 'images/img_' . $post->_id . '.jpg'; ^ Now Make change in this line to make available the extension dynamically. I am supposing that you are storing the image name with extension than: $file = 'images/img_' . $post->_id . $post->image_name; Note : $post->image_name should be like : $post->image_name = abc.png (image_name.extension);
{ "language": "en", "url": "https://stackoverflow.com/questions/24142209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the importance of watch command in ExtJS I am using ExtJS 5 to create a web application. I am also using sencha app build command to create the production build. During development I never use sencha app watch or sencha app build commands. I just do the changes in the application code and in our web server's(tomcat) server.xml file I have given context path of the application code root folder. I just start the tomcat server and load the context by giving the context path. Now i want to know what is the use of sencha app watch command and what are the benefits that developer is going to get using watch command. A: Well, besides providing a web server, the watch command does two main things: * *it rebuilds your bootstrap.js file continuously. *it provides a Fashion server If you're trying to change the CSS for your app, by introducing a custom theme, then using Fashion and sencha app watch is a massive time saver. You can also use Tomcat and sencha app watch in parallel, by making your Tomcat instance a proxy to the sencha app watch version.
{ "language": "en", "url": "https://stackoverflow.com/questions/38436711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to write cell array to text file MATLAB, error with dlmwrite I understand that this is a recurrent topic, I have tried understanding the answers that people provided but none of them seemed easy to transfer to my particular problem as the solutions are usually for an implementation that is too far from what I'm trying to do Could anyone help with the following. When I run the code below I get: Error using dlmwrite (line 118) The input cell array cannot be converted to a matrix. Error in GAVNeuroScan (line 25) dlmwrite(outputfile, CondRowDone); I give an example of what I want to achieve in the comments at the end of the code. If someone can help me getting the contents of CondRowDone to a text file as exemplified in the comments that would be great! studyname='TestGav'; subjects={'504','505'}; conditions={'HighLabel','LowLabel','HighSound','LowSound'}; nCond=4; GFPorBMR='GFP'; for curCond=1:length(conditions) for curSubject=1:length(subjects) gavRow{curSubject}=[subjects(curSubject) '-' conditions{curCond} '-' GFPorBMR '.avg']; end CondRowDone{curCond,:}=['GROUPAVG' '{' gavRow '}' 'G Y 1 N N' conditions{curCond} 'avg.']; end outputfile = [studyname '_GAV_' curSubject '.txt']; dlmwrite(outputfile, CondRowDone); % What I want is a text file that would look exactly like that. I think I'm % not far but it fails to write... % % GROUPAVG {{HighLabel-504-GFP.avg} {HighLabel-505-GFP.avg}} G Y 1 N N {HighLabel.avg} % GROUPAVG {{LowLabel-504-GFP.avg} {LowLabel-505-GFP.avg}} G Y 1 N N {LowLabel.avg} % GROUPAVG {{HighSound-504-GFP.avg} {HighSound-505-GFP.avg}} G Y 1 N N {HighSound.avg} % GROUPAVG {{LowSound-504-GFP.avg} {LowSound-505-GFP.avg}} G Y 1 N N {LowSound.avg} A: From what I have seen using the debugger, you have a little bit of confusion between the curly braces as text and the curly braces to handle MATLAB cell arrays. Here is a re-write of your for-loop to produce the cell array of strings you have given in your code example. Also, to produce the exact output you specified, subject and condition have to be given in a different order: for curCond=1:length(conditions) gavRow = []; for curSubject=1:length(subjects) if (curSubject ~= 1) gavRow = [gavRow ' ']; end gavRow = [gavRow '{' [conditions{curCond} '-' subjects{curSubject} '-' GFPorBMR '.avg'] '}']; end CondRowDone{curCond}=['GROUPAVG ' '{' gavRow '} ' 'G Y 1 N N {' conditions{curCond} '.avg}']; end As for the task of writing the strings to disk, MATLAB is telling you that it cannot handle your cell array as a matrix. When it comes to write cell arrays to disk, I think you have to write it yourself using low-level functions, like this: outputfile = [studyname '_GAV_' curSubject '.txt']; fid = fopen(outputfile, 'w'); for i=1:length(CondRowDone) fprintf(fid, '%s\n', CondRowDone{i}); end fclose(fid); A: dlmwrite only handles numeric data. One way around this, if you have Excel, would be to use xlswrite - it can take in (some kinds of) cell arrays directly. xlswrite(outputfile, CondRowDone); Then, do some batch xls to csv conversion (for example, see this question and answers). To get a text file directly you'll need to use lower level commands (as in blackbird's answer).
{ "language": "en", "url": "https://stackoverflow.com/questions/21511225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Security Best Practices for Email-based User Registration? I have a website, and want to register new users. The registration process is as follows: * *User enters email address, clicks 'Register' *email address is sent to server *Server generates a registration code, stores a hashed version *Server sends an email containing a link: confirm?code=<reg_code> *User checks email, clicks link *Server receives request, confirms validity of code *Server stores email address as a user id *Server issues token, stores token, sends response with token *User's browser stores token as a cookie *Cookie is used as a Bearer token for authentication in subsequent requests. I was wondering if there is any way to improve the security of this approach. Here are some considerations: * *Manual cut-and-paste of code, with session-id check In step 4, instead of providing a link confirm?code=<reg_code>, the email could contain a link to a 'code submission' page which says "Please cut-and-paste the code in your email here, and click submit". This way, javascript could grab a session cookie that was previously generated and stored during step 1. Then, the server could validate that the session cookies match between requests. * *2FA After the user clicks the original email link, the system could ask for a second factor confirmation. It seems that the Manual cut-and-paste with session-id check takes care of a stolen email scenario, because that would fail the session-id check. And, 2FA requires the hacker to hack a second channel, or to steal a device. Both of these measures seem extremely secure. However, the Manual cut-and-paste is onerous for the user, and the 2FA is annoying because it must ask the user for a phone number or to install some authenticator app. Is there any other way?
{ "language": "en", "url": "https://stackoverflow.com/questions/57585038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I set credentials for Symfony plugins? I have a backend with SfGuard, and I have plugins like sfGuard, which have modules. How do I change their security settings? they don't have folders in my backend app where I could put a security.yml. A: Create module which you would like to secure, for example /app/backend/modules/sfGuardRegister After that you can secure the module with creating /module_path/config/security.yml and configure credentials. I have not tryed that beheivour with security.yml, but I've rewroten the templates, actions, components. It should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/5636406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass List through activities ArrayList<Item> arrayOfList; I want to pass arrayOfList; to next activity on Itemclick of listview Tried Things Intent sec = new Intent(this, IndividualPage.class); Bundle b = new Bundle(); b.putParcelableArrayList("mylist", arrayOfList); sec.putExtras(b); To retrieve the arraylist Bundle b = this.getIntent().getExtras(); ArrayList<Item> cats = b.getParcelableArrayList("mylist"); System.out.println(cats); But i am getting null in console. Is there any other efficient way to pass the data. Item.java public class Item implements Parcelable { private String Name; private String Location; private String Image; private String Sector; private int Founded; private String Status; private int RowVAls; public String getName() { return Name; } public void setName(String Name) { this.Name = Name; } public String getLocation() { return Location; } public void setLocation(String Location) { this.Location = Location; } public String getImage() { //return "http://23.253.164.20:8099/"+Image; return "http://23.253.164.20:8099/"+Image; } public void setImage(String Image) { this.Image = Image; } public String getSector() { return Sector; } public void setSector(String Sector) { this.Sector = Sector; } public int getFounded() { return Founded; } public void setFounded(int Founded) { this.Founded = Founded; } public String getStatus() { return Status; } public void setStatus(String Status) { this.Status = Status; } public int getRowVAls() { return RowVAls; } public void setRowVAls(int RowVAls) { this.RowVAls = RowVAls; } protected Item(Parcel in) { Name = in.readString(); Location = in.readString(); Image = in.readString(); Sector = in.readString(); Founded = in.readInt(); Status = in.readString(); RowVAls = in.readInt(); } @SuppressWarnings("unused") public static final Parcelable.Creator<Item> CREATOR = new Parcelable.Creator<Item>() { @Override public Item createFromParcel(Parcel in) { return new Item(in); } @Override public Item[] newArray(int size) { return new Item[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(Name); dest.writeString(Location); dest.writeString(Image); dest.writeString(Sector); dest.writeInt(Founded); dest.writeString(Status); dest.writeInt(RowVAls); } Note:- Item is neither Parcelable nor Serializable . And i would not like to make any changes in that. A: You should make your Item implement Parcelable. Try this site to make your Item Parcelable A: Item is neither Parcelable nor Serializable . And i would not like to make any changes in that. then you can't. I would strongly recommend you to look into the Parcelable interface, avoiding tricks like making the field public static A: As others have said, you can't do it properly without implementing parcelable - which sometimes isn't possible. You're only other option is to architect a way in which you can put your list in a static context so it's accessible from wherever. You could create a singleton SparseArray and related integer, and pass around the integer between activities describing the position in the SparseArray. You'd just have to ensure that you incremented your integer and removed the item from the SparseArray once you'd grabbed it. Off the top of my head - private class ComplexObjectPassing { private static SparseArray<Object> sArray = new SparseArray<Object>(); private static int count = 0; public static int putObject(Object obj) { count++; sArray.put(count, obj); } public static Object getObject(int index) { Object obj = sArray.get(index); sArray.put(index, null); return obj; } } Obviously, this would end with a huge memory leak when you passed things and they weren't pulled out by the new activity. All of the alternatives are going to have downsides and need to be carefully managed to reduce inevitable problems.
{ "language": "en", "url": "https://stackoverflow.com/questions/31556866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a java program that calculates fares for a toll road I am having a hard time getting started with this program. It is supposed to promped user for vehichle typ, number of miles to be traveled, and whether or not they have an EZ-Pass. then calculate and print vehicle type, number of miles traveled, whether or not they have an EZ-Pass, and the fare collected. toll road spans 76.4 miles. Fares for the toll road are calculated based on vehicle type: Motorcycle – Flat Fee of $1.06 Car - $0.05 per mile SUV - $0.08 per mile Truck - $0.14 per mile Vehicles having an E-ZPass attached to them earn a 10% discount off their fare. After the user has indicated they wish to exit the program (this is the only way the program should exit), the program will display a report containing a list of each vehicle type and the number of fares collected for that vehicle type, the total number of vehicles, the number of vehicles that used an E-ZPass, and the total fare collected across all vehicles. I tried using if statements but wasn't happy with the result, maybe for statements fit it better? Thanks for reading A: Try starting with a defining diagram that helps you identify the problem you're trying to solve, continuing through the remaining steps of the problem solving process. This will yield a much better result than jumping immediately to coding and posting algorithm questions on Internet forums (which by the way, violates the Honor Code). Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/28567786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: when sending strings via put extra the underline under some words has gone when I send strings via put extra the underlined words will not be underlined <string name="s_hello_txt">\n{ <u>hello all</u> }\n</string> MainActivity Button Code public void c_hello(View v){ Intent hello= new Intent(MainActivity.this, MainTextActivity.class); intent_collection_e3tiraf.putExtra("key",getResources().getString(R.string.s_hello_txt)); startActivity(hello); finish(); } MainActivityText onCreate Code textview = (TextView) findViewById(R.id.id_text_txt); Intent n = getIntent(); String mrng = n.getStringExtra("key"); textview.setText(mrng); if I put a text with direct string it will be underlined For Example if I put in the layout of MainActivityText(activity_maintext.xml) <TextView android:id="@+id/id_dailyprayers_txt" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/s_hello_txt" android:textSize="30sp" /> the textview in MainActivityText Show the text(hello all) underlined any help!!!! A: As long as the string still has the underline html you should be able to utilize the Html.fromHtml method to style the string. textview.setText(Html.fromHtml(mrng)); A: Actually, the string getResource().getString(R.string.s_hello_txt) is not be underlined. The best way to add html source code in strings.xml is to use <![CDATA[html source code]]>. Here is an example: <string name="s_hello_txt"><![CDATA[<u>Text</u>]]></string> And then use Html.fromHtml(mrng) to show the underlined string A: // Try This One This Will Help For Your Acheivement **String.xml** <string name="s_hello_txt">&lt;br/>{ &lt;u>hello all&lt;/u> }&lt;br/></string> **activity_main1.xml** <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/txtValue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/s_hello_txt"/> <Button android:id="@+id/btnClick" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GoTo Second Activity"/> </LinearLayout> **MainActivity1 Activity** public class MainActivity1 extends Activity { private Button btnClick; private TextView txtValue; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main1); txtValue = (TextView)findViewById(R.id.txtValue); btnClick = (Button)findViewById(R.id.btnClick); txtValue.setText(Html.fromHtml(getString(R.string.s_hello_txt))); btnClick.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(MainActivity1.this, MainActivity2.class); intent.putExtra("EXTRA",getString(R.string.s_hello_txt)); startActivity(intent); } }); } } **activity_main2.xml** <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/txtValue" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> **MainActivity2 Activity** public class MainActivity2 extends Activity { private TextView txtValue; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); txtValue = (TextView)findViewById(R.id.txtValue); txtValue.setText(Html.fromHtml(getIntent().getStringExtra("EXTRA"))); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/18675126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IPython import error - pattern I'm a newbie to IPython/Anaconda (for Windows 7), and for some reason, I'm getting an import error: --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-6-484073d472a5> in <module>() 6 import matplotlib.pyplot as plt 7 import requests ----> 8 import pattern ImportError: No module named pattern Here's what I did to set up Anaconda/IPython: * *Installed Anaconda. I already have a version of python on this computer. The Anaconda distribution was installed to C:\Users\MyName, while the regular python distribution (2.7) was installed to C:\Python27. *When I tried to import some packages (sklearn, pandas, requests, pattern), for some reason those packages just wouldn't import so I installed them manually (downloading them to a local folder on my desktop and running $ python setup.py install, and after that it all seemed to work). *I can run IPython notebooks fine. However, when I try to import pattern specifically, I get that error (which I don't get for sklearn or any of the other packages I installed manually). Printing my sys path from the terminal (import sys print sys.path) and IPython notebook gives: Terminal: ['C:\\Users\\MyName\\Desktop\\Data Science\\cs109\\Labs', 'C:\\python27\\lib\\site- packages\\mrjob-0.4.2_dev-py2.7.egg', 'C:\\python27\\lib\\site- packages\\simplejson-3.3.1- py2.7.egg', 'C:\\python27\\lib\\site-packages\\pyyaml-3.10-py2.7-win32.egg', 'C:\\python27\\lib\\site-packages\\boto-2.18.0-py2.7.egg', 'C:\\python27\\lib\\site-packages\\requests-2.0.1-py2.7.egg', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\lib\\site-packages\\Orange\\orng', 'C:\\python27\\DLLs', 'C:\\python27\\lib', 'C:\\python27\\lib\\plat-win', 'C:\\python27\\lib\\lib-tk', 'C:\\python27', 'C:\\python27\\lib\\site-packages', 'C:\\python27\\lib\\site- packages\\PIL', 'C:\\python27\\lib\\site-packages\\win32', 'C:\\python27\\lib\\site- packages\\win32\\lib', 'C:\\python27\\lib\\site-packages\\Pythonwin'] IPython notebook: ['', 'C:\\Users\\MyName\\Anaconda\\python27.zip', 'C:\\Python27\\lib\\site- packages\\Orange\\orng', 'C:\\Users\\MyName\\Anaconda\\DLLs', 'C:\\Users\\MyName\\Anaconda\\lib', 'C:\\Users\\MyName\\Anaconda\\lib\\plat-win', 'C:\\Users\\MyName\\Anaconda\\lib\\lib-tk', 'C:\\Users\\MyName\\Anaconda', 'C:\\Users\\MyName\\Anaconda\\lib\\site-packages', 'C:\\Users\\MyName\\Anaconda\\lib\\site-packages\\PIL', 'C:\\Users\\MyName\\Anaconda\\lib\\site-packages\\win32', 'C:\\Users\\MyName\\Anaconda\\lib\\site-packages\\win32\\lib', 'C:\\Users\\MyName\\Anaconda\\lib\\site-packages\\Pythonwin', 'C:\\Users\\MyName\\Anaconda\\lib\\site-packages\\setuptools-0.6c11-py2.7.egg- info', 'C:\\Users\\MyName\\Anaconda\\lib\\site-packages\\IPython\\extensions'] If I do import pattern print pattern It shows that pattern is located at: C:\python27\lib\site-packages\pattern\__init.pyc Any thoughts as to why IPython can't import pattern? A: I struggled with this - I kept getting an error saying package couldn't be found. Running below in command prompt worked for me. conda install -c asmeurer pattern=2.5 A: On windows, open cmd.exe and type: conda install pattern This should do it ;) A: Sometimes this happens when you have multiple versions of Python/Anaconda installed on your machine. As the Pattern package does not run on Python 3.4, you need to launch IPython Notebook from the Anaconda server that runs Python 2.7. So the first step is to make sure that you install the Pattern package using pip in the version of Anaconda that runs Python 2.7. For example, C:\Users\MyName\Anaconda\Scripts\pip install pattern The second step is to make sure that you run ipython notebook from the correct path. For example, C:\Users\MyName\Anaconda\Scripts\ipython notebook That should do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/20274124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to pass operators like "<",">","=" (less than,greater than,equals to) as parameters to a native query in springboot? For example let my query be as shown below: String query="select * from table_name where column_name1 > ?1 and column_name2 < ?2"; @Query(value = query, nativeQuery = true) public List<Object[]> getResult(String filterValue1,Integer filterValue2); how to pass the operator(<,>,=) also as a parameter? I am using postgreSQL database. Thank you. A: If you have an option to construct/concat a String prior to run the query, there is no problem: public String methodOne(String firstOperator , String secondOperator) { return "select * from table_name where column_name1 " + firstOperator + " ?1 and column_name2 " + secondOperator +" ?2"; } It is more complicated if you use SpringData repositories. There isn't a lot you can do with native queries parameters because SpringData is looking for native SQL operators inside the query string. But you can try to do some tricks with LIKE operator and built-in functions (in SQL, sometimes >,< can be replaced with LIKE) (not completely an answer to your question, but) A condition that can be omitted @Query(value = ... AND column_name LIKE IIF(:myParam <> '%', :myParam,'%') <skipped> ... repositoryMethod(@Param("myParam") String myParam); IIF - a ternary operator function in MSSQL, you can find something like this in your RDBMS when you send myParam='actualValue' it will be transformed into and column_name LIKE 'actualValue' i.e. column_name='actualValue' when you send myParam='%' it will be transformed into and column_name LIKE '%' i.e. "and TRUE"
{ "language": "en", "url": "https://stackoverflow.com/questions/64467900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: video-stabilization
{ "language": "en", "url": "https://stackoverflow.com/questions/65919398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress Pagination not work in category page I want to display pagination on category pages of WordPress theme This is my code global $post; $category = get_the_category($post->ID); $category = $category[0]->cat_ID; $posts = get_posts(array( 'numberposts' => 150, 'posts_per_page'=>16, 'offset' => 0, 'category__not_inint' => array($category), 'post_status'=>'publish', 'order'=>'ASC' )); foreach($posts as $post){ setup_postdata($post); $city_name = get_field( "city-name" ); $display = '<a href="' . get_permalink() . '">' . $city_name . '</a>'; } the_posts_pagination(); wp_reset_query(); return $display; and displays the pagination. But the results of all pages are similar to the first page. A: You shouldn't be using get_posts if you need the query to be paginated. Whilst it can be done, this is a total ball ache to achieve. Instead, you should be looking at WP_Query. Further reading on WP_Query - WP_Query @ wordpress.org Your code could look something like the following; <?php $paged = (get_query_var('page')) ? get_query_var('page') : 1; // explain to wordpress we need this paged $wp_query = new WP_Query(array( // the query 'post_type' => 'post', 'post_category' => '', 'post_status' => 'publish', 'numberposts' => 150, 'posts_per_page' => 15, //'orderby' => 'title', 'order' => 'ASC', 'paged' => $paged)); while ($wp_query->have_posts()) : $wp_query->the_post(); // the loop // some code to make it look pretty ?> <div class="post-grid"> <a href="<?php the_permalink(); ?>"> <h3 class="card-title"><?php the_title(); ?> </h3> </a> </div> <?php endwhile; echo ( paginate_links($args = array( 'base' => site_url().'%_%', // site_url prefix is needed for pagination on homepage 'format' => '?page=%#%', 'total' => $wp_query->max_num_pages, 'current' => $paged, 'show_all' => false, 'end_size' => 2, 'mid_size' => 2, 'prev_next' => true, 'prev_text' => 'Prev', 'next_text' => 'Next', 'type' => 'list', 'add_args' => false, 'add_fragment' => '' ))); wp_reset_query();
{ "language": "en", "url": "https://stackoverflow.com/questions/74262711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why when i debug my value option tag html is undefined? I've tried debugging the following error for several hours with no solution JS is still undefined but id parameter in controller has a value. Please help. I need it. This html code when i debug, the value is undefined, why the value is undefined? <select id="cmbTipe" class="form-control"> <option value="-1">Select Jenis</option> <option value="undefined">undefined</option> <option value="undefined">undefined</option> </select> My Controller namespace PerhitunganKeuntunganParkir.Controllers{ public class ParkirController : Controller { private readonly JenisKendaraanRepository _jeniskendaraanRepository = null; private readonly TipeKendaraanRepository _tipekendaraanRepository = null; private readonly ParkirContext _context = null; //Dependency Injection public ParkirController(JenisKendaraanRepository jenisKendaraanRepository, TipeKendaraanRepository tipeKendaraanRepository, ParkirContext context) { _jeniskendaraanRepository = jenisKendaraanRepository; _tipekendaraanRepository = tipeKendaraanRepository; _context = context; } public async Task<ViewResult> GetAllJenis() { ViewBag.Jenis = await _jeniskendaraanRepository.GetJenisKendaraan(); return View(); } public IActionResult LoadTipeC(int jenisId) { return Json(_context.TipeKendaraan.Where(s=>s.JenisKendaraanId == jenisId).Select(s=> new TipeKendaraanModel{ Id = s.Id, Tipe=s.Tipe }).ToList()); } My View In HTML my cascading dropdown the value is undefined, why does this happen? The JavaScript is working but the value is undefined in HTML @{ ViewData["Title"] = "Input Form"; @model JenisKendaraanModel <div class="container"> <form method="post" asp-action="GetAllJenis" asp-controller="Parkir"> <div class="form-group"> <label asp-for="Jenis"></label> <select id="cmbJenis" class="form-control"> <option value="-1">Select Jenis</option> @foreach (var jenis in ViewBag.Jenis) { <option value="@jenis.Id">@jenis.Jenis</option> } </select> <span asp-validation-for="Jenis" class="text-danger"></span> </div> <div class="form-group"> <select id="cmbTipe" class="form-control"> </select> </div> <script src="~/lib/jquery/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $('#cmbJenis').on('change', function () { var jenisId = $('#cmbJenis option:selected').val(); $.ajax({ type: 'GET', data: { jenisId: jenisId }, url: '@Url.Action("LoadTipeC","Parkir")', success: function (result) { //var tipe = JSON.parse(result); var s = '<option value="-1">Select tipe</option>'; for (var i = 0; i < result.length; i++) { s += '<option value="' + result[i].Id + '">' + result[i].Tipe + '</option>'; } $('#cmbTipe').html(s); } }); }); }); </script> </form> </div> A: After my test, I found that your problem may lie in your Js. Try to change your code: for (var i = 0; i < result.length; i++) { s += '<option value="' + result[i].Id + '">' + result[i].Tipe + '</option>'; } To for (var i = 0; i < result.length; i++) { s += '<option value="' + result[i].id + '">' + result[i].tipe + '</option>'; } id and tipe the first letter should be lowercase.
{ "language": "en", "url": "https://stackoverflow.com/questions/65582220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: change output directory of nuget package I created a NuGet package from my project. The output directory of the package is the solution directory. I would like to output it to a specific directory. I tried a target in the csproj file and in the nuspec file. None worked. How do I get the package generated in the specified folder? In my .csproj: <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild"> <PropertyGroup> <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText> </PropertyGroup> <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" /> </Target> In my .nuspec: <?xml version="1.0"?> <package > <metadata> <id>MyPackage.dll</id> <version>1.0.0</version> <authors>me</authors> <owners>me</owners> <requireLicenseAcceptance>false</requireLicenseAcceptance> <description>Package description</description> <releaseNotes>Summary of changes made in this release of the package.</releaseNotes> <copyright>Copyright 2016</copyright> <files> <file src="bin\MyPackage.dll" target="C:\LocalPackageRepository" /> </files> </metadata> </package> A: In the 'old' way of NuGet (which you seem to use, check this for info on new vs old) this was possible by using the command in the .nuget\NuGet.targets file you mention. If you change the line with PackageOutputDir to below it will work. <PackageOutputDir Condition="$(PackageOutputDir) == ''">C:\LocalPackageRepository</PackageOutputDir> Even better would be to set a property on the PropertyGroup in the .csproj like this: <PackageOutputDir>C:\LocalPackageRepository</PackageOutputDir> In the new way of NuGet you would add this key to the NuGet.config file: <add key="repositoryPath" value="C:\LocalPackageRepository" /> A: Not sure why the global config settings didn't work for me, but adding below solution solved my problem: * *Create an environment variable under user variables: Variable name: MyNugetsOutput Variable value: D:\myteam\teampackages * *Then add below settings to .csproj file: <Target Name="CopyPackage" AfterTargets="Pack"> <Copy SourceFiles="$(OutputPath)\$(PackageId).$(PackageVersion).nupkg" DestinationFolder="$(MyNugetsOutput)\$(PackageId).$(PackageVersion).nupkg" /> </Target> reference: Target build order Update Currently I'm using below code, it is simpler but it copies all .nupkg files to the "Local" path <Target Name="AfterPack" AfterTargets="Pack"> <Exec Command="dotnet nuget push $(PackageOutputPath)*.nupkg --source Local" /> </Target> A: You cannot do this from the .nuspec file. You can create a NuGet.Config file and define a global packages directory for all solutions: <configuration> <config> <add key="repositoryPath" value="C:\myteam\teampackages" /> </config> ... </configuration> This is done outside the .nupkg file and stored either under your profile or in a subdirectory which is a parent to all the directories containing your solutions. See the NuGet documentation for more details on this feature.
{ "language": "en", "url": "https://stackoverflow.com/questions/35893005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: When does a javascript function is being executed in a jquery mobile page? I have a php function that, after it did his computations, contains this code: echo("<script> window.location.replace('index.php#login'); </script>"); meant to redirect the page to another, under certain circumstances. The function works, the javascript code works, but if fails in one case. If i write manually the address of the page the javascript part of the code seems not to be executed, while if i manually reload the page (for example using the reload button in firefox) works like a charm. The php function is being executed, with his redirect code, at the beginning of the page index.php in the head section. The page index php is a jquery mobile page, that include every other page of the site, so if i want to call a page, i have to write an address like site.com/index.php#nameOfThePage. The problem happen when i am, for example on a page site.com/index.php#Page1 and i call another Page manually deleting from the address the part "Page1" and writing, for instance, "Page2". Instead, if i reload, the script is being correctly executed. So the question is: when does a javascript function is being executed in a jquery mobile page? What i have to do to make the function works in every way, even manually, a page is called? EDIT: the problem happens in firefox e safari, while with chrome the code works in every case...
{ "language": "en", "url": "https://stackoverflow.com/questions/20492409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to email photo attachment without edit screen I'm trying to send an email with a photo attachment without showing the editor. Eventually I'm trying to make it so when someone logs into the app it will send them an email automatically. My implementation: if let videoConnection = stillImageOutput!.connectionWithMediaType(AVMediaTypeVideo) { videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait //initiates a still image and returns //samplebugger data was captured stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(sampleBuffer, error) in if (sampleBuffer != nil) { var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) //creates core graphics image var dataProvider = CGDataProviderCreateWithCFData(imageData) var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, kCGRenderingIntentDefault) var image = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.Right) //saves image after taken UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) var myController = MFMailComposeViewController() myController.mailComposeDelegate = self myController.setSubject(" Your Sherpa Photo") myController.setMessageBody("hello World", isHTML: false) myController.setToRecipients(["keli5466@colorado.edu"]) var emailimageData = UIImagePNGRepresentation(image) myController.addAttachmentData(emailimageData, mimeType: "image/png", fileName: "image") self.presentViewController(myController, animated: true, completion: nil) } }) } // ... func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) { if result.value == MFMailComposeResultSent.value { let alertView = UIAlertView() alertView.message = "Mail Sent!" alertView.addButtonWithTitle("OK") alertView.show() } self.dismissViewControllerAnimated(false, completion: nil) } A: Short answer: You can't do that, by design. The only way you can send email without display a compose mail view controller is if you have a server that offers mail services, but you will have to collect the user's mail credentials. Apple does not want 3rd party developers sending email from a user's account with the user being the one to click the button and do the sending. This protects the user from apps sending mail without the user's knowledge or permission. Imagine the explosion of spam if this restriction was not in place.
{ "language": "en", "url": "https://stackoverflow.com/questions/31060644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Https request returning error in response 'certificate has expired' for shortswitch api I am making a request to shortswitch api using https package of nodejs. It returns error 'certificate has expired' in response. Shortswitch doesn't have a client-side certificate that we can send with the request. They have a server-side certificate which is valid when verified through an SSL-checker. I am using node version 6.14.0 (since the app is on production and running we can't update node version yet). Any suggestions on how to solve this issue? Code snippet: https.request('https://api.shortswitch.com/shorten?apiKey=****&longUrl=***********&format=json', function(res){ console.log("Connected"); res.on('data',function(data){ console.log(data); }); }); Edit: I added the following cert as per suggested solution. const ISRGCAs = [`-----BEGIN CERTIFICATE-----MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2VhcmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygch77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6UA5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sWT8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyHB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UCB5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUvKBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWnOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTnjh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbwqHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CIrU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkqhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZLubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KKNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7UrTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdCjNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVcoyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPAmRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57demyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=-----END CERTIFICATE-----`]; const options = { host: 'api.shortswitch.com', path: '/shorten?apiKey=***&longUrl=*****&format=json', method: 'GET', port: 443, ca: ISRGCAs } https.request(options, function(res){ var data = []; res.on('data', function(chunk) { data.push(chunk); console.log((Buffer.concat(data)).toString()); }); res.on('end', function() { var buffer = Buffer.concat(data); console.log(buffer.toString()); }); }); but now getting error: A: The API/server is not 'returning' expired; it is using a certificate/chain which your nodejs client is rejecting, because the cert is from LetsEncrypt which by default still uses a 'compatibility' root (DSTX3) that expired last Sept, but which most clients (including the sslchecker you used) can replace with the newer and still-valid ISRG root. nodejs uses OpenSSL with by default its own hardcoded list of CA certs, which in nodejs 6 did not include the ISRG root; further, depending on your system and build, it may be using an older version of OpenSSL which doesn't do the replacement-with-new-root correctly. To solve this problem you must have recentish (>=1.1.0) OpenSSL and add the ISRG root; you can do the latter in code by setting the ca option, or with environment variable NODE_EXTRA_CA_CERTS. See Axios fails with 'certificate has expired' when certificate has not expired LetsEncrypt root certificate expiry breaks Azure Function Node application Giving Axios LetsEncrypt's New Root Certificate On Old Version Of Node
{ "language": "en", "url": "https://stackoverflow.com/questions/71848405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: List of classes and indices for my trained neural network model in keras I have trained the MNIST dataset using the code from https://www.kaggle.com/code/himanshuyadav95627/image-classification, and the model is working perfectly. Now I want to extract the class names and indices from the trained model. Why I need this: I am trying to produce a heatmap. The MNIST data set has handwritten images of the numbers 0 to 9. I believe the classes here will be 0 to 9. My code: jsn_model = model.to_json()# here model is my trained NN model and I am converting to json format clasdf = pd.read_json(jsn_model) # convert it to a dataframe print(clasdf['class_name']) present output: layers Sequential name Sequential Name: class_name, dtype: object Expected output: Class names 0 to 9 and indices 0 to 9 or 1 to 10 For instance, an example class and indices for a known dataset https://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.json
{ "language": "en", "url": "https://stackoverflow.com/questions/74200551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Worksheet Change: Multiple target values not working Need to hide/ unhide rows in a multiple excel sheets based on dropdown cell values in a cell of another sheet. I have 3 sheets, Dashbaord, Data Inputs, Metrics table, I have put the following code in Dashboard sheet. The 3 cells mentioned below are dropdown and contain different set of values. When a user selects one value say in dropdown C4, I'm hiding/ unhiding certain rows in all the 3 sheets mentioned above. But only the select case of cell C4 works fine. As you can see I have formulas for C23 and C32 as well, but it doesn't seem to work, not sure it is due to operations on same sheets Another example, when say I select a dropdown value for Cell C23. The operations listed under C23 below works fine (respective macro is called and rows are hidden/ unhidden). But when I check the earlier selection on Cell value C4 is gone. Please help Private Sub Worksheet_Change(ByVal Target As Range) Dim c As Range If Not Intersect(Target, Range("C4,C23,C32")) Is Nothing Then For Each c In Intersect(Target, Range("C4,C23,C32")) Select Case c.Address(0, 0) Case "C4" If Target.Value = "Ecommerce" Then Call Ecommerce If Target.Value = "Non-Commerce" Then Call NonCommerce If Target.Value = "Ecommerce & Non-Commerce" Then Call Both If Target.Value = "Select Ecommerce/Non-Commerce" Then Call Both Case "C23" If Target.Value = "Select Year" Then Call SelectYear If Target.Value = "2020" Then Call Twentytwenty If Target.Value = "2021" Then Call TwentyOne If Target.Value = "2022" Then Call TwentyTwo If Target.Value = "2023" Then Call TwentyThree If Target.Value = "2024" Then Call TwentyFour If Target.Value = "2025" Then Call TwentyFive Case "C32" If Target.Value = "Select PPC" Then Call SelectPPC If Target.Value = "PPC 2" Then Call PPCTwo If Target.Value = "PPC 3" Then Call PPCThree If Target.Value = "PPC 4" Then Call PPCFour If Target.Value = "PPC 5" Then Call PPCFive If Target.Value = "PPC 6" Then Call PPCSix If Target.Value = "PPC 7" Then Call PPCSeven End Select Next c End If End Sub I want the sheet to operate on all the 3 cells together, right now its broken and only one works at a time. Appreciate your help. A: Reading the comments, it sounds like every time you select a different value from one of the three drop downs, you want to run three macros, depending on the values selected. If that is the case, then you don't need to iterate through the Target cells (only one can be assigned, using the drop down anyway). All you need to do is identify that one of the three cells has been changed and then based on the three specific cells, run the corresponding macros. Private Sub Worksheet_Change(ByVal Target As Range) ' This is all that you have to check, before deciding to run the macros If Intersect(Target, Range("C4,C23,C32")) Is Nothing Then Exit Sub Select Case Range("C4").Value Case "Ecommerce" Call Ecommerce Case "Non-Commerce" Call NonCommerce Case "Ecommerce & Non-Commerce", "Select Ecommerce/Non-Commerce" Both End Select Select Case Range("C23").Value Case "Select Year" Call SelectYear Case "2020" Call Twentytwenty Case "2021" Call TwentyOne Case "2022" Call TwentyTwo Case "2023" Call TwentyThree Case "2024" Call TwentyFour Case "2025" Call TwentyFive End Select Select Case Range("C32").Value Case "Select PPC" Call SelectPPC Case "PPC 2" Call PPCTwo Case "PPC 3" Call PPCThree Case "PPC 4" Call PPCFour Case "PPC 5" Call PPCFive Case "PPC 6" Call PPCSix Case "PPC 7" Call PPCSeven End Select End Sub Or better yet, listen to BruceWayne and you end up with something like this: Private Sub Worksheet_Change(ByVal Target As Range) ' This is all that you have to check, before deciding to run the macros If Intersect(Target, Range("C4,C23,C32")) Is Nothing Then Exit Sub Select Case Range("C4").Value Case "Ecommerce" Ecommerce Case "Non-Commerce" NonCommerce Case "Ecommerce & Non-Commerce", "Select Ecommerce/Non-Commerce" Both End Select If IsNumeric(Range("C23").Value) Then SelectYear CInt(Range("C23").Value) If IsNumeric(Mid(Range("C32").Value, 5)) Then SelectPPC CInt(Mid(Range("C32").Value, 5)) End Sub Sub SelectYear(Year As Integer) ' Do stuff End Sub Sub SelectPPC(Value As Integer) ' Do stuff End Sub FYI, You don't really need to use Call. The only real difference that it makes is whether parenthesis are required or not, when a Sub-routine has parameters.
{ "language": "en", "url": "https://stackoverflow.com/questions/54698357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check if any of the textboxes is empty wpf Is there any way to iterate through all the textboxes to see if any of the textboxes is empty? I want the user to enter values in all textboxes. Suppose the event handler has the following code: private void Add_Click(object sender, RoutedEventArgs e) { //check if textboxes are empty if (/*logic here for checking*/) MessageBox.Show("Please enter values in all the fields"); else {//send values entered to other window. Window1 w1 = new Window1(customername.Text, "", "", "", Phoneno.Text, Symptoms.Text, Total.Text, datepick); this.Hide(); this.Owner.Show(); } } A: This code should work: private void Add_Click(object sender, RoutedEventArgs e) { if (gridcontrol.Children .OfType<TextBox>() .Any(tb => string.IsNullOrEmpty(tb.Text))) { MessageBox.Show("Please enter values in all the fields"); } else { ... } }
{ "language": "en", "url": "https://stackoverflow.com/questions/70200919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Error handling with loop and user input For i = 1 To repNumber TryAgain: On Error GoTo ErrH: repName = InputBox("Enter rep name you want to exclude.", "Name of Rep") .PivotItems(repName).Visible = False Next i ErrH: MsgBox "Try Again" GoTo TryAgain: It shows an error if I type in Rep name that doesn't exist in the PivotTable. So I'm trying to use an error handler to let a user type Rep name again. But after the second time I type something wrong, instead of going to the error handler, the code terminates itself. I'm not sure if 'On Error GoTo' is in the wrong line. A: You can avoid Error Handing and GoTo statements all together (which is definitely best practice) by testing within the code itself and using If blocks and Do loops (et. al.). See this code which should accomplish the same thing: Dim pf As PivotField, pi As PivotItem Set pf = PivotTables(1).PivotField("myField") 'adjust to your needs For i = 1 To repNumber Do Dim bFound As Boolean bFound = False repName = InputBox("Enter rep name you want to exclude.", "Name of Rep") For Each pi In pf.PivotItems If pi.Value = repName Then pi.Visible = False bFound = True Exit For End If Next pi Loop Until bFound = True Next i A: Try Resume TryAgain instead of GoTo TryAgain. (You don't need : in these statements, it is by coincidence allowed because it is also used to seperate multiple statements within a line, so it is just meaningless here).
{ "language": "en", "url": "https://stackoverflow.com/questions/33288604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: App engine - raw request body - stripe webhooks I'm trying to run my node.js app app engine and I am having trouble with stripe webhooks - with the constructEvent, that I need to give a request raw body. Worked on virtual machine but not on app engine. event = stripe.webhooks.constructEvent(req.rawBody, sig, stripeKeys.webhookPaymentIntent); Says: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing A: Just looking at the code that you posted here, I wonder if the last parameter is indeed the value that you wanted to pass to the constructEvent function. it reads webHookPaymentIntent. I wonder if this should really be the webhook signature secret? It may be that it really is the webhook secret value, but just named a bit misleadingly. Maybe this is something though you can verify? A simple test would really to be to pass the string literal here to see if that would work first. Of course make sure not to commit that to any source control. The stripe-node method params are listed here for reference: https://github.com/stripe/stripe-node/blob/1d6207e34f978d8709d42d8a05d7d7e8be6599c7/lib/Webhooks.js#L11
{ "language": "en", "url": "https://stackoverflow.com/questions/59047172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }