text
stringlengths
15
59.8k
meta
dict
Q: Build parent pom and run specific integration test in Jenkins through maven? Executing mvn clean install on my parent pom builds all the sub-modules and runs the related junit tests. It doesn't run the integration tests. After building and running the junits, I want to run a specific integration test in a particular sub-module. I am using following command: mvn clean install -DTest=integrationTestName The job fails with No Test Found error during build phase. I also tried using mvn clean install -DTest=integrationTestName -pl=sub-module-name but this only builds my sub-module having integration test. Question: How to run a single integration test of a certain module? A: I suppose you tried the test option (lower case) of the Maven Surefire Plugin to invoke a specific test, which Surefire couldn't find in the first module of the reactor build and hence fails. I also suppose integration tests are executed by the Maven Failsafe Plugin. If not, they should, as mentioned by official documentation: The Failsafe Plugin is designed to run integration tests while the Surefire Plugin is designed to run unit tests. ... If you use the Surefire Plugin for running tests, then when you have a test failure, the build will stop at the integration-test phase and your integration test environment will not have been torn down correctly. .. The Failsafe Plugin will not fail the build during the integration-test phase, thus enabling the post-integration-test phase to execute. To make it short: it's safer and much more robust to do so. Although the plugin configuration entry for the Maven Failsafe Plugin is also test, its corresponding command line option is it.test, so you should instead run: mvn clean install -Dit.test=SampleIT Where SampleIT is an integration Test (note the standard IT suffix, recognized by default by Failsafe. The official Running a Single Test documentation also provides further details on running single integration tests. Also note: the invocation above will work if you don't have other integration tests in other modules of the build, otherwise it will fail not finding it earlier (before hitting the concerned module). If you are using Surefire to run the concerned integration test (again, you shouldn't) or you have several modules running integration tests, you should then configure a profile in the concerned module which would take care of this specific invocation, something like as following: <profiles> <profile> <id>run-single-it-test</id> <activation> <property> <name>single.it.test</name> </property> </activation> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.19.1</version> <configuration> <test>${single.it.test}</test> </configuration> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> And then invoke the build as following: mvn clean install -Dsingle.it.test=SampleIT As such, Maven will activate the profile based on the existence of a value for the single.it.test property and pass it to the test property of the Failsafe Plugin (or the Surefire, if it was the case), Failsafe will ignore any other integration test for that execution and other modules would not suffer any impact (ignoring that property). A: A_Di-Matteo's answer gets you most of the way there, but you need the following config for maven-surefire-plugin to suppress all the unit tests as well. <profiles> <profile> <id>run-single-it-test</id> <activation> <property> <name>single.it.test</name> </property> </activation> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <skipTests>true</skipTests> <failIfNoTests>false</failIfNoTests> </configuration> <executions> <execution> <goals> <goal>test</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <configuration> <test>${single.it.test}</test> <failIfNoTests>false</failIfNoTests> </configuration> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles>
{ "language": "en", "url": "https://stackoverflow.com/questions/36341830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to 'undraw' an Image? I am trying to make a simple game in Java, All i need to do is draw an im onto the screen and then wait for 5 seconds then 'undraw it'. Code (this class draws the image on the screen): package com.mainwindow.draw; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Timer; import javax.swing.ImageIcon; import javax.swing.JPanel; @SuppressWarnings("serial") public class MainWindow extends JPanel{ Image Menu; String LogoSource = "Logo.png"; public MainWindow() { ImageIcon ii = new ImageIcon(this.getClass().getResource(LogoSource)); Menu = ii.getImage(); Timer timer = new Timer(5, new ActionListener() { public void actionPerformed(ActionEvent e) { repaint(); } }); timer.start(); } public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; g2.drawImage(Menu, 0, 0, getWidth(), getHeight(), null); } } Code #2 (this creates the JFrame) package com.mainwindow.draw; import javax.swing.JFrame; @SuppressWarnings("serial") public class Frame extends JFrame { public Frame() { add(new MainWindow()); setTitle("Game Inviroment Graphics Test"); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(640, 480); setLocationRelativeTo(null); setVisible(true); setResizable(false); } public static void main(String[] args) { new Frame(); } } A: Use some kind of flag to determine if the image should be drawn or not and simply change it's state as needed... @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; if (draw) { g2.drawImage(Menu, 0, 0, getWidth(), getHeight(), null); } } Then change the state of the flag when you need to... Timer timer = new Timer(5, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { draw = false; repaint(); } }); Note: It's not recommended to to override paint, paint is at the top of the paint change and can easily break how the paint process works, causing no end of issues. Instead, it's normally recommended to use paintComponent instead. See Performing Custom Painting for more details Also note: javax.swing.Timer expects the delay in milliseconds...5 is kind of fast...
{ "language": "en", "url": "https://stackoverflow.com/questions/22398145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pass Ionic2 popover ngModel value to and call function in parent Page component? Here's what I am trying to do. * *Putting group radio buttons in the Ionic2 popover menu. *The options are actually controling which JSON file the content is going to load. *User select an option, close the popover, content will update accordingly in the page. I am not sure how to pass value from a Ionic2 Popover to it's parent component. If I understand it correctly Ionic2's Popover is a child component. However I dont know how to pass the [(ngModel)] value out. I know it looks messy here... well if only someones kind enough to make a simple example of how to pass value from PopOver to the Page... So... this all in one file: import {Component, Injectable, Input, Output, EventEmitter} from '@angular/core'; import {ViewController, NavController, Popover, Content, Events, NavParams} from 'ionic-angular'; import {CardService} from '../../providers/card-service/card-service'; import {LangService} from '../../providers/lang-service/lang-service'; import {GlobalService} from '../../providers/global-service'; The Popover component: @Component({template: ` <ion-list radio-group [(ngModel)]="selected" (ionChange)="loadc(selected)"> <ion-item *ngFor="let chapter of menuArray"> <ion-label>{{chapter.ctitle}}</ion-label> <ion-radio value="{{chapter.cchap}}" ></ion-radio> </ion-item> </ion-list> `, providers: [CardService, LangService, GlobalService], directives: [LangService] }) @Injectable() export class ChapterService{ private chpselected : any; private menuArray: any; constructor( private viewCtrl: ViewController, private navController: NavController, public cardService: CardService, public langService: LangService, public globalService: GlobalService ) { this.menuArray = [ { id: 0, cchap: '01', ctitle: 'One', }, { id: 1, cchap: '02', ctitle: 'Two', }, { id: 2, cchap: '03', ctitle: 'Three', }, ]; /// this.chpselected = this.menuArray[0]; /// }; close() { this.viewCtrl.dismiss(); } ///------------------------------- Here I triggers an even when clicking the radio buttons in the popover. I want to call the loadCards() function in the HomePage class below so it returns what is selected and load the correct JSON in the DOM. However I do not how to pass this loadc() value to loadCards(). ///------------------------------- loadc(x){ console.log(x); this.globalService.nowchap = x; }; }; Another Class here, the Page: @Component({ templateUrl: 'build/pages/home/home.html', providers: [CardService, LangService, ChapterService, HomePage, GlobalService], directives: [LangService] }) @Injectable() export class HomePage { /// public cards; public viewmode : any; constructor( private navController: NavController, public cardService: CardService, public langService: LangService, public globalService: GlobalService //public chapterService: ChapterService ){ this.viewmode ="read"; this.loadCards(); }; /* POPOVER*/ presentPopover(myEvent) { let popover = Popover.create(ChapterService); this.navController.present(popover, { ev: myEvent }); } /* Contents are loading here */ public loadCards(x){ console.log("this chp is "+x); this.cardService.load(x) .then(data => { this.cards = data; }); } /* LOAD CARDS ENDED*/ /// } A: No need for Service, it just complicates things.. See complete plunkr here - https://plnkr.co/edit/s6lT1a?p=info it the caller, pass a callback... presentPopover(myEvent) { let popover = Popover.create(PopoverComponent,{ cb: function(_data) { alert(JSON.stringify(_data)) } }); this.nav.present(popover, { ev: myEvent }); } in the popover... constructor(private params: NavParams. /* removed rest for purpose of demo */ ) { this.callback = this.params.get('cb') } public loadc(x) { this.callback(x) // Close the popover this.close(); } A: Here's what I am trying to do. Putting group radio buttons in the Ionic2 popover menu. The options are actually controling which JSON file the content is going to load. User select an option, close the popover, content will update accordingly in the page. You can easily achive that by using a shared service to handle the communication between your popover page and your HomePage. Please take a look at this workin plunker. I've seen you're using a globalService so I propose a small change to make it work like this: import {Injectable} from '@angular/core'; import {Platform} from 'ionic-angular/index'; import {Observable} from 'rxjs/Observable'; @Injectable() export class GlobalService { // Your properties... public getChapterObserver: any; public getChapter: any; constructor(...){ // Your code... // I'm adding an observer so the HomePage can subscribe to it this.getChapterObserver = null; this.getChapter = Observable.create(observer => { this.getChapterObserver = observer; }); } // Method executed when selecting a radio from the popover public selectChapter(chapter : any) { this.getChapterObserver.next(chapter); } } Then, in your PopoverPage: public loadc(x) { // You can call your globalService like this //this.globalService.selectChapter(this.menuArray[this.selected]); // O by simply doing this.globalService.selectChapter(x); // Close the popover this.close(); } So now we're telling our service that the selectChapter has changed. And finally, in your HomePage: constructor(private nav: NavController, private globalService: GlobalService) { // We subscribe to the selectChapter event this.globalService.getChapter.subscribe((selectedChapter) => { this.selectedChapter = selectedChapter; }); } With that, we're subscribing the HomePage to that GlobalService, so when the chapter changes, we're going to be noticed and we can handle that as we want.
{ "language": "en", "url": "https://stackoverflow.com/questions/38489737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do i add an image to an element using javascript I basically have this link, where when i click it, i want an image to show over it. Using javascript how can i do this? <a> click me </a> css: a.clicked { /*what goes here?*/ } A: Adding a new image element is pretty easy: // Append an image with source src to element function appendImage(element, src, alt) { // DOM 0 method var image = new Image(); // DOM 1+ - use this or above method // var image = document.createElement('img'); // Set path and alt properties image.src = src; image.alt = alt; // Add it to the DOM element.appendChild(image); // If all went well, return false so navigation can // be cancelled based on function outcome return false; } so in an A element: <a onclick="appendImage(this, 'foo.jpg', 'Picture of foo');">Add an image</a> If the A is a link and you wish to cancel navigation, return whatever the function returns. If the function doesn't return false, the link will be followed and should provide equivalent functionality: <a href="link_to_picture or useful page" onclick=" return appendImage(this, 'foo.jpg', 'Picture of foo'); ">Add an image</a> A: You should use like this. There are several other good methods, this is just for simplicity and understanding purpose <body> <a onClick='ChangeImage(this);return false'> Click Me <a> </body> <script> function ChangeImage(obj) { obj.innerHTML = "<img src='imangename.jpg'>"; } </script> A: The javascript plugin you may need is Highslides, Check here for examples. Download highslides here. A: First, you'll probably want to give the link an ID. <a id="click-me">Click me!</a> Then for the JavaScript.. document.getElementById('click-me').addEventListener('click', function () { var image = new Image(); image.src = "your-picture.jpeg/png/whatever"; this.appendChild(image); });
{ "language": "en", "url": "https://stackoverflow.com/questions/6119315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Filtering file in unix using grep/sed/awk other? I have gigantic error log files that show errors encountered on a dataload. I need to report errors that are NOT unique constrain violations, but searching through the files manually are impractical due to their size. The log file: Record 1: Rejected - Error on table DMT_. ORA-00001: unique constraint (DM.DMT__PK) violated Record 2: Rejected - Error on table DMT_. ORA-01400:cannot insert NULL in to("DM"."DMT_INSURANCE"."INSURANCE_FUND_CODE") Record 3: Rejected - Error on table DMT_. ORA-00001: unique constraint (DM.DMT__PK) violated Record 4: Rejected - Error on table DMT_ADDRESS, column ORIGINAL_POSTCODE. ORA-12899: value too large for column "DM"."DMT_ADDRESS"."ORIGINAL_POSTCODE" (actual: 12, maximum: 10) Desired output file is Record 2: Rejected - Error on table DMT_. ORA-01400:cannot insert NULL in to("DM"."DMT_INSURANCE"."INSURANCE_FUND_CODE") Record 4: Rejected - Error on table DMT_ADDRESS, column ORIGINAL_POSTCODE. ORA-12899: value too large for column "DM"."DMT_ADDRESS"."ORIGINAL_POSTCODE" (actual: 12, maximum: 10) I'm pretty sure this can be done in grep, sed or awk, but I'm new to this sort of thing...I'd really appreciate a pointer or two. A: Use grep. You don't want the lines that would be produced by: grep -B1 "unique constraint.*violated" filename Now eliminate these lines from the input: grep -v -f <(grep -B1 "unique constraint.*violated" filename) filename and you get the result: Record 2: Rejected - Error on table DMT_. ORA-01400:cannot insert NULL in to("DM"."DMT_INSURANCE"."INSURANCE_FUND_CODE") Record 4: Rejected - Error on table DMT_ADDRESS, column ORIGINAL_POSTCODE. ORA-12899: value too large for column "DM"."DMT_ADDRESS"."ORIGINAL_POSTCODE" (actual: 12, maximum: 10 (This assumes that the Record ... and ORA-... are on different lines. If those are on the same line, grep -v "unique constraint.*violated" filename would work!) A: If you have perl available you can use its paragraph mode: $ perl -00 -ne 'print unless /unique constraint/m;' < foo.input Record 2: Rejected - Error on table DMT_. ORA-01400:cannot insert NULL in to("DM"."DMT_INSURANCE"."INSURANCE_FUND_CODE") Record 4: Rejected - Error on table DMT_ADDRESS, column ORIGINAL_POSTCODE. ORA-12899: value too large for column "DM"."DMT_ADDRESS"."ORIGINAL_POSTCODE" (actual: 12, maximum: 10) Same using awk: $ awk -v RS= '!/unique constraint/' foo.input Record 2: Rejected - Error on table DMT_. ORA-01400:cannot insert NULL in to("DM"."DMT_INSURANCE"."INSURANCE_FUND_CODE") Record 4: Rejected - Error on table DMT_ADDRESS, column ORIGINAL_POSTCODE. ORA-12899: value too large for column "DM"."DMT_ADDRESS"."ORIGINAL_POSTCODE" (actual: 12, maximum: 10) A: Here is a possible solution using Perl-regex (with negative lookahead) to exclude the ORA-00001 and then get the line before the matching ORAs too (-B1): grep -B1 -P 'ORA\-(?!00001)' logfile A: This might work for you (GNU sed): sed '/^Record/{N;N;/\nORA-00001:/d}' logfile Read 3 lines for each record and if those lines contain the undesired code delete them. If more filtering is needed, further codes may be added before the enclosing }. A: One way using sed. For every field that begins with Record read next one and try to match the string unique .... If it doesn't suceed, print both adding a newline. sed -n '/^Record/ { N; /unique constraint .* violated/! { s/$/\n/; p } }' infile It yields: Record 2: Rejected - Error on table DMT_. ORA-01400:cannot insert NULL in to("DM"."DMT_INSURANCE"."INSURANCE_FUND_CODE") Record 4: Rejected - Error on table DMT_ADDRESS, column ORIGINAL_POSTCODE. ORA-12899: value too large for column "DM"."DMT_ADDRESS"."ORIGINAL_POSTCODE" (actual: 12, maximum: 10)
{ "language": "en", "url": "https://stackoverflow.com/questions/17986185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does the MessagePack error extension (0x03) have top-level MP_MAP? In Tarantool 2.4.1, a new MessagePack extension was introduced to serialize errors. At the very top level of the extension body there is a map with only one element, an error stack (an array consisting of error maps). I wonder if this top-level map can contain more than one element, and if not, why it is needed at all? Why not just have an error stack as the extension body? A: Short answer. Currently (in 2.4.1) it contains only one field, IPROTO_ERROR_STACK (0). But in future more fields may be added to this map. The format of MP_MAP with a single key is chosen for better extendibility. All connectors should be able to parse IPROTO_ERROR_STACK key, and skip any other key. So even if in future Tarantool versions new fields are added to the map, the old connectors still would be able to parse responses. Long answer. In Tarantool most of the responses of the binary protocol (IProto) have form of a MessagePack map: MP_MAP. Even if there is just 1 or 2 fields in this map, it is still MP_MAP, not an MP_ARRAY, and of course not just a non-formatted byte array. Some such responses exist for many years. There appear lots of connectors to Tarantool, which are able to send/receive and parse responses from Tarantool in IProto protocol. And when it becomes necessary to change something in these responses after all the years of exploitation with all the created software to handle the responses, the MP_MAP comes in hand. With MP_MAP it is easy to add new fields into the response not breaking all the old connectors. Assuming that they are ready that some new unknown keys may be received, and they just skip them. This is why MP_MAP is used in Tarantool a lot as a top level of response type. It is easy to extend and not break old code. Error MessagePack format, with IPROTO_ERROR_STACK, is MP_MAP by the same reason. In future there may be added more keys to the error object.
{ "language": "en", "url": "https://stackoverflow.com/questions/62052725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a limit to displaying columns for results in HUE? I only get the first 10 columns displayed in results in HUE, and the next columns greyed out. Is this an expected behavior in HUE interface ? If so, is there a configuration to override this ? Thanks, Parag Checked hue.ini configuration file to see if there is a config to override this.
{ "language": "en", "url": "https://stackoverflow.com/questions/57516454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you overload an operator in swift? Say you have a class C. It has two instance variables, number and vector. vector is just an array of either ints or doubles. I would like to do the following: c1 = C() c1.number = 2 c1.vector = [1,2,3] c2 = C() c2.number = 3 c2.vector = [4,6,7] println(c1.number + c2.number) \\print to screen 5 println(c1.vector + c2.vector) \\ print [5,8,10] Basically, I'm looking to overload the "+" operator so that it knows which "version" of the "+" to use depending of the type. A: The + operator is already defined for the type Array. It does an array merge and tacks the values of the rvalue onto the lvalue. To do a sum of values by index you can do something like this: protocol Numeric { } extension Double: Numeric {} extension Int: Numeric {} func +<T: Numeric>(left: [T], right: [T]) -> [T]? { var numElements: Int = 0 if count(left) != count(right) { return nil } else { numElements = count(left) } var result = [T]() for var i = 0; i < numElements; ++i { if let lvalue = left[i] as? Int, rvalue = right[i] as? Int { result.append(lvalue + rvalue as! T) } else if let lvalue = left[i] as? Double, rvalue = right[i] as? Double { result.append(lvalue + rvalue as! T) } } return result } But generally, I wouldn't advise overriding a predefined operator because of the high potential to cause confusion and chaos later on down the road.
{ "language": "en", "url": "https://stackoverflow.com/questions/28552379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Matlab, how to iterate over a multi dimentional array I am trying this code arr = [[400, 200], [100, 50]] for a = arr a(2) % Should display the 2nd element of the sub-array end but I get: Index exceeds the number of array elements (1) Any idea ? A: Solution is to define arr differently, i.e.: arr = [400 200; 100 50];
{ "language": "en", "url": "https://stackoverflow.com/questions/67619618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I deny access to a symmetric key alias in SQL Server? I have a table with some encrypted data: select * from Test1; that yields some rows with garbage data that I created... two rows, both with a name and ciphertext, created by the following command, issued twice with slight variation: insert into Test1 values ('travis', ENCRYPTBYKEY(key_guid('aes128'), convert(varchar, 1234567))); The key was created on the EKM device and aliased in SQL by the following: create symmetric key aes128 from provider EKMProvider with provider_key_name = 'aes128', creation_disposition = open_existing; I have two users: a user (administrator) that I want to have unfettered access with full permissions over SQL Server granted, and a second user (restrictedsql) that I want to deny access to this encryption key. Now, if I attempt to use this key as restrictedsql, I can DECRYPT but I cannot ENCRYPT: select ENCRYPTBYKEY(key_guid('aes128'), 'Hello World'); yields NULL. However, select name, CONVERT(varchar, DECRYPTBYKEY(number)) from Test1; yields all of the plaintext data. I believe that the reason that the encrypt function does not work while decrypt does has to do with ddladmin privileges being granted, which is strange but somewhat beside to point: My desired outcome is that this user should have NO access to this key, and any attempt to decrypt or encrypt should fail. The user should retain access to the column and to the ciphertext, just not be able to view the plaintext or to insert properly encrypted data. I issued the following commands: DENY View Definition ON SYMMETRIC KEY::aes128 TO restrictedsql; DENY Control ON SYMMETRIC KEY::aes128 TO restrictedsql; They succeed, but do not yield any different results. Note that the key is EKM-provided, so it is NOT possible to protect the key by wrapping it in a UAC'ed certificate/key. I need to directly UAC the symmetric key alias. Update: I have two scripts that demonstrate the difference in behavior for the permissions statements between native SQL Server AES keys and EKM-provided SQL Server AES keys. Note that this presumes the EKM provider is already created and the key is created on the EKM provider. First script gets executed by an administrative, full-access user: create table Test2 ( name varchar(25), ekm128_enc varbinary(256), local128_enc varbinary(256), ); CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'sql$server123'; CREATE CERTIFICATE localcert WITH SUBJECT = 'TestSqlServer'; CREATE SYMMETRIC KEY local128 WITH ALGORITHM = AES_128 ENCRYPTION BY CERTIFICATE localcert; CREATE SYMMETRIC KEY ekm128 FROM PROVIDER EKMProvider WITH provider_key_name = 'ekm128', creation_disposition = open_existing; OPEN SYMMETRIC KEY local128 DECRYPTION BY CERTIFICATE localcert; insert into Test2 values ('travisthomas', ENCRYPTBYKEY(key_guid('ekm128'), 'travisthomas_ekm'), ENCRYPTBYKEY(key_guid('local128'), 'travisthomas_local')); select name, ekm128_enc, convert(varchar, DECRYPTBYKEY(ekm128_enc)) as ekm128_dec, local128_enc, CONVERT(varchar, DECRYPTBYKEY(local128_enc)) as local128_dec from Test2; /* execute through this point... the select statement should work flawlessly... the ciphertext and the plaintext should all be visible and not-null */ /* execute after this point next to set the permissions on both ekm128 and local128 */ DENY View Definition ON SYMMETRIC KEY::ekm128 TO restrictedsql; DENY Control ON SYMMETRIC KEY::ekm128 TO restrictedsql; DENY View Definition ON SYMMETRIC KEY::local128 TO restrictedsql; DENY Control ON SYMMETRIC KEY::local128 TO restrictedsql; select name, ekm128_enc, convert(varchar, DECRYPTBYKEY(ekm128_enc)) as ekm128_dec, local128_enc, CONVERT(varchar, DECRYPTBYKEY(local128_enc)) as local128_dec from Test2; /* This select statement should provide identical output as the select statement above the "DENY"s */ The second script should be executed by the restricted user, restrictedsql in this case. OPEN SYMMETRIC KEY local128 DECRYPTION BY CERTIFICATE localcert; /* this statement fails due to lack of permissions */ select name, ENCRYPTBYKEY(key_guid('ekm128'), 'test') as ekm128_encrypt, CONVERT(varchar, decryptbykey(ekm128_enc)) as ekm128_dec, ENCRYPTBYKEY(key_guid('local128'), 'test') as local128_encrypt, CONVERT(varchar, decryptbykey(local128_enc)) as local128_dec from Test2; /* null for all except EKM decryption! permissions don't apply! */ A: The answer I received from Microsoft: this isn't possible in this architecture. The key identifier is bound up in the ciphertext and interpreted by the EKM provider, not SQL Server. SQL Server doesn't even know which key is being used. It would be on the EKM provider to provide UAC.
{ "language": "en", "url": "https://stackoverflow.com/questions/30489709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using 3rd party script in html So actually i am not much familiar with javascript that's why i am going to post it to know something that i am going to know, So here it is, Suppose i have html page and hosted on some where on internet and its coding is, <html> <head> <title>Title of the document</title> </head> <body> The content of the document......</p> The <a href="http://sitelink.com">link</a> of the document ...... </body> </html> In this code Link anchor text use for hyperlink, I would like to use javascript that call from another site, where the link exist and it display over there like this. <script type="text/javascript" src="http://mysite.com/java.js"> I want to know that what code i put on java.js so it show the hyperlink in my html file and how and where do i add code to html page and in javascript Advance Thanks for help :) A: Apologies in advance if I misunderstood your question, but it sounds like you'd like to use JavaScript from another location on your site. Using the example above, here's what that would look like: <html> <head> <title>Title of the document</title> </head> <body> The content of the document......</p> The <a href="http://sitelink.com">link</a> of the document ...... <script type="text/javascript" src="http://mysite.com/java.js"></script> </body> </html> You could also link to it in the <head> instead, but it's better for performance if the scripts are placed in the footer. A: your anchor: href="javascript:linksomething()" and js: function linksomething(){ window.location.href=url; } is this what you want?
{ "language": "en", "url": "https://stackoverflow.com/questions/18179025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: BeautifulSoup and Selenium won't retrieve full html from website This is the site I'm trying to retrieve information from: https://www.baseball-reference.com/boxes/CLE/CLE202108120.shtml I want to get the box score data so like the Oakland A's total batting average in the game, at bats in the game, etc. However, when I retreive and print the html from the site, these box scores are missing completely from the html. Any suggestions? Thanks. Here's my code: from bs4 import BeautifulSoup import requests url = "https://www.baseball-reference.com/boxes/CLE/CLE202108120.shtml" page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') print(soup.prettify) Please help! Thanks! I tried selenium and had the same problem. A: The page is loaded by javascript. Try using the requests_html package instead. See below sample. from bs4 import BeautifulSoup from requests_html import HTMLSession url = "https://www.baseball-reference.com/boxes/CLE/CLE202108120.shtml" s = HTMLSession() page = s.get(url, timeout=20) page.html.render() soup = BeautifulSoup(page.html.html, 'html.parser') print(soup.prettify) A: The other tables are there in the requested html, but within the comments. So you need to parse out the comments to get those additional tables: import requests from bs4 import BeautifulSoup, Comment import pandas as pd url = "https://www.baseball-reference.com/boxes/CLE/CLE202108120.shtml" result = requests.get(url).text data = BeautifulSoup(result, 'html.parser') comments = data.find_all(string=lambda text: isinstance(text, Comment)) tables = pd.read_html(url) for each in comments: if 'table' in str(each): try: tables.append(pd.read_html(str(each))[0]) except: continue Output: Oakland print(tables[2].to_string()) Batting AB R H RBI BB SO PA BA OBP SLG OPS Pit Str WPA aLI WPA+ WPA- cWPA acLI RE24 PO A Details 0 Mark Canha LF 6.0 1.0 1.0 3.0 0.0 0.0 6.0 0.247 0.379 0.415 0.793 23.0 19.0 0.011 0.58 0.040 -0.029% 0.01% 1.02 1.0 1.0 0.0 2B 1 Starling Marte CF 3.0 0.0 2.0 3.0 0.0 1.0 4.0 0.325 0.414 0.476 0.889 12.0 7.0 0.116 0.90 0.132 -0.016% 0.12% 1.57 2.8 1.0 0.0 2B,HBP 2 Stephen Piscotty PH-RF 1.0 0.0 1.0 2.0 0.0 0.0 2.0 0.211 0.272 0.349 0.622 7.0 3.0 0.000 0.00 0.000 0.000% 0% 0.00 2.0 1.0 0.0 HBP 3 Matt Olson 1B 6.0 0.0 1.0 2.0 0.0 0.0 6.0 0.283 0.376 0.566 0.941 21.0 13.0 -0.057 0.45 0.008 -0.065% -0.06% 0.78 -0.6 9.0 1.0 GDP 4 Mitch Moreland DH 5.0 3.0 2.0 2.0 0.0 0.0 6.0 0.230 0.290 0.415 0.705 23.0 16.0 0.049 0.28 0.064 -0.015% 0.05% 0.50 1.5 NaN NaN 2·HR,HBP 5 Josh Harrison 2B 0.0 1.0 0.0 0.0 1.0 0.0 1.0 0.294 0.366 0.435 0.801 7.0 3.0 0.057 1.50 0.057 0.000% 0.06% 2.63 0.6 0.0 0.0 NaN 6 Tony Kemp 2B 4.0 3.0 3.0 0.0 1.0 0.0 5.0 0.252 0.370 0.381 0.751 16.0 10.0 -0.001 0.14 0.009 -0.010% 0% 0.24 1.6 2.0 2.0 NaN 7 Sean Murphy C 4.0 3.0 2.0 2.0 2.0 1.0 6.0 0.224 0.318 0.419 0.737 25.0 15.0 0.143 0.38 0.151 -0.007% 0.15% 0.67 2.7 7.0 0.0 2B 8 Matt Chapman 3B 1.0 3.0 0.0 0.0 5.0 1.0 6.0 0.214 0.310 0.365 0.676 31.0 10.0 0.051 0.28 0.051 0.000% 0.05% 0.49 2.2 1.0 3.0 NaN 9 Seth Brown RF-CF 5.0 1.0 1.0 1.0 0.0 1.0 6.0 0.204 0.278 0.451 0.730 18.0 12.0 -0.067 0.40 0.000 -0.067% -0.07% 0.70 -1.7 4.0 0.0 SF 10 Elvis Andrus SS 5.0 2.0 1.0 2.0 1.0 0.0 6.0 0.233 0.283 0.310 0.593 20.0 15.0 0.015 0.42 0.050 -0.034% 0.02% 0.73 -0.1 0.0 4.0 NaN 11 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 12 Chris Bassitt P NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 1.0 0.0 NaN 13 A.J. Puk P NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 0.0 0.0 NaN 14 Deolis Guerra P NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 0.0 0.0 NaN 15 Jake Diekman P NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 0.0 0.0 NaN 16 Team Totals 40.0 17.0 14.0 17.0 10.0 4.0 54.0 0.350 0.500 0.575 1.075 203.0 123.0 0.317 0.41 0.562 -0.243% 0.33% 0.72 12.2 27.0 10.0 NaN
{ "language": "en", "url": "https://stackoverflow.com/questions/71167677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ionic 2 Crosswalk for Android: this.platform.height()/width() inconsistent result on this.platform.ready() event I use Crosswalk plugin for Android with Ionic 2 and I've noticed, when running on a real device, that this gives an inconsistent result: this.platform.ready().then(() => { console.log("this.platform.height(): " + this.platform.height() + " / this.platform.width(): " + this.platform.width()); }); Sometimes I get height and width both > 0: in this case it works. Sometimes I get height and width == 0: in this case it does not work. My assumption is that there might be another event in Crosswalk to notify that it is ready to display the right height and width. I had a look around this Crosswalk web api page but I did not find what I was looking for. A: https://ionicframework.com/docs/v2/api/platform/Platform/ width() Gets the width of the platform’s viewport using window.innerWidth. Using this method is preferred since the dimension is a cached value, which reduces the chance of multiple and expensive DOM reads. height() Gets the height of the platform’s viewport using window.innerHeight. Using this method is preferred since the dimension is a cached value, which reduces the chance of multiple and expensive DOM reads. * *Please try using window.innerHeight and window.innerWidth to get height and width of the device at first. *Try // Add readySource to check if platform ready was used. The resolved value is the readySource, which states which platform ready was used. // For example, when Cordova is ready, the resolved ready source is cordova. The default ready source value will be dom. import { Component } from '@angular/core'; import { Platform } from 'ionic-angular'; @Component({...}) export MyApp { constructor(platform: Platform) { platform.ready().then((readySource) => { console.log('Platform ready from', readySource); console.log('Width: ' + platform.width()); console.log('Height: ' + platform.height()); }); } *Remove Crosswalk in Ionic 2 to check if system webview can get correct results, then it should be Crosswalk issue rather than Ionic issue. Relevant topic: https://forum.ionicframework.com/t/how-to-get-device-width-and-height/28372
{ "language": "en", "url": "https://stackoverflow.com/questions/40718494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: call local .asmx webservice from phonegap android app to get data? i m creating one phonegap test application, for that i want data from database through webservice (.asmx). i m just newer for this technology. i have spent 2 days for this call posible bt couldnt. function test() { jQuery.support.cors = true; $.mobile.allowCrossDomainPages = true; $.ajax({ data: "{}", type: "GET", dataType: "json", contentType: "application/json; charset=utf-8", url: "http://localhost:xxxxx/yyyy/testservice.asmx?op=testfunction", success: function (msg) { $('#divToBeWorkedOn').html(msg.text); }, error: function (e) { $('#divToBeWorkedOn').html("unavailable"); } }); } Its local service. A: I would replace http://localhost:xxxxx/ with the actual internal IP address of the server (probably something like http://192.168.x.x:xxxxx/) - just make sure your server and mobile device are connected to the same network through wi-fi not gsm network. Also make sure you updated the domain white list. more info how to do that can be found here http://docs.phonegap.com/en/2.2.0/guide_whitelist_index.md.html#Domain%20Whitelist%20Guide hope this will help, good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/13305715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set react createtableselect to prevent creating element not in options? I was trying to have a create select option that limit users from adding their own option to the predefine option list, Sample code for setting options in create table select. Unfortunately this this doesn't solve the problem. please help with a simple fix <CreatableSelect name="dataN" id="dataN" className="selctInputs" placeholder="Select" isMulti onChange={(e) => getData(e)} options={Options} /> A: ## React createtableselect prevent creating element not in option ## ''' import CreatableSelect from 'react-select/creatable'; const createOption = (label, dataId) => ({ label, value: dataId, }); const levelOptions = ([{ "name": "Course1", "id": 1 }, { "name": "Course2", "id": 2 }, { "name": "Course3", "id": 3 }, { "name": "Course4", "id": 4 }])?.map((post, id) => { return createOption(post.name, post.id); }); <CreatableSelect name="dataN" id="dataN" className="selctInputs" placeholder=" Select..." isMulti onChange={(e) => getData(e)} options={Options} /> ''' ## Set isLoading to true provides a simple fix ## ''' <CreatableSelect isLoading={true} name="dataN" id="dataN" className="selctInputs" placeholder=" Select" isMulti onChange={(e) => getData(e)} options={Options} /> '''
{ "language": "en", "url": "https://stackoverflow.com/questions/66881285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sqaure brackets & asterisk sign as WildCards chars in Redis keys or scan with match We query redis using SCAN command along with MATCH, in following manner: scan 0 MATCH "S*" this will find anything starting with S then there is a square brackets syntax is also supported([]) which OR scan 0 MATCH "[ef]*" this will find anything that's starting with e OR f Now, I am looking to combination of both. * *match anything that start with e OR f *AND match anything that has S after e OR f I came up with following: scan 0 MATCH "[ef]S*" But this just keep running without any results. is is the above correct? let me know A: Should work as is - verified locally: 127.0.0.1:6379> FLUSHALL OK 127.0.0.1:6379> MSET a "" e "" f "" eSz "" fSx "" efg "" fgi "" SSX "" OK 127.0.0.1:6379> scan 0 MATCH "[ef]S*" 1) "0" 2) 1) "eSz" 2) "fSx" 127.0.0.1:6379>
{ "language": "en", "url": "https://stackoverflow.com/questions/26700337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error in converting images in Imagemagick I use Imagemagick convert to convert pdf file to png as follows: Magick convert -density 300 PointOnLine.pdf -quality 90 PointOnLine.png It gives me the following warning: convert: profile 'icc': 'RGB ': RGB color space not permitted on grayscale PNG `PointOnLine.png' @ warning/png.c/MagickPNGWarningHandler/1744. And png image created is all black. However, convert to jpg image is fine. Update: After adding -define profile:skip=ICC, image is still dark. But if convert to jpg and then to png, it is ok, but background is dark. The same warning is still there. What is the problem? Thanks. A: The following works for me without error in ImageMagick 7.0.7.22 Q16 Mac OSX Sierra with Ghostscript 9.21 and libpng @1.6.34_0. Your PDF has an alpha channel, so you might want to flatten it. magick -density 300 PointOnLine.pdf -flatten -quality 90 result.png This also works without error, but leaves the alpha channel in the png, though you won't see it here until you extract the image: magick -density 300 PointOnLine.pdf -quality 90 result2.png Note that in IM 7 you should just use magick and not magick convert. Check that you are using a current version of Ghostscript and libpng, if you do not get the same results. Your delegates.xml file for PS:alpha should show sDEVICE=pngalpha rather than pnmraw as follows. <delegate decode="ps:alpha" stealth="True" command="&quot;gs&quot; -sstdout=%%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 &quot;-sDEVICE=pngalpha&quot; -dTextAlphaBits=%u -dGraphicsAlphaBits=%u &quot;-r%s&quot; %s &quot;-sOutputFile=%s&quot; &quot;-f%s&quot; &quot;-f%s&quot;"/> USER REQUESTED RESULTING IMAGES THAT I POSTED TO BE REMOVED! A: Command which worked for me was: magick -density 300 PointOnLine.pdf -depth 8 -strip -background white -alpha off PointOnLine.tiff It did not gave any warning, also removed black blackground as well. I was able to convert it to the text afterwards using tesseract: tesseract PointOnLine.tiff PointOnLine A: I understand you are using ImageMagick under Windows, even if not stated (and the respective versions of IM, Win were not posted) I am under Ubuntu 16.04 LTS, and I will provide an answer possibly useful. (Under Win, prepend everything with Magick). For me, convert -density 300 -quality 90 PointOnLine.pdf PointOnLine.png works fine, with no warnings, producing a suitable output. I tried other things which work as well, some of them may suit you. * *First convert your pdf to RGB and then to png. convert -density 300 -colorspace RGB PointOnLine.pdf PointOnLine_rgb.pdf convert -density 300 PointOnLine_rgb.pdf PointOnLine_rgb.png A: If you post your PDF, I can check it out. Otherwise, perhaps it is CMYK, which PNG does not support. So try magick -quiet -density 300 -colorspace srgb PointOnLine.pdf -quality 90 PointOnLine.png Note in IM 7, use magick not magick convert. Also not that -quality is different for PNG than JPG. See https://www.imagemagick.org/script/command-line-options.php#quality A: I had the same issue and resolved adding -colorspace RGB before the output filename. convert -density 300 PointOnLine.pdf -quality 90 -colorspace RGB PointOnLine.png
{ "language": "en", "url": "https://stackoverflow.com/questions/48628878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Lifetime of std::initializer_list when used recursively I am trying to use std::initializer_list in order to define and output recursive data-structures. In the example below I am dealing with a list where each element can either be an integer or another instance of this same type of list. I do this with an intermediate variant type which can either be an initializer list or an integer. What is unclear to me is whether the lifetime of the std::initializer_list will be long enough to support this use-case or if I will be experiencing the possibility of inconsistent memory access. The code runs fine, but I worry that this is not guaranteed. My hope is that the std::initializer_list and any intermediate, temporary std::initializer_list objects used to create the top-most list are only cleaned up after the top-level expression is complete. struct wrapped { bool has_list; int n = 0; std::initializer_list<wrapped> lst; wrapped(int n_) : has_list(false), n(n_) {} wrapped(std::initializer_list<wrapped> lst_) : has_list(true), lst(lst_) {} void output() const { if (!has_list) { std::cout << n << ' '; } else { std::cout << "[ "; for (auto&& x : lst) x.output(); std::cout << "] "; } } }; void call_it(wrapped w) { w.output(); std::cout << std::endl; } void call_it() { call_it({1}); // [ 1 ] call_it({1,2, {3,4}, 5}); // [ 1 2 [ 3 4 ] 5 ] call_it({1,{{{{2}}}}}); // [ 1 [ [ [ [ 2 ] ] ] ] ] } Is this safe, or undefined behavior? A: As far as I can tell the program has undefined behavior. The member declaration std::initializer_list<wrapped> lst; requires the type to be complete and hence will implicitly instantiate std::initializer_list<wrapped>. At this point wrapped is an incomplete type. According to [res.on.functions]/2.5, if no specific exception is stated, instantiating a standard library template with an incomplete type as template argument is undefined. I don't see any such exception in [support.initlist]. See also active LWG issue 2493. A: What you're doing should be safe. Section 6.7.7 of the ISO Standard, paragraph 6, describes the third and last context in which temporaries are destroyed at a different point than the end of the full expression. Footnote (35) explicitly says that this applies to the initialization of an intializer_list with its underlying temporary array: The temporary object to which the reference is bound or the temporary object that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference if the glvalue to which the reference is bound was obtained through one of the following: ... ...(where a glvalue is, per 7.2.1, an expression whose evaluation determines the identity of an object, bit-field, or function) and then enumerates the conditions. In (6.9), it specifically mentions that: A temporary object bound to a reference parameter in a function call (7.6.1.2) persists until the completion of the full-expression containing the call. As I read it, this protects everything needed to build up the final argument to the top call to call_it, which is what you intend.
{ "language": "en", "url": "https://stackoverflow.com/questions/72103800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Keycloak user resource - return user representation with roles and groups instead querying rest api for roles and groups I have to search users by text, groups and roles and it takes 6 seconds to query for users, groups and roles for each user, it is about 15 HTTP requests to Keycloak REST API. Such slow searching is not acceptable from GUI point of view.. How u search users in your projects with Keycloak ? Do you synchronize users from Keycloak? Then data would not be fresh.. or maybe it is possible to write someadapter in Keycloak to synchronize data to my application, so the changes would be reflected immediatelly in my database and I would search users in my database. .? Or maybe uconnect to Keycloak data database ? But then u limit yourself to Keycloak version.. When serching users you get UserResources and u can do userResource.toRepresentation() to get specific data an you see groups and roles collections that are always empty. Is it possible to retrieve UserResources that have groups and roles filled? Currently userResource.toRepresentation() returns user but with null groups and roles. So what groups and roles collections are for in UserRepresentation if they are always null? A: It's not exactly the topic but I needed to find the roles associated with a specific user and this question pops first with my keywords web search. Here's what worked for me with keycloak client 13.0.1 RealmResource realmResource = keycloak.realm(REALM); UsersResource usersResource = realmResource.users(); UserResource userResource = usersResource.get(USER_ID); RoleMappingResource roleMappingResource = userResource.roles(); // either realmLevel or clientLevel RoleScopeResource roleScopeResource = roleMappingResource.realmLevel(); List<RoleRepresentation> rolesRepresentation = roleScopeResource.listAll(); I didn't find it elsewhere, I hope it can be useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/62213682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AOSP build both x86 and x64 for aosp_x86_64-eng When building Android 9.0.0_r30, I lunch "aosp_x86_64-eng", but it builts both x86 and x64 targets, i.e. there are two clang invokes for each C/C++ source in the build log: ...clang...-target i686-linux-android... ...clang...-target x86_64-linux-android... which generates two sets of binaries which wastes time and disk space. Can I/how to only build x64 target? A: You will probably not have success with building an x64 Android without any x86 binaries. Every module can decide to be built in the target architecture, a fixed one or both and a lot of modules do that. If you start to grep for LOCAL_MULTILIB in Android.mk and compile_multilib in Android.bp, you will find lots of modules and have to figure out the reason for every one of them to build for x86, x64 or both. grep -rn "compile_multilib" --include="Android.bp" grep -rn "LOCAL_MULTILIB" --include="Android.mk" You can find out what the configurations mean here: https://source.android.com/setup/develop/64-bit-builds
{ "language": "en", "url": "https://stackoverflow.com/questions/57863059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to redirect Woocommerce to a specific page? I use "Woocommerce User Email Verification" which after the user registers, it redirects user to the main page. It doesn't have built in option to redirect users to a page where I can tell them that they should check their email and confirm it to access my-account section! Plugin link: https://wordpress.org/plugins/woo-confirmation-email/ download link: https://downloads.wordpress.org/plugin/woo-confirmation-email.3.1.15.zip Please tell me how I can redirect a user after they press the Register to any page of my own website that I want? Ps. I know that without this plugin, when user registers, they automatically go to my-account section. So this plugin is causing the Redirect I think. Would you be so kind and help? Thanks! A: Try to add this in function.php function wpse_registration_redirect() { return home_url().'/my-page' ; } add_filter( 'registration_redirect', 'wpse_registration_redirect' ); or function custom_registration_redirect() { return home_url().'/my-page' ; } add_action('woocommerce_registration_redirect', 'custom_registration_redirect', 2); or After login function admin_default_page() { return home_url().'/my-page' ; } add_filter('login_redirect', 'admin_default_page'); or After WooCommerce login function iconic_login_redirect( $redirect_to) { $redirect_to = 'http://yoursiteshop'; return $redirect_to ; } add_filter( 'woocommerce_login_redirect', 'iconic_login_redirect',1100, 2 );
{ "language": "en", "url": "https://stackoverflow.com/questions/50811013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I'm having trouble rounding decimals while encoding in python import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import StratifiedShuffleSplit from sklearn.preprocessing import OrdinalEncoder df = pd.read_csv("mushrooms.csv",index_col=False,header=None) def n(target): if target == 'p': return 1 elif target == 'e': return 0 df[0] = df[0].apply(n) #manually encoding the targets targets = df[0] inputs = df[df.columns[1:]] def test_train_split(mydf, inputs, tratio, target): splitter = StratifiedShuffleSplit(n_splits = 1, test_size = tratio, random_state = 42) train_index, test_index = next(splitter.split(inputs, target)) strat_train = mydf.iloc[train_index] strat_test = mydf.iloc[test_index] return strat_train, strat_test def print_test_train_dfs(train_df, test_df, target_column = 'None'): print("\nTraining data:") train_df.info() if target_column != 'None': print(train_df[target_column].value_counts()) print('\nTest data:') test_df.info() if target_column != 'None': print(test_df[target_column].value_counts()) traindf, testdf = test_train_split(df, inputs, 0.2, targets) enc = OrdinalEncoder() enc.fit(traindf) df = enc.transform(testdf) for i in range(len(df)): for j in range(len(df[1])): df[i][j].round(0) df = pd.DataFrame.from_records(df) print(df) df always ends up with decimals like 1.0 instead of just 1 which is what I want. The dataset I'm using is here https://www.kaggle.com/uciml/mushroom-classification I'll also add that after .transform, df is in more of an array than a dataframe A: df.astype(int) should load as integer Refer to this question for more information Change data type of columns in Pandas
{ "language": "en", "url": "https://stackoverflow.com/questions/59348335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Error: A "url" property or function must be specified, except url is specified I have a Conversation model and a view that displays this model. This model is fetched from the server without any problem (the url property works fine then), and the view is rendered. However, when I attempt to destroy the model in a function of the view, I get the error 'A "url" property or function must be specified', even though when I display said url right before the destroy call, it is exactly the url it should be. Here is the code for the model: MessageManager.models.Conversation = Backbone.Model.extend({ defaults: { uid: '', title: '', messages: [], users: [], dateUpdated: null, isNew: true, message: '' }, url: function(){ var url = '/api/conversations'; if(this.get('uid').length > 0) url += '/'+this.get('uid'); return url; } }); And the view: MessageManager.views.ConversationFull = Marionette.CompositeView.extend({ template: this.template(MessageManager.templates.ConversationFull), childView: MessageManager.views.MessageListItem, childViewContainer: '#message-container', events: { 'click a#btn-delete-conversation': 'deleteConversation' }, deleteConversation: function(e){ e.preventDefault(); var self = this; console.log(self.model.url()); //This returns a correct url self.model.destroy({//This fires the error error: function(model, result, xhr){ console.log(result.responseText); }, success: function(model, response, options){ MessageManager.conversations.sync(); AMMain.router.pNavigate('welcome/'); } }); } }); Can anyone give some insight on how to resolve this problem? Is there something wrong in the way I declare the model? EDIT: It should be noted that other calls (like fetch or sync) on this model fire the same error, even though the original fetch works without a problem. EDIT2: Well, not completely out of the frying pan yet, but I changed the way I defined the model's url, using urlRoot and the "id" attribute, and now the DELETE request is sent to the server without error. A: It happens because you have to specify urlRoot property of the model. Without it url is not considered. So try this maybe: MessageManager.models.Conversation = Backbone.Model.extend({ defaults: { uid: '', title: '', messages: [], users: [], dateUpdated: null, isNew: true, message: '' }, urlRoot: function() { var url = '/api/conversations'; if (this.get('uid').length > 0) url += '/'+this.get('uid'); return url; } }); Documentation says: urlRootmodel.urlRoot or model.urlRoot() Specify a urlRoot if you're using a model outside of a collection, to enable the default url function to generate URLs based on the model id. "[urlRoot]/id" Normally, you won't need to define this. Note that urlRoot may also be a function. And source code for Backbone.Model url method: url: function() { var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); if (this.isNew()) return base; return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id); }, A: defsq answer is good. The only thing missing is to define the idAttribute on your model, since it's not the convention-based id field, but uid. MessageManager.models.Conversation = Backbone.Model.extend({ idAttribute: 'uid', defaults: { uid: '', title: '', messages: [], users: [], dateUpdated: null, isNew: true, message: '' }, urlRoot: "/api/conversations" }); You don't need to append the "id" manually. Just tell Backbone that your id attribute is uid and everything else will work. In fact, you can event call mymodel.id to get the id of the model -event if it's stored internally as uid. :) http://backbonejs.org/#Model-idAttribute Personally I don't like all that default values. Everything will be undefined if you don't set default values, which you can simply guard against with an if (undefined is a falsey value). if(!model.get("messages")){ //no messages }
{ "language": "en", "url": "https://stackoverflow.com/questions/26400601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Handler from Looper.getMainLooper didn't receive message I have an activity and a handler created inside its onCreate function which looks like this: private Handler mHandler; private Button helloBtn; private TextView helloText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(...); helloBtn = (Button)findViewById(R.id.hello); helloBtn.setOnClickListener(this); helloText = (TextView)findViewById(R.id.text); mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what){ case MSG_REPORT_PROGRESS: int progress = msg.arg1; seekBar.setProgress(progress); break; case MSG_HELLO: helloText.setText("hello world"); break; } } }; } public void onClick(View view) { if(view == helloBtn) { Handler mainHanlder = new Handler(Looper.getMainLooper()); Message msg = new Message(); msg.what = MSG_HELLO; mainHandler.sendMessage(msg); } } the mainHandler didn't receive message when helloBtn been clicked. Why? it works if I directly use mHandler to replace the mainHandler, why? A: use the below code.. and let me know the feedback. To show the text, handler is not needed. /** The m handler. */ private Handler mHandler; /** The hello btn. */ private Button helloBtn; /** The hello text. */ private TextView helloText; /** The msg hello. */ private final int MSG_HELLO = 2; /* * (non-Javadoc) * * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); helloBtn = (Button) findViewById(R.id.btn_hello); helloBtn.setOnClickListener(this); helloText = (TextView) findViewById(R.id.txt_hello); mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_HELLO: helloText.setText("hello world"); break; } } }; } /* * (non-Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ public void onClick(View view) { if (view.getId() == R.id.btn_hello) { Message msg = new Message(); msg.what = MSG_HELLO; mHandler.sendMessage(msg); } } A: The class Message has a field "target" which is used to store the handler that you used to send message. When you call a Handler's sendMessage(msg) method, the reference of the handler will be stored in the message. When the Looper dispatch your message it'll call msg.target.dispatchMessage(msg), which means that your msg will be dispatched to the same handler that you used to send it. The method dispatchMessage(msg) will call handleMessage(msg) eventually. You can use a BroadcastReceiver to solve your problem. Register a BroadcastReceiver in the Activity that you want to update in the future, and send a Broadcast to it from the other part of you app.
{ "language": "en", "url": "https://stackoverflow.com/questions/27225510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there way to position border with css (IMAGE EXAMPLE)? Below are a couple of examples of what I want: Example 1: Example 2: I tried by using background but I don't know how to make the background smaller than its container, so I decided to try with border-bottom and to position it with sth like 10px-top. I've tried: background: rgba(196,196,196,0.8); background-position: -10px 10px; However, I cant find how to postion border... Is there some way? A: You can use the border-image css property. More info here DEMO #borderimg1 { border: 10px solid transparent; padding: 15px; -webkit-border-image: url(https://www.w3schools.com/cssref/border.png) 30 round; -o-border-image: url(https://www.w3schools.com/cssref/border.png) 30 round; border-image: url(https://www.w3schools.com/cssref/border.png) 30 round; } #borderimg2 { border: 10px solid transparent; padding: 15px; -webkit-border-image: url(https://www.w3schools.com/cssref/border.png) 30 stretch; -o-border-image: url(https://www.w3schools.com/cssref/border.png) 30 stretch; border-image: url(https://www.w3schools.com/cssref/border.png) 30 stretch; } <p id="borderimg1">Here, the image tiles to fill the area. The image is rescaled if necessary, to avoid dividing tiles.</p> <p id="borderimg2">Here, the image is stretched to fill the area.</p> A: You could achieve this with :before HTML <div class="wrap"> <p class="text">Lorem ipsum dolor sit amet</p> <br /> <p class="text alt">Amet cum et ad earum commodi</p> </div> CSS .wrap { padding: 50px; background: url(https://placedog.net/1000/500?id=12); background-size: cover; } .text { position: relative; z-index: 1; margin: 0 0 50px; font-size: 40px; font-family: sans-serif; display: inline-block; } .text:before { content: ''; position: absolute; display: block; top: 15px; bottom: 15px; left: -20px; right: -20px; background: rgba(255,255,255,0.8); z-index: -1; } Change the values top, bottom, left, right in the :before to suit your needs. JSFiddle: https://jsfiddle.net/74kLwyxb/
{ "language": "en", "url": "https://stackoverflow.com/questions/57286458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Bootstrap Button Collapse in navbar While following "Bootstrap 3 Tutorials - #2 - Responsive Collapsing Navbar [1080p]", I got stuck w/ this button; https://www.youtube.com/watch?v=qpWlaOeGZ_4 When button is cliked, home link is supposed to show in mobile size of the page. But nothing happens, can anyone help me with this ? <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="css/bootstrap.min.css" rel = "stylesheet"> <link href="css/styles.css" rel="stylesheet"> </head> <body> <div class="navbar navbar-default navbar-static-top"> <div class="container"> <a href="" class="navbar-brand">My Home</a> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navHeaderCollapse">Button Test</button> <div class="collapse navbar-collapse navHeaderCollapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Home</a></li> </ul> </div> </div> </div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> <script src="js/bootstrap.js"></script> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/38675593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Conditional validations in angular2 I want to use same template for guest and customer registration forms but validations may varies as follows Let us assume it is a Register form for Guests - firstName is required <form #f="ngForm" novalidate (ngSubmit)="save()"> <label>First Name:</label> <input type="text" name="firstName" [(ngModel)]="values.FirstName" required #firstName="ngModel"> <div *ngIf="firstName.hasError('required') && (!firstName.pristine && !f.submitted)" class="text-danger">You must include a first name.</div> </form> And this is for Customer - firstName is optional <form #f="ngForm" novalidate (ngSubmit)="save()"> <label>First Name:</label> <input type="text" name="firstName" [(ngModel)]="values.FirstName" #firstName="ngModel"> </form> I want to use same/onlyone template for both forms but validations varies! how could i achieve it. TIA! NOTE: by using reactive forms I could achieve it, but knowingly I want to achieve in Template-Driven forms. A: Based on this topic you can try <input name="first" ngModel [required]="isRequired">
{ "language": "en", "url": "https://stackoverflow.com/questions/44024833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: 'Project.API.Hubs.ChatHub.OnDisconnected()': no suitable method found to override public override Task OnDisconnected() { var name = dic.FirstOrDefault(x => x.Value == Context.ConnectionId.ToString()); string s; dic.TryRemove(name.Key, out s); return Clients.All.disconnected(name.Key); } I don't know why I am getting this error. A: They changed signature of the method in SignalR 2.1 It now looks like public override Task OnDisconnected(bool stopCalled)
{ "language": "en", "url": "https://stackoverflow.com/questions/29818866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting empty string on h:selectOneMenu I do not know why it is empty because I have the same piece of code in my system for a user register. This is mu xhtml page <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui"> <ui:composition template="/template/main.xhtml"> <ui:define name="content"> <!--h:outputScript name="js/myjs.js" /--> <h1 class="page-header text-center"> <i class="fa fa-exclamation-triangle"></i> Denunciar </h1> <div id="wrapper"> <h:form id="cadastrarDenuncia" styleClass="form-horizontal" p:role="form"> <!-- Número de denuncias --> <h:inputHidden value="#{denunciaBean.denuncia.ndenuncia}"/> <!-- Tabs para visualizacao --> <p:wizard flowListener="#{denunciaBean.onFlowProcess}"> <!-- Tipos de Crime --> <p:tab id="tabtipocrime" title="Local do Crime"> <div class="form-group panel panel-default"> <div class="panel-body"> <h:outputLabel for="idTipoCrime" class="col-md-4 control-label">Tipo de Crime: </h:outputLabel> <div class="col-md-4"> <h:selectOneMenu class="form-control" id="idTipoCrime" value="#{denunciaBean.denuncia.tipoCrime}" required="true" requiredMessage="Campo obrigatório!"> <f:selectItem itemValue="" itemLabel="Selecione"/> <f:selectItem itemValue="Roubo" itemLabel="Roubo"/> <f:selectItem itemValue="Furto" itemLabel="Furto"/> <f:selectItem itemValue="TraficoEntorpecentes" itemLabel="Tráfico de Entorpecentes"/> <f:selectItem itemValue="Homicidio" itemLabel="Homicídio"/> <f:selectItem itemValue="Latrocinio" itemLabel="Latrocício"/> <f:selectItem itemValue="Receptacao" itemLabel="Receptação"/> <f:selectItem itemValue="Estupro" itemLabel="Estupro"/> <f:selectItem itemValue="Quadrilha" itemLabel="Quadrilha"/> <f:selectItem itemValue="CrimeAmbiental" itemLabel="Crime Ambiental"/> <f:selectItem itemValue="Sequestro" itemLabel="Sequestro"/> <f:selectItem itemValue="ViolenciaDomestica" itemLabel="Violência Doméstica"/> <f:selectItem itemValue="Assassinato" itemLabel="Assassinato"/> <f:selectItem itemValue="Agressao" itemLabel="Agressão"/> <f:selectItem itemValue="Ameaca" itemLabel="Ameaça"/> <f:selectItem itemValue="Pedofilia" itemLabel="Pedofilia"/> </h:selectOneMenu> </div> <div class="text-danger"><h:message for="idTipoCrime"/></div> </div> </div> </p:tab> <!-- Local do Crime--> <p:tab id="tabcrimelocal" title="Local do Crime"> <!-- Se der tempo pegar o local do ususário atraves do ip http://stackoverflow.com/questions/15517667/how-to-mark-users-current-location-on-primefaces-gmap http://stackoverflow.com/questions/1415851/best-way-to-get-geo-location-in-java https://mvnrepository.com/artifact/com.maxmind.geoip/geoip-api/1.3.1 --> <div class="form-group panel panel-default"> <div class="panel-body"> <h:outputLabel class="col-md-4 control-label">Clique no local aproximado do acontecimento: </h:outputLabel> <p:growl id="mensagem" showDetail="true" /> <p:gmap id="idmapcrimelocal" center="-10.9232843, -37.0501223" zoom="15" type="HYBRID" widgetVar="idmapcrimelocal" style="width:470px; height:300px" onPointClick="handlePointClick(event);"> </p:gmap> <p:remoteCommand name="onPoint" actionListener="#{denunciaBean.onPointSelect}" update="mensagem" /> <h:inputHidden id="lat" value="#{denunciaBean.denuncia.latitude}" /> <h:inputHidden id="lng" value="#{denunciaBean.denuncia.longitude}" /> </div> </div> </p:tab> <!-- Outras Informacoes --> <p:tab id="tabextrainformation" title="Observações"> <div class="form-group panel panel-default"> <div class="panel-body"> <!-- Data e Hora do Crime --> <div class="form-group"> <h:outputLabel class="col-md-4 control-label" for="idDataHoraCrime">Data e Hora do crime: </h:outputLabel> <div class="col-md-4"> <h:inputText id="data" label="Data e Hora do Crime" value="#{denunciaBean.denuncia.dataHoraCrime}" size="16" maxlength="16" required="true"> <f:convertDateTime dateStyle="long" pattern="dd/MM/yyyy HH:mm" /> </h:inputText> </div> <div class="col-md-8 control-label text-danger"><h:message for="idDataHoraCrime"/></div> </div> <!-- Observacoes--> <div class="form-group"> <h:outputLabel class="col-md-4 control-label" for="idObservacao">Observações: </h:outputLabel> <div class="col-md-4"> <h:inputTextarea class="form-control input-md" value="#{denunciaBean.denuncia.observacao}" id="idObservacao" placeholder="Observacao"/> </div> <div class="col-md-8 control-label text-danger"><h:message for="idObservacao"/></div> </div> <!-- Botões --> <div class="form-group"> <label class="col-md-4 control-label" for="idConfirmar"></label> <div class="col-md-8"> <h:commandButton id="idConfirmarBt" styleClass="btn btn-primary" action="#{denunciaBean.salvar}" value="Confirmar" onclick="if (!confirm('Confirmar denúncia?')) return false;"/> <h:commandButton styleClass="btn btn-danger" value="Cancelar" onclick="redirecionar()"/> </div> </div> </div> </div> </p:tab> </p:wizard> </h:form> </div> <script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyAj8u8gZyCkVaMTiRcTXWclFgs0s7sv2nY&amp;" /> <script type="text/javascript" > function handlePointClick(event) { if (navigator.geolocation) { browserSupportFlag = true; var latlng = event.latLng; geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'latLng' : latlng }, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { onPoint([ { name : 'lng', value : event.latLng.lng() }, { name : 'lat', value : event.latLng.lat() } ]); } }); } } </script> </ui:define> </ui:composition> </html> This is the class package br.com.smartpatrolling.denuncia; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import br.com.smartpatrolling.usuario.Usuario; @Entity @Table(name = "denuncia") public class Denuncia implements Serializable { private static final long serialVersionUID = -387555820515169694L; @Id @GeneratedValue private Integer ndenuncia; @ManyToOne // Permite excluir todas as denuncias do usuario ao excluir um usuário @OnDelete(action = OnDeleteAction.CASCADE) @JoinColumn(nullable = false) private Usuario usuario; private String tipoCrime; /** Local do crime */ private double latitude; private double longitude; private String observacao; /** Data e hora aproximados do crime */ private Date dataHoraCrime; /** Data e hora do cadastro da denuncia */ @Column(nullable = false, updatable = false) private Date dataHoraCadastro; public Integer getNdenuncia() { return ndenuncia; } public void setNdenuncia(Integer ndenuncia) { this.ndenuncia = ndenuncia; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public String getTipoCrime() { return tipoCrime; } public void setTipoCrime(String tipoCrime) { this.tipoCrime = tipoCrime; } public String getObservacao() { return observacao; } public void setObservacao(String observacao) { this.observacao = observacao; } public Date getDataHoraCrime() { return dataHoraCrime; } public void setDataHoraCrime(Date dataHoraCrime) { this.dataHoraCrime = dataHoraCrime; } public Date getDataHoraCadastro() { return dataHoraCadastro; } public void setDataHoraCadastro(Date dataHoraCadastro) { this.dataHoraCadastro = dataHoraCadastro; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dataHoraCadastro == null) ? 0 : dataHoraCadastro.hashCode()); result = prime * result + ((dataHoraCrime == null) ? 0 : dataHoraCrime.hashCode()); long temp; temp = Double.doubleToLongBits(latitude); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(longitude); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((ndenuncia == null) ? 0 : ndenuncia.hashCode()); result = prime * result + ((observacao == null) ? 0 : observacao.hashCode()); result = prime * result + ((tipoCrime == null) ? 0 : tipoCrime.hashCode()); result = prime * result + ((usuario == null) ? 0 : usuario.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Denuncia other = (Denuncia) obj; if (dataHoraCadastro == null) { if (other.dataHoraCadastro != null) return false; } else if (!dataHoraCadastro.equals(other.dataHoraCadastro)) return false; if (dataHoraCrime == null) { if (other.dataHoraCrime != null) return false; } else if (!dataHoraCrime.equals(other.dataHoraCrime)) return false; if (Double.doubleToLongBits(latitude) != Double.doubleToLongBits(other.latitude)) return false; if (Double.doubleToLongBits(longitude) != Double.doubleToLongBits(other.longitude)) return false; if (ndenuncia == null) { if (other.ndenuncia != null) return false; } else if (!ndenuncia.equals(other.ndenuncia)) return false; if (observacao == null) { if (other.observacao != null) return false; } else if (!observacao.equals(other.observacao)) return false; if (tipoCrime == null) { if (other.tipoCrime != null) return false; } else if (!tipoCrime.equals(other.tipoCrime)) return false; if (usuario == null) { if (other.usuario != null) return false; } else if (!usuario.equals(other.usuario)) return false; return true; } } this is the bean package br.com.smartpatrolling.web; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import org.primefaces.event.FlowEvent; import br.com.smartpatrolling.denuncia.Denuncia; import br.com.smartpatrolling.denuncia.DenunciaRN; @ManagedBean(name = "denunciaBean") @RequestScoped public class DenunciaBean { private Denuncia denuncia = new Denuncia(); private List<Denuncia> lista = null; @ManagedProperty(value = "#{contextoBean}") private ContextoBean contextoBean; public String salvar() { this.denuncia.setUsuario(this.contextoBean.getUsuarioLogado()); DenunciaRN denunciaRN = new DenunciaRN(); denunciaRN.salvar(this.denuncia); this.denuncia = new Denuncia(); this.lista = null; return "minhasDenuncias"; } public String excluir() { DenunciaRN denunciaRN = new DenunciaRN(); denunciaRN.excluir(this.denuncia); this.denuncia = new Denuncia(); this.lista = null; return null; } public List<Denuncia> getLista() { if (this.lista == null){ DenunciaRN denunciaRN = new DenunciaRN(); this.lista = denunciaRN.listarDenuncias(this.contextoBean.getUsuarioLogado()); } return lista; } public void onPointSelect(ActionEvent event) { FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO, "Point Selected", "Lat:" + denuncia.getLatitude() + ", Long:" + denuncia.getLongitude())); } public void setLista(List<Denuncia> lista) { this.lista = lista; } public Denuncia getDenuncia() { return denuncia; } public void setDenuncia(Denuncia denuncia) { this.denuncia = denuncia; } public String onFlowProcess(FlowEvent event) { return event.getNewStep(); } public ContextoBean getContextoBean() { return contextoBean; } public void setContextoBean(ContextoBean contextoBean) { this.contextoBean = contextoBean; } } This is my data base when i make a dennounce. tipocrime is empty enter image description here A: My mistake was that I was using @RequestScoped instead of @ViewScoped in my bean.
{ "language": "en", "url": "https://stackoverflow.com/questions/44096866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WHILE loop script I am trying to write a script that will continue to prompt a user to enter a grade, until the user enters 999. If the user enters 90 or more, echo A. If the user enters 80 or more, echo B. If the user enters 70 or more, echo C. Otherwise echo Failed. I am thinking this needs a WHILE script. Below is my current code #!/bin/bash # Asuume that the first paramter is going to be a grade if [ $# -lt 1 ]; then echo -n "Please pass a a grade " fi gr=$1 if [ $gr -ge 90 ] then echo "A" elif [ $gr -ge 80 ] then echo "B" elif [ $gr -ge 70 ] then echo "C" else echo "Failed" fi exit 0 The script prompts me, but closes after I enter 1 grade. Thanks in advance A: That's not a prompt, it's just a message. Prompting would be: read -p "Please pass a grade: " gr But this get's into conflict with your following gr=$1, so put this into an else block: if [ $# -lt 1 ] then read -p "Please pass a grade: " gr else gr=$1 fi Note that you don't need a semicolon at the line end; it's the line break, which can be substituted by the semicolon. And you don't need an exit to end a script, if you don't want to exit prematurely. A: As you want to prompt the user to input grades until he enters 999, you should use read instead of command line arguments. As bash doesn't have a do-while loop, we can emulate it's behavior using while as shown below: #!/bin/bash read -p "Please pass a grade " gr while [ $gr -ne 999 ]; do if [ $gr -ge 90 ] then echo "A" elif [ $gr -ge 80 ] then echo "B" elif [ $gr -ge 70 ] then echo "C" else echo "Failed" fi read -p "Please pass a grade " gr done exit 0 A: Please try below code. while true do read -p "Please pass a grade:" gr if [ ${gr} -eq 999 ] then exit 0 elif [ ${gr} -ge 90 ] then echo "A" elif [ ${gr} -ge 80 ] then echo "B" elif [ ${gr} -ge 70 ] then echo "C" else echo "Failed" fi done
{ "language": "en", "url": "https://stackoverflow.com/questions/49664993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: String concatenation of algebric term I would like to add two integers and concatenate their result to a string, that is: Add 1 to $i, and concatenate that result to the string 'icon'. I thought the following syntax would work: $x = 'icon'.$i+1; However it doesn't do what I want - it keeps returning the value 'icon1', disregarding the value of $i. What's the right way to do what I want? A: Try with: $i = 0; // init $i $x = 'icon'.($i+1); If you want to regularly increment $i variable: $x = 'icon'.(++$i); A: try this : $temp = $i+1; $x = 'icon'.$temp; You are getting wrong answer because of "Operator Precedence", Ref this link : http://php.net/manual/en/language.operators.precedence.php Here see the line : left + - . arithmetic and string . has more Precedence than +, So your expression will be like : $x = ('icon'.$i)+1; To solve it either use the method i mentioned above or hsz answer ie : $x = 'icon'.($i+1); A: Operator Precedence explains why this is happening. You can use brackets: $x = 'icon'.($i+1); This should do the job. My test: $i = 18; $x = 'icon'.($i+1); var_dump($x); --> string(6) "icon19"
{ "language": "en", "url": "https://stackoverflow.com/questions/15472456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: distributed associative domains in Chapel Are there any working examples of distributed domain maps for associative and/or opaque domains in Chapel, or any hints on how one would distribute a non-rectangular structure such as a graph over multiple locales? I know about distributed sparse arrays, but I am looking at less structured data. The documentation mentions a prototype domain map for associative domains -- is it available anywhere to experiment with? Thank you. A: Yes, these distributed associative domains are new in 1.19 (which as of this writing will be released soon, but you can try them out using a master branch before then). The documentation for them here has an example: https://chapel-lang.org/docs/master/modules/dists/HashedDist.html
{ "language": "en", "url": "https://stackoverflow.com/questions/55050943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to download files from a FTP using PhantomJS I have a file on a FTP Server. I´m trying to download it using PhantomJS. I´ve tried using the following code: var page = require('webpage').create(); page.open('ftp://USERNAME:PASSWORD@www.mywebsite.com/exempleFIle.xlsx'); phantom.exit(); It runs without throwing any errors, however the file is not downloaded. Is it possible to download it with PhantomJS? My main goal is synchronizing the files in the FTP with my computer, so I can put it in my Google Drive and from there using it in my reports. I use PhantomJS to access some webpages and get some data for the same purpose. Since I´m already using PhantomJS, I thought I could do the same for the ftp server, but if there is a simpler solution that use other methods, I´m open to trying it. Thank You A: PhantomJS is a headless web-browser, it's not an FTP client, so it won't be able to help you. My main goal is synchronizing the files in the FTP with my computer I'd suggest using lftp. lftp -u user,password -e 'mirror /remote/server/files/ /local/computer/files/' ftp.myserver.com This will get files from the remote server to the local computer.
{ "language": "en", "url": "https://stackoverflow.com/questions/34923943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Symfony 3 - Form with OneToMany association in database I work on a OneToMany association in my database. This association work perfectly when I try to add data from fixtures and when I try to return data from database. The problem is with my FormType CommandType which does'nt work. Symfony and Doctrine return this error message : An exception occurred while executing 'INSERT INTO command_product (quantity, command_id, product_id) VALUES (?, ?, ?)' with params [3, null, 1]:\n\nSQLSTATE[23000]: Integrity constraint violation: 1048 Column 'command_id' cannot be null CommandType's code : class CommandType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('establishment', EntityType::class, array( 'class' => Company::class, 'required' => true )) ->add('dateCreation', DateTimeType::class, array( 'widget' => 'single_text', 'format' => 'yyyy-MM-dd', 'required' => true )) ->add('contains', CollectionType::class, array( 'entry_type' => CommandProductType::class, 'required' => true, 'allow_add' => true )) ->add('state',TextType::class, array( 'required' => true )) ->add('totalAmount', MoneyType::class, array( 'required' => true )); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => Command::class )); } public function getBlockPrefix() { return 'appbundle_command'; } } CommandProductType's code : class CommandProductType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('quantity', NumberType::class, array( 'required' => true )) ->add('product', EntityType::class, array( 'class' => Product::class, 'required' => true )); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => CommandProduct::class )); } public function getBlockPrefix() { return 'appbundle_commandproduct'; } } Command's code class : class Command { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var Company $establishment * * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Company") * @ORM\JoinColumn(name="establishment_id", referencedColumnName="id", nullable=false) */ private $establishment; /** * @var DateTime $dateCreation * * @ORM\Column(name="dateCreation", type="datetime", nullable=false) * @Assert\Type("datetime") */ private $dateCreation; /** * @var string $state * * @ORM\Column(name="state", type="string", length=255, nullable=false) * @Assert\Type("string") */ private $state; /** * @var float $totalAmount * * @ORM\Column(name="totalAmount", type="float", precision=10, scale=2, nullable=false) * @Assert\NotBlank() * @Assert\Type(type="float") */ private $totalAmount; /** * @var mixed $contains * * @ORM\OneToMany(targetEntity="AppBundle\Entity\CommandProduct", mappedBy="contain", cascade={"persist", "remove"}) */ private $contains; public function __construct() { $this->contains = new ArrayCollection(); } /** * @var CommandProduct $commandProduct */ public function addContain(CommandProduct $commandProduct = null) { $commandProduct->setContain($this); $this->contains->add($commandProduct); } /** * @param CommandProduct $commandProduct */ public function removeContain(CommandProduct $commandProduct) { if ($this->contains->contains($commandProduct)) { $this->contains->removeElement($commandProduct); } } } CommandOrder's code class : class CommandProduct { /** * @var int $id * * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") * @ORM\Column(type="integer") */ private $id; /** * @var Command $contain * * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Command", inversedBy="contains") * @ORM\JoinColumn(name="command_id", referencedColumnName="id", nullable=false) */ private $contain; /** * @var int $quantity * * @ORM\Column(name="quantity", type="integer", nullable=true, options={"default": 1}) * @Assert\NotBlank() * @Assert\Type(type="int") */ private $quantity; /** * @var Product $product * * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Product") * @ORM\JoinColumn(name="product_id", referencedColumnName="id") */ private $product; }
{ "language": "en", "url": "https://stackoverflow.com/questions/51086012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Signalr: firsttime user, cannot get 'server button event' to 'hub' to 'client' to work hey guys I am trying out siqnalr for the first time and am having some issues getting it to work. I can get the client to call the hub method with no issues. I can get the hub to call the client with no issues. But I want to call the hub from my server side button click event so I can update the client with processing info but no matter what I try I cannot get it to work. does anyone have any ideas? I am probably missing some thing simple but I have no idea what is wrong. here is my code: Global.asax protected void Application_Start(object sender, EventArgs e) { RouteTable.Routes.MapHubs(); } TestHub.cs using System; using System.Linq; using Microsoft.AspNet.SignalR; namespace Hubs { /// <summary> /// Summary description for TestHub /// </summary> public class TestHub : Hub { public void Send(string name, string message) { // Call the broadcastMessage method to update clients. Clients.Caller.broadcastMessage(name, message); } internal static void Send2(string name, string message) { //test 1 IHubContext context = GlobalHost.ConnectionManager.GetHubContext<TestHub>(); context.Clients.All.Send(name, message); //test 2 IHubContext context2 = GlobalHost.ConnectionManager.GetHubContext<TestHub>(); context2.Clients.All.broadcastMessage(name, message); } } } default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="Signalr2._default" %> <!DOCTYPE html> <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <telerik:RadScriptManager ID="RadScriptManager1" Runat="server"> <Scripts> <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" /> <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" /> <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" /> <asp:ScriptReference Path="~/Scripts/jquery.signalR-1.1.2.js"/> <asp:ScriptReference Path="~/signalr/hubs" /> </Scripts> </telerik:RadScriptManager> <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server"> <script type="text/javascript"> $(function () { // Declare a proxy to reference the hub. var ifiHub = $.connection.testHub; // Create a function that the hub can call to broadcast messages. ifiHub.client.broadcastMessage = function (name, message) { // Html encode display name and message. var encodedName = $('<div />').text(name).html(); var encodedMsg = $('<div />').text(message).html(); // Add the message to the page. $('#discussion').append('<li><strong>' + encodedName + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>'); }; //Start the connection. $.connection.hub.start().done(function () { ifiHub.server.send('connection started:', $.connection.hub.id); }); }); </script> </telerik:RadScriptBlock> <asp:Button ID="Button1" runat="server" Text="Server To Client Test" OnClick="Button1_Click" /> <br /><br /> <ul id="discussion"/> </form> </body> </html> default.aspx.cs using System; using System.Linq; using Hubs; using Microsoft.AspNet.SignalR; namespace Signalr2 { public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { //test 1 IHubContext context = GlobalHost.ConnectionManager.GetHubContext<TestHub>(); context.Clients.All.broadcastMessage("Now", DateTime.Now.ToString()); //test 2 IHubContext context2 = GlobalHost.ConnectionManager.GetHubContext<TestHub>(); context2.Clients.All.Send("Now", DateTime.Now.ToString()); //test 3 TestHub.Send2("Now", DateTime.Now.ToString()); string test = ""; } } } A: Methods on hubs to be called from clients need to be public- try switching from Internal to Public for Send2-
{ "language": "en", "url": "https://stackoverflow.com/questions/17350751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Returning Video file to a view on laravel 5.4 I am encountering a problem rendering video to my view in Laravel 5.4. I have a view as follows: <main class="video-player"> @if(!empty($video)) <video id="my-video" class="video-js vjs-big-play-centered" controls data-setup="{}"> <source src="{{url('video/'.$token.'/'.$video)}}" type="{{$video_mime_type}}"> <p class="vjs-no-js"> Please upgrade your browser. </p> </video> @else <div class="alert alert-info"><span class='fa fa-info-circle'></span> Lesson video is unavailable!!! </div> @endif </main> The route for getting the video content is as follows: Route::get('video/{token}/{video}','ResourceController@show_video'); And the ResourceController class is as shown below: <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Storage; use Response; use File; use GuzzleHttp\Mimetypes; use App\Mime; class ResourceController extends Controller { public function __construct() { $this->middleware('auth')->only('show_video'); } ........ ........ public function show_video($token,$filename) { $token=\App\VideoPermission::where('token',$token)->first(); if(!empty($token)) { $token->delete(); $mime_type=Mime::from_extension($filename); return response()->file(storage_path('app/lesson-files/'.$filename),[ 'Content-Type' => $mime_type, 'Content-Disposition' => 'inline; filename="Lesson-file"' ]); } return false; } } When I play it on laptop browser, it plays well as expected but when I try to play the same video on a mobile phone browser (same Chrome browser on both situations), it throws the following exception: UnexpectedValueException: The Response content must be a string or object implementing __toString(), "boolean" given. in /home/username/domainname.com/vendor/symfony/http-foundation/Response.php:409 Please could anyone help me figure out the source of the issue. Thank you A: I have later discovered that the problem is a result of an 'if' condition in the method that returns the file content. So, when the condition is not met for any reason, it returns 'false' as a response instead of the video file therefore resulting in the boolean response I receive. That is the way the code is written to function when the required token is missing as shown below if(!empty($token)) { $token->delete(); $mime_type=Mime::from_extension($filename); return response()->file(storage_path('app/lesson-files/'.$filename),[ 'Content-Type' => $mime_type, 'Content-Disposition' => 'inline; filename="Lesson-file"' ]); } return false; } I later discovered that this happens when the user tries to access the application with an outdated browser which does not fulfill one of the conditions expected to return the video content. In other words, the system is actually working as intended. Thank you to all who tried to assist in one way or the other. I appreciate you all.
{ "language": "en", "url": "https://stackoverflow.com/questions/45168094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show the custom user control(s) in flow layout panel dragging and at the same with a move icon mouse cursor in Winform in c#? How to show the custom user control(s) in flow layout panel dragging and at the same with a move icon mouse cursor in Winforms in c#? I have been working on a Winforms Application and is using drag and drop functionality. I have the drag and drop functionality working, but need to make it more intuitive and user friendly. Part of this will involve actually showing the item being dragged, preferably semi-transparent when dragging and also considered with the mouse down location at the item. What is the easiest way to do this? The items I am dragging are custom user control(s) with text, pictures, data auto-created and in flow layout panel,but I am not even sure where to look for how to do this. I added my code worked here : A) In the main form : public main_form() { InitializeComponent(); flowLayoutPanel1.AllowDrop = true; flowLayoutPanel1.DragDrop += new DragEventHandler(this.flowLayoutPanel1_DragDrop); flowLayoutPanel1.DragEnter += new DragEventHandler(this.flowLayoutPanel1_DragEnter); foreach (uploaded_items c in flowLayoutPanel1.Controls) c.MouseDown += new MouseEventHandler(c_MouseDown); } private void c_MouseDown(object sender, MouseEventArgs e) { uploaded_items data=new uploaded_items(); foreach (uploaded_items c in flowLayoutPanel1.Controls) { if (c._isDragging == true) data = c; } Bitmap bmp = new Bitmap(data.Size.Width, data.Size.Height); data.DrawToBitmap(bmp, new Rectangle(Point.Empty, bmp.Size)); bmp.MakeTransparent(Color.White); Cursor cur = new Cursor(bmp.GetHicon()); Cursor.Current = cur; } private void flowLayoutPanel1_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Move; } private void flowLayoutPanel1_DragDrop(object sender, DragEventArgs e) { uploaded_items data = (uploaded_items)e.Data.GetData(typeof(uploaded_items)); FlowLayoutPanel _destination = (FlowLayoutPanel)sender; Point p = _destination.PointToClient(new Point(e.X, e.Y)); var item = _destination.GetChildAtPoint(p); int index = _destination.Controls.GetChildIndex(item, false); _destination.Controls.SetChildIndex(data, index); _destination.Invalidate(); } B) In the user control : public partial class uploaded_items : UserControl { public uploaded_items() { InitializeComponent(); AllowDrag = true; } public bool AllowDrag { get; set; } public bool _isDragging = false; private int _DDradius = 4; //the min distance the mouse req to dragged so that drag action would be taken private int _mX = 0; //positon on mouse down private int _mY = 0; protected override void OnGotFocus(EventArgs e) { this.BackColor = Color.SandyBrown; base.OnGotFocus(e); } protected override void OnLostFocus(EventArgs e) { this.BackColor = Color.Transparent; base.OnLostFocus(e); } protected override void OnClick(EventArgs e) { this.Focus(); base.OnClick(e); } protected override void OnMouseDown(MouseEventArgs e) { this.Focus(); base.OnMouseDown(e); _mX = e.X; _mY = e.Y; this._isDragging = false; } protected override void OnMouseMove(MouseEventArgs e) { if (!_isDragging) { // This is a check to see if the mouse is moving while pressed. // Without this, the DragDrop is fired directly when the control is clicked, now I have to drag a few pixels first. if (e.Button == MouseButtons.Left && _DDradius > 0 && this.AllowDrag) { int dist_x_dragged = e.X - _mX ; int dist_y_dragged = e.Y - _mY ; if (((dist_x_dragged ^ 2) + (dist_y_dragged ^ 2)) > _DDradius) { DoDragDrop(this, DragDropEffects.All); _isDragging = true; return; } } base.OnMouseMove(e); } } protected override void OnMouseUp (MouseEventArgs e) { _isDragging = false; base.OnMouseUp(e); } #region Properties private string _title; private string _msg; private Image _icon; [Category("Custom Props")] public string title { get { return _title; } set { _title = value; lbl_title.Text = value; } } [Category("Custom Props")] public string msg { get { return _msg; } set { _msg = value; lbl_msg.Text = value; } } [Category("Custom Props")] public Image icon { get { return _icon; } set { _icon = value; pictureBox1.Image = value; } } #endregion } The primary drag and drop function is ok, but I found I could not show the control / picture of the control dragging in this scheme: * *Limited area covered: the bmp only appears when it's mouse down and dragged "carefully" on the user control, and it's only limited on the user control but not the text/ picture on the user control or the flow layout panel *When I try to drag, the bmp disappeared *the bmp is centered at mouse instantaneous location, but I wish it situated at the location at which the mouse initially down on the user control
{ "language": "en", "url": "https://stackoverflow.com/questions/58445776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get output of a php file in separate html form at the middle of screen of lesser size How to get output of a php file in separate html form at the middle of screen of lesser size. See tyhe below part. It is not working. Help pl. <html> <head> <script type="text/javascript"> //This function auto-fills fields the form 'qform' and auto submits. function datcal(subnm, chpno, qsnno) { document.qform.subnm1.value = subnm; document.qform.chpno1.value = chpno; document.qform.qnumber1.value = qsnno; document.getElementById("qform").submit(); } //calling the function with some data datcal('chem11','1','2'); </script> </head> <body> <form> <!-- This is the other part of form here.....--> </form> <!-- I want to get the out put of below form at center of screen separately --> <form id = "qform" name="qform" action="getques.php" style="visibility:hidden" method="post" target="_blank"> <input type="text" name="subnm1" ><br> <input type="text" name="chpno1" ><br> <input type="text" name="qnumber1" ><br> <input type="submit"> </form> </body> </html> The above code is opening a new window but i want the size of that window not full screen but less. How to do that? A: If I understand your question then, The easiest way would be to open create a page which takes all these parameter as query string. You can then open the new page in the window by making it a hyperlink. The new page can also process your input by taking all these parameter from query string. <script language ="javascript"> function submitForm(){ var url = "http://www.newpage.php?subnm1="+value1+"chpno1="+value2 //and like this window.open (url, "acb", "status=no, width=960, height=700") } </script> <a href="#" onclick="submitForm()">Submit</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/19973369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: LCC-- How to stop debugger from breaking at the start of the application? I'm not sure of how many users there are out there that use the LCC C compiler and the WEdit GUI for Windows but it has a "feature" that is can get to be quite annoying. When you start an application with the debugger, it breaks the application at the start of the Main function. How can I cut this off so that the debugger immediately executes the code until I halt it or it hits a break point that I've created? A: Wow, people still use LCC... Last time I used it was ~10 years ago. I decompiled wedit.exe and can confirm there is no official way to disable this behavior. I patched the binary if that works for you. I uploaded it here. To those who concerned about viruses and such I patched wedit taken from here. About box says it's version 4.0 compiled at Sep 16 2009. Here is patched function to those who interested: int __cdecl sub_44CF0D(HANDLE hProcess) { int result; // eax@1 int v2; // ST0C_4@10 int v3; // eax@20 int v4; // eax@23 int v5; // eax@25 int v6; // [sp+10h] [bp-68h]@11 int v7; // [sp+14h] [bp-64h]@1 struct _DEBUG_EVENT DebugEvent; // [sp+18h] [bp-60h]@1 v7 = 1; result = WaitForDebugEvent(&DebugEvent, dwMilliseconds); if ( result ) { sub_44C67A(&DebugEvent); if ( DebugEvent.dwDebugEventCode == 1 ) { if ( DebugEvent.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && !(dword_482860 & 1) && !dword_484328 && DebugEvent.u.Exception.dwFirstChance ) { sub_44E1A5(0); sub_44CEB2(v2); return ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x80010001u); } v6 = 0; v7 = sub_44D2C4((int)&DebugEvent, hProcess, (int)&v6); if ( v6 && DebugEvent.u.Exception.dwFirstChance ) return ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x80010001u); goto LABEL_41; } if ( DebugEvent.dwDebugEventCode == 3 ) { if ( dword_483C94 ) { dword_48428C = 1; LABEL_41: if ( dword_483C6C ) sub_44ECDC(); if ( v7 ) { result = ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x10002u); } else { dword_49BF68 = 1; ResetEvent(dword_484AE4); dword_4843C8 = DebugEvent.dwThreadId; result = sub_4524CD(); } return result; } Sleep(0x32u); dword_49BF64 = 1; dword_49BF68 = 1; qword_483C74 = __PAIR__( (unsigned int)DebugEvent.u.Exception.ExceptionRecord.ExceptionAddress, DebugEvent.u.Exception.ExceptionRecord.ExceptionInformation[2]); if ( dword_484288 ) ::hProcess = (HANDLE)DebugEvent.u.Exception.ExceptionRecord.ExceptionFlags; else ::hProcess = hProcess; dword_483C84 = DebugEvent.dwProcessId; hThread = DebugEvent.u.Exception.ExceptionRecord.ExceptionRecord; dword_483C9C = (HANDLE)DebugEvent.u.Exception.ExceptionRecord.ExceptionCode; dwThreadId = DebugEvent.dwThreadId; dword_483C94 = 0; if ( sub_45A83A() ) { v4 = sub_4026A6(28); dword_484330 = v4; *(_DWORD *)(v4 + 4) = hThread; *(_DWORD *)(v4 + 8) = dwThreadId; if ( dword_484288 ) { sub_455B58(); } else { Sleep(0x64u); v5 = sub_45AAFC(); if ( !v5 ) return PostMessageA(dword_4849EC, 0x111u, 0x64u, 0); if ( dword_484354 ) goto LABEL_50; sub_455B58(); if ( dword_483C70 && *(_DWORD *)(dword_483C70 + 52) ) *(_DWORD *)(*(_DWORD *)(dword_483C70 + 52) + 36) = sub_451577(**(_DWORD **)(dword_483C70 + 52), 1u); v5 = *(_DWORD *)(dword_483C70 + 52); if ( v5 && *(_DWORD *)(v5 + 36) ) { LABEL_50: if ( !dword_483C6C ) sub_44E92A(v5); sub_44CC3D(); sub_451600(); PostMessageA(dword_4849EC, 0x111u, 0x154u, 0); } else { sub_4029CA("Imposible to find %s\nRunning without source display", *(_DWORD *)(dword_483C70 + 20)); dword_484344 = 1; v7 = 1; PostMessageA(dword_4849EC, 0x111u, 0x154u, 0); } } goto LABEL_41; } dword_484338 = 1; v3 = sub_44DB56(qword_483C74); if ( v3 ) *(_BYTE *)(v3 + 29) &= 0xFDu; result = ContinueDebugEvent(DebugEvent.dwProcessId, DebugEvent.dwThreadId, 0x10002u); } else { if ( DebugEvent.dwDebugEventCode != 5 ) goto LABEL_41; if ( DebugEvent.dwProcessId != dword_483C84 ) { v7 = 1; goto LABEL_41; } dword_49BF64 = 0; dword_49BF68 = 1; dword_481614 = 0; result = sub_402A32(4520, SLOBYTE(DebugEvent.u.Exception.ExceptionRecord.ExceptionCode)); if ( !dword_483C6C ) result = sub_40B155(lpCmdLine); } } else { if ( dword_483C6C ) result = sub_44ECDC(); } return result; } if under LABEL_50 is what I patched (from 0x75 to 0xEB). It was easy to spot the place because I expected WriteProcessMemory to be used to write 0xCC at entry-point of application that is being debugged.
{ "language": "en", "url": "https://stackoverflow.com/questions/7012999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: SCNShadable protocol gives internal error during fragment function compilation on newer devices We have written a shader modifier based on the SCNShadable protocol which works well until the number of uniform variables is rather slow (say 5-10). Later we needed to extend the shader modifier and use new uniforms, a total number of 25, including 8 textures and corresponding float4x4 matrices. Then it stopped working, could not compile the fragment function, which gave the following useless error message: Error Domain=AGXMetalA12 Code=3 "Internal error during fragment function compilation" UserInfo={NSLocalizedDescription=Internal error during fragment function compilation} When we reduced the number of float4x4 matrices to 2, it started to work again on an iPhone 7 and other Metal GPU Family 3 devices, but not on Metal GPU Family 4 or newer devices. Our question is if someone knows any limitations that explain this kind of behaviour.
{ "language": "en", "url": "https://stackoverflow.com/questions/60262881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get an array of files to upload I am running into a scenario that I cannot get more than one file to upload. If I add more than one file, only the last one will send through. I know this means I need to put the files into an array, but when I try I get an error from the fileUpload class. IF I change the input html's name to `name="uploadedFile[]"' then I get the following error in my fileUpload class: PHP Warning: basename() expects parameter 1 to be string, array given in /php/fileUpload.php on line 11 PHP Warning: move_uploaded_file() expects parameter 1 to be string, array given in /php/fileUpload.php on line 46 Then in my Communication class, you will see that if there is more than one file being uploaded, I send it as a zip, so I'm not sure if anything would need to be changed in there. Does anyone see what I need to do to get the array to work? HTML: <input type="file" name="uploadedFile" class="inputfile" id="uploadedFileTest" data-multiple-caption="{count} files selected" multiple> FileUpload class: class fileUpload { public function __construct() {} public function upload() { $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["uploadedFile"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION)); // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { return 0; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["uploadedFile"]["tmp_name"], $target_file)) { return basename($_FILES["uploadedFile"]["name"]); } else { return 0; } } } } Rest of the php file: $files = null; if (!empty($_FILES['uploadedFile']['name']) && $_FILES['uploadedFile']['error'] != 4) { $fu = new fileUpload(); $filename = $fu->upload(); $template = str_replace("{filename}", "A file was uploaded. You can download the file from: <a href='https://mbkit.com/php/uploads/{$filename}'>{$filename}</a>", $template); clearstatcache(); } Communication Class - what sends out the attachment(s): if (!empty($file) && !$recipient && count($file['uploadedFile']['name']) > 1) { $f = new ZipArchive(); $zip = $f->open('uploads/' . $file['uploadedFile']['name'][0] . ".zip", ZipArchive::CREATE | ZipArchive::OVERWRITE); if ($zip) { for ($index = 0; $index < count($file['uploadedFile']['name']); $index++) { // echo $file['uploadedFile']['name'][$index] . "\n"; $f->addFile($file['uploadedFile']['tmp_name'][$index], $file['uploadedFile']['name'][$index]); } $f->close(); $message["attachment[0]"] = curl_file_create("uploads/{$file['uploadedFile']['name'][0]}.zip", pathinfo("uploads/{$file['uploadedFile']['name'][0]}.zip", PATHINFO_EXTENSION), $file['uploadedFile']['name'][0] . ".zip"); } else { throw new Exception("Could not zip the files."); } // $message['html'] = str_replace("{filename}", "A file was uploaded. You can download the file from: <a href='https://mbkit.com/php/uploads/{$file['uploadedFile']['name']}.zip'>{$file['uploadedFile']['name']}</a>", $message['html']); } elseif (count($file['uploadedFile']['name']) == 1) { $message["attachment[0]"] = curl_file_create("uploads/{$file['uploadedFile']['name']}", pathinfo("uploads/{$file['uploadedFile']['name']}", PATHINFO_EXTENSION), $file['uploadedFile']['name']); } A: Try inspecting the $_FILES array to see the structure of a single file upload and a mulit-file upload. Here is a small function you can use to visually inspect an array: function varDumpToString($var, $type=false){ ob_start(); var_export($var); $return = ob_get_clean(); return ($type === 'web' ? str_replace("\n", '<br/>', $return) : $return ); } Usage: echo varDumpToString($_FILES, 'web'); Alternatively: error_log(varDumpToString($_FILES));
{ "language": "en", "url": "https://stackoverflow.com/questions/57328909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to configure spark runner for apache beam pipeline for java I'm new to Apache Beam and Apace spark, i want to configure the beam pipeline for spark runner. what is mentioned in the documentation is not clear to me. A: You can pass argument --runner SparkRunner to the pipeline launcher to use spark as the underlying runner. Also, Please share what language of Beam SDK you are using. Python and java have some what different ways to run on Spark via Beam.
{ "language": "en", "url": "https://stackoverflow.com/questions/61276715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: LLVM segmentation fault with opt command when i am trying to run the very simple (Hello world) pass given in llvm (my file is pass Hello.cpp) on a file XX.c (X64 OS) the opt command opt -load ../../../Release+Asserts/lib/Hello.so -hello vv.bc > vv.txt gives this error 0 libLLVM-3.2svn.so 0x00007f314b0f1e52 1 libLLVM-3.2svn.so 0x00007f314b0f22b3 2 libpthread.so.0 0x00007f314a0c7340 3 libstdc++.so.6 0x00007f31499645cb std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(std::string const&) + 11 4 libLLVM-3.2svn.so 0x00007f314aadef1d llvm::createPrintFunctionPass(std::string const&, llvm::raw_ostream*, bool) + 77 5 libLLVM-3.2svn.so 0x00007f314aad1585 llvm::PMTopLevelManager::schedulePass(llvm::Pass*) + 37 6 opt 0x0000000000413e4f main + 4767 7 libc.so.6 0x00007f31492eeec5 __libc_start_main + 245 8 opt 0x000000000040dfca Stack dump: 0. Program arguments: opt -load ../../../Release+Asserts/lib/Hello.so -hello vv.bc Segmentation fault (core dumped) any suggestion would be appreciable. I am new to both Linux and llvm A: Something I found extremely useful is to use the verifier pass. So first, make sure basic opt flow works as intended, and that the input file is legal: opt -verify vv.bc -o out.bc Then make sure your pass results in a legal module: opt -load ../../../Release+Asserts/lib/Hello.so -hello -verify vv.bc -o out.bc If that still won't help, I'd fire up the debugger.
{ "language": "en", "url": "https://stackoverflow.com/questions/25230681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to create fluent interface that can nest generic types many times in C# I'm trying to create a Fluent API that describes a nested structure and as a result I would like to use generics to type the resulting object. I would like to do something like: var test = new Query<Entity>().Select(x => x.UniqueValue<string>()) .Select(x => x.UniqueValue<DateTime>()) .Select(x => x.UniqueValue<decimal>()); Where test would be of type: Result<Entity, string, Result<Entity, DateTime, Result<Entity, decimal>>> So far I have code like: class Program { static void Main(string[] args) { // test : ResultWithResult<Entity,string, Result<Entity, DateTime, ChildLessResult<Entity, decimal>>> var test = new Query<Entity>().Select(x => x.UniqueValue<string>()) .Select(x => x.UniqueValue<DateTime>()) .Select(x => x.UniqueValue<decimal>()); } } public class Entity { public string Item1 { get; set; } } public class Aggregate<TEntity> { public ChildLessResult<TEntity, TReturnValue> UniqueValue<TReturnValue>() { return new ChildLessResult<TEntity, TReturnValue>(); } } public class Query<TEntity> { public ChildLessResult<TEntity, TReturnValue> Select<TReturnValue>(Func<Aggregate<TEntity>, ChildLessResult<TEntity, TReturnValue>> predicate) { var aggregator = new Aggregate<TEntity>(); return predicate(aggregator); } } public class ChildLessResult<TEntity, TReturnValue> { public Result<TEntity, TReturnValue, TChild> Select<TChild>(Func<Aggregate<TEntity>, ChildLessResult<TEntity, TChild>> predicate) { return new Result<TEntity, TReturnValue, TChild>(); } } public class Result<TEntity, TReturnValue, TChild> { private ChildLessResult<TEntity, TChild> _child = new ChildLessResult<TEntity, TChild>(); public ResultWithResult<TEntity, TReturnValue, Result<TEntity, TChild, ChildLessResult<TEntity, TNewChild>>> Select<TNewChild>(Func<Aggregate<TEntity>, ChildLessResult<TEntity, TNewChild>> predicate) { return new ResultWithResult<TEntity, TReturnValue, Result<TEntity, TChild, ChildLessResult<TEntity, TNewChild>>>(); } } public class ResultWithResult<TEntity, TReturnValue, TChild> { } As you can see this is pretty limited since it only allows you to go as deep as the structures you have defined and you would need a new structure for each level deeper. Is it possible to create types that would allow an unlimited number of levels (i.e. as many Selects as you would ever want without the same corresponding number of Types). A: Yes, sort of.... it is possible to create some very long and deep nested types, more or less automatically. The trick is you need to use generic type inference, and since constructors don't do inference, you have to use a factory method. For example: public class MyType<TData,TChild> { public MyType(TData data, TChild child) { } } public class MyTypeFactory { public static MyType<TData,TChild> Create<TData,TChild>(TData data, TChild child) { return new MyType<TData,TChild>(data, child); } public static MyType<TData,object> Create<TData>(TData data) { return new MyType<TData,object>(data, null); } } public static class Program { static public void Main() { var grandchild = MyTypeFactory.Create( 12 ); var child = MyTypeFactory.Create( 13D, grandchild ); var parent = MyTypeFactory.Create( 14M, child) ; var grandparent = MyTypeFactory.Create( 15F, parent ); Console.WriteLine( grandchild.GetType().FullName ); Console.WriteLine( child.GetType().FullName ); Console.WriteLine( parent.GetType().FullName ); Console.WriteLine( grandparent.GetType().FullName ); } } The output: MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] MyType'2[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]] MyType'2[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]] MyType'2[[System.Single, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]] It's even type-safe, amazingly enough. If you add the necessary properties... public class MyType<TData,TChild> { protected readonly TChild _child; protected readonly TData _data; public MyType(TData data, TChild child) { _data = data; _child = child; } public TChild Child { get { return _child; } } public TData Data { get { return _data; } } } ...this will work: var grandchildValue = grandparent.Child.Child.Child.Data; Console.WriteLine(grandchildValue); //12 Console.WriteLine(grandchildValue.GetType().Name); //int32 And of course you can use the builder pattern: public static class ExtensionMethods { static public MyType<TDataAdd,MyType<TDataIn,TResultIn>> AddColumn<TDataIn,TResultIn,TDataAdd>(this MyType<TDataIn,TResultIn> This, TDataAdd columnValue) { return MyTypeFactory.Create(columnValue, This); } } var grandparent = MyTypeFactory.Create( 12 ) .AddColumn( 13D ) .AddColumn( 14M ) .AddColumn( 15F ); var grandchildValue = grandparent.Child.Child.Child.Data; Console.WriteLine(grandchildValue); //12 Console.WriteLine(grandchildValue.GetType().FullName); //System.Int32 See my code on DotNetFiddle P.S. This is a great example of why we needed the var keyword! Otherwise you'd be typing forever.
{ "language": "en", "url": "https://stackoverflow.com/questions/49764089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can declaring POD types throw an exception? When I declare a condition_variable, it may throw std::system_error. But how about when I declare a POD type (e.g. int, double or float)? Like the code below: int main() { //do something int i; //will here throw exception? } If declaring a POD type may throw exception, how do I guarantee void test() noexcept { //do something int i; } is noexcept? A: But how about declare a fundamental type (e.g., int, double or float)? Declaring POD type objects won't cause an exception to be thrown. Constructors of non-POD types can throw exceptions. Only the documents/source code of those types can help you figure out whether that will happen for a particular type. A: It is the constructor of std::condition_variable that can throw an exception. Primitive types like int and double do not have any constructors. They simply have some stack space allocated for them and that's it, plus a value being written if you initialize the variable. The only way this could cause an exception is if you overflow the stack and the ensuing undefined behaviour happens to throw one. A: POD types typically are initialized with initializer expressions instead of constructors. Like constructors, initializers can throw exceptions. But if you have neither a constructor nor an initializer, there's no code associated with the definition and therefore also no possibility for that code to throw.
{ "language": "en", "url": "https://stackoverflow.com/questions/34892423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL query to replace multiple occurrences with the most frequent ones I have a products table, which has the product description in two languages, one in English and one in an alternate language. Let's say: Product_Desc Product_Desc_Alt A A1 A A2 A A1 A A3 B B1 B B2 B B2 C C1 If I do a GROUP BY statement, there are multiple alternate language occurrences for the same product. So, let's say: SELECT Product_Desc, COUNT(DISTINCT Product_Desc_Alt) AS CNT FROM products GROUP BY Product_Desc ORDER BY CNT DESC Product_Desc CNT A 3 B 2 C 1 I would like to replace the Product_Desc_Alt occurrences with the most frequent ones, so for example I would like the output to be: Product_Desc Product_Desc_Alt A A1 A A1 A A1 A A1 B B2 B B2 B B2 C C1 Obviously, if a product has only one alter lang description, just keep that one. There may be lots of ways to do that, but I can't think of one. I am using Azure Databricks so this could also happen with PySpark, but I am interested in doing this the SQL way. Thanks a lot! A: Is this what you mean? UPDATE products SET Product_Desc_Alt = ( SELECT TOP 1 Product_Desc_Alt FROM products P2 WHERE P2.Product_Desc = products.Product_Desc GROUP BY Product_Desc_Alt ORDER BY COUNT(*) DESC )
{ "language": "en", "url": "https://stackoverflow.com/questions/71842667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get text wrapped with I wanted to get the text inside break html but this it's not wrap with paragraph just a text inside break. Division is my only identifier for this which is "Msg". How can I get one of each element? <div name="Msg"style="display:block"> <b> HI! </b> 2017-11-30-15.28.09.133 <br/> <b> 123 </b> abc <br/> Your number is 5. <br/> </div> Draft: HtmlElement msg = (HtmlElement) page.getFirstByXPath("//div[@name='Msg']/text()"); System.err.println(msg.getTextContent()); A: Understood correctly you might want the code output as Your number is 5. <b>123</b> <b>123</b> <b>HI!</b>2017-11-30-15.28.09.133 Maybe you might want to try with StringTokenizer (the codes below will hit java.util.NoSuchElementException as the nextToken() call is forced, but hopefully it will become a general idea) import java.util.StringTokenizer; .. String sampleStr= "Hello <br/> there <br/>"; StringTokenizer token = new StringTokenizer(sampleStr); System.out.println(token.nextToken());//You can use .trim() System.out.println(token.nextToken()); Would this help?
{ "language": "en", "url": "https://stackoverflow.com/questions/47568514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to save media file in app specific folder using Media Store API - Scoped Storage Android I am trying to use scoped storage for Android 10 and above to save images taken from the camera in the app specific folder. I know how to do it using File API but I am looking for to do it with Media store API. Here is the issue, using the below code it saves images in Internal storage > Pictures, but doesn't save it in app specific folder. Hence if I uninstall the app, the images saved by the app still remains in the memory. I want them to get deleted automatically if user removes the app from his phone. Let me know if I am doing it wrong or missing something. private void dispatchTakePictureIntent() throws IOException { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camera activity to handle the intent if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; if (!checkIfVersionCodeQAndAbove()) { try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File return; } // Continue only if the File was successfully created if (photoFile != null) { Uri photoURI = FileProvider.getUriForFile(getActivity().getApplicationContext(), getActivity().getPackageName() + ".provider", createImageFile()); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); } } if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) { startActivityForResult(takePictureIntent, TAKE_PICTURE); } } } private void storeImageUsingMediaApi(Intent data) { if (getActivity()!=null) { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; ContentValues contentValues = new ContentValues(); contentValues.put(MediaStore.Images.Media.TITLE, imageFileName + ".jpg"); contentValues.put(MediaStore.Images.Media.DESCRIPTION, "profile_image"); contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + File.separator + "MyApp"); ContentResolver resolver = getActivity().getContentResolver(); OutputStream stream = null; Uri uri = null; try { Bundle extras = data.getExtras(); Bitmap bitmap = null; if (extras != null) { bitmap = (Bitmap) extras.get("data"); } final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; uri = resolver.insert(contentUri, contentValues); if (uri == null) { throw new IOException("Failed to create new MediaStore record."); } stream = resolver.openOutputStream(uri); if (stream == null) { throw new IOException("Failed to get output stream."); } if (bitmap!=null && !bitmap.compress(Bitmap.CompressFormat.JPEG, 95, stream)) { throw new IOException("Failed to save bitmap."); } stream.close(); selctedImageUri = String.valueOf(uri); Glide.with(getActivity()).load(uri).into(imageProfile); } catch (IOException e) { if (uri != null) { // Don't leave an orphan entry in the MediaStore resolver.delete(uri, null, null); } e.printStackTrace(); } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { CgUtils.showLog(getTag(), "frag onActivityResult"); if (resultCode == Activity.RESULT_OK) { if (requestCode == TAKE_PICTURE) { CgUtils.showLog(getTag(), "frag TAKE_PICTURE"); if (checkIfVersionCodeQAndAbove()) { storeImageUsingMediaApi(data); } else { Uri imageUri = Uri.parse(selctedImageUri); if (imageUri.getPath() != null) { File file = new File(imageUri.getPath()); try { InputStream ims = new FileInputStream(file); imageProfile.setImageBitmap(BitmapFactory.decodeStream(ims)); } catch (FileNotFoundException e) { CgUtils.showLog(TAG, "error " + e.toString()); } } } if (!selctedImageUri.isEmpty()) { if (null != loginResponse) loginResponse.setImageUri(selctedImageUri); new InsertLoginResponse(getActivity(), loginResponse, false).executeOnExecutor(CgUtils.getExecutorType()); sharedPreferencesEditor.putString(CgConstants.USER_PROF_PIC, selctedImageUri); sharedPreferencesEditor.commit(); } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/64330009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Auto dial out issue in asterisk I am applying an auto dial in asterisk using .call file My a.call Channel: DAHDI/g0/09********* MaxRetries: 1 RetryTime: 600 WaitTime: 30 Context: outgoing Extension: 10 Priority: 1 My problem is that every time above number is called by same number means even if i change the dialled number(receiver number above) the caller number is same.How can i set the caller number in an outgoing call? Thanks in advance. A: You can use Channel: DAHDI/g0/09********* MaxRetries: 1 RetryTime: 600 WaitTime: 30 Context: outgoing Extension: 10 Priority: 1 Callerid: 12345 Note, dahdi g0 have be digital trunk and ALLOW change of callerid. A: You just add the parameter on your .call file Callerid: <your_callerid>
{ "language": "en", "url": "https://stackoverflow.com/questions/24210322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fetching cached image not working I was trying to load and cache images in my app for showing on UITableView. The original concepts looks like: if (image in cache){ show cached image; }else{ if (image in file){ show filed image; }else{ load image from web asynchronously; if (finished){ store in cache; store in file; } } } Here's the whole class I created to handle image storage: ImageStore.h @interface ImageStore : NSObject @property (nonatomic, strong) NSCache *imageCache; + (ImageStore*)sharedImageStore; //cache - (void)writeImage: (UIImage*)image ToCacheForKey: (NSString*)imageURL; - (UIImage*)readImageFromCacheForKey: (NSString*)imageURL; - (BOOL)imageCachedForKey: (NSString*)imageURL; //file - (BOOL)writeImage: (UIImage*)image ToPlistFileForKey: (NSString*)imageURL; - (UIImage*)readImageFromPlistFileForKey: (NSString*)imageURL; - (BOOL)imageFiledInPlistForKey: (NSString*)imageURL; @end ImageStore.m #import "ImageStore.h" @implementation ImageStore static ImageStore* sharedImageStore; NSMutableDictionary* plistDictioary; +(ImageStore*)sharedImageStore { if (sharedImageStore == nil){ sharedImageStore= [[self alloc] init]; } return sharedImageStore; } +(id)alloc { { NSAssert(sharedImageStore == nil, @"second singleton"); sharedImageStore = [super alloc]; return sharedImageStore; } return nil; } -(id)init { self = [super init]; if (self != nil) { _imageCache = [[NSCache alloc] init]; } return self; } #pragma mark - Cache - (void)writeImage:(UIImage *)image ToCacheForKey:(NSString *)imageURL{ if(image != nil){ [_imageCache setObject:image forKey:imageURL]; }else{ NSLog(@"NIL image:%@ ",imageURL); } } - (UIImage *)readImageFromCacheForKey:(NSString *)imageURL{ return [_imageCache objectForKey:imageURL]; } - (BOOL)imageCachedForKey:(NSString *)imageURL{ if ([_imageCache objectForKey:imageURL] == nil) { return false; } return true; } #pragma mark - File - (BOOL)writeImage:(UIImage*)image ToPlistFileForKey: (NSString*)imageURL{ NSData *data = [NSKeyedArchiver archivedDataWithRootObject:image]; if (plistDictioary == nil) { plistDictioary = [NSMutableDictionary new]; } [plistDictioary setObject:data forKey:imageURL]; BOOL didWriteSuccessfull = [plistDictioary writeToFile:[self getPlistFilePath] atomically:YES]; return didWriteSuccessfull; } - (UIImage *)readImageFromPlistFileForKey:(NSString *)imageURL{ NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[self getPlistFilePath]]; NSData * data = [dict objectForKey:imageURL]; UIImage * image = [UIImage imageWithData:data]; return image; } - (BOOL)imageFiledInPlistForKey:(NSString *)imageURL{ NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[self getPlistFilePath]]; if ([dict objectForKey:imageURL] == nil) { return NO; }else{ return YES; } } - (NSString*)getPlistFilePath{ NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString * documentsDirectory = [paths objectAtIndex:0]; NSString * path = [documentsDirectory stringByAppendingPathComponent:@"Images.plist"]; return path; } @end Implementation in tableView:cellForRowAtIndex: if ([[ImageStore sharedImageStore]imageCachedForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]]) { //cache NSLog(@"cached"); cell.image = [[ImageStore sharedImageStore] readImageFromCacheForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]]; }else{ NSLog(@"nothing cached"); if ([[ImageStore sharedImageStore] imageFiledInPlistForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]]) { //plist file cell.image = [[ImageStore sharedImageStore] readImageFromPlistFileForKey:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]]; }else{ //loading with UIImage category async method (see below) [UIImage loadFromURL:[NSURL URLWithString:[[dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]] completionBlock:^(BOOL succeeded, UIImage *image) { if (succeeded){ cell.image = image; } }]; } } EDIT Downloaded Images stored in the UIImage Category: + (void)loadFromURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if ( !error ) { UIImage *image = [[UIImage alloc] initWithData:data]; [[ImageStore sharedImageStore] writeImage:image ToCacheForKey:[url absoluteString]];//write to NSCache [[ImageStore sharedImageStore] writeImage:image ToPlistFileForKey:[url absoluteString]];//write to Plist completionBlock(YES,image); } else{ completionBlock(NO,nil); } }]; } (Sorry for the long method naming.) The console returns "nothing cached" for every onscreen cell, and sometimes the scrolling become stutter when checking cache and file. I've been trying handy caching for a couple of days while there's already a bunch of useful image caching library. It'd be nice to know what am I doing wrong with this! Thanks for any advice. A: The problem is in the writeImage:ToPlistFileForKey: method. You convert an image to a data as below: NSData *data = [NSKeyedArchiver archivedDataWithRootObject:image]; But convert the data to image like this: UIImage * image = [UIImage imageWithData:data]; This will always return a nil that because the format of the archived data is NSPropertyListBinaryFormat_v1_0 not PNG(or bitmap format). Instead of using [NSKeyedArchiver archivedDataWithRootObject:image], you should use UIImagePNGRepresentation(image) as below: - (BOOL)writeImage:(UIImage*)image ToPlistFileForKey: (NSString*)imageURL { archivedDataWithRootObject:image]; NSData *data = UIImagePNGRepresentation(image); if (plistDictioary == nil) { plistDictioary = [NSMutableDictionary new]; } [plistDictioary setObject:data forKey:imageURL]; BOOL didWriteSuccessfull = [plistDictioary writeToFile:[self getPlistFilePath] atomically:YES]; return didWriteSuccessfull; } The UIImagePNGRepresentation function which returns the data for the specified image in PNG format, then you get an image [UIImage imageWithData:data]. Hope this will help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/30590943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP stream_context_create with proxy I'm currently developing an web application which uses an XML Interface located on a different server, that I have to access via a proxy. So I tried to set the proxy in a stream_context_create array, but it doesn't seem to work. $set = array( 'http' => array( 'method' => 'GET', 'header' => sprintf( 'Proxy-Authorization: Basic %s', base64_encode(Constants::XML_AUTH) ), 'protocol_version' => '1.1', 'proxy' => '89.122.180.178:46565' ) ); $stream = stream_context_create($set); I'm not quite sure what I'm doing wrong. If I comment out the proxy key i get a 403 Forbidden Response as it should be. If I comment in the proxy key I receive a 400 Bad Request Response. I'm not quite sure what I'm doing wrong. Can you help me out? I never did a communication through a proxy before with PHP. A: My guess is that the proxy declaration is missing the protocol. An URI has to be specified (according to the doc), that contains the protocol (scheme). So this could work: 'proxy' => 'tcp://89.122.180.178:46565'. It might be necessary to remove 'protocol_version' since this may not be required for tcp. Does that work for you? (or have you already solved it? ... ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/11502416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Want to multiply, not repeat variable I want to input a command-line variable and then multiply it, but when I print the variable it repeats by the number I want to multiply it by. eg: #!/usr/bin/env python3 import sys st_run_time_1 = sys.argv[1]*60 print ("Station 1 : %s" % st_run_time_1) When I run the script I get the following: python3 test.py 2 Station 1 : 222222222222222222222222222222222222222222222222222222222222 A: sys.argv[x] is string. Multiplying string by number casue that string repeated. >>> '2' * 5 # str * int '22222' >>> int('2') * 5 # int * int 10 To get multiplied number, first convert sys.argv[1] to numeric object using int or float, .... import sys st_run_time_1 = int(sys.argv[1]) * 60 # <--- print ("Station 1 : %s" % st_run_time_1) A: You are multiplying a string with an integer, and that always means repetition. Python won't ever auto-coerce a string to an integer, and sys.argv is always a list of strings. If you wanted integer arithmetic, convert the sys.argv[1] string to an integer first: st_run_time_1 = int(sys.argv[1]) * 60
{ "language": "en", "url": "https://stackoverflow.com/questions/20401871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NotificationHub Push Notification returns : The Token obtained from the Token Provider is wrong I have Wp8.1 Silverlight app that receives push notification (WNS) from Mobileservice (the old azure service). I therefore wanted to update to the new service because of the new features. I have now created/upgraded a new server to use App Service - Mobile App. And tested push notification with the sample app from azure (everything works). Going back to my app WP8.1 -> Adding the new package Microsoft.Azure.Mobile.Client through NuGet (2.0.1), there is the issue that the Microsoft.WindowsAzure.Mobile.Ext does not contain the 'GetPush' extension. It seems like it is missing it? looking to the WP8 version, it only registers to MPNS, and I need WNS. So I do not know if any other assembly could be used. Can I add another assembly reference? Update The following code lets me register the device on the server, and I can see the device register correctly. where the channelUri and the installationInformation are retrieved by the client and send to the server. Installation ins = new Installation(); ins.Platform = NotificationPlatform.Wns; ins.PushChannel = uTagAndChan.ChannelUri; ins.Tags = uTagAndChan.Tags; ins.InstallationId = uTagAndChan.installationInformation; await hubClient.CreateOrUpdateInstallationAsync(ins); Sending a test toast-notification to the registered tags, results in the following error : The Token obtained from the Token Provider is wrong Searching on this issue I found Windows Store App Push Notifications via Azure Service Bus. Which the proposed solution says to register to the notification hub directly from the app, I would rather not have the app to have directly access to the hub. But is this the only way? (mind you the answer was not accepted, but I will try it all though it is not a desired solution) Update Registering for notifications via client (WP8.1 Silverligt), makes a registration to MPNS, which I do not want. The snippet on the server registers a WNS, the two registrations can be seen here: The URI retrieval is done using var channel = await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); which in the description states it returns a WNS. This seems to infer that the registration I am doing on the server (code snippet in the top) is correct and the registration on the client is faulty. But the registration on the image seems wrong. Shouldn't the PNS Identifier be different for the two registrations? also expiration date seems wrong ? How to mend this since the GetPush() (which was available in the sample registered the client correctly for notifications) does not exist in the NuGet package? Update I read one place that deleting and recreating the NotificationHub could help. I will try this today. Even IF it works, it would be more desirable to have the solution, and to know if the registrations are done correctly? Temporary solution: Deltede, recreated, inserted Package SID and Secret. And it works again (strange)! Still interested in the underlying issue! A: Deleted and recreated the service, setting all the same settings made it work again. A: I had same issue with my UWP. But in my case I had issue with self signed certificate. When I set the AppxPackageSigningEnabled property to True (in .csproj) then notifications stopped working and I got "The token obtained from the Token Provider is wrong" (Test send from Azure Portal). The certificate must have same issuer as Publisher in Identity element in .appxmanifest file.
{ "language": "en", "url": "https://stackoverflow.com/questions/37011339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to turn users input into a list in Python? Here is my code so far. def pfunc(): portList = [] user_choice_port = userPort.get() portList.append(user_choice_port) the userPort is basically a text variable for what the user will enter into an entry box (which will be ports). The user will enter the port numbers like this: 23, 80, 44, etc. How do I take those numbers and put them into a list. Cause whenever I do it puts them in as a string that looks like this: ['23, 80, 44'] When I want it to look like this: [23,80,44] I cannot figure this out so any help would be appreciated A: This should help. user_choice_port = "23, 80, 44" print map(int, user_choice_port.split(",")) print [int(n) for n in user_choice_port.split(",")]
{ "language": "en", "url": "https://stackoverflow.com/questions/24093487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Leads to implement cart in shopping cart using Spring I have implemented shopping cart up to product. But have no idea on how to implement separate cart for each user. Please share your ideas A: Please share your effort / code along with your question always. According to me this can go with many scenarios One of the scenarios would be like, User have One Cart, Cart will have many products and many Products belongs to many carts Code goes as below, You can go ahead and add required parameters to the entity. User Entity import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "USERS") public class User { @Id @Column(name = "ID") @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "USER_NAME") private String userName; @OneToOne(mappedBy = "user", fetch = FetchType.LAZY) private Cart cart; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Cart getCart() { return cart; } public void setCart(Cart cart) { this.cart = cart; } } Cart Entity import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "CART") public class Cart { @Id @Column(name = "ID") @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinColumn(name = "USER_ID") private User user; @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JoinTable(name = "CART_PRODUCT", joinColumns = @JoinColumn(name = "CART_ID") , inverseJoinColumns = @JoinColumn(name = "PRODUCT_ID") ) private Set<Product> products; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Set<Product> getProducts() { return products; } public void setProducts(Set<Product> products) { this.products = products; } } Product Entity import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name = "PRODUCT") public class Product { @Id @Column(name = "ID") @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(name = "name") private String productName; @ManyToMany(cascade = CascadeType.ALL, mappedBy = "products") private Set<Cart> carts; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public Set<Cart> getCarts() { return carts; } public void setCarts(Set<Cart> carts) { this.carts = carts; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/43173237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Format to Currency using DisplayFor Html Helper I have page that will show some currency data. I want to format the data with currency format but only using Display Template. I have the following code: @foreach (var item in Model.Data) { <tr class="@(item.Group%2==0? "odd-colore": "even-colore")"> <td>@Html.DisplayFor(modelItem => item.Name)</td> <td>@Html.DisplayFor(modelItem => item.Amount1)</td> <td>@Html.DisplayFor(modelItem => item.LName)</td> <td>@Html.DisplayFor(modelItem => item.Amount2)</td> <td>@Html.DisplayFor(modelItem => item.Amount3)</td> </tr> } I have created a DisplayTemplate String.cshtml, since my datatype is string: @model string @{ IFormatProvider formatProvider = new System.Globalization.CultureInfo("en-US"); <span class="currency">@Model.ToString("C",formatProvider)</span> } But when I run it, I'm getting the error: No overload for method 'ToString' takes 2 arguments How can I display positive amount as $1000.00 and negative amount as ($1000.00) either using DisplayTemplate or string.Format("{0:C}") A: The problem you're having is because you're trying to convert a string to a currency. From MSDN: The Currency ("C") Format Specifier The "C" (or currency) format specifier converts a number to a string that represents a currency amount. The .ToString(string format, IFormatProvider formatProvider) overload you're trying to use only exists for numeric types, which is why it's not compiling. As an example to demonstrate this: public class TestModel { public decimal Amount { get; set; } public string StringAmount { get; set; } } class Program { static void Main(string[] args) { var model = new TestModel { Amount = 1.99M, StringAmount = "1.99" }; IFormatProvider formatProvider = new CultureInfo("en-US"); // Prints $1.99 Console.WriteLine(model.Amount.ToString("C", formatProvider)); // Prints 1.99 Console.WriteLine(string.Format(formatProvider, "{0:C}", model.StringAmount)); } } So you have a couple of choices: * *Convert your data to a numeric type in the template, and then format it. *Store your data as a numeric type to begin with. I believe 2 is the better option, because you're wanting to work with numeric data, so storing it as a string only adds complexity when it comes to calculating and formatting (as you can see here), as you're always going to have to perform conversions first.
{ "language": "en", "url": "https://stackoverflow.com/questions/42773268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring's CachingConnectionFactory. Why do we need to close sessions although they are to be cached? I am trying to get my head around the Spring CachingConnectionFactory. ActiveMQ documentation recommends when using JmsTemplate that a Spring CachingConnectionFactory or an ActiveMQ PooledConnectionFactory is used as the connection factory implementation. I understand this because using the normal ConnectionFactory a connection is created, a session started, and both are closed for EVERY call of the jmsTemplate.send() which is very wasteful. So I am trying to implement a custom JmsTemplate bean with a CachingConnectionFactory for use where I may have many requests that are A) Persisted to DB B) Enqueued JMS. @Configuration public class JMSConfig { @Autowired private CachingConnectionFactory cachingConnectionFactory; @Bean @Qualifier("jmsTemplateCached") public JmsTemplate jmsTemplateCachingConnectionFactory() { cachingConnectionFactory.setSessionCacheSize(10); JmsTemplate jmsTemplate = new JmsTemplate(); jmsTemplate.setDeliveryMode(DeliveryMode.PERSISTENT); jmsTemplate.setSessionAcknowledgeMode(JmsProperties.AcknowledgeMode.CLIENT.getMode()); jmsTemplate.setSessionTransacted(true); jmsTemplate.setDeliveryPersistent(true); jmsTemplate.setConnectionFactory(cachingConnectionFactory); return jmsTemplate; } } My first question regards the Spring Docs For CachngConnecionFactory which say: SingleConnectionFactory subclass that adds Session caching as well MessageProducer caching. This ConnectionFactory also switches the "reconnectOnException" property to "true" by default, allowing for automatic recovery of the underlying Connection. By default, only one single Session will be cached, with further requested Sessions being created and disposed on demand. Consider raising the "sessionCacheSize" value in case of a high-concurrency environment. But then in bold: NOTE: This ConnectionFactory requires explicit closing of all Sessions obtained from its shared Connection. This is the usual recommendation for native JMS access code anyway. However, with this ConnectionFactory, its use is mandatory in order to actually allow for Session reuse. Does this mean I only need to close sessions if I create a connection "manually" via the template or my CachingConnectionFactory bean? In other words like: Connection connection = jmsTemplateCached.getConnectionFactory().createConnection(); Session sess = connection.createSession(true, JmsProperties.AcknowledgeMode.CLIENT.getMode()); MessageProducer producer = sess.createProducer(activeMQQueue); try { producer.send(activeMQQueue, new ActiveMQTextMessage()); sess.commit(); } catch (JMSException e) { sess.rollback(); } finally { sess.close(); } If I use the template like below, should I close or not close the session? @Autowired public JmsTemplate jmsTemplateCached; @Transactional public InboundResponse peristAndEnqueueForProcessing(InboundForm inboundForm) throws IrresolvableException, JsonProcessingException, JMSException { //Removed for clarity, an entity has been persisted and is then to be enqueued via JMS. log.debug("Queue For Processing : {}", persistedRequest); String serialisedMessage = objectMapper.writeValueAsString(persistedRequest); ActiveMQTextMessage activeMQTextMessage = new ActiveMQTextMessage(); activeMQTextMessage.setText(serialisedMessage); //Will throw JMS Exception on failure Session sessionUsed = jmsTemplateCached.execute((session, messageProducer) -> { messageProducer.send(activeMQQueue, activeMQTextMessage); session.commit(); return session; }); return response; } Secondly, if the above jmsTemplate.execute() throws an exception, what happens to the session? Will it rollback after x time? A: The JmsTemplate reliably closes its resources after each operation (returning the session to the cache), including execute(). That comment is related to user code using sessions directly; the close operation is intercepted and used to return the session to the cache, instead of actually closing it. You MUST call close, otherwise the session will be orphaned. Yes, the transaction will roll back (immediately) if its sessionTransacted is true. You should NOT call commit - the template will do that when execute exits normally (if it is sessionTransacted).
{ "language": "en", "url": "https://stackoverflow.com/questions/67641252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ASP.NET MVC With MEF integration I am following the same approach used in this link in my ASP.NET MVC 2 project and it is working fine. All my pages are partial views (ascx). So I have created a class library in my solution as a plugin the same way done in the link sample and put a new partial view and a controller that is called from the host application using MEF the same way also and it worked fine. The difference in my plugin project is that I created a new folder to put my models in. This code below represent the partial view showing as a plugin view in my host application through MEF successfully <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> <div class="Container"> <p>Hello I am a Plugin Partial View</p> </div> But since I have added a model in my application models folder, I need to bind it to the partial view the same way done in my host ASP.NET MVC 2 host project. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Plugin.Models.ViewModel>" %> <div class="Container"> <p>Hello I am a Plugin Partial View</p> </div> Once adding the ViewModel to the partial view an error shows in firebug and my view is not loading anymore. The error in http response showing in firebug looks as follows: <!DOCTYPE html> <html> <head> <title>Parser Error</title> <meta name="viewport" content="width=device-width" /> <style> body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } pre {font-family:"Consolas","Lucida Console",Monospace;font- size:11pt;margin:0;padding:0.5em;line-height:14pt} .marker {font-weight: bold; color: black;text-decoration: none;} .version {color: gray;} .error {margin-bottom: 10px;} .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; } @media screen and (max-width: 639px) { pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; } } @media screen and (max-width: 479px) { pre { width: 280px; } } </style> </head> <body bgcolor="white"> <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1> <h2> <i>Parser Error</i> </h2></span> <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif "> <b> Description: </b>An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. <br><br> <b> Parser Error Message: </b>Could not load type 'System.Web.Mvc.ViewUserControl&lt;Plugin.Models.ViewModel&gt;'.<br><br> <b>Source Error:</b> <br><br> <table width=100% bgcolor="#ffffcc"> <tr> <td> <code><pre> Line 11: --%&gt; Line 12: <font color=red>Line 13: &lt;%@ Control Language=&quot;C#&quot; Inherits=&quot;System.Web.Mvc.ViewUserControl&lt;Plugin.Models.ViewModel&gt;&quot; %&gt; </font>Line 14: Line 15: </pre></code> </td> </tr> </table> <br> <b> Source File: </b> /Modules/Message/Views/Message/PartialView.ascx<b> &nbsp;&nbsp; Line: </b> 13 <br><br> <hr width=100% size=1 color=silver> <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18010 </font> </body> </html> <!-- [HttpException]: Could not load type &#39;System.Web.Mvc.ViewUserControl&lt;Plugin.Models.ViewModel&gt;&#39;. at System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError) at System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly) at System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData) [HttpParseException]: Could not load type &#39;System.Web.Mvc.ViewUserControl&lt;Plugin.Models.ViewModel&gt;&#39;. at System.Web.UI.TemplateParser.ProcessException(Exception ex) at System.Web.UI.TemplateParser.ParseStringInternal(String text, Encoding fileEncoding) at System.Web.UI.TemplateParser.ParseString(String text, VirtualPath virtualPath, Encoding fileEncoding) [HttpParseException]: Could not load type &#39;System.Web.Mvc.ViewUserControl&lt;Plugin.Models.ViewModel&gt;&#39;. at System.Web.UI.TemplateParser.ParseString(String text, VirtualPath virtualPath, Encoding fileEncoding) at System.Web.UI.TemplateParser.ParseFile(String physicalPath, VirtualPath virtualPath) at System.Web.UI.TemplateParser.Parse() at System.Web.Compilation.BaseTemplateBuildProvider.get_CodeCompilerType() at System.Web.Compilation.BuildProvider.GetCompilerTypeFromBuildProvider(BuildProvider buildProvider) at System.Web.Compilation.BuildProvidersCompiler.ProcessBuildProviders() at System.Web.Compilation.BuildProvidersCompiler.PerformBuild() at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath) at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean throwIfNotFound) at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp) at System.Web.Mvc.WebFormViewEngine.FileExists(ControllerContext controllerContext, String virtualPath) at System.Web.Mvc.VirtualPathProviderViewEngine.GetPathFromSpecificName(ControllerContext controllerContext, String name, String cacheKey, String[]& searchedLocations) at System.Web.Mvc.VirtualPathProviderViewEngine.GetPath(ControllerContext controllerContext, String[] locations, String[] areaLocations, String locationsPropertyName, String name, String controllerName, String cacheKeyPrefix, Boolean useCache, String[]& searchedLocations) at System.Web.Mvc.VirtualPathProviderViewEngine.FindView(ControllerContext controllerContext, String viewName, String masterName, Boolean useCache) at System.Web.Mvc.ViewEngineCollection.<>c__DisplayClass6.<FindView>b__5(IViewEngine e) at System.Web.Mvc.ViewEngineCollection.Find(Func`2 cacheLocator, Func`2 locator) at System.Web.Mvc.ViewResult.FindView(ControllerContext context) at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass14. <InvokeActionResultWithFilters>b__11() at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) at System.Web.Mvc.Controller.ExecuteCore() at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4() at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0() at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) --> I have also copied the web.config file and added the model namespace as following: <system.web> <pages> <namespaces> <add namespace='Plugin.Models.ViewModel' /> </namespaces> </pages> </system.web> But this is not working either. A: See Tom Clarkson answer on Views in separate assemblies in ASP.NET MVC
{ "language": "en", "url": "https://stackoverflow.com/questions/17566983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: datetime field won't update in MySQL Database Hi I am having an issue with updating a users last login time in my database, if I set it to update a different column it works perfectly, but it just does not work when i try to update the specific column "lastlogin". My code: @mysql_query("UPDATE my_users SET lastlogin=NOW() WHERE id=".$_SESSION["id"]); My DB column: column name: lastlogin type: datetime Null: No Default: 0000-00-00 00:00:00 Anything wrong with the way the column is setup in the DB? Like I mentioned above if I was to tell it to put NOW() in another column it works fine. A: Solved. There was another similar statement further down which was over riding this one! How stupid of me but easy to miss! A: use mysql_error to try and find what is wrong, then post that into here so we can help if you need it. (Would comment but to low rep) A: From my experience in the past, mysql_query() doesn't necessarily substitute variables before executing sql. Try writing in this format. Also use mysql_error to check if there are any issues with your code execution: $sql = "UPDATE my_users SET lastlogin=NOW() WHERE id=".$_SESSION["id"]; mysql_query($sql) or die(mysql_error()); If there is no error, then there are few possibilities as to why the laslogin entry is not happening: * *$_SESSION["id"] does not hold any value and no value is being passed to mysql. *There is no id matching with $_SESSION["id"]. To debug: * *Also try updating some other columns. *You might also want to check if you are using correct extensions like PDO.. Also found that, earlier version of mysql doesn't support updating datetime column with now(). In that case try resetting column type to TIMESTAMP. Refer this for details: https://bugs.mysql.com/bug.php?id=27645
{ "language": "en", "url": "https://stackoverflow.com/questions/44092365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How can I model association between two polymorphic classes without using an enumeration I am using an enum to label two different classes of products - a SensorDevice and a [data]CaptureDevice. They are intended to be used physically plugged to one another, but not every sensor model can be used by each receiver model, so I created an Enum for the different platforms, so the GUI would only display the compatible accessories for a given device: enum Platform { Standard, Deluxe, Jumbo } abstract class CaptureDevice { public Platform platform; public bool IsCompatibleWith(SensorDevice sd) { return sd.Platforms.Contains(this.Platform); // <- this is type-checking! } } abstract class SensorDevice { public IEnumerable<Platform> Platforms; public bool IsCompatibleWith(CaptureDevice cd) { return this.Platforms.Contains(cd.Platform); // <- this is type-checking! } } I started to find this quite smelly, since the enum is hard-coded. I am considering to use "Replace Type Code by Polymorphism" refactor, but I am not quite sure how to do it for this situation. Any suggestion? A: You could do the following to get rid of enum. Replace enum with a class. public abstract class Platform {} Add Device class which answers if it's compatible with a Platform. public abstract class Device { public abstract bool IsCompatibleWith(Platform platform); } Make CaptureDevice a subclass of Device. public abstract class CaptureDevice : Device { public Platform Platform; public override bool IsCompatibleWith(Platform platform) { // I'm using type comparison for the sake of simplicity, // but you can implement different business rules in here. return this.Platform.GetType() == platform.GetType(); } public bool IsCompatibleWith(SensorDevice sd) { // We are compatible if sensor is compatible with my platform. return sd.IsCompatibleWith(this.Platform); } } Make SensorDevice a subclass of Device. public abstract class SensorDevice : Device { public IEnumerable<Platform> Platforms; public override bool IsCompatibleWith(Platform platform) { // I'm using type comparison again. return this.Platforms.Any(p => p.GetType() == platform.GetType()); } public bool IsCompatibleWith(CaptureDevice cd) { // We are compatible if capture is compatible with one of my platforms. return this.Platforms.Any(p => cd.IsCompatibleWith(p)); } } Basically, that's all you need to do. To illustrate how it works, I've added the code below. // Platforms public class StandardPlatform : Platform { } public class DeluxPlatform : Platform { } public class JumboPlatform : Platform { } // Capture device(s) public class CD1 : CaptureDevice { public CD1() { Platform = new StandardPlatform(); } } // Sensor device(s) public class SD1 : SensorDevice { public SD1() { Platforms = new List<Platform> { new StandardPlatform(), new DeluxPlatform() }; } } public class SD2 : SensorDevice { public SD2() { Platforms = new List<Platform> {new JumboPlatform()}; } } // Somewhere in the code... var cd1 = new CD1(); var sd1 = new SD1(); Console.WriteLine(cd1.IsCompatibleWith(sd1)); // True Console.WriteLine(sd1.IsCompatibleWith(cd1)); // True var sd2 = new SD2(); Console.WriteLine(sd2.IsCompatibleWith(cd1)); // False Console.WriteLine(cd1.IsCompatibleWith(sd2)); // False A: EDIT: If you want to get rid off the enum, why shouldn't use a config file ? You configure your platforms like this: <Platforms> <Platform name="Standard"> <Device>Namespace.of.your.Device.CaptureDevice</Device> <Device>Namespace.of.another.Device.AnotherDevice</Device> </Platform> <Platform name="Deluxe"> <Device>Namespace.of.your.Device.CaptureDevice</Device> </Platform> </Platforms> Other syntax: <Platforms> <Platform> <Name>Standard</Name> <Devices> <Device>Namespace.of.your.Device.CaptureDevice</Device> <Device>Namespace.of.another.Device.AnotherDevice</Device> <Devices> </Platform> </Platforms> Then, you have the same base structure, you could do something like this: abstract class ADevice<T> where T : ADevice<T> { public ADevice<T>(T device , string filename) { // Parsing of the file // Plus, setting the Platforms Property } // Or (but you should keep the first constructor to see the filename dependency) public ADevice<T>(T device) { // Parsing of the file } public IEnumerable<Platform> Platforms { get; private set; } public bool IsCompatibleWith(T device) { return this.Platforms.Contains(device.Platform); // <- this is type-checking! } } Then: abstract class CaptureDevice : ADevice<CaptureDevice> { public CaptureDevice(CaptureDevice device, string filename) : base(device, filename) { } // Or (But still same comment) public CaptureDevice(CaptureDevice device) : base(device, defaultFilename) { } } Same for SensorDevice And instead of the Enum, you can create a simple class for the moment as: public class Platform { public Platform(string name) { Name = name; } public string Name { get; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/39898585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: List.Remove(T item) removing item from original List I have the following code foreach (var d in dots) { var _tempPointList = new List<Point>(); _tempPointList = _pointList; foreach (var point in _tempPointList) { if (d >= point.X && d <= point.Y) { _tempPointList.Remove(point); } } } so when the integer d is between X and Y of the point type, it will be removed from the temporary list because the next d doesn't have to check the same _tempPointList element. But when the code reaches _tempPointList.Remove(point); the point element is getting removed from the _tempPointList and _pointList which I felt strange. Why is it removing from the main list as well? A: Because you are working on the same list. You are assigning effectively the same instance to _tempPointList in this line (and removing the reference to your original _tempPointList which you created in the line above.): _tempPointList = _pointList; I'd suggest you instantiate your copy list by directly copying the list with this call: var _tempPointList = new List<Point>(_pointList); //creates a shallow copy I see yet another problem: you are removing elements from a list while you are iterating over it. Don't you get an System.InvalidOperationException when continuing to iterate? I'd solve this by iterating over the original list and remove from the copy list like this: foreach (var d in dots) { var _tempPointList = new List<Point>(_pointList); foreach (var point in _pointList) { if (d >= point.X && d <= point.Y) { _tempPointList.Remove(point); } } _pointList = _tempPointList; } As mentionend in the comments of your question, you could just use a predicate on List.RemoveAll() which deletes an item if the predicate returns true. I didn't test the performance, but feel free to compare. foreach (var d in dots) { _pointList.RemoveAll(point => d >= point.X && d <= point.Y); } A: You will need to make a copy of the list for your logic to work. // instead of this var _tempPointList = new List<Point>(); // make a copy like this var _tempPointList = new List<Point>(_pointList); Otherwise, you have just copied a reference to the list and both _tempPointList and _pointList point to same memory A: You're having this problem because both _tempPointList and _pointList have the same reference so when you modify one list the other is modified automatically. another problem you're having is with Foreach you can't moidify a list when iterating over it using Foreach
{ "language": "en", "url": "https://stackoverflow.com/questions/30454526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C0209: Formatting a regular string which could be a f-string (consider-using-f-string) For the below line, I am getting pylint issue: " C0209: Formatting a regular string which could be a f-string (consider-using-f-string)" auth = str(base64.b64encode(bytes("%s:%s" % (self.user, self.password), "utf-8")), "ascii").strip() I tried resolving it, but I am not sure if it is the right way to fix it. Can someone please advise? auth = str(base64.b64encode(bytes(f'{self.user, self.password}', "utf-8")), "ascii").strip() A: auth = str(base64.b64encode(bytes(f'{self.user}:{self.password}', "utf-8")), "ascii").strip() You may not be using the f-string correctly, change f'{self.user, self.password}' to f'{self.user}:{self.password}' More info
{ "language": "en", "url": "https://stackoverflow.com/questions/73325378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Encoding Issue with PHP and MySQL In MySQL with phpmyadmin my text looks like: & eacute; <-- no space, added to see. When I read it into PHP and print it to the error_log it looks like: \xe9 When I try to look at it in a web browser it looks like: � It should look like this in the web browser: é Does anyone know what is wrong? my html page has the tags <meta charset='UTF-8'> and <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> A: Is your database set to use uft8_unicode_ci charset? A: Solved: I had to change the my.cnf file my MySQL [client] default-character-set=utf8 [mysql] default-character-set=utf8 [mysqld] collation-server = utf8_unicode_ci init-connect='SET NAMES utf8' character-set-server = utf8
{ "language": "en", "url": "https://stackoverflow.com/questions/22738422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to move a WordPress website to my computer for development? I was just hired to work in web design with WordPress and I'm struggling because I'm not experienced with the platform. My job is, basically, take the design made in Adobe Illustrator and build the layout in HTML and CSS. Today I was assigned a site that's already online and had to build the new layout. My instructions were to activate the new template in the WordPress wp-admin, to create the new files (index.php, header.php, footer.php and style.css) in the FTP server and build from there. Everything OK with that except that when I'm working on the site (maybe 3 or 4 hours), the site is kinda down because I'm uploading the new (incomplete) layout, am I explaining correctly?. E.g., if the web address is theclientsite.com I go to theclientsite.com/wp-admin/themes, define and activate new theme, write the code and test it directly in the browser going to theclientsite.com. The question is: is there a way to work locally with the WordPress installation? I mean a way to test the site in something like localhost/theclientsite in the browser. My intuition says that the answer is YES, because we're talking about php code. But, as I said, I'm not experienced in the WordPress platform. I don't know if I need to be connected to a WordPress's server or something like that, or if I need to install something in my machine. Any help, guide or tutorial is welcomed and will be appreciated. Thanks in advance for your answers. A: Yes, it is possible to work offline by installing locally: * *Apache / Nginx *PHP *MySQL That can be done...: * *with WampServer (Windows) *with XAMPP (ALL) *with MAMP (OSX) *manually by installing all apps. You will have to edit your host file to map the domain.com to your localhost (127.0.0.1). The reason is that, by default, WordPress is not domain agnostic, which means absolute links (including the domain) are stored in the database. Otherwise, you will need to edit the data to map it to localhost. As you are new with WordPress, I will remind you to backup the website BEFORE doing any change. A free tool like BackWPup can do the job to backup all files and the database. The changes you made on the website were made directly in production (meaning on the live site). That is a really bad practice, as you probably know why now, because your visitors see and incomplete and buggy website. That is why you need a dev environment where you can build and test everything. If you did not do any backup and feel screwed, you can install a maintenance plugin like Ultimate Coming Soon Page and configure it to tell your visitors that the site is having a make over and come back later. As for tutorials, I would start with How to install WordPress with WampServer. First, you will understand how to install WordPress... in general. Once you understand this part, you are ready to export an existing website and import it locally. I would suggest to read more about How move a WordPress website locally. This is a start! Use Google as you go... it will help a lot! :-) A: You can install XAMPP packages that ships with Apache, Mysql (MariaDB actually) and PHP environments. All already configured so you can just Next > Next > Install. https://www.apachefriends.org/pt_br/index.html A: I've always preferred working directly on the remote server using Aptana with built-in FTP client. I've known others that prefer working locally using WAMP. https://sourceforge.net/projects/wampserver/
{ "language": "en", "url": "https://stackoverflow.com/questions/38840598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: accessors in class extending JPanel I'm writing a clone of Risk in Java, and am having some trouble with my code. When I create a new game, I create a JPanel with a JTextField (for the player name) and a JComboBox(for the player color), one panel for each player the user wants to create. Instances of this panel are created dynamically based on a second JComboBox which lets the user select a number of players from three to eight. My problem is that when I want to create the player objects from the data entered into the player creation panel, each player object retrieves the data from the most-recently-created player creation panel. I have a functional solution, but I can't seem to figure out why what seems to be the 'proper' solution () won't work. This is the code that I have working right now: Creation panel class: package risk; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class PlayerCreatePanel extends JPanel{ public static ImageIcon[] playerColors = {Resources.red,Resources.green,Resources.blue,Resources.cyan,Resources.magenta,Resources.yellow,Resources.orange,Resources.gray}; public JComboBox playerColor; public JTextField playerName; public PlayerCreatePanel(int index){ this.setPreferredSize(new Dimension(360, 30)); JLabel numberLabel = new JLabel ("Player " + index + ": "); JLabel nameLabel = new JLabel("Name: "); JLabel colorLabel = new JLabel(" Color: "); playerName = new JTextField(""); playerName.setColumns(13); playerColor = new JComboBox(playerColors); this.add(numberLabel); this.add(nameLabel); this.add(playerName); this.add(colorLabel); this.add(playerColor); } } And for the new game class, the part that creates players: package risk; import java.awt.Color; import java.awt.Dimension; import javax.swing.JPanel; public class NewGame { private static PlayerCreatePanel [] panels = { new PlayerCreatePanel(1), new PlayerCreatePanel(2), new PlayerCreatePanel(3), null, null, null, null, null}; private static int playerCount = 3; public static void createPlayers(){ Resources.players = new Player[playerCount]; switch(playerCount){ case 8: Resources.players[7] = new Player (panels[7].playerName.getText(), Resources.colors[panels[7].playerColor.getSelectedIndex()], 8); case 7: Resources.players[6] = new Player (panels[6].playerName.getText(), Resources.colors[panels[6].playerColor.getSelectedIndex()], 7); case 6: Resources.players[5] = new Player (panels[5].playerName.getText(), Resources.colors[panels[5].playerColor.getSelectedIndex()], 6); case 5: Resources.players[4] = new Player (panels[4].playerName.getText(), Resources.colors[panels[4].playerColor.getSelectedIndex()], 5); case 4: Resources.players[3] = new Player (panels[3].playerName.getText(), Resources.colors[panels[3].playerColor.getSelectedIndex()], 4); case 3: Resources.players[2] = new Player (panels[2].playerName.getText(), Resources.colors[panels[2].playerColor.getSelectedIndex()], 3); Resources.players[1] = new Player (panels[1].playerName.getText(), Resources.colors[panels[1].playerColor.getSelectedIndex()], 2); Resources.players[0] = new Player (panels[0].playerName.getText(), Resources.colors[panels[0].playerColor.getSelectedIndex()], 1); break; default: break; } } } Now, what I've learned is the proper way to do this is to make my JTextField and JComboBox private, and write accessors, like so: private JComboBox playerColor; private JTextField playerName; //...same method as above public static String getName(){ return playerName.getText(); } public static int getColorIndex(){ return playerColor.getSelectedIndex(); } and change the creation lines in the new game method to read something like this: Resources.players [0] = new Player (panels[0].getName(), panels[0].getColorIndex(), 1);
{ "language": "en", "url": "https://stackoverflow.com/questions/12732048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Two RigidBodies - How Do I Make One Immobile? In a 2D shooter, I have one RigidBody that is a rotating wall. My player (ship) is another RigidBody. Both have gravity of 0 and are non-kinematic. I want the ship to not be able to move the wall, but to halt up against it. Currently, the ship hits it and both are affected by the collision and start floating around. Is the proper way to accomplish this to set the constrain Y and Z on the rotating wall so that it can't be moved by a collision with the ship? When I do this, the rotating wall's rotation stops working so before I go further down that path I wanted to see if this is the canonical approach to making something with a rigidbody immobile (constraining X and Y). A: Make the one you don't want to move kinematic A: I've been through this, I had a wall and a character with RigidBody. I didn't want the wall to move in a collision with the character, to solve that, I just made the wall a LOOOTT heavier than the character, just make the "MASS" of the wall very high! The character will not be able to move it! /o/ Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/32084105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do restructure the trip data to prepare a link data using spread and gather functions in R? I have a trip data set as follows: df <- data.frame(user =c("P001", "P001", "P002"), tripID = c("tid1", "tid2", "tid3"), mode =c("bus", "train", "taxi"), Origin = c("Westmead", "Redfan", "Westmead"), Destination = c("Redfan", "Darlington", "Strathfield"), depart_dt = c("8:00", "8:30", "8:45") ) I need to restructure the above data using probably spread() and gather() functions from tidyr to prepare a link trip data as follows: df_new <- data.frame(user=c("P001", "P002"), tripID = c("newtid1", "newtid2"), mode = c("bus + train", "taxi"), Origin = c("Westmead", "Westmead" ), Destination = c("Darlington", "Strathfield"), depart_dt = c("8:00", "8:45")) I am a new bee in R. Can anyone help me here? Many thanks in advance. A: Using dplyr: library(dplyr) df <- data.frame(user =c("P001", "P001", "P002"), tripID = c("tid1", "tid2", "tid3"), mode =c("bus", "train", "taxi"), Origin = c("Westmead", "Redfan", "Westmead"), Destination = c("Redfan", "Darlington", "Strathfield"), depart_dt = c("8:00", "8:30", "8:45") ) df %>% group_by(user) %>% arrange(depart_dt, .by_group = TRUE) %>% summarize(Origin = Origin[1], mode = paste(mode, collapse = " + "), Destination = Destination[length(Destination)], depart_dt = depart_dt[1]) %>% mutate(tripID = paste0("newtid", row_number())) #> # A tibble: 2 x 6 #> user Origin mode Destination depart_dt tripID #> <fct> <fct> <chr> <fct> <fct> <chr> #> 1 P001 Westmead bus + train Darlington 8:00 newtid1 #> 2 P002 Westmead taxi Strathfield 8:45 newtid2 Created on 2020-05-06 by the reprex package (v0.3.0) A: You don't need to use spread() or gather() (or their successors pivot_longer. and pivot_wider(). The below should give you what you want. library(tidyverse) df %>% group_by(user) %>% arrange(tripID, .by_group = TRUE) %>% summarise(mode = str_c(mode, collapse = " + "), Origin = first(Origin), Destination = last(Destination), depart_dt = first(depart_dt)) %>% mutate(tripID = str_c("newtrid", row_number())) # user mode Origin Destination depart_dt tripID # <fct> <chr> <fct> <fct> <fct> <chr> # 1 P001 bus + train Westmead Darlington 8:00 newtrid1 # 2 P002 taxi Westmead Strathfield 8:45 newtrid2
{ "language": "en", "url": "https://stackoverflow.com/questions/61636854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Workflow Foundation Threading and WCF OperationContext I am using the WorkFlowServiceHost(in .net 3.5) to host a State Machine Workflow. I use the WCF receive activities to handle calls into the workflow. I am using a WCF authorization policy to attach claims to the incoming requests based on info in the message headers. So, further down the chain I can use the ServiceSecurityContext or just the Thread.CurrentPrincipal to get authorization info about the request(roles, user, etc). I know this will not work for us because the workflow is dispatching different threads to handle the events that the runtime engine raises when there is work to do(ie. the receiveactivity). The contextual info about the request(OperationContext) is no longer available within the workflow(except randomly when the work is executed on the runtime thread). What I would like to do is get the info about the request(OperationContext) before the worker thread is created, get the worker thread and attach the contextual info to it so it is available within the workflow instance. I am thinking there must be some event on the runtime I can handle to do this but I am not coming up with anything. And I really don't want to use the manual workflow scheduler. Any help is appreciated. Thanks! A: I'm pretty late with this, but I was googling "silverlight operationcontext" and found your SO question as well as the blog post that I am linking (one right after the other in the Google results). I don't know if it will help or not (he says, almost two years later). I haven't worked much with WCF and not at all with WFF, so I don't really have much to add aside from this link.
{ "language": "en", "url": "https://stackoverflow.com/questions/541039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: App delegate methods aren't being called in iOS 13 I am using Xcode 11 and building an app for iOS 13. In a new project I created in Xcode some of the UIApplicationDelegate methods were missing so I added them back into the app delegate file. The new template for a "Single View App" project was missing the methods. The problem is that none of the delegate methods are getting called except -application:didFinishLaunchingWithOptions:. Here is my app delegate: @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSLog(@"application:didFinishLaunchingWithOptions:"); return YES; } - (void)applicationDidEnterBackground:(UIApplication *)application { NSLog(@"applicationDidEnterBackground:"); } - (void)applicationWillEnterForeground:(UIApplication *)application { NSLog(@"applicationWillEnterForeground:"); } #pragma mark - UISceneSession lifecycle - (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options { return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role]; } - (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions { } @end A: This thread helped me: View controller responds to app delegate notifications in iOS 12 but not in iOS 13 Objective C: if (@available(iOS 13.0, *)) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UISceneWillDeactivateNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidBecomeActive:) name:UISceneDidActivateNotification object:nil]; } else { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(appDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil]; } A: Application and scene lifecycle is not the same thing! In my opinion, disabling calls of application state change methods (as well as sending application state change notifications on change the state of each scene) is a mistake, even though there was an understandable intention to force programmers to adapt to the new scenes lifecycle. Here is a scene delegate template restoring the expected calls of application state change methods of the application delegate: @available(iOS 13.0, *) class SceneDelegate: UIResponder, UIWindowSceneDelegate { func sceneWillResignActive(_ scene: UIScene) { if !UIApplication.shared.connectedScenes.contains(where: { $0.activationState == .foregroundActive && $0 != scene }) { UIApplication.shared.delegate?.applicationWillResignActive?(.shared) } } func sceneDidEnterBackground(_ scene: UIScene) { if !UIApplication.shared.connectedScenes.contains(where: { $0.activationState == .foregroundActive || $0.activationState == .foregroundInactive }) { UIApplication.shared.delegate?.applicationDidEnterBackground?(.shared) } } func sceneWillEnterForeground(_ scene: UIScene) { if !UIApplication.shared.connectedScenes.contains(where: { $0.activationState == .foregroundActive || $0.activationState == .foregroundInactive }) { UIApplication.shared.delegate?.applicationWillEnterForeground?(.shared) } } func sceneDidBecomeActive(_ scene: UIScene) { if !UIApplication.shared.connectedScenes.contains(where: { $0.activationState == .foregroundActive && $0 != scene }) { UIApplication.shared.delegate?.applicationDidBecomeActive?(.shared) } } } SceneDelegate.swift A: iOS 13 has a new way of sending app lifecycle events. Instead of coming through the UIApplicationDelegate they come through the UIWindowSceneDelegate which is a UISceneDelegate sub-protocol. UISceneDelegate has the important delegate methods. This change is to support multiple windows in iOS 13. There's more information in WWDC 2019 session 212 "Introducing Multiple Windows on iPad". The technical information starts at around 14:30 and is presented by a man with very sparkly high-tops. The shorter session 258 Architecting Your App for Multiple Windows also has a great introduction to what's changed. Here's how it works: If you have an "Application Scene Manifest" in your Info.plist and your app delegate has a configurationForConnectingSceneSession method, the UIApplication won't send background and foreground lifecycle messages to your app delegate. That means the code in these methods won't run: * *applicationDidBecomeActive *applicationWillResignActive *applicationDidEnterBackground *applicationWillEnterForeground The app delegate will still receive the willFinishLaunchingWithOptions: and didFinishLaunchingWithOptions: method calls so any code in those methods will work as before. If you want the old behaviour back you need to * *Delete the "Application Scene Manifest" entry from the app's Info.plist *Comment or delete the application:configurationForConnectingSceneSession:options: method (or the Swift application(_:configurationForConnecting:options:)function) *Add the window property back to your app delegate (@property (strong, nonatomic) UIWindow *window;) Alternatively, open the SceneDelegate file that Xcode made and use the new lifecycle methods in there: - (void)sceneDidBecomeActive:(UIScene *)scene { } - (void)sceneWillResignActive:(UIScene *)scene { } ... etc It's possible to use the new UIScene lifecycle stuff without adopting multiple window support by setting "Enable Multiple Windows" ("UIApplicationSupportsMultipleScenes") to "NO" in the Info.plist (this is the default for new projects). This way you can start adopting the new API in smaller steps. You can see that the scene delegate method names are a close match for the app delegate ones. One confusing thing is that the app delegate methods aren't deprecated so you won't get a warning if you have both app delegate and scene delegate methods in place but only one will be called. Other things that UISceneDelegate takes over are user activities (continueUserActivity: etc), state restoration (stateRestorationActivityForScene: etc), status bar questions and opening URLs. (I'm not sure if these replace the app delegate methods). It also has analogous notifications for the lifecycle events (like UISceneWillDeactivateNotification). From the WWDC Session, some images for you: The function equivalents for Swift: The class responsibilities:
{ "language": "en", "url": "https://stackoverflow.com/questions/56508764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "76" }
Q: How to get a C# Custom TextBox to change cursor location on mouse click I have a custom textbox, which is just a standard textbox with a couple additional small features, and it all works as expected. The problem I am having is that clicking in the field to change the cursor location does not actually change the location of the cursor, the cursor just stays at the beginning of the field. Below is the code I am working with, I am hoping someone will be able to tell me what I am missing: using System; using System.ComponentModel; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace Test.UI.Controls { public partial class TestTextBox : TextBox { private Color normalForegroundColor = Color.Gray; private Color textChangedForegroundColor = Color.Red; private string startingText = string.Empty; [Description("TextBox border color when text is changed"), Category("Appearance")] public Color TextChangedColor { get { return textChangedForegroundColor; } set { textChangedForegroundColor = value; } } [Description("Set starting text of textbox, as well as the Text property"), Category("Appearance")] public String StartingText { get { return startingText; } set { startingText = value; this.Text = startingText; } } public TestTextBox() { InitializeComponent(); normalForegroundColor = this.ForeColor; } protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); this.ForeColor = this.Text == startingText ? normalForegroundColor : textChangedForegroundColor; } } } Below is a screen grab of what the custom textbox looks like with data in it:
{ "language": "en", "url": "https://stackoverflow.com/questions/25638211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating Link to Specific Page through Table field I'm pretty new to HTML, PHP, JavaScript, etc. I have a table that will be uploaded by a Database, with fields such as name, id,email etc. I would like to show a page with all people in the table, with a link to a details page that will show all the attributes (field in the table) of the person. I use MySQL and I'm trying to build an Admin interface for better user management. A: Your link could be like this person.php?id=1243 Where person.php is the page where you display the information about the Person with id = 1243 You can retrieve the id by using $id = $_GET['id'] and then use it on a mysql query: SELECT * from Person WHERE id = $id; // Don't forget to handle SQL injection And you're done. EDIT: For multiple fields The link person.php?id1=1243&id2=5678 Retrieve the value $id1 = $_GET['id1'] and $id2 = $_GET['id2'] MySQL: SELECT * from Person WHERE id IN($id1, $id2); EDIT2 : For a range of users The link person.php?startId=1&endId=5000 Retrieve the value $startId = $_GET['startId'] and $endId = $_GET['endId'] MySQL: SELECT * from Person WHERE id BETWEEN $startID AND $endId; ALTERNATIVE suggested by @PierreGranger Your link could be like this person.php?id[]=1243&id[]=5678 Where person.php is the page where you display the information about the Person with id = 1243 and id = 5678 You can retrieve the id by using $id = $_GET['id'][0] and then use it on a mysql query: if ( isset($_GET['id']) && is_array($_GET['id']) ) // Check if parameter is set { $ids = $_GET['id'] ; foreach ( $ids as $k => $v ) if ( ! preg_match('#^[0-9]+$#',$v) ) unset($ids[$k]) ; // Remove if parameters are not identifiers if ( sizeof($ids) > 0 ) // If there is still at least 1 id, do your job { $sql = ' SELECT * from Person WHERE id in (".implode('","',$ids).") ' ; $rq = mysql_query($sql) or die('SQL error') ; while ( $d = mysql_fetch_assoc($rq) ) { // Do your SQL request and build your table } } } Wich will result in : SELECT * from Person WHERE id in ("1234","5678") ; And you're done. A: Based on Akram response you can try this one. There is 2 cases : if you only have 4 or 5 particular ids, you can do this : page.php?id[]=1&id[]=2&id[]=9 And if you want to reach a range (id from 1 to 1000) : page.php?from=1&to=1000 unset($sql) ; if ( isset($_GET['id']) && is_array($_GET['id']) ) // Check if parameter is set { $ids = $_GET['id'] ; foreach ( $ids as $k => $v ) if ( ! preg_match('#^[0-9]+$#',$v) ) unset($ids[$k]) ; // Remove if parameters are not identifiers if ( sizeof($ids) > 0 ) // If there is still at least 1 id, do your job { $sql = ' SELECT * from Person WHERE id in ("'.implode('","',$ids).'") ' ; } } elseif ( isset($_GET['from']) && isset($_GET['to']) ) { if ( preg_match('#^[0-9]+$#',$_GET['from']) && preg_match('#^[0-9]+$#',$_GET['to']) ) { $sql = ' SELECT * from Person WHERE id between "'.$_GET['from'].'" and "'.$_GET['to'].'"' ; } } if ( isset($sql) ) { $rq = mysql_query($sql) or die('SQL error') ; while ( $d = mysql_fetch_assoc($rq) ) { // Do your SQL request and build your table } }
{ "language": "en", "url": "https://stackoverflow.com/questions/29493454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EmberJS and web components: extend an existing HTML tag within an initializer (is it possible?) Edit: this issue only seems to be in the .hbs rendering as this code does work when the extended web component is inserted in the top level index.html of the EmberJS project Edit 2: However, when I put it in a minimal .hbs example, then it did work. So it is clearly an interaction with EmberJS rendering and perhaps with Handlebars, somehow. Edit 3: The issue also persist when I use Glimmer as a standalone rendering library and build these web components via the constructor() function of a Glimmer component (hacky, I know, but it works for standalone custom web components). I am trying to understand how to use web components in EmberJS. I know that I could rewrite a web component into an EmberJS component, but that is not the point. I want to know how to directly integrate web components into EmberJS. There is a tutorial that describes how to make custom web components and put that in EmberJS by making an initializer. https://tenbit.co/blog/a-simple-way-to-integrate-web-components-with-your-ember-app/ So you'd think, that it is a piece of cake to do the same thing for an extended native HTML component right? It turns out that it isn't. Here is a minimal example of what isn't working. In this particular example <p>hello world</p> gets displayed but <p>hello Mars</p> does not. However, in the standalone HTML file (see on the bottom of this post) which has the same classes and define() calls, then it does work. I also made an EmberJS Twiddle, in which you can see it: https://ember-twiddle.com/5b85957f52aba288bfe9e94ce42b811e // app/initializers/custom-elements.js class HelloWorld extends HTMLElement { constructor() { super(); console.log("constructor() HelloWorld"); let shadowRoot = this.attachShadow({ mode: "open" }); shadowRoot.innerHTML = `<p>hello world</p>`; } } //similar to HelloWorld -- it's simply an extension class TestingAParagraph extends HTMLParagraphElement { constructor() { super(); console.log("constructor() TestingAParagraph"); let shadowRoot = this.attachShadow({ mode: "open" }); shadowRoot.innerHTML = `<p>hello Mars</p>`; } } export function initialize(application) { window.customElements.define("hello-world", HelloWorld); window.customElements.define("testing-a-paragraph", TestingAParagraph, { extends: "p" }); } export default { initialize }; Here is the Handlebars file: {{!-- my-template.hbs --}} <p>Bladiebla</p> <hello-world></hello-world> <p>A test is coming</p> <p is="testing-a-paragraph"></p> Note: this minimal example does work as a standalone HTML file. <!DOCTYPE html> <html> <head> <script type="text/javascript"> // app/initializers/custom-elements.js class HelloWorld extends HTMLElement { constructor() { super(); console.log("constructor() HelloWorld"); let shadowRoot = this.attachShadow({ mode: "open" }); shadowRoot.innerHTML = `<p>hello world</p>`; } } //similar to HelloWorld -- it's simply an extension class TestingAParagraph extends HTMLParagraphElement { constructor() { super(); console.log("constructor() TestingAParagraph"); let shadowRoot = this.attachShadow({ mode: "open" }); shadowRoot.innerHTML = `<p>hello Mars</p>`; } } window.customElements.define("hello-world", HelloWorld); window.customElements.define("testing-a-paragraph", TestingAParagraph, { extends: "p" }); </script> </head> <body> <p>Bladiebla</p> <hello-world></hello-world> <p>A test is coming</p> <p is="testing-a-paragraph"></p> </body> </html> A: In the answer, my extendable component is an h1 as opposed to a p. As it made things easier to debug. I figured out that the flow works as stated by jelhan in the comments. * *There is a createElement (I'm a 100% positive as I saw in the debugger that my h1 custom tag was breaking on __openElement). *It then parses all the attributes one by one with setAttribute (100% positive, because debugger). Ultimately, the "is" attribute is set by setAttribute. I know that when setAttribute is used, then the web component will not be instantiated. *It ends with an insertBefore call, at either a flushElement or somewhere else (I saw this in my debugger, didn't bother to pinpoint it). There is a Stackoverflow question on how a web component should be added in vanillaJS. With that knowledge, I created a JS fiddle, in which you see the workflow of how Glimmer does it now (workflow-wise), and how Glimmer could be doing it. I also created a hacky workaround for statically defined elements in a .hbs file (warning: I don't create libraries, I merely poke around in them) You need to replace __setAttribute with something like this: __setAttribute(name, value, namespace) { if(name === "is"){ //hack, hack, hackerdeehack //I need the actual document, this.dom doesn't cut it. I suppose it's kind of like a shadow DOM, similar to what ReactJS does. let webComponent = window.document.createElement(this.constructing.tagName, { is: value }); //copy attributes that are already parsed [...this.constructing.attributes].forEach( attr => { this.dom.setAttribute(webComponent, attr.nodeName, attr.nodeValue, namespace) }); this.constructing = webComponent; } this.dom.setAttribute(this.constructing, name, value, namespace); } Ultimately, it's up to the EmberJS/Glimmer maintainers to propose a certain way forward. This particular hack was made, because I did not want to mess around with the VM and I also did not want to mess around with the parsing behavior of Glimmer. But I did want to see if I was right in my thinking, and I am (2 days ago, I didn't know that Glimmer existed, so I needed to be a bit thorough). Some extra info for the curious people Terminology that I saw: * *opcodes: VM thingy, I kind of forgot what it meant in a VM context, but I've seen it in my compiler construction and computer architecture courses. I always translate it as: the table of numbers to which CPUs understand what instruction they should execute. *System calls: DOM function calls are system calls, as they are what the rendering engine is about. A couple of handy breakpoints (+ console.log()s) in order to verify the workflow that I outlined: //element-builder.js __openElement(tag) { console.log('NewElementBuilder - __openElement', tag, [this.element], this.element.attributes, 'modules'); debugger; return this.dom.createElement(tag, this.element); } __setAttribute(name, value, namespace) { debugger; this.dom.setAttribute(this.constructing, name, value, namespace); //this is how the "is" attribute is set } //note: it could also be that __flushElement is called... I didn't check this thoroughly __appendText(text) { let { dom, element, nextSibling } = this; debugger; console.log('__appendText', dom, element, nextSibling, text); let node = dom.createTextNode(text); dom.insertBefore(element, node, nextSibling); return node; } // just to be sure __flushElement(parent, constructing) { debugger; this.dom.insertBefore(parent, constructing, this.nextSibling); }
{ "language": "en", "url": "https://stackoverflow.com/questions/58529308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sequelize get created record's autoincrement id I have an autoincrement id int column. I am trying to retrieve id of a created record during save but I am of course sending DEFAULT within the insert. Is it possible to retrieve the id without an additional query? My attempt is below however, auditWithAssignedId's id stays undefined. void audit.save().then(auditWithAssignedId => { console.log('auditWithAssignedId', auditWithAssignedId); this.backup(auditWithAssignedId); }); Model AccountAudit.init( { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, }, account: { type: DataTypes.STRING }, action: { type: DataTypes.STRING }, executedOn: { type: DataTypes.DATE, defaultValue: DataTypes.Now }, }, { sequelize, schema: 'AUDITS', tableName: 'ACCOUNT', underscored: true, timestamps: false, } }); export class AccountAudit extends Model< InferAttributes<AccountAudit>, InferCreationAttributes<AccountAudit> > { declare id: CreationOptional<number>; declare account: string; declare action: AuditAction; declare executedOn: CreationOptional<Date>; }
{ "language": "en", "url": "https://stackoverflow.com/questions/75577551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using ModelAndView object properties inside javascript I am returning a list from my Controller as list to view and I am passing this list object to my javascript function like this window.onload = function() { showDirectory("$(S3DirectoryList)"); }; S3DirectoryList is the object that is returned from controller. This is my model class class Directory { String folderName; HashMap< String, String> objects; List<Directory> dChild; } I want to use the folderName property of Directory in function. Currently my javascript function is defined like this function showDirectory( dirList) { var markup=""; <c:forEach var="dir" items="dirList"> markup += ${dir.folderName} + "<br>"; </c:forEach> document.getElementById("dispdir").innerHTML = markup; } A: I added some code to your Directory class. If you run it(I also added a Main method for testing purposes), you see it creates a list of directories and serializes this list as JSON. I added a constructor to make it easy to create some directories. I also added a getJSON method that serializes a directory. I added a getJSON(List directories) method to serialize a list of directories. If you see to it this serialized list gets into your variable S3DirectoryList you can pass it to your javascript function as follows: function showDirectory(dirList) { var markup = ""; for(var i = 0; i < dirList.length; i++) { markup += dirList[i].folderName + "<br />"; } document.getElementById("dispdir").innerHTML = markup; } window.onload = function() { showDirectory($(S3DirectoryList)); }; the Directory class: import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class Directory{ String folderName; HashMap<String, String> objects; List<Directory> dChild; public Directory(String folderName, String[] objects) { this.folderName = folderName; this.objects = new HashMap<String, String>(); for(int i = 0; i < objects.length; i = i + 2) { this.objects.put(objects[i], objects[i + 1]); } this.dChild = new ArrayList<Directory>(); } public void addChildDirectory(Directory childDirectory) { if(this.dChild == null) this.dChild = new ArrayList<Directory>(); this.dChild.add(childDirectory); } public String toJSON() { StringBuilder b = new StringBuilder(); b.append("{"); b.append("'folderName': '").append(folderName == null ? "" : folderName).append("'"); b.append(",objects: {"); if(objects != null) { Iterator<Map.Entry<String, String>> objectsIterator = objects.entrySet().iterator(); if(objectsIterator.hasNext()) { Map.Entry<String, String> object = objectsIterator.next(); b.append("'").append(object.getKey()).append("': '").append(object.getValue()).append("'"); } while (objectsIterator.hasNext()) { Map.Entry<String, String> object = objectsIterator.next(); b.append(",'").append(object.getKey()).append("': '").append(object.getValue()).append("'"); } } b.append("}"); b.append(",'dChild': "); b.append("["); if(dChild != null) { if(dChild.size() > 0) b.append(dChild.get(0).toJSON()); for(int i = 1; i < dChild.size(); i++) { b.append(",").append(dChild.get(i).toJSON()); } } b.append("]"); b.append("}"); return b.toString(); } public static String getJSON(List<Directory> directories) { StringBuilder b = new StringBuilder(); b.append("["); if(directories.size() > 0) b.append(directories.get(0).toJSON()); for(int i = 1; i < directories.size(); i++) { b.append(",").append(directories.get(i).toJSON()); } b.append("]"); return b.toString(); } private static Directory generateDirectory(int seed) { List<Directory> directories = new ArrayList<Directory>(); for(int i = 0; i < 5; i++) { directories.add( new Directory( "folderName_" + seed + "_" + i, new String[]{"k_" + seed + "_" + i + "_1", "v_" + seed + "_" + i + "_1", "k_" + seed + "_" + i + "_2", "k_" + seed + "_" + i + "_2"})); } Directory directory_root = directories.get(0); Directory directory_1_0 = directories.get(1); Directory directory_1_1 = directories.get(2); Directory directory_1_0_0 = directories.get(3); Directory directory_1_0_1 = directories.get(4); directory_root.addChildDirectory(directory_1_0); directory_root.addChildDirectory(directory_1_1); directory_1_0.addChildDirectory(directory_1_0_0); directory_1_0.addChildDirectory(directory_1_0_1); return directory_root; } public static void main(String[] args) { List<Directory> directories = new ArrayList<Directory>(); for(int i = 0; i < 2; i++) { directories.add(generateDirectory(i)); } System.out.println(toJSON(directories)); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/24382770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: primefaces message not working I am implementing a login form with primefaces but my messages are not displayed, what can be? I've tried using the id field or passing null in method addMessage (). my xhtml code: <?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:p="http://primefaces.prime.com.tr/ui"> <h:head> <title>Test</title> </h:head> <h:body> Wellcome<br/> <h:form id="login"> <p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" /> <p:growl id="msg" showDetail="true" life="3000" /> <p:panel header="Login" style="width: 360px;"> <h:panelGrid id="loginPanel" columns="2"> <h:outputText value="Email:" for="email" /> <p:inputText id="email" value="#{loginBean.email}" ></p:inputText> <p:spacer></p:spacer> <p:message for="email" /> <h:outputText value="Senha" for="senha" /> <p:password id="senha" value="#{loginBean.senha}" feedback="false" minLength="1"></p:password> <p:spacer></p:spacer> <p:message for="senha" /> <p:spacer></p:spacer> <p:commandButton action="#{loginBean.loginAction}" value="Login" update="loginForm" ajax="true"></p:commandButton> </h:panelGrid> </p:panel> </h:form> </h:body> </html> my bean: @ManagedBean @RequestScoped public class LoginBean { private static final long serialVersionUID = 1L; private String email; private String senha; @ManagedProperty(value="#{usuarioSessionBean}") private UsuarioSessionBean usuarioSessao; public String loginAction() { //Valida preenchimento dos campos de email e senha boolean campoBranco = false; if((email == null) || (email.trim().length() == 0)) { campoBranco = true; FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Email não informado!","Preencha o email e tente novamente!")); } if((senha == null) || (senha.trim().length() == 0)) { campoBranco = true; FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Senha não informada!","Preencha a senha e tente novamente!")); } if(campoBranco) return "login"; } } Can anyone tell me what is wrong? He returns to the login page but does not show the messages. A: If my understanidng is correct you mean to say you want to show the message to the user, try following: if((senha == null) || (senha.trim().length() == 0)) { campoBranco = true; FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR, "Senha não informada!","Preencha a senha e tente novamente!")); return null; } this is what you have to add return null; so that it will stay in the same page and show up the message, As you are trying to navigate to the login page once agin after getting the error also, it will simply navigate rather than showing error messages. as well try to modify in the xhtml as suggested below: and in your xhtml: <p:growl id="growlLoginValidationStatus" showDetail="true" sticky="false" autoUpdate="true" life="4000" redisplay="false" showSummary="true" globalOnly="false" /> and remove your <p:message/> tag and make ajax as false in your command button. try this, if still not able to show the message, let me know in comment A: It seems like you're updating the wrong id. <h:form id="login" > <p:commandButton value="Login" update="loginForm" action="#{loginBean.loginAction}"/> </h:form> In this case, you need to change loginForm to login or change the id of your form to loginForm.
{ "language": "en", "url": "https://stackoverflow.com/questions/16243699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to change the default filter operator in kendo ui grid mvc I have managed to change the default filter order for the Kendo Grid using: .Filterable(filterable => filterable .Extra(true) .Operators(ops => ops.ForString(str => str.Clear() .Contains("Contains") .StartsWith("Starts with") .EndsWith("Ends with") .IsEqualTo("Is equal to")) )) Is there any way I can change the default operator to OR? A: This can be done via the filterMenuInit event: /* grid configuration snip */ .Events(e => e.FilterMenuInit("filterMenuInit")) /* grid configuration snip */ <script> function filterMenuInit(e) { e.container .find("select.k-filter-and") .data("kendoDropDownList") .value("or"); } </script> Here is a live demo: http://jsbin.com/etItEpi/1/edit A: You can also do this on a per column basis on your grid definition (MVC): cols.Bound(m => m.xxx).Filterable(f=> f.Cell(cell => cell.Operator("or")));
{ "language": "en", "url": "https://stackoverflow.com/questions/18997638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: MySQL SELECT with data from another table Probably it's easier than what i think, but i am loosing my mind about it, i have a table with product with thousand of entry, something like ID|NAME 0 |first product 1 |second product ... N |nth product every time someone click a product i save and update a table called click PRODUCT_ID|CLICKS 0 |1 1 |3 so, if a product never received a click does not exist in click table now i want a list of all the products (or a category subset for example) ordered by clicks. of course the entry that are not on click table should be present in the result with clicks column to 0 (or empty) ID|NAME |CLICKS 0 |first name |1 5 |fifth name | ... N |nth name |2 all the joins i tried were only able to give me a combined result for entry that are present in both table, i know its very easy and i am running around it from about two hours... but i cant succeed! any suggestion? A: select from master table and make it LEFT JOIN with clicks table. A: a LEFT JOIN works for your query CREATE TABLE products ( `ID` INTEGER, `NAME` VARCHAR(14) ); INSERT INTO products (`ID`, `NAME`) VALUES ('0', 'first product'), ('1', 'second product'), ('2', 'thirdproduct'), ('3', 'forth product'); CREATE TABLE ciicks ( `PRODUCT_ID` INTEGER, `CLICKS` INTEGER ); INSERT INTO ciicks (`PRODUCT_ID`, `CLICKS`) VALUES ('0', '1'), ('1', '3'); SELECT p.ID,p.NAME,IFNULL(c.CLICKS,0) FROM products p LEFT JOIN ciicks c ON p.ID = c.PRODUCT_ID ID | NAME | IFNULL(c.CLICKS,0) -: | :------------- | -----------------: 0 | first product | 1 1 | second product | 3 2 | thirdproduct | 0 3 | forth product | 0 db<>fiddle here A: Select p.id, p.name, ifnull(c.clicks,0) as clicks from product p left join click c on p.id = c.product_id A: You can use LEFT JOIN (https://www.mysqltutorial.org/mysql-left-join.aspx/) to combine tables where one table may not have matching rows. See http://sqlfiddle.com/#!9/db9d5a/4 for an example: SELECT p.id, p.name, IFNULL(c.clicks, 0) FROM products p LEFT JOIN clicks c ON c.product_id = p.id ORDER BY c.clicks DESC; will return the following: id | name | clicks 4 fourth 5 2 second 3 1 first 1 3 third 0
{ "language": "en", "url": "https://stackoverflow.com/questions/62542113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Azure automation, PowerShell to fetch a file in private blob container I have an azure blob container set to private. I want to download files in this container using PowerShell. This is what I put, however it is giving me ResourceNotFound error every time. Even when I put -Credential and my user name/access key. When I switch the container to public access, it always works. So am I missing anything? Invoke-WebRequest -Uri $uri -OutFile $filePath A: Using Invoke-WebRequest is analogous to opening a link in your browser. It's a legitimate way to download files from Azure Storage, however to do that you'll need the URI to include a SAS (Shared Access Signature), which you'll have to have generated before you use it in your code. The PowerShell to achieve this is: #Download via URI using SAS $BlobUri = 'https://yourstorageaccount.blob.core.windows.net/yourcontainer/yourfile.txt' $Sas = '?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D' $OutputPath = 'C:\Temp\yourfile.txt' $FullUri = "$BlobUri$Sas" (New-Object System.Net.WebClient).DownloadFile($FullUri, $OutputPath) Alternatively, if you have the Azure PowerShell module installed, you can do it without any of that added pain: # Download via Azure PowerShell $StorageAccountName = 'yourstorageaccount' $StorageAccountKey = Get-AzureStorageKey -StorageAccountName $StorageAccountName $StorageContext = New-AzureStorageContext $StorageAccountName -StorageAccountKey $StorageAccountKey.Primary $FileName = 'yourfile.txt' $OutputPath = 'C:\Temp' $ContainerName = 'yourcontainer' Get-AzureStorageBlobContent -Blob $FilebName -Container $ContainerName -Destination $OutputPath -Context $StorageContext A: I ended up to resolve similar requirement with Azure PowerShell Az module as follows: $BlobFilePath = 'dir\blob.file' # Relative path in blob starting from container $OutputFilePath = 'C:\temp\blob.file' # Path to download the file to $StorageAccountName = 'storageaccountname' $ContainerName = 'blob-container-name' # Prompt for Azure Account creds, if working from VM with managed identity could add also switch -Identity to use that identity directly Connect-AzAccount $StorageContext = New-AzStorageContext -StorageAccountName $StorageAccountName Get-AzStorageBlobContent -Blob $BlobFilePath -Container $ContainerName -Destination $OutputFilePath -Context $StorageContext A: $StartTime = $(get-date) $datetime = $(get-date -f yyyy-MM-dd_hh.mm.ss) $connection_string = '' $AzureBlobContainerName = '' $destination_path = "c:\download" If(!(test-path $destination_path)) { New-Item -ItemType Directory -Force -Path $destination_path } $storage_account = New-AzStorageContext -ConnectionString $connection_string # Download from all containers #$containers = Get-AzStorageContainer -Context $storage_account # Download from specific container $containers = Get-AzStorageContainer -Context $storage_account | Where-Object {$_.Name -eq "$AzureBlobContainerName"} $containers Write-Host 'Starting Storage Dump...' foreach ($container in $containers) { Write-Host -NoNewline 'Processing: ' . $container.Name . '...' $blobs = Get-AzStorageBlob -Container $container.Name -Context $storage_account $container_path = $destination_path + '\' + $container.Name new-item -ItemType "directory" -Path $container_path Write-Host -NoNewline ' Downloading files...' foreach ($blob in $blobs) { $fileNameCheck = $container_path + '\' + $blob.Name if(!(Test-Path $fileNameCheck )) { Get-AzStorageBlobContent -Container $container.Name -Blob $blob.Name -Destination $container_path -Context $storage_account } } Write-Host ' Done.' } Write-Host 'Download complete.' $elapsedTime = $(get-date) - $StartTime $totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks) Write-Output " -OK $totalTime" | Out-String
{ "language": "en", "url": "https://stackoverflow.com/questions/34903180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: area chart with d3 is not rendering on jsp page but working fine with html i sucessfully rendered d3js area chart in a html page here is the code which is rendering sucessfully in chrome or mozilla.The name of the file is say temp.html.Here is the code <!DOCTYPE html> <html lang="en" class="no-js"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>js graphs and charts libraries</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://d3js.org/d3.v3.js"></script> <body> <div id="dbar"> </div> <script type="text/javascript"> var margin = {top:10, right: 20, bottom: 30,left: 40}, width = 960 - margin.left - margin.right, height = 400 - margin.top - margin.bottom; var svg = d3.select ("#dbar").append("svg").attr("width", width+margin.left+margin.right).attr("height",height+margin.top+margin.bottom) .append("g"). attr("transform","translate("+margin.left+","+margin.top+")"); var parseDate = d3.time.format("%m-%Y").parse; var x = d3.time.scale().range([0, width]); var y = d3.scale.linear().range([height, 0]); var xAxis = d3.svg.axis().scale(x).orient("bottom"); var yAxis = d3.svg.axis().scale(y).orient("left"); var area = d3.svg.area().x(function(d) { return x(d.date); }) .y0(height) .y1(function(d) { return y(d.count); }); d3.json("data/json.json", function(error, data) { data.StoreVisitGraphCount.list.forEach(function(d) { d.date = parseDate(d.date); d.count = +d.count; }); //console.log(data.StoreVisitGraphCount.list); x.domain(d3.extent(data.StoreVisitGraphCount.list, function(d) { return d.date; })); y.domain([0, d3.max(data.StoreVisitGraphCount.list, function(d) { return d.count; })]); console.log(data.StoreVisitGraphCount.list); svg.append("path") .datum(data.StoreVisitGraphCount.list) .attr("class", "area") .attr("d", area); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("Price ($)"); }); </script> </body> </html> But when i am copy pasting this code to say "temp.jsp" page its not rendering and chart is not coming.I am running this page on tomcat server. need suggestions A: It is not because you saved it as jsp or html page. You need to add charset="UTF-8" to your script declaration as d3.js uses UTF characters. eg. <script src="http://d3js.org/d3.v3.js" charset="UTF-8"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/14500380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Extracting highlighted content in pdf automatically as images I have a pdf file in which some text and images are highlighted using highlight text(U) tool. Is there a way to automatically extract all the highlighted content as separate images and save it to a folder? I dont want readable text. I just want all the highlighted content as images. Thanks A: You would need to use PDF library to iterate through all the Annotation objects and their properties to see which ones are using a highlight annotation. Once you have found the highlight annotation you can then extract the position and size (bounding box) of the annotation. Once you have a list of the annotation bounding boxes you will need to render the PDF file to an image format such as PNG/JPEG/TIFF so that you can extract / clip the rendered image of the annotation text you want. You could use GDI+ or something like LibTIFF There are various PDF libraries that could do this including http://www.quickpdflibrary.com (I consult for QuickPDF) or http://www.itextpdf.com Here is a C# function based on Quick PDF Library that does what you need. private void ExtractAnnots_Click(object sender, EventArgs e) { int dpi = 300; Rectangle r; List<Rectangle> annotList = new List<Rectangle>(); QP.LoadFromFile("samplefile.pdf", ""); for (int p = 1; p <= QP.PageCount(); p++) { QP.SelectPage(p); // Select the current page. QP.SetOrigin(1); // Set origin to top left. annotList.Clear(); for (int i = 1; i <= QP.AnnotationCount(); i++) { if (QP.GetAnnotStrProperty(i, 101) == "Highlight") { r = new Rectangle((int)(QP.GetAnnotDblProperty(i, 105) * dpi / 72.0), // x (int)(QP.GetAnnotDblProperty(i, 106) * dpi / 72.0), // y (int)(QP.GetAnnotDblProperty(i, 107) * dpi / 72.0), // w (int)(QP.GetAnnotDblProperty(i, 108) * dpi / 72.0)); // h annotList.Add(r); // Add the bounding box to the annotation list for this page. string s = String.Format("page={0}: x={1} y={2} w={3} h={4}\n", p, r.X, r.Y, r.Width, r.Height); OutputTxt.AppendText(s); } } // Now we have a list of annotations for the current page. // Delete the annotations from the PDF in memory so we don't render them. for (int i = QP.AnnotationCount(); i >= 0; i--) QP.DeleteAnnotation(i); QP.RenderPageToFile(dpi, p, 0, "page.bmp"); // 300 dpi, 0=bmp Bitmap bmp = Image.FromFile("page.bmp") as Bitmap; for (int i=0;i<annotList.Count;i++) { Bitmap cropped = bmp.Clone(annotList[i], bmp.PixelFormat); string filename = String.Format("annot_p{0}_{1}.bmp", p, i+1); cropped.Save(filename); } bmp.Dispose(); } QP.RemoveDocument(QP.SelectedDocument()); } A: Do you want each piece of text as a separate highlight or all the higlhights on a separate pane?
{ "language": "en", "url": "https://stackoverflow.com/questions/8930622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Foxx dependencies import by name, not by mounting point As far as I understand from reading this snippet in this documentation regarding 'Defining dependencies': will allow using any app to be used to meet the dependency. sessions or sessions@* will match any app with the name sessions (such as the sessions app in the Foxx application store). sessions@1.0.0 will match the version 1.0.0 of any app with the name sessions. Foxx will look for any dependency with name 'sessions'. However, when I tried it locally, it seems like it tries to find any app mounted at /sessions rather than name 'sessions' and this error populated in the logs if I use like this format 'sessions@1.0.0': [ArangoError 3007: Mountpoint can only contain a-z, A-Z, 0-9 or _.]: [object Arguments] Is this an expected behaviour? I really hope if it's possible to import an app by name rather than the mount point though. A: The blurb in the documentation refers to the value in the manifest.json file. Dependencies in the manifest are defined by an alias mapped to a string in the format of <name>@<version>. The exact meaning of that string is not currently enforced so it just serves as documentation for the app. If you mount an app that has dependencies, you need to set up the dependencies (e.g. using the web frontend). The web frontend's dependencies dialog lets you enter mount paths of apps you want to use to meet the dependencies. The code of the app itself will then be able to refer to the exports of the apps mounted at those paths by the aliases defined in the manifest. For example: * *You create an app called example with the following dependencies: "dependencies": {"mySessions": "sessions@^1.0.0"} *You install a sessions app (e.g. the sessions app from the Foxx app store) and mount it at /my-sessions. *You install your example app and mount it somewhere else. *You open the app details of your example app in the web frontend and open the dependencies dialog (boxes icon in the top right). *The dialog should show a single input field titled MySessions with a help popup saying sessions@^1.0.0. *Enter /my-sessions into the input field and save. *Your example app should now be able to access the exports of the app at applicationContext.dependencies.mySessions.
{ "language": "en", "url": "https://stackoverflow.com/questions/31112997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to set validation rules in foreach loop in codeigniter I need to set rules dynamically I don't know what will be the name of input type. For example I have input type<input type="text" name="first_name"> I can set rule for it like $this->form_validation->set_rules("first_name", "First Name", "required"); But I am doing it dynamically suppose I have $_POST array I don't know the input type name value. So I did it this way foreach($post as $key => val){ $this->form_validation->set_rules($key, remove_underscore($key), "required"); } $this->form_validation->set_error_delimiters("<p class='text-danger'>", "</p>"); if($this->form_validation->run()){ //do stuff here.. } The validation does not work in this loop way. If I set rules in a string and echo it outside the loop like $str = ''; foreach($post as $key => val){ $str .= '$this->form_validation->set_rules($key' } echo $str; That doesn't work either because I have to do echo json_encode(var) at the end. If I echo it first it will stop there only. I hope I have clear my point, if any one can guide me I will appreciate.
{ "language": "en", "url": "https://stackoverflow.com/questions/52706354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to create query to export data as csv I have a Postgresql table I wish to export as CSV on demand using a query, without superuser. I tried: COPY myapp_currencyprice to STDOUT WITH (DELIMITER ',', FORMAT CSV, HEADER) \g /tmp/prices.csv But I get a syntax error at "\g" So I tried: \copy myapp_currencyprice to '/tmp/prices.csv' with (DELIMITER ',', FORMAT CSV, HEADER) But I also get a syntax error at "" from "\copy" A: Running the command that way works only when connection is done through psql. A: You can do the following in psql. SELECT 1 as one, 2 as two \g /tmp/1.csv then in psql \! cat /tmp/1.csv or you can copy (SELECT 1 as one, 2 as two) to '/tmp/1.csv' with (format csv , delimiter '|'); But You can't STDOUT and filename. Because in manual(https://www.postgresql.org/docs/current/sql-copy.html): COPY { table_name [ ( column_name [, ...] ) ] | ( query ) } TO { 'filename' | PROGRAM 'command' | STDOUT } [ [ WITH ] ( option [, ...] ) ] the Vertical line | means: you must choose one alternative.(source: https://www.postgresql.org/docs/14/notation.html)
{ "language": "en", "url": "https://stackoverflow.com/questions/73322162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Hamburger menu styling doesn't appear the same on phone I have created a mobile hamburger menu with several items in it. The thing is, when I try to edit the CSS and make changes they appear fine in my inspect preview, but when I actually check the website on the mobile I don't exactly see the styling I was trying to achieve. Here are the things that I tried to do: I want to change the distance between the borders that are visible on ::focus (make them a bit more far from the text). When I insepct, it looks different than when I check it out on my phone. I tried adding margin: 30px 0; padding-top: 25px; to the span class on focus, but it doesn't work on phone. I have tried changing the margins, paddings and using whitespace:nowrap. It looked fine when I previewed the changes on my desktop, but when I checked out my phone my styling looked different. Here's the HTML of the menu: <div class="elementor-column-wrap elementor-element-populated"> <div class="elementor-widget-wrap"> <div data-id="da3c1dd" class="elementor-element elementor-element-da3c1dd elementor-widget elementor-widget-spacer" data-element_type="spacer.default"> <div class="elementor-widget-container"> <div class="elementor-spacer"> <div class="elementor-spacer-inner"></div> </div> </div> </div> <div data-id="5fa72fd" class="elementor-element elementor-element-5fa72fd elementor-widget elementor-widget-heading" id="regulation-menu-mobile" data-element_type="heading.default"> <div class="elementor-widget-container"> <h4 class="elementor-heading-title elementor-size-default"><a href="#regulation-mobile"><span class="menu-item-text"><span align="center">?מהי רגולציה</span></span></a></h4> </div> </div> <div data-id="4e7c2bc" class="elementor-element elementor-element-4e7c2bc elementor-widget elementor-widget-heading" id="about-menu-mobile" data-element_type="heading.default"> <div class="elementor-widget-container"> <h4 class="elementor-heading-title elementor-size-default"><a href="#maya-about-mobile"><span class="menu-item-text"><span align="center">?אודות</span></span></a></h4> </div> </div> <div data-id="45788e2" class="elementor-element elementor-element-45788e2 elementor-widget elementor-widget-heading" id="about-menu-mobile" data-element_type="heading.default"> <div class="elementor-widget-container"> <h4 class="elementor-heading-title elementor-size-default"><a href="#fit-mobile"><span class="menu-item-text"><span align="center">?למי זה מתאים</span></span></a></h4> </div> </div> <div data-id="2a24b44" class="elementor-element elementor-element-2a24b44 elementor-widget elementor-widget-heading" id="contact-menu-mobile" data-element_type="heading.default"> <div class="elementor-widget-container"> <h4 class="elementor-heading-title elementor-size-default"><a href="#solution-mobile"><span class="menu-item-text"><span align="center">פתרונות</span></span></a></h4> </div> </div> <div data-id="fcd1ddb" class="elementor-element elementor-element-fcd1ddb elementor-widget elementor-widget-heading" id="contact-menu-mobile" data-element_type="heading.default"> <div class="elementor-widget-container"> <h4 class="elementor-heading-title elementor-size-default"><a href="#contact-mobile"><span class="menu-item-text"><span align="center">צור קשר</span></span></a></h4> </div> </div> <section data-id="23d1d02" class="elementor-element elementor-element-23d1d02 elementor-section-boxed elementor-section-height-default elementor-section-height-default elementor-section elementor-inner-section" data-element_type="section"> <div class="elementor-container elementor-column-gap-default"> <div class="elementor-row"> <div data-id="b6d5052" class="elementor-element elementor-element-b6d5052 elementor-column elementor-col-100 elementor-inner-column" data-element_type="column"> <div class="elementor-column-wrap elementor-element-populated"> <div class="elementor-widget-wrap"> <div data-id="4f72658" class="elementor-element elementor-element-4f72658 mobilemenucontact elementor-widget elementor-widget-text-editor" id="mobilemenucontact" data-element_type="text-editor.default"> <div class="elementor-widget-container"> <div class="elementor-text-editor elementor-clearfix"><p style="text-align: center;"><img class="email-mobile" src="http://mayabarber.co.il/wp-content/uploads/2018/06/Untitled-1.svg" width="33" height="33">&nbsp;<img class="facebook-mobile" src="http://mayabarber.co.il/wp-content/uploads/2018/06/Untitled-2.svg" width="33" height="33">&nbsp;<label style="color: #61f6ff;" data-mce-fragment="1">|&nbsp;<span style="color: #001a71;" href="tel:052-6582643" data-mce-fragment="1">&nbsp;052-6582643</span></label></p></div> </div> </div> </div> </div> </div> </div> </div> </section> Here's the CSS: .menu-item-text-mobile { -webkit-transition: border 200ms ease-out; -moz-transition: border 200ms ease-out; -o-transition: border 200ms ease-out; transition: border 200ms ease-out; border-bottom: 2.11px solid transparent; border-top: 2.11px solid transparent; margin-left:50px; display: inline-block; margin: 20px 0; padding-top: 25px; } .menu-item-text-mobile::after bottom: 1px; } #who-menu-mobile:hover .menu-item-text, #who-menu-mobile:focus .menu-item-text, #who-menu-mobile:active .menu-item-text{ border-bottom: 2.11px solid #61f6ff; margin-top: 5px; margin-bottom: 5px; border-top: 2.11px solid #61f6ff; bottom: -3px; } #solutions-menu-mobile:hover .menu-item-text, #solutions-menu-mobile:focus .menu-item-text, #solutions-menu-mobile:active .menu-item-text{ border-bottom: 2.11px solid #61f6ff; border-top: 2.11px solid #61f6ff; display: inline-block; margin: 20px 0 } #regulation-menu-mobile:hover .menu-item-text, #regulation-menu-mobile:focus .menu-item-text, #regulation-menu-mobile:active .menu-item-text{ border-bottom: 2.11px solid #61f6ff; border-top: 2.11px solid #61f6ff; } @media(min-width: 300px) and (max-width: 749px){ .elementor-widget-heading .elementor-heading-title > a{ justify-content: center !important; display: flex !important; }} Here's the website if you wanna inspect it: mayabarber.co.il And here's a screenshot of how I want it to look: Thanks! A: 1 and 2: For adjusting the distance between the options target span and reduce the margin on it to make them closer between each other. You can add the class to your spans like this, then use padding to make the lines farther from text. Play with the values. Would look something like: <span class="spanMenu"> .spanMenu { padding: 5px; margin-bottom: -20px; } 3. To keep the phone number from going onto two different lines use an @media Currently inspecting and fiddling to get the correct CSS so bear with me. To resize you can add a class="makeSmall" to the p tag like this: <p style="text-align: center;" class="makeSmall"> Then add this @media to your CSS @media only screen and (max-width: 600px) { .makeSmall { font-size:12px; } } This will allow you to adjust just the text size in the p tag. This is a quick and dirty way of doing it; I don't have the time to do the hierarchy of your CSS to just target them with CSS. I hope this helps though. :) A: Can the issue be that your phone is not cleaning out its cache correctly? Can you try borrowing someones else's phone, who has never visited the site, and take a look at it with their phone? If this solves your issue, you should figure out how to clean the cache from your phone to continue development.
{ "language": "en", "url": "https://stackoverflow.com/questions/50978718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to CountIf items in ListView VB.Net i have a form that has two listviews, lv = listview lv1 from textbox lv2 countif items from lv1. my question, how i can count the items in lv1 and show it in lv2. thank you very much. :) Best regards, HMZ A: You can try this: ListView1.Items.Add("Buah").SubItems.Add("Apel") ListView1.Items.Add("Buah").SubItems.Add("Mangga") ListView1.Items.Add("Buah").SubItems.Add("Jambu") ListView1.Items.Add("Buah").SubItems.Add("Durian") ListView1.Items.Add("Buah").SubItems.Add("Rambutan") ListView1.Items.Add("Sayur").SubItems.Add("Apel") ListView1.Items.Add("Sayur").SubItems.Add("Apel") ListView1.Items.Add("Sayur").SubItems.Add("Apel") Dim firstColDistinctItems() As String = ListView1.Items.Cast(Of ListViewItem).Select(Function(item As ListViewItem) item.Text).Distinct().ToArray() For i = 0 To firstColDistinctItems.Count - 1 Dim repeatCount As Integer = ListView1.Items.Cast(Of ListViewItem).Where(Function(item As ListViewItem) item.Text = firstColDistinctItems(i)).Count ListView2.Items.Add(firstColDistinctItems(i)).SubItems.Add(repeatCount) Next A: Although I haven't tried it, Youssef13's answer should work. Here's a "more readable" routine that will do just what you want. Hopefully, the comments are enough to understand how it works. Private Sub CountItems() ' Delete any existing items in lv2 lv2.Items.Clear() ' A dictionary that will contain a list of all unique items from lv1 and their occurrence count Dim items As New Dictionary(Of String, Integer) ' Simple For loop to scan all items in lv1 For Each itm As ListViewItem In lv1.Items If items.ContainsKey(itm.Text) Then ' Check if the item has already been added items(itm.Text) += 1 ' In that case, increment its counter Else items.Add(itm.Text, 1) ' Otherwise, create add it as a new item and set its internal counter to 1 End If Next ' Finally, display the dictionary contents in lv2 For Each itm In items lv2.Items.Add(itm.Key).SubItems.Add(itm.Value.ToString()) Next End Sub UPDATE: Here's a highly optimized (performance-wise) version: Private Sub CountItems() lv2.Items.Clear() Dim items As IEnumerable(Of Tuple(Of String, Integer)) = lv1.Items.Cast(Of ListViewItem).GroupBy(Function(i) i.Text).Select(Function(i) Tuple.Create(i.Key, i.Count)) For Each itm In items lv2.Items.Add(itm.Item1).SubItems.Add(itm.Item2.ToString()) Next End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/46125019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Can't bind to Service I have an aidl file defined as follows: package com.erbedo.callalert; interface RemoteCallAlert { void notifyCallEnded(); } The service is: package com.erbedo.callalert; public class CallAlert extends Service { Filter callListener; private final RemoteCallAlert.Stub mBinder = new RemoteCallAlert.Stub() { @Override public void notifyCallEnded() throws RemoteException { // TODO } }; @Override public IBinder onBind(Intent intent) { return mBinder; } @Override public void onCreate() { super.onCreate(); Toast.makeText(this, "CallAlert Created", Toast.LENGTH_LONG).show(); } @Override public void onDestroy() { super.onDestroy(); Toast.makeText(this, "CallAlert Destroyed", Toast.LENGTH_LONG).show(); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Toast.makeText(this, "CallAlert Started", Toast.LENGTH_LONG).show(); callListener = new Filter(); TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE); tm.listen(this.callListener, PhoneStateListener.LISTEN_CALL_STATE); } public void callEnded() { // TODO } } and the Activity that has to bind to the service is: package com.erbedo.callalert; public class DummyStart extends Activity { Filter callListener; RemoteCallAlert mService; private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { Log.d("CONNECT","OK"); } public void onServiceDisconnected(ComponentName className) { } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout l = new LinearLayout(this); setContentView(l); this.startService(new Intent(this, CallAlert.class)); } } The onServiceConnected isn't called. Am I missing something obvious? A: startService() does not use a ServiceConnection. bindService() does. A: Intent intent = new Intent(CallAlert.class.getName()); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); A: The onServiceConnected isn't called. For binding with the service you need to call bindService(). It provide the persistence connection, and after connection establishment onServiceConnected() is called. Second point:- If you are using AIDL IPC mechanism then I think you need the communication between 2 diff processes/Application. Here you need to have same copy of .aidl file in both service and Activity side in same PACKAGE. Then you need to modify little bit in your Activity side.. you can find here http://www.zestofandroid.blogspot.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/2484286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I add buttons over an image using the netbeans IDE? I am using netbeans as an IDE to make my desktop application. I have to add 3 buttons over an image. How do I do that? I have been unable to do this using the drag and drop features of netbeans. A: Put the buttons in a custom panel with an image background (example here). In IDE use a regular JPanel and drag the JButtons over it, then change the code from JPanel to ImagePanel (or whatever name you used for it). A: This is a little cheeky, but. * *Start by setting the layout of the base component to BorderLayout. *Drop a JLabel into it. Set the labels icon image to the background image you want to use. *Set the layout manager of the label to what ever you want to use. *Drop your buttons onto it... A: 1.Add the JLabel and in Properties, Set text to null and add the image by selecting it from the icons menu (this image should be in your package). 2.Set the appropriate size of the background and set the layout to NULL Layout. 3.Place the background label as the bottom most layer and keep adding buttons or labels as per your need.
{ "language": "en", "url": "https://stackoverflow.com/questions/18608142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RuntimeError: ERROR Mrelation "tablename" does not exist Rails - 2.3.8 Database - Postgres(9.2) Active record query is not able to generate tablename in double quotes ie # this ran fine Table.find_by_sql('Select * from "Table" Limit 1') Sql generated - Select * from "Table" Limit 1 But issue comes in, Table.find(:first) Sql generated - Select * from Table Limit 1 (Clearly noticed that table not in double quotes) Active record displaying error ActiveRecord::StatementInvalid: RuntimeError: ERROR C42P01 Mrelation "Table" does not exist P15 Fparse_relation.c L864 RparserOpenTable: SELECT * FROM Table LIMIT 1 I feel that postgresql adapter is not able to generate tablename in double quotes. A: I never get a chance to work on Postgres. But I have a workaround solution for this. Try as follows: table_name = '"Table"' table_name.find(:first) I haven't try this in my machine since I do not have the required setup. I hope it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/17924818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Git commit command is not working properly with atom editor When I give the command "$git commit" to git bash, then $ git commit hint: Waiting for your editor to close the file... atom --wait: atom: command not found error: There was a problem with the editor 'atom --wait'. Please supply the message using either -m or -F option. this error is thrown by git. I have configured atom in git using this command :- $ git config --global core.editor "atom --wait" A: If this problem appears, you have to : 1 - Go to the Atom menu. 2 - Select "Install Shell Commands". 3 - Restart the terminal It's magic it works :D A: Here are some tools to figure this out. Check current configuration: git config --list Check Status: git status See which configuration below works for the atom text editor: git config --global core.editor "atom" git config --global core.editor "atom --wait" git config --global core.editor "atom -w -s" Be sure to leave a message in the file that opens after running "git commit" in terminal. Save and completely exit the editor. A: Walking down the error you included: hint: Waiting for your editor to close the file... tells you that git has attempted to open your specified editor to write a commit message. This much is normal. The next part: atom --wait: atom: command not found tells you that git tried to execute $ atom --wait, but couldn't find the atom command. This indicates that the atom command was either never installed, or is not on your path. (For reference, the executable to run Atom on my Mac is located at /usr/local/bin/atom) The solution depends on your operating system. Solution for Mac This exactly matches the problem described by the Installing Atom on Mac official documentation: When you first open Atom, it will try to install the atom and apm commands for use in the terminal. In some cases, Atom might not be able to install these commands because it needs an administrator password. Therefore... To install the atom and apm commands, run "Window: Install Shell Commands" from the Command Palette, which will prompt you for an administrator password. Alternatively, the steps given in Fizik26's Answer will accomplish the same thing. Note: the "Window: Install Shell Commands" action only seems to be available on Mac, not Windows or Linux. A: In my case for Windows 10, I only uninstalled Git (v2.32) and kept Atom. I re-installed Git, and I chose Atom to be my default editor from the drop-down menu that appears in the installation wizard. If you kept pressing the NEXT button during the installation, you will end up with VIM as your default editor, and we sure don't want that. A: This is because there is no atom command at least in the PATH. To enable opening Atom from the command-line, you will need to install shell commands from the either the Atom menu or the Atom Command Palette. Next ensure that atom is in your path.
{ "language": "en", "url": "https://stackoverflow.com/questions/58218086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Yahoo Currency Exchange Rates in Android 4 In my application, I need to get the current exchange rates for different currencies. As it has been suggested by this, this and this question a nice way to do it, is to use the Yahoo Finance service. So, when I want to find, for example, the rate between USD and Canadian dollars, I simply send this link: http://download.finance.yahoo.com/d/quotes.csv?s=USDCAD=X&f=sl1d1t1ba&e=.csv This is working fine for both my Motorola Atrix phone with Android 2.3.4 and the emulator again with Google API 2.3.3. However, when I try the exact same link from a Galaxy SII with Android ICS 4.0 and an emulator with Google API 4.0, in both cases the quotes.csv file contains only the "Missing Symbols List". After digging around, I found out that this response can happen in case the rates were not found. But this response is for ANY currency I try under Android 4.0 (either Galaxy SII or emulator). Hence, I cannot get the rates with Android 4.0, but I can with Android 2.x. Does anyone have experienced the same problem? Is there any workaround? EDIT: This is the thread code that deals with downloading rates from the Yahoo Currency Service: //show the progress dialog downloadingDialog.show(); Runnable getRates = new Runnable() { public void run(){ dataNotFound = false; final String baseDir = getApplicationContext().getFilesDir().getAbsolutePath(); //download the rates from yahoo to a CSV file downloadFileViaHTTP (baseDir); //read the file line String filePath = baseDir + "/" + "quotes.csv"; Log.d(tag, "-> filePath = " + filePath); try { // open the file for reading InputStream instream = new FileInputStream(filePath); // if file the available for reading if (instream != null) { // prepare the file for reading InputStreamReader inputreader = new InputStreamReader(instream); BufferedReader buffreader = new BufferedReader(inputreader); //read the line String fileLine = buffreader.readLine(); Log.d(tag, "fileLine = " + fileLine); instream.close(); } } catch (Exception ex) { // print stack trace. } } }; final Thread t = new Thread(getRates); t.start(); And this is my function for downloading the quotes.csv file from the Yahoo site: public void downloadFileViaHTTP (String localPath) { Log.d(tag, "downloadFileViaHTTP..."); try { //this is the Yahoo url String urlFile = "http://download.finance.yahoo.com/d/quotes.csv?s=" + fromCurrency + toCurrency + "=X&f=sl1d1t1ba&e=.csv"; Log.d(tag,"urlFile = " + urlFile); URL url = new URL(urlFile); //create the new connection HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.connect(); //pointer to the downloaded file path String localFileName = localPath + "/" + "quotes.csv"; //this is the actual downloaded file File MyFilePtrDest = new File(localFileName); Log.d(tag,"localFileName = " + localFileName); //this will be used in reading the data from the Internet InputStream inputStream = urlConnection.getInputStream(); //this will be used to write the downloaded data into the file we created FileOutputStream fileOutput = new FileOutputStream(MyFilePtrDest); byte[] buffer = new byte[1024]; int bufferLength = 0; //used to store a temporary size of the buffer //write buffer contents to file while ((bufferLength = inputStream.read(buffer)) > 0 ) { //add the data in the buffer to the file in the file output stream (the file on the sd card fileOutput.write(buffer, 0, bufferLength); } inputStream.close(); //close the output stream when done fileOutput.flush(); fileOutput.close(); urlConnection.disconnect(); } catch (IOException e) { //data were not found dataNotFound = true; // TODO Auto-generated catch block e.printStackTrace(); } } This is the log from the Google API 2.3.3 emulator: 12-18 11:04:24.091: D/CurrencyConverter(414): downloadFileViaHTTP... 12-18 11:04:24.091: D/CurrencyConverter(414): urlFile = http://download.finance.yahoo.com/d/quotes.csv?s=EURUSD=X&f=sl1d1t1ba&e=.csv 12-18 11:04:24.282: D/CurrencyConverter(414): localFileName = /data/data/com.myapps.currencyconverter/files/quotes.csv 12-18 11:04:24.461: D/CurrencyConverter(414): -> filePath = /data/data/com.myapps.currencyconverter/files/quotes.csv 12-18 11:04:24.461: D/CurrencyConverter(414): fileLine = "EURUSD=X",1.3172,"12/18/2012","4:03am",1.317,1.3174 And this is the log from the Google API 4.0 emulator: 12-18 11:47:36.130: D/CurrencyConverter(668): downloadFileViaHTTP... 12-18 11:47:36.130: D/CurrencyConverter(668): urlFile = http://download.finance.yahoo.com/d/quotes.csv?s=EURUSD=X&f=sl1d1t1ba&e=.csv 12-18 11:47:36.449: D/dalvikvm(668): GC_CONCURRENT freed 306K, 4% free 11714K/12167K, paused 5ms+10ms 12-18 11:47:36.951: D/CurrencyConverter(668): localFileName = /data/data/com.myapps.currencyconverter/files/quotes.csv 12-18 11:47:37.159: D/CurrencyConverter(668): -> filePath = /data/data/com.myapps.currencyconverter/files/quotes.csv 12-18 11:47:37.159: D/CurrencyConverter(668): fileLine = Missing Symbols List. As you can see the "fileLine" String variable, in the first case it gets the proper rates, while at the second, the quotes.csv file merely contains the "Missing Symbols List." value. EDIT2: I have uploaded to a shared folder the complete Android project, so everyone can try it. You may compile and run with both Android 2.x and 4 emulators (or phones if you have :-)) EDIT3: Although this is not a direct answer, still it is a workaround. I use the Google currency calculator instead of the Yahoo one. To use the Google currency calculator, simply change the Yahoo url with this one: http://www.google.com/ig/calculator?hl=en&q=1" + fromCurrency + "=?" + toCurrency. Click this link to see an example of converting 78 Euros to USDs. I checked and it works with both Android versions. However if anyone finds out why this is happening with the Yahoo site, it would be good to share it with us.. A: Try to remove urlConnection.setDoOutput(true); when you run in ICS. Because ICS turns GET request to POST when setDoOutput(true). This problem is reported here and here
{ "language": "en", "url": "https://stackoverflow.com/questions/13928436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Hadoop: ERROR conf.Configuration: error parsing conf core-site.xml Trying to set up a single-node system and am getting this error when running hadoop jar HadoopWordCount.jar HadoopWordCount input.txt output from the command line. and getting the following error. Input, output, and jar file are all in the same directory. 2018-08-30 10:43:23,266 ERROR conf.Configuration: error parsing conf core-site.xml com.ctc.wstx.exc.WstxParsingException: Illegal to have multiple roots (start tag in epilog?). at [row,col,system-id]: [22,2,"file:/usr/local/Cellar/hadoop/3.1.1/libexec/etc/hadoop/core-site.xml"] Runs perfectly in IntelliJ but assignment calls for the command line. Below is the core-site.xml file. <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <!-- Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. See accompanying LICENSE file. --> <!-- Put site-specific property overrides in this file. --> <configuration> </configuration> <property> <name>hadoop.tmp.dir</name> <value>/usr/local/Cellar/hadoop/hdfs/tmp</value> <description>A base for other temporary directories.</description> </property> <property> <name>fs.default.name</name> <value>hdfs://localhost:9000</value> </property> A: property tag should be within configuration tag <configuration> <property> <name>hadoop.tmp.dir</name> <value>/usr/local/Cellar/hadoop/hdfs/tmp</value> <description>A base for other temporary directories.</description> </property> <property> <name>fs.default.name</name> <value>hdfs://localhost:9000</value> </property> </configuration>
{ "language": "en", "url": "https://stackoverflow.com/questions/52100010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to display the Navigation item title in IOS 7? I'm using this code.suggest me. UINavigationItem *navigationItem = [[UINavigationItem alloc] init]; [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]]; [self.navigationController.navigationBar setTranslucent:NO]; self.navigationItem.title=@"Mliestones"; A: use this self.navigationItem.title = @"The title";
{ "language": "en", "url": "https://stackoverflow.com/questions/26780703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: EF6 Many to Many Relationship: SqlException: Invalid column name 'SubAccount_SubAccountID' I'm getting an error while loading my data from Entity Framework EF6 with: SqlException: Invalid column name 'SubAccount_SubAccountID'. This is my query to EF6: var subAccounts = Context .SubAccount .Include(i => i.Users) .ToList(); Exception Image this ICollation Users is a many to many relationship using Fluent API. This is the Fluent API configuration in the UserConfiguration class: HasMany(p => p.SubAccounts) .WithMany(r => r.Users) .Map(mc => { mc.MapLeftKey("UserID"); mc.MapLeftKey("SubAccountID"); mc.ToTable("MOB_USER_SUBACCOUNT"); }); Can someone help me please? A: Try this guide: https://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx It will guide you trough the configuration of a Many To Many relationship, using EF6 Code First and Fluent Api
{ "language": "en", "url": "https://stackoverflow.com/questions/63712004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is having a active MySQL Connection for long periods of time bad? I'm developing an MMORPG, it's pretty far along. However, I'm noticing now that the MySQL Server has a automatic connection terminate time limit. So after x time, a connection is terminated. So what's happening with my server is after about 8 hours of run time, users can't login or update their characters on logout. A simple fix would be to make the time out value very very large, but I want to know if this is a bad idea? Another solution would be, to check if the connection is still valid before making a SQL Query, and if not start a new connection. Although I prefer the first option if it has no bad side-effects. A: In case you're not already doing that I'd like to say that the best option would be to use a proper connection pool on the server instead of reusing a single connection. Now, increasing the timeout SHOULD be safe, but MySQL might have memory leaks (of sorts) that are tied to the connection, so dropping the connection from time to time might be much safer. For example, if you're using dynamically generated prepared queries (some APIs do that to make the queries safe from the SQL injection attacks) then MySQL might have a problem caching all the prepared queries in memory. You might have to implement such eviction yourself, unfortunately.
{ "language": "en", "url": "https://stackoverflow.com/questions/26426906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Textarea startswith function not working I am trying to apply starts with function on textarea, but obviously I am doing something wrong. I don't understand javascript, so I am sorry for obvious mistakes or problems. At least I tried what seemed logical to me... Fiddle here: http://jsfiddle.net/SVxbW/235/ HTML: $("textarea").bind(function () { if ($(this).startsWith("Hello") { $(".kuk").show(); } else { $(".kuk").hide(); } }); .kuk { display: none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <textarea></textarea> <button class="kuk">Clear</button> And what if someone pastes the text "Hello" with right click of mouse? How to recognize that action too? A: You need to get the val() then use startsWith(). Additionally you need to bind proper event handler. Here I have used keyup $("textarea").on('keyup', function() { if ($(this).val().startsWith("Hello")) { $(".kuk").show(); } else { $(".kuk").hide(); } }); Updated Fiddle A: Try this. You need to bind an event also you need to get val to check whether it startswith hello or not. $("textarea").bind('keyup',function () { if ($(this).val().startsWith("Hello")) { $(".kuk").show(); } else { $(".kuk").hide(); } }); Here is jsfiddle A: I made jsfiddle for those wondering which code I am using right now. I added few kinds of input options and now it works in chrome as well. final fiddle $("textarea").bind('change keyup paste blur input',function () { if ($(this).val().startsWith("Hello") || $(this).val().startsWith("HELLO") || $(this).val().startsWith("hello")) { $(".kuk").show(); } else { $(".kuk").hide(); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/40992147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: nested object JSON sorting JavaScript I'm not sure I am asking the right question or not. I get a JSON response like this from my server request { "20150917": { "Daily01sec": { "TG01152600000": "\/20150917\/Daily01sec\/TG0115260.bin", "TG01152600600": "\/20150917\/Daily01sec\/TG0115260.bin", } }, "201510": { "05": { "Daily01sec": { "TG01152780600": "\/201510\/05\/Daily01sec\/TG01152780600.bin", } } }, "201509": { "05": { "Daily01sec": { "TG01152780600": "\/201510\/05\/Daily01sec\/TG01152780600.bin", } } } } I want to count all folders and sort them. I want to get sorted like this for master folders: "201509" "201510" "20150817" please check the example data at here http://jsfiddle.net/ebrahimmm/ncykb0qq/1/ here is the code receiving via $http at angularJS angular.module('app',[]) .controller('cntl',function($scope,$http){ $http.get('http://'+'server' + "/getdatalogtree"). then( function (response) { var data=response.data; //here i need sorting },function(response){ }); }); I also want to put each mast folders and its content to be an element of an array. A: You can use Object.keys(Your_JSON_Response) method, to get array of keys. And then Array.sort() method... A: Edit :: One-Liner This should do the job : function foo(dataString) { return Object.keys(JSON.parse(dataString)).map(parseFloat).sort(function(a,b) {return a[0]-b[0]}).map(String); //datastring -> Your JSON string which you get from the server } A: This one line will do this job: function foo(dataString) { return Object.keys(dataString).sort();}
{ "language": "en", "url": "https://stackoverflow.com/questions/32956649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Rails 4 - ActiveModel::ForbiddenAttributesError with has_many and accepts_nested_attributes_for I have a problem with accepts_nested_attributes_for.. Here's my Zone model class Zone < ActiveRecord::Base has_many :zones_users, inverse_of: :zone, dependent: :delete_all has_many :users, through: :zones_users accepts_nested_attributes_for :zones_users, :update_only => true, :allow_destroy => true end and ZonesUser model for the many-to-many association with the User model class ZonesUser < ActiveRecord::Base belongs_to :zone belongs_to :user end now in the ZonesController I'm permitting attributes and nested attributes for the ZonesUser association as follows def zone_params params.require(:zone) .permit(:id, :name, :description, :image, zones_users_attributes: [:user_id, :zone_id, :is_admin]) end so that I can update the Zone's data and the association all at once as follows def update @zone = Zone.find_by_id(zone_params[:id]) @zone.update(zone_params) end but this gives me the error ActiveModel::ForbiddenAttributesError and the error goes like this: ActiveModel::ForbiddenAttributesError - ActiveModel::ForbiddenAttributesError: activemodel (4.2.4) lib/active_model/forbidden_attributes_protection.rb:21:in `sanitize_for_mass_assignment' activerecord (4.2.4) lib/active_record/attribute_assignment.rb:33:in `assign_attributes' activerecord (4.2.4) lib/active_record/core.rb:564:in `init_attributes' activerecord (4.2.4) lib/active_record/core.rb:281:in `initialize' activerecord (4.2.4) lib/active_record/inheritance.rb:61:in `new' activerecord (4.2.4) lib/active_record/reflection.rb:131:in `build_association' activerecord (4.2.4) lib/active_record/associations/association.rb:250:in `build_record' I'm using rails 4, and have read that attr_accessible is no longer used to allow access to nested models/associations, and that I should permit the attributes on a controller level (the permit zones_users_attributes part).. what have I missed?
{ "language": "en", "url": "https://stackoverflow.com/questions/36604909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create Interface All Optional Fields from class I have a constructor that takes as a parameter an object containing properties of the object. class MyObj { a = 0; b = 0; c = 0; d = 0; constructor(params){ for(var i in params) this[i] = params[i]; } } My goal is to have autocompletion when writing something like new MyObj({a:1}). Right now, I need to create a separated interface to have autocompletion interface MyObjOptions { a?:number; b?:number; c?:number; d?:number; } with constructor(params:MyObjOptions){...} Is there a way to do that without having to duplicate all fields in an interface? A: Is there a way to do that without having to duplicate all fields in an interface? You can put the object into a config property: interface MyObjOptions { a?:number; b?:number; c?:number; d?:number; } class MyObj { constructor(public options:MyObjOptions) { } } But if you want defaults you have to list them in the interface + write them out so you must write e.g. a twice. No way around it
{ "language": "en", "url": "https://stackoverflow.com/questions/37505791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Collision detection between ImageViews I need help getting two ImageViews to collide, I looked around on this website and many youtube videos and think I have found one solution to my problem. I found some code from another person post, how to detect when a ImageView is in collision with another ImageView? and I'm just wondering where I should place that code in my program because when it's at the bottom i try to log.d to show if I was succesful on trying to detect whether the imageViews collided and nothing shows. Anyways here is my code and the code I used from the other question is at the very bottom and used as a comment. YOUR HELP IS EXTREMELY APPRECIATED, THANK YOU IF YOU HELPED ME! Main.java package com.example.admin.basketball; import android.graphics.Point; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Display; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity { //Layout private RelativeLayout myLayout = null; //Screen Size private int screenWidth; private int screenHeight; //Position private float ballDownY; private float ballDownX; //Initialize Class private Handler handler = new Handler(); private Timer timer = new Timer(); //Images private ImageView net = null; private ImageView ball = null; //for net movement along x-axis float x; float y; //points private int points = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myLayout = (RelativeLayout) findViewById(R.id.myLayout); //score final TextView score = (TextView) findViewById(R.id.score); //imageviews net = (ImageView) findViewById(R.id.net); ball = (ImageView) findViewById(R.id.ball); //retrieving screen size WindowManager wm = getWindowManager(); Display disp = wm.getDefaultDisplay(); Point size = new Point(); disp.getSize(size); screenWidth = size.x; screenHeight = size.y; //move to out of screen ball.setX(-80.0f); ball.setY(screenHeight + 80.0f); //start timer timer.schedule(new TimerTask() { @Override public void run() { handler.post(new Runnable() { @Override public void run() { changePos(); } }); } }, 0, 20); } public void changePos() { //down ballDownY += 10; if (ball.getY() > screenHeight) { ballDownX = (float) Math.floor((Math.random() * (screenWidth - ball.getWidth()))); ballDownY = -100.0f; } ball.setY(ballDownY); ball.setX(ballDownX); //make net follow finger myLayout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { MainActivity.this.x = event.getX(); y = event.getY(); if (event.getAction() == MotionEvent.ACTION_MOVE) { net.setX(MainActivity.this.x); net.setY(y); } return true; } }); } } /* private boolean viewsOverlap(ImageView net, ImageView ball) { int[] net_coords = new int[2]; net.getLocationOnScreen(net_coords); int net_w = net.getWidth(); int net_h = net.getHeight(); Rect net_rect = new Rect(net_coords[0], net_coords[1], net_coords[0] + net_w, net_coords[1] + net_h); int[] ball_coords = new int[2]; ball.getLocationOnScreen(ball_coords); int ball_w = ball.getWidth(); int ball_h = ball.getHeight(); Rect ball_rect = new Rect(ball_coords[0], ball_coords[1], ball_coords[0] + ball_w, ball_coords[1] + ball_h); return net_rect.intersect(ball_rect) || net_rect.contains(ball_rect) || ball_rect.contains(net_rect); }*/ A: Collision detction and score increase ;-) public class MainActivity extends AppCompatActivity { //Layout private RelativeLayout myLayout = null; //Screen Size private int screenWidth; private int screenHeight; //Position private float ballDownY; private float ballDownX; //Initialize Class private Handler handler = new Handler(); private Timer timer = new Timer(); //Images private ImageView net = null; private ImageView ball = null; //score private TextView score = null; //for net movement along x-axis public float x = 0; public float y = 0; //points private int points = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.activity_main); this.myLayout = (RelativeLayout) findViewById(R.id.myLayout); this.score = (TextView) findViewById(R.id.score); this.net = (ImageView) findViewById(R.id.net); this.ball = (ImageView) findViewById(R.id.ball); //retrieving screen size WindowManager wm = getWindowManager(); Display disp = wm.getDefaultDisplay(); Point size = new Point(); disp.getSize(size); screenWidth = size.x; screenHeight = size.y; //move to out of screen this.ball.setX(-80.0f); this.ball.setY(screenHeight + 80.0f); //Error here /*//Run constantly new Handler().postDelayed(new Runnable() { @Override public void run() { Render(); } }, 100); //100 is miliseconds interval than sleep this process, 1000 miliseconds is 1 second*/ Thread t = new Thread() { @Override public void run() { try { while (!isInterrupted()) { Thread.sleep(100); runOnUiThread(new Runnable() { @Override public void run(){Render();}});} }catch (InterruptedException e) {}}}; t.start(); } public void Render() { changePos(); if(Collision(net, ball)) { points++; //You dont need findView Textview score for that exists in OnCreate Method this.score.setText("Score:" + points); } } public void changePos() { //down ballDownY += 10; if (ball.getY() > screenHeight) { ballDownX = (float) Math.floor((Math.random() * (screenWidth - ball.getWidth()))); ballDownY = -100.0f; } ball.setY(ballDownY); ball.setX(ballDownX); //make net follow finger myLayout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { x = event.getX(); y = event.getY(); if (event.getAction() == MotionEvent.ACTION_MOVE) { net.setX(x); net.setY(y); } return true; } }); public boolean Collision(ImageView net, ImageView ball) { Rect BallRect = new Rect(); ball.getHitRect(BallRect); Rect NetRect = new Rect(); net.getHitRect(NetRect); return BallRect.intersect(NetRect); } } A: Let me give you an example how I implemented working collision detection in only 10 rows of code. It is not exactly the same problem but it can give you an idea how to manipulate objects based on coordinates. // update the canvas in order to display the game action @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); int xx = 200; int yy = 0; if (persons != null) { synchronized (persons) { Iterator<Person> iterate = persons.iterator(); while (iterate.hasNext()) { Person p = iterate.next(); if (p.getImage() != 0) { bitmap = BitmapFactory.decodeResource(getResources(), p.getImage()); //load a character image // Draw the visible person's appearance if(xx > canvas.getWidth()) xx = 0; canvas.drawBitmap(bitmap, xx , canvas.getHeight()- bitmap.getHeight() , null); // Draw the name Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); canvas.save(); paint.setStrokeWidth(1); paint.setColor(Color.WHITE); paint.setTextSize(50); canvas.drawText(p.name, (float)(xx+0.25*bitmap.getWidth()), (float) (canvas.getHeight() ), paint); xx += bitmap.getWidth()*0.75; } } } } canvas.save(); //Save the position of the canvas. canvas.restore(); //Call the next frame. invalidate(); } } In the above code, I just check if xx collides with an array of other images, then I just update xx accordingly. You are welcome to check out my open source repository with this code.
{ "language": "en", "url": "https://stackoverflow.com/questions/49289120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to find probability of drawing ball from a given container? A container having 2 balls, one is red and second one is black. One ball is drawn each time and placed again in the container.Drawing of ball is done ntimes where 1<=n<=10^6.I want to find out the probability of drawing red ball at least rwhere 0<=r<=n.For example, let n=3and r=2then probability pcan be calculated as : p=( C(3,2)+C(3,3) ) / (2^3) p=(3+1)/8 p=0.5 where C(n,r) = n!/(n-r)!r!. It can also be solved using binomial distribution. But, it is difficult to calculate for given nand r. A: You can try using logarithms, i.e. instead of P(r, n) = n! / ((n-r)! * r! * r**n) compute just log(P(r, r)) = log(n!) - log((n-r)!) - log(r!) - r*log(n) All factorials are easy computable as logarithms: log(n!) = log(n) + log(n - 1) + ... + log(2) + log(1) When obtain log(P(r, n)) all you have to do is to exponentiate. As a further improvement you can use Stirling's approximation for the factorials in case n is large: n! ~ (n / e)**n * sqrt(2 * PI * n) so (ln stands for the natural logarithm) ln(n!) ~ n * ln(n) - n - ln(n)/2 - ln(2 * PI)/2 Edit: If you are looking for CDF (Cumulative Distribution Function, probability that random value is less or equal given x), it can be represented as regularized imcomplete beta function: https://en.wikipedia.org/wiki/Binomial_distribution P(x <= k) = I(1 - p, n - r, r+1) p = 1/2 in your case in case C++, the implementation can be found in Boost
{ "language": "en", "url": "https://stackoverflow.com/questions/42197785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }