source
sequence
text
stringlengths
99
98.5k
[ "scifi.stackexchange", "0000216875.txt" ]
Q: When did J.K. Rowling decide to make Ron and Hermione a couple? We see in Harry Potter and the Goblet of Fire that Hermione seems more than disgruntled when Fleur kisses Ron on both cheeks (my emphasis): Fleur bent down, kissed Harry twice on each cheek (he felt his face burn and wouldn’t have been surprised if steam was coming out of his ears again), then said to Ron, “And you too-you ‘elped” “Yeah,” said Ron, looking extremely hopeful, “yeah, a bit -” Fleur swooped down on him too and kissed him. Hermione looked simply furious, but just then, Ludo Bagman’s magically magnified voice boomed out beside them, making them all jump, and causing the crowd in the stands to go very quiet. We also see that in Harry Potter and the Half-Blood Prince that Hermione was going to ask Ron to the Christmas dance/ball with Slughorn and that he genuinely seemed to want to go with her: “‘Slug Club,’”repeated Ron with a sneer worthy of Malfoy. “It’s pathetic. Well, I hope you enjoy your party. Why don’t you try hooking up with McLaggen, then Slughorn can make you King and Queen Slug —” “We’re allowed to bring guests,” said Hermione, who for some reason had turned a bright, boiling scarlet, “and I was going to ask you to come, but if you think it’s that stupid then I won’t bother!” Harry suddenly wished the pod had flown a little farther, so that he need not have been sitting here with the pair of them. Unnoticed by either, he seized the bowl that contained the pod and began to try and open it by the noisiest and most energetic means he could think of; unfortunately, he could still hear every word of their conversation. “You were going to ask me?” asked Ron, in a completely different voice. “Yes,” said Hermione angrily. “But obviously if you’d rather I hooked up with McLaggen...” There was a pause while Harry continued to pound the resilient pod with a trowel. “No, I wouldn’t,” said Ron, in a very quiet voice. Were there other reasons for this happening other than Hermione and Ron were smitten with each other, or had J.K. Rowling gotten the love train started by then? If she hadn't, when did she decide to make them a couple? A note on the answers: I do not want an answer coming from the books or movies! A Rowling interview is the sort of material that would work (Pottermore is also good). Anything which is not fictional and written by J.K. Rowling is considered an acceptable answer... Also know that Wikia answers are acceptable if the source by which Wikia received this information is reliable (i.e. there should be a footnote with a reliable source on the Wikia page). A: It seems like it was planned from the very beginning. In a February 2014 interview with Emma Watson for the magazine Wonderland Rowling stated: I wrote the Hermione/Ron relationship as a form of wish fulfillment. That's how it was conceived, really. For reasons that have very little to do with literature and far more to do with me clinging to the plot as I first imagined it, Hermione ended up with Ron. As you can see, she claims that the relationship sprung from "the plot as [she] first imagined it", which indicates to me that it was always the plan, though the way that the books changed as she wrote them made it less natural than it might otherwise have been. A: Rowling began publicly hinting at the relationship from at least 2000. Since the question seeks Rowling quotes, I thought I'd assemble an answer of public statements she made before she had finished writing the books. Hopefully the chronological progression of her decision-making is apparent. The quotes are almost entirely sourced from www.accio-quote.org. As early as 1999 (before the publication of Goblet of Fire) she went as far as to seemingly rule out a Harry-Hermione relationship. She hinted at another relationship, which may have been a reference to Ron-Hermione: JKR: Oh I like this one: "Do Harry and Hermione have a date?" No! They're, they're very platonic friends. But I won't answer for anyone else, nudge, nudge, wink, wink. (National Press Club luncheon, 20th October 1999). This is the clearest demonstration that she was happy to tease Ron-Hermione as a concept prior to the publication of Goblet of Fire. Obviously, the tension between Ron and Hermione features quite evidently in Goblet of Fire. After that book was published, in 2000, she confirmed that there was "something going on" between them in that book. sammyohyeah: Is it just me, or was something going on between Ron and Hermione during the last half of GOF? [...] jkrowling_bn: yes, something's 'going on'... jkrowling_bn: but Ron doesn't realise it yet... jkrowling_bn: typical boy (Barnes & Noble online chat, 20th October 2000). Perhaps she was misdirecting and perhaps she hadn't definitively determined that Ron and Hermione would get together at that stage. Nevertheless, she was happy to strongly imply that a relationship between them was feasible. Such a comment is certainly consistent with her having decided to make Ron and Hermione an item in a future book. It's probable that she wouldn't have been so blatant both in her public remarks and in her writing if she wasn't sure the relationship would materialise in time. In 2003, just before the publication of Order of the Phoenix, she again distanced herself from the notion that Hermione would enter into a relationship with Harry and said that Hermione and Ron had "more tension". JKR And he, yes, [Harry] does have certain adolescent, um, rights of passage happen to him. Couric: Any snogging with Hermione? JKR: Hermione and Harry! Do you think so? Couric: No I’m kidding. JKR: Ron and Hermione, I would say, have more tension there. (Dateline NBC Interview, 20th June 2003). In Half-Blood Prince the chemistry between Ron and Hermione is pretty blatant. Ron dates Lavender Brown just to try and get in a relationship and Hermione responds with a huge amount of jealousy. Rowling seemed to see Half-Blood Prince as the confirmation that Ron and Hermione would be an item in the final book. In 2005, after the book was published, she again shot down the idea that Hermione would end up with Harry. JKR: Well I think anyone who is still shipping Harry/Hermione after this book ES: [whispered] Delusional! JKR: Uh - no! But they need to go back and reread, I think. (Mugglenet Interview, 16th July 2005). In 2006, she regarded the question as obvious. FAQ: Does Hermione love Ron or Harry? JKR: I can't believe that some of you haven't worked this one out yet. (www.jkrowling.com, 2nd March 2006). She obviously didn't rule out Hermione loving one of Ron or Harry and, since she had gone to such pains to rule out Harry-Hermione, she was evidently teasing Ron-Hermione. Later that year she again implied that they would get together, and dismissed Hermione dating Harry. "Then one bored afternoon, I googled 'Harry Potter'. Oh... my... God. I had NO idea. The shipping wars? For people who are over 18 who may not know about this - because I certainly didn't - it's like cyber gang warfare. People who wanted Harry and Hermione to end up together...[crowd screams]...they're still out there! Get over it! And other people who wanted Hermione and Ron...[crowd screams]...And there are very weird couplings as well, but we will not go anywhere near there." (Event with Steven King and John Irving, 1st August 2006). Pottermore also references a quote, probably from the same event, where Rowling discusses what Hermione would see in the Mirror of Erised. Apparently, she "would see her and her friends triumphant after their mission" but also see herself "closely entwined" with somebody else (possibly Ron). "Hermione would also see herself closely entwined...with...another...person..." ("Clues J.K. Rowling gave us about the Harry Potter books: Harry’s friends and family", Pottermore, 2nd August 2006). By this point Rowling was being very open about Hermione having feelings for another character. The context from Half-Blood Prince made it clear that person was Ron. From the above quotes I'd deduce that Rowling was happy to publicly confirm the basis of a relationship between Ron and Hermione in 2000. She admits that there was "something going on" between them in Goblet of Fire. A year beforehand she teased that another relationship other than Harry-Hermione was in the offing but didn't clarify who she was referring to. After Half-Blood Prince she considered it more-or-less public knowledge that Ron and Hermione would become a couple. None of this gives us a precise date when she decided that the relationship would happen. Presumably she planned the relationship before she began talking about it in interviews. The quote in Kyle Doyle's answer certainly indicates that she probably planned the relationship from the very beginning. Nevertheless, by the time Deathly Hallows was released readers had a pretty clear understanding that Ron and Hermione would likely become a couple at some point.
[ "stackoverflow", "0010953796.txt" ]
Q: Flat, 3D triangle, made out of voxels I have a problem that I can't seem to get a working algorithm for, I've been trying to days and get so close but yet so far. I want to draw a triangle defined by 3 points (p0, p1, p2). This triangle can be any shape, size, and orientation. The triangle must also be filled inside. Here's a few things I've tried and why they've failed: 1 Drawing lines along the triangle from side to side Failed because the triangle would have holes and would not be flat due to the awkwardness of drawing lines across the angled surface with changing locations 2 Iterate for an area and test if the point falls past the plane parallel to the triangle and 3 other planes projected onto the XY, ZY, and XZ plane that cover the area of the triangle Failed because for certain triangles (that have very close sides) there would be unpredictable results, e.g. voxels floating around not connected to anything 3 Iterate for an area along the sides of the triangle (line algorithm) and test to see if a point goes past a parallel plane Failed because drawing a line from p0 to p1 is not the same as a line from p1 to p0 and any attempt to rearrange either doesn't help, or causes more problems. Asymmetry is the problem with this one. This is all with the intent of making polygons and flat surfaces. 3 has given me the most success and makes accurate triangles, but when I try to connect these together everything falls apart and I get issues with things not connecting, asymmetry, etc. I believe 3 will work with some tweaking but I'm just worn out from trying to make this work for so long and need help. There's a lot of small details in my algorithms that aren't really relevant so I left them out. For number 3 it might be a problem with my implementation and not the algorithm itself. If you want code I'll try and clean it up enough to be understandable, it will take me a few minutes though. But I'm looking for algorithms that are known to work. I can't seem to find any voxel shape making algorithms anywhere, I've been doing everything from scratch. EDIT: Here's the third attempt. It's a mess, but I tried to clean it up. // Point3i is a class I made, however the Vector3fs you'll see are from lwjgl public void drawTriangle (Point3i r0, Point3i r1, Point3i r2) { // Util is a class I made with some useful stuff inside // Starting values for iteration int sx = (int) Util.min(r0.x, r1.x, r2.x); int sy = (int) Util.min(r0.y, r1.y, r2.y); int sz = (int) Util.min(r0.z, r1.z, r2.z); // Ending values for iteration int ex = (int) Util.max(r0.x, r1.x, r2.x); int ey = (int) Util.max(r0.y, r1.y, r2.y); int ez = (int) Util.max(r0.z, r1.z, r2.z); // Side lengths float l0 = Util.distance(r0.x, r1.x, r0.y, r1.y, r0.z, r1.z); float l1 = Util.distance(r2.x, r1.x, r2.y, r1.y, r2.z, r1.z); float l2 = Util.distance(r0.x, r2.x, r0.y, r2.y, r0.z, r2.z); // Calculate the normal vector Vector3f nn = new Vector3f(r1.x - r0.x, r1.y - r0.y, r1.z - r0.z); Vector3f n = new Vector3f(r2.x - r0.x, r2.y - r0.y, r2.z - r0.z); Vector3f.cross(nn, n, n); // Determines which direction we increment for int iz = n.z >= 0 ? 1 : -1; int iy = n.y >= 0 ? 1 : -1; int ix = n.x >= 0 ? 1 : -1; // Reorganize for the direction of iteration if (iz < 0) { int tmp = sz; sz = ez; ez = tmp; } if (iy < 0) { int tmp = sy; sy = ey; ey = tmp; } if (ix < 0) { int tmp = sx; sx = ex; ex = tmp; } // We're we want to iterate over the end vars so we change the value // by their incrementors/decrementors ex += ix; ey += iy; ez += iz; // Maximum length float lmax = Util.max(l0, l1, l2); // This is a class I made which manually iterates over a line, I already // know that this class is working GeneratorLine3d g0, g1, g2; // This is a vector for the longest side Vector3f v = new Vector3f(); // make the generators if (lmax == l0) { v.x = r1.x - r0.x; v.y = r1.y - r0.y; v.z = r1.z - r0.z; g0 = new GeneratorLine3d(r0, r1); g1 = new GeneratorLine3d(r0, r2); g2 = new GeneratorLine3d(r2, r1); } else if (lmax == l1) { v.x = r1.x - r2.x; v.y = r1.y - r2.y; v.z = r1.z - r2.z; g0 = new GeneratorLine3d(r2, r1); g1 = new GeneratorLine3d(r2, r0); g2 = new GeneratorLine3d(r0, r1); } else { v.x = r2.x - r0.x; v.y = r2.y - r0.y; v.z = r2.z - r0.z; g0 = new GeneratorLine3d(r0, r2); g1 = new GeneratorLine3d(r0, r1); g2 = new GeneratorLine3d(r1, r2); } // Absolute values for the normal float anx = Math.abs(n.x); float any = Math.abs(n.y); float anz = Math.abs(n.z); int i, o; int si, so; int ii, io; int ei, eo; boolean maxx, maxy, maxz, midy, midz, midx, minx, miny, minz; maxx = maxy = maxz = midy = midz = midx = minx = miny = minz = false; // Absolute values for the longest side vector float rnx = Math.abs(v.x); float rny = Math.abs(v.y); float rnz = Math.abs(v.z); int rmid = Util.max(rnx, rny, rnz); if (rmid == rnz) midz = true; else if (rmid == rny) midy = true; midx = !midz && !midy; // Determine the inner and outer loop directions if (midz) { if (any > anx) { maxy = true; si = sy; ii = iy; ei = ey; } else { maxx = true; si = sx; ii = ix; ei = ex; } } else { if (anz > anx) { maxz = true; si = sz; ii = iz; ei = ez; } else { maxx = true; si = sx; ii = ix; ei = ex; } } if (!midz && !maxz) { minz = true; so = sz; eo = ez; } else if (!midy && !maxy) { miny = true; so = sy; eo = ey; } else { minx = true; so = sx; eo = ex; } // GeneratorLine3d is iterable Point3i p1; for (Point3i p0 : g0) { // Make sure the two 'mid' coordinate correspond for the area inside the triangle if (midz) do p1 = g1.hasNext() ? g1.next() : g2.next(); while (p1.z != p0.z); else if (midy) do p1 = g1.hasNext() ? g1.next() : g2.next(); while (p1.y != p0.y); else do p1 = g1.hasNext() ? g1.next() : g2.next(); while (p1.x != p0.x); eo = (minx ? p0.x : miny ? p0.y : p0.z); so = (minx ? p1.x : miny ? p1.y : p1.z); io = eo - so >= 0 ? 1 : -1; for (o = so; o != eo; o += io) { for (i = si; i != ei; i += ii) { int x = maxx ? i : midx ? p0.x : o; int y = maxy ? i : midy ? p0.y : o; int z = maxz ? i : midz ? p0.z : o; // isPassing tests to see if a point goes past a plane // I know it's working, so no code // voxels is a member that is an arraylist of Point3i if (isPassing(x, y, z, r0, n.x, n.y, n.z)) { voxels.add(new Point3i(x, y, z)); break; } } } } } A: You could use something like Besenham's line algorithm, but extended into three dimensions. The two main ideas we want to take from it are: rotate the initial line so its slope isn't too steep. for any given x value, find an integer value that is closest to the ideal y value. Just as Bresenham's algorithm prevents gaps by performing an initial rotation, we'll avoid holes by performing two initial rotations. Get the normal vector and point that represent the plane your triangle lies on. Hint: use the cross product of (line from p0 to p1) and (line from p0 to p2) for the vector, and use any of your corner points for the point. You want the plane to be sufficiently not-steep, to avoid holes. You must satisfy these conditions: -1 >= norm.x / norm.y >= 1 -1 >= norm.z / norm.y >= 1 Rotate your normal vector and initial points 90 degrees about the x axis and 90 degrees about the z axis until these conditions are satisfied. I'm not sure how to do this in the fewest number of rotations, but I'm fairly sure you can satisfy these conditions for any plane. Create a function f(x,z) which represents the plane your rotated triangle now lies on. It should return the Y value of any pair of X and Z values. Project your triangle onto the XZ plane (i.e., set all the y values to 0), and use your favorite 2d triangle drawing algorithm to get a collection of x-and-z coordinates. For each pixel value from step 4, pass the x and z values into your function f(x,z) from step 3. Round the result to the nearest integer, and store the x, y, and z values as a voxel somewhere. If you performed any rotations in step 2, perform the opposite of those rotations in reverse order on your voxel collection.
[ "unix.stackexchange", "0000474484.txt" ]
Q: Failed to open root LUKS device on LVM during boot I have LVM partitions which are encrypted using LUKS. My root partition is /dev/HDD/root: LVM group "HDD" (at /dev/HDD): Encrypted LUKS device "root" at /dev/HDD/root I'm trying to decrypt it via grub parameters, GRUB_CMDLINE_LINUX: dolvm crypt_root=/dev/HDD/root root=/dev/mapper/root root_keydev=UUID=<usb-uuid> root_key=hdd.key The key for LUKS is located on usb-device at /hdd.key But when it is loading, it shows error message: >> Scanning for and activating Volume Groups Reading all physical volumes. This may take a while... Found volume group "HDD" using metadata type lvm 3 logical volume(s) in volume group "HDD" now active >> Using key device /dev/sdc2. >> Removable device /dev/sdc2 mounted. >> hdd.key on device /dev/sdc2 found No key available with this passphrase. !! Failed to open LUKS device /dev/HDD/root !! Could not find the root in /dev/HDD/root. !! Please specify another value or: !! - press Enter for the same !! - type "shell" for a shell !! - type "q" to skip... According to logs the volume group was found, the device with key was mounted successfully, the key on the device was found, but then it failed to open it using LUKS. Then I'm using shell option to fix it manually. Device with the key is mounted to /mnt/key, so I can find it here and open LUKS device with this key: cat /mnt/key/hdd.key | cryptsetup luksOpen /dev/HDD/root root this command opens LUKS device at /dev/mapper/root, so I can exit the shell and press q to skip this error. After that the system is booting successfully. It seems that something is wrong with my grub configuration, because it is possible to open LUKS device and mount it using my key manually, so my question is how to fix it to open LUKS device automatically on boot using grub2? A: The issue was that I used a key as a passphrase for LUKS instead of keyfile. To convert it to keyfile it's needed to add a keyfile via cryptsetup and remove passphrase for it: cat /bood/hdd.key | cryptsetup luksAddKey -d /bood/hdd.key /dev/root cat /bood/hdd.key | cryptsetup luksRemoveKey /dev/root
[ "stackoverflow", "0008491771.txt" ]
Q: Third party JavaScript - good idea to use try catch? I am developing a third party JavaScript widget that will be included by users on their applications/blogs. I have good tests around the library, but I am afraid that if despite that if some syntax error sneaks through and cause the other scripts on the user's application to stop loading. So - to prevent this from happening, is it a good idea to surround my entire widget code in a try/catch like this? try { // my library } catch(e) { // notify me about the error } A: Here is a good common approach to what try-catch blocks are used for. If you can catch an exception and do something with that exception then go ahead and catch it. For example, BadHtmlException or something similar is an exception you can catch to provide user with feedback that you should fix the HTML and try again. There are types of exceptions that there is no action that can be done. For example, the application was configured incorrectly with a bad user/password. This should be a critical error and should be push all the way up to the application. Possibly an exception that might not make sense to the user. So what am I suggesting? I am suggesting don't wrap anything in a try-catch unless you know there will be that exception thrown. If there is a bug or exception, the person using your code should see it and report it as an issue. You really can't spend all your time going through possible issues that may or may not be your code. Finally, you should write unit tests and make sure each part of your library is well tested before each release. Doing this will make sure that future releases don't break anything.
[ "stackoverflow", "0038554675.txt" ]
Q: 404 not found while testing spring boot rest api I am trying to write tests on my applicatoin's rest api. I am using spring boot, jersey rest. For testing I am trying to use MockMvc, but for all GET requests I get 404 status code. I tried different ways to run it, but result is always the same. I think I am missing something, so, please, advise. REST resource: @Component @Path("/v1/users") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Transactional(readOnly = true) public class UserResource { private final UserService userService; @Inject public UserResource(UserService userService) { this.userService = userService; } @GET public Collection<User> list() { return userService.fetchAllUsers(); } } Application class: @SpringBootApplication @ComponentScan("com.glasierr.application") @EnableJpaRepositories("com.glasierr.application.infrastructure.persistence.spring") public class UserServiceApplication { public static void main(String[] args) { new SpringApplicationBuilder() .sources(UserServiceApplication.class) .run(args); } } Jersey config: @Configuration @ApplicationPath("/api") public class JerseyConfig extends ResourceConfig { public JerseyConfig() { packages("com.glasierr.application.resource"); } } Test properties snippet: server: port: 9999 database: driverName: org.h2.Driver url: jdbc:h2:mem:test;IGNORECASE=TRUE;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1 username: sa password: hibernateDialect: org.hibernate.dialect.H2Dialect hibernateShowSql: true hibernateHbm2ddl: update Testing class: @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(UserServiceApplication.class) @WebIntegrationTest public class UserResourceTest { @InjectMocks private UserResource userResource; @Mock private UserService userService; @Autowired private WebApplicationContext context; private MockMvc mvc; @Before public void setUp() { MockitoAnnotations.initMocks(this); mvc = MockMvcBuilders .webAppContextSetup(context) .build(); } @Test public void test() throws Exception { when(userService.fetchAllUsers()).thenReturn(Arrays.asList(new User("user1"), new User("user2"))); mvc.perform(get("/api/v1/users").accept(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andExpect(status().isOk()); } } Some console output: 2016-07-24 20:17:40.909 INFO 5532 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2016-07-24 20:17:42.121 INFO 5532 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@11c9af63: startup date [Sun Jul 24 20:17:32 EEST 2016]; root of context hierarchy 2016-07-24 20:17:42.264 INFO 5532 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2016-07-24 20:17:42.266 INFO 5532 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) 2016-07-24 20:17:42.320 INFO 5532 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2016-07-24 20:17:42.320 INFO 5532 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2016-07-24 20:17:42.413 INFO 5532 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2016-07-24 20:17:42.877 INFO 5532 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 9999 (http) 2016-07-24 20:17:42.885 INFO 5532 --- [ main] e.s.h.a.resource.OperatorResourceTest : Started OperatorResourceTest in 10.898 seconds (JVM running for 13.017) 2016-07-24 20:17:43.126 INFO 5532 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet '' 2016-07-24 20:17:43.127 INFO 5532 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization started 2016-07-24 20:17:43.148 INFO 5532 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : FrameworkServlet '': initialization completed in 21 ms java.lang.AssertionError: Status Expected :200 Actual :404 A: Problem solved. I have included configurations in application class and it worked. @SpringBootApplication @Configuration @Import({JerseyConfig.class}) public class UserServiceApplication { public static void main(String[] args) { new SpringApplicationBuilder() .sources(UserServiceApplication.class) .run(args); } }
[ "es.stackoverflow", "0000129782.txt" ]
Q: ¿Como puedo detectar la posición del scroll de pantalla con javascript? Mi duda sería la siguiente: ¿Puedo detectar en que posición esta el scroll de pantalla con javascript? A: Sí, puedes usar window.scrollY y window.scrollX para comprobar en qué posición te encuentras. A: Podes usar: element.scrollTop // Vertical - Son los píxeles ocultos en la parte superior element.scrollLeft // Horizontal - Son los píxeles ocultos en la parte izquierda Para obtener el desplazamiento vertical y horizontal, respectivamente, que se ha desplazado. Aclaraciones: element puede ser document.body si necesitas saber de toda la página. Podes compararlo con: element.offsetHeight // Son la cant de píxeles (a lo alto) que ves en el navegador. element.offsetWidth // Son la cant de píxeles (a lo ancho) que ves en el navegador. si necesitas porcentajes. Osea, por ejemplo: El scroll esta en el 50% verticalmente. A: Te muestro un ejemplo con Jquery y otro con javaScript puro que hace lo que quieres: JQUERY $(window).scroll(function(event) { var scrollLeft = $(window).scrollLeft(); var scrollTop = $(window).scrollTop(); console.log("Vertical "+scrollTop); console.log("Horizontal "+scrollLeft); }); .body{ width: 105%; height: 700px; background:#FFCC99; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="body"> </div> JavaScript puro window.onscroll = function() { console.log("Vertical: " + window.scrollY); console.log("Horizontal: " + window.scrollX); }; .body { width: 105%; height: 700px; background: #FFCC99; } <div id="body" class="body"> </div>
[ "stackoverflow", "0012983197.txt" ]
Q: How to use xslt with attribute values as selectors ? I am trying to learn xslt and i am working an xml which looks like this. <Beats> <Beat> <Personal type="set"> <Usages type="box"> 1233 </Usages> <NonUsages type="box"> 4122 </NonUsages> </Personal> <NonPersonal type="unset"> <Damages type="box"> 6466 </Damages> <NonDamages type="box"> 5544 </NonUsages> </NonPersonal> <Confidential type="set"> <Discounts type="box"> 1233 </Discounts> <NonDiscounts type="box"> 4122 </NonDiscounts> </Confidential> </Beat> </Beats> My Current aim is to just print out the numbers inside the inner tags. But i cannot use the names of the tags as selectors as only the attribute 'type'is of importance. I tried using the following xslt. But it didnt seem to work. <xsl:output method="text"/> <xsl:template match="*"> <html> <body> <h2> Test</h2> <xsl:for-each select="//Beats/Beat/[@type='set']"> <xsl:value-of select="[@type='box'] /> <br/> </xsl:for-each> </body> </html> </xsl:template> </xsl:stylesheet> What am i doing wrong ? And one more thing i couldnt figure out was how to get the name of tags while using attributes as selectors. Instead of <xsl:value-of select="[@type='box'] /> which gives whats inside the tag; what can i use to get the name of the tag which contains this 'type=box' attribute ? (For. eg Usages, NonUsages, etc..) A: This transformation is intended to only provide the necessary corrections to your original transformation: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <html> <body> <h2> Test</h2> <xsl:for-each select="/*/*/*[@type='set']/*[@type='box']"> <xsl:value-of select="." /> <br/> </xsl:for-each> </body> </html> </xsl:template> </xsl:stylesheet> When this transformation is applied on the provided XML document (after correcting it to make it well-formed XML document): <Beats> <Beat> <Personal type="set"> <Usages type="box"> 1233 </Usages> <NonUsages type="box"> 4122 </NonUsages> </Personal> <NonPersonal type="unset"> <Damages type="box"> 6466 </Damages> <NonDamages type="box"> 5544 </NonDamages> </NonPersonal> <Confidential type="set"> <Discounts type="box"> 1233 </Discounts> <NonDiscounts type="box"> 4122 </NonDiscounts> </Confidential> </Beat> </Beats> the (what I guess is) wanted result is produced: <html> <body> <h2> Test</h2> 1233 <br/> 4122 <br/> 1233 <br/> 4122 <br/> </body> </html> and it is displayed in the browser as: Test 1233 4122 1233 4122 On your second question: And one more thing i couldnt figure out was how to get the name of tags while using attributes as selectors. Instead of <xsl:value-of select="[@type='box'] /> You want something as: <xsl:for-each select="/*/*/*[@type='set']/*[@type='box']"> <xsl:value-of select="name()"/> <xsl:text> : </xsl:text> <xsl:value-of select="." /> <br/> </xsl:for-each> The complete transformation now becomes: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/> <xsl:template match="/"> <html> <body> <h2> Test</h2> <xsl:for-each select="/*/*/*[@type='set']/*[@type='box']"> <xsl:value-of select="name()"/> <xsl:text> : </xsl:text> <xsl:value-of select="." /> <br/> </xsl:for-each> </body> </html> </xsl:template> </xsl:stylesheet> and when it is applied on the same XML document (above), the result is: <html> <body> <h2> Test</h2>Usages : 1233 <br/>NonUsages : 4122 <br/>Discounts : 1233 <br/>NonDiscounts : 4122 <br/> </body> </html> and this is displayed by the browser as: TestUsages : 1233 NonUsages : 4122 Discounts : 1233 NonDiscounts : 4122
[ "stackoverflow", "0032762168.txt" ]
Q: Paginate with Sequelize.js at SQL 2008 (that does not support FETCH) So, I'm using sequelize.js with tediousfor mssql support. MSSQL = SQL Server 2008 Well, So there is this big table named Clientes. I have to fetch data from it, but it is quite huge so I'll have to paginate trhough I tried the 'right way', as in the docs: app.use('/clientes', function(req, res){ var page = req.params.page || 0; sequelize.Clientes.findAll({limit: 30, offset: 5 }) .then(function(result) { res.json({result: result}); }); }); It should work, BUT it uses a query that is something like SELECT .......... from [Clientes] as [Clientes] ORDER BY [CNPJ] OFFSET 5 ROWS FETCH NEXT 30 ROWS ONLY; and the SQL Server return a terrible Invalid usage of the option NEXT in the FETCH statement! So, after lots of search, I got to a point that apparently FETCH will not work with SQL 2008. That being said (and sad) I tried to force TDS version to 7_3_A. I did this using dialectOptions: { tdsVersion: '7_3_A' }, but the query sintax did not change with this :( I'm not sure what to do anymore.... I even will use another way instead of paginate... I found a nice sintax to SQL pagination (involving row_number()) , but I was not able to perform it as a raw query on sequelyze. myModel.query('SQL QUERY HERE') returned undefined function oO' Any helps will be appreciated A: Ok, so after lots of searching and debugging, I found 2 things. 1) My sequelize instance was sequelize.sequelize, due to a module.exports with lodash. My bad, I did not remember that, and did not even mention it in the question. I'm sorry about this. 2) The offset and limit do use fetch and thus generates invalid SQL sintax for SQL 2008. I had to perform a raw query, using sequelize.sequelize.query() (since my instance was sequelize.sequelize). The query used for pagination in mssql 2008 was found In this answer: here's my full code, including express routing and ugly format for the query: var express = require('express') var app = express(); app.use('/tableName', function(req, res){ var page = req.params.page || 2; var rowsPerPage = req.params.perpage || 30; if(rowsPerPage > 100){ rowsPerPage = 100; //this limits how many per page } var theQuery = 'declare @rowsPerPage as bigint; '+ 'declare @pageNum as bigint;'+ 'set @rowsPerPage='+rowsPerPage+'; '+ 'set @pageNum='+page+'; '+ 'With SQLPaging As ( '+ 'Select Top(@rowsPerPage * @pageNum) ROW_NUMBER() OVER (ORDER BY ID asc) '+ 'as resultNum, * '+ 'FROM tableName )'+ 'select * from SQLPaging with (nolock) where resultNum > ((@pageNum - 1) * @rowsPerPage);'; sequelize.sequelize.query(theQuery) .spread(function(result) { res.json({result: result}); }); }); And if you (as I did) wonder why sequelize.sequelize instead of only sequelize? Well, this is because var sequelize is a require() from a file with the following module.exports: module.exports = lodash.extend({ sequelize: sequelize, //reffers to new Sequelize(db,user,pass,{}); Sequelize: Sequelize }, db) So this is why just sequelize.query() was returned undefined, and sequelize.sequelize.query() works fine, because in true my sequelize variable is an Object with the sequelize property being the real sequelize connection instance.
[ "stackoverflow", "0048622867.txt" ]
Q: Facebook Ads SDK integration changing existing project configuration I have written an app using Kotlin which has all integration which uses Fragment/Activity. Now I'm integrating Facebook Ads SDK, but as soon dependency get sync, application code started to throw compilation error on building. implementation 'com.facebook.android:facebook-android-sdk:[4,5)' Most of these are relate with how kotlin null assertion I have used across application. PFA. Any chance FB SDK changed default property but how come that is possible though this has added as external SDK. Any suggestion what is issue & how can this be fixed ? A: Got fix for this. This was issue with dependent lib version mis matching, it was different in my app project & FB SDK. There is well directed solution propose here And I modified it as per my need, In following case both app & added 3rd part libs will use same version 26.1.0. // Configuration need to align & force FB SDK to use app using version which is 26.1.0. configurations.all { resolutionStrategy.eachDependency { DependencyResolveDetails details -> if (details.requested.group == 'com.android.support') { details.useVersion "26.1.0" } } }
[ "stackoverflow", "0021702264.txt" ]
Q: Test if Object is a generic list of specific type For various reasons, a method of mine accepts a generic Object argument. What the method does depends on the actual type, so I do some instanceof Now, in one specific case, I need to check if the type is Iterable. I have found that instanceof with generics does not work. x instanceof Iterable<Integer> So what are the alternatives, apart from looping through each element and testing their type? A: If you can't influence the signature of your method or the Iterable instances you get, then there is no way to distinguish an instance of e.g. Iterable<Object> containing only integers from an instance of Iterable<Integer>. They are identical in every respect; in fact, the very concept "instance of Iterable<Integer>" is nebulous for this reason. Instances are runtime artifacts and constructor type parameters are a compile-time artifact.
[ "ru.stackoverflow", "0000850127.txt" ]
Q: Как считать/изменить переменные COLUMNS и LINES из программы? Пробовал считать эти переменные через getenv(), но ничего не вышло, да и сама функция возвращает строку, а не число. Как считать эти переменные из программы используя средства С/С++? Как их изменить, чтобы изменить размер экрана? Какие аналогичные переменные используются в cmd? A: // Linux размер консоли # include <sys/ioctl.h> # include <stdio.h> # include <unistd.h> int main ( int argc , char * * argv ) { struct winsize w ; // считать размеры ioctl ( STDOUT_FILENO , TIOCGWINSZ , & w ) ; printf ( "lines %d\n" , w . ws_row ) ; printf ( "columns %d\n" , w . ws_col ) ; w . ws_row = w . ws_row / 2 ; w . ws_col = w . ws_col / 2 ; // изменить размеры ioctl ( STDOUT_FILENO , TIOCSWINSZ , & w ) ; // считать размеры ioctl ( STDOUT_FILENO , TIOCGWINSZ , & w ) ; printf ( "lines %d\n" , w . ws_row ) ; printf ( "columns %d\n" , w . ws_col ) ; return 0 ; }
[ "stackoverflow", "0015795728.txt" ]
Q: Chain the completion of an async function to another I am working on a Windows Store (C++) app. This is a method that reads from the database using the web service. task<std::wstring> Ternet::GetFromDB(cancellation_token cancellationToken) { uriString = ref new String(L"http://myHost:1234/RestServiceImpl.svc/attempt"); auto uri = ref new Windows::Foundation::Uri(Helpers::Trim(uriString)); cancellationTokenSource = cancellation_token_source(); return httpRequest.GetAsync(uri, cancellationTokenSource.get_token()).then([this](task<std::wstring> response)->std::wstring { try { Windows::UI::Popups::MessageDialog wMsg(ref new String(response.get().c_str()), "success"); wMsg.ShowAsync(); return response.get(); } catch (const task_canceled&) { Windows::UI::Popups::MessageDialog wMsg("Couldn't load content. Check internet connectivity.", "Error"); wMsg.ShowAsync(); std::wstring abc; return abc; } catch (Exception^ ex) { Windows::UI::Popups::MessageDialog wMsg("Couldn't load content. Check internet connectivity.", "Error"); wMsg.ShowAsync(); std::wstring abc; return abc; } } , task_continuation_context::use_current()); } I'm confused how to return the received data to the calling function. Now, I am calling this function in the constructor of my data class like this: ternet.GetFromDB(cancellationTokenSource.get_token()).then([this](task<std::wstring> response) { data = ref new String(response.get().c_str()); }); I am getting a COM exception whenever I try to receive the returned data from GetFromDB(). But this one runs fine: ternet.GetFromDB(cancellationTokenSource.get_token()); Please suggest a better way of chaining the completion of GetFromDB to other code. And how to get the returned value from inside the try{} block of GetFromDB() 's then. Please keep in mind I am a very new student of async programming. A: If the continuation of the call to GetFromDB is happening on the UI thread (which I believe it will by default, assuming the call site you pasted is occurring in the UI thread), then calling get() on the returned task will throw an exception. It won't let you block the UI thread waiting for a task to finish. Two suggestions, either of which should fix that problem. The first should work regardless, while the second is only a good option if you're not trying to get the response string to the UI thread (to be displayed, for example). 1) Write your continuations (lambdas that you pass to then) so that they take the actual result of the previous task, rather than the previous task itself. In other words, instead of writing this: ternet.GetFromDB(...).then([this](task<std::wstring> response) { ... }); write this: ternet.GetFromDB(...).then([this](std::wstring response) { ... }); The difference with the latter is that the continuation machinery will call get() for you (on a background thread) and then give the result to your continuation function, which is a lot easier all around. You only need to have your continuation take the actual task as an argument if you want to catch exceptions that might have been thrown by the task as it executed. 2) Tell it to run your continuation on a background/arbitrary thread: ternet.GetFromDB(...).then([this](task<std::wstring> response) { ... }, task_continuation_context::use_arbitrary()); It won't care if you block a background thread, it only cares if you call get() on the UI thread.
[ "stackoverflow", "0048133227.txt" ]
Q: How does passing input as an argument work? I've been using variables to pass as arguements this entire time, but I came across a solution that uses input and I'm having a hard time wrapping my head around how it works. def reverse(input=''): return input[::-1] What is the point of using input when you could do this? def reverse(string): return string[::-1] They both work exactly the same. I thought using input would let you enter any string you want but it doesn't. I got this from Excercism. A: The only difference between those two definitions of reverse is that the first gives a default value for the argument. The name of the argument is irrelevant. With the first definition you could do reverse() # => '' Calling the second definition with no arguments would cause an error.
[ "stackoverflow", "0001986586.txt" ]
Q: Get current ISO8601 date/time stamp I would like to get the current date/time stamp of the server or client in ISO8601 format (ex. 31 Dec 2009, 02:53). I know that server time can be observed using PHP and brought into the DOM using jQuery $.getJson. Client side time can be recorded from the browser using javascript/jQuery. I want the time stamp to be static (not dynamic/real-time). Im php/JS newbie and would greatly appreciate your help. Thanks. A: In PHP 5, you can do date("c"); // ISO 8601 date (added in PHP 5) see date A: For JavaScript just create a new Date object like this var currentDate = new Date(); and then you can construct your date in any format you want using the methods that Date provides. See this reference for the complete list of methods you can use. In your case you could do something like this: var months = Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); var currentDate = new Date(); var formatedDate = currentDate.getDate() + ' ' + months[currentDate.getMonth()] + ' ' + currentDate.getFullYear() + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes(); As for PHP it's as simple as this: $formatedDate = date("c"); See this page for full reference on the Date() function.
[ "stackoverflow", "0001877333.txt" ]
Q: How to handle alternative themes for visual impaired users Has anyone got an thoughts on how to handle theming a WSS site for a single user who is visually impaired ... she uses high contrast settings for Word, etc. But still leave the usual theme for everyone else A: That second link on choppen's answer is one of the craziest/most clever workarounds I've ever seen haha. By all means if you don't have much programming knowledge, use that idea. Onto coding, you have different ways to achieve that, but without going into features and overriding sharepoint's render engine / site definitions, HttpModules and MasterPages sound more reasonable for this, MasterPages are even easier. Have your code hooked in the Page_Load of the MasterPage and check if the SPContext.Current.Web.CurrentUser.LoginName is your user and then append to the head object a secondary theme link: <link href="/highcontrast.css" etc /> Remember if you put .NET code in the MasterPage you need to allow it on the web.config with the PageParsePaths. With a HttpModule override the Page_PreInit event in the Application_PreRequestHandlerExecute and you should be good.
[ "superuser", "0000347364.txt" ]
Q: Deleting and moving files is sluggish starting today on Windows 7 with SSD I have an SSD on a Windows 7 laptop, and it worked extremely well for past 3-4 month. I followed several guides to minimize writes to it etc. Today, I noticed that deleting files is very slow. Also while moving (Ctrl-X), the original file disappeared after 5-8 seconds. Which is pretty slow! Is there anything I can do to see what's wrong? A: Off the top of my head, all I can think of is the TRIM function is off. Unlikely, but might as well check. fsutil behavior query disabledeletenotify should equal to zero. Deleting a file could be because the recycle bin is full.
[ "stackoverflow", "0061856501.txt" ]
Q: Removing component at index 0 remove all item I have a component inside a loop, and a remove button per component. If I remove components at index 1 and above, it is removing fine, but when I remove an item at index 0 (first one), all of the components disappear but the data is still available in the Vue console. //form.vue <template> <div> <div v-for="(item, index) in items" :key="index" > <viewer :item="item" :index="index" @removed="remove" ></viewer> </div> </div> </template> <script> import default { //truncated data() { items: ['sample 1', 'sample 2', 'sample 3'] }, methods: { remove(index) { this.items.splice(index,1) } } } </script> //viewer.vue <template> <div> <div>{{ item }}</div> <div @click="remove()">Remove</div> </div> </template> <script> import default { //tuncated props: { item, index }, methods: { remove() { this.$emit("removed", this.index) } } } </script> A: You have several errors: v-for should be written like this: <div v-for="(item, index) in items" :key="index" > props should be defined like this: props: ["item", "index"], data() should be written like this: data() { return { items: ["sample 1", "sample 2", "sample 3"] }; },
[ "stackoverflow", "0059695717.txt" ]
Q: How to add/update many to many relations with one end of entity in EF core We have visited quite a few links on EF Core many to many update, yet could not figure a concrete answer to our question and clear our understanding. Scenario: We wish to add/update an entity and its related many to many relations in one go like (dbset.Add() or dbset.Update()) We were trying the following and could only add/update the parent entity and not the many-to-many relation list. Can you help us know where we are wrong? and what can be done? Current Model Structure: public class Teacher { [DatabaseGenerated(DatabaseGeneratedOption.Identity), Required] public long Id { get; set; } public string Name { get; set; } public List<TeacherDuty> TeacherDuties { get; set; } } public class Duty { [DatabaseGenerated(DatabaseGeneratedOption.Identity), Required] public long Id { get; set; } public string Description { get; set; } public List<TeacherDuty> TeacherDuties { get; set; } } public class TeacherDuty { public long TeacherId { get; set; } public Teacher Teacher { get; set; } public long DutyId { get; set; } public Duty Duty { get; set; } } And we are trying to add/update using following methods: public async Task<Teacher> AddTeacher(Teacher pTeacher) { try { return await _teacher.AddAsync(pTeacher); } catch (Exception ex) { throw ex; } } public async Task<Teacher> UpdateTeacher(Teacher pTeacher) { try { return await _teacher.Update(pTeacher); } catch (Exception ex) { throw ex; } } Kindly point us to our misinterpretation of concept and solution if possible. Thanks. A: I create a demo to add and edit a teacher.(_context is database context) Add a teacher: [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(Teacher teacher) { //get your desired dutyId with your own logic var SelectedDutyIds = new int[] { 1 }; var teacherDuties = new List<TeacherDuty>(); if (ModelState.IsValid) { _context.Add(teacher); await _context.SaveChangesAsync(); foreach (var id in SelectedDutyIds) { var item = new TeacherDuty() { TeacherId = teacher.Id, DutyId = id, }; teacherDuties.Add(item); } _context.AddRange(teacherDuties); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(teacher); } Edit the teacher: remove all the existing TeacherDuties of the teacher firstly and then add new ones. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(long id, Teacher teacher) { if (id != teacher.Id) { return NotFound(); } if (ModelState.IsValid) { try { //your new dutyIds var newSelectedDutyIds = new int[] { 3 }; var teacherDuties = new List<TeacherDuty>(); var tdList = await _context.TeacherDuties.Where(td => td.TeacherId == teacher.Id).ToListAsync() ; _context.RemoveRange(tdList); foreach (var newid in newSelectedDutyIds) { var item = new TeacherDuty() { TeacherId = teacher.Id, DutyId = newid, }; teacherDuties.Add(item); } _context.AddRange(teacherDuties); _context.Update(teacher); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TeacherExists(teacher.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(teacher); } Refer to Entity framework core update many to many
[ "stackoverflow", "0036040073.txt" ]
Q: django-allauth: email confirmation i've set up django-allauth and using email confirmation when new users register which works fine but in the confirmation email, i get Hello from example.com! You're receiving this e-mail because user abc13 at example.com has given yours as an e-mail address to connect their account. To confirm this is correct, go to http://<mysite>.com/accounts/confirm-email/q3rknxpflshgwddlbjw6aqzlr1ayqtnfrtezucoq2ysmfbm2etcldusq5dyrcoap/ Thank you from example.com! example.com How can i replace "example.com" with my website name? thanks A: It sounds like you need to update the Site entry in the Django admin. You can access this at: http://<yoursite>.com/admin/sites/site/
[ "stackoverflow", "0002993292.txt" ]
Q: Potential leak of an object allocated Using the build and analyze of XCode I saw i have a memory leak in my code: - (NSString *) doIt { NSString *var = [[NSString alloc] init]; return var; } This is of course a simplified snippet of my problem where do i release the object? A: This is a perfect situation for autorelease. return [var autorelease]; will return the object with its present retain count of 1 and decrement the retain count of the object at some point in the future, after which the calling code should have retained the object if it needs to.
[ "stackoverflow", "0052899193.txt" ]
Q: No Icons in Kentico Admin Page I'm very new to Kentico and just started using Kentico 11 for my companies CMS and have run into a lot of issues...most of which I've figured out by trial and error. The issue that comes up most often for me is that each time I create a new website with the wizard in the Admin page, no icons appear in either the dashboard or the applications list or on the top menu bar. It doesn't look like anyone has had this issue before, and I'm curious about how to fix it. I'm using IE 11. Here is a screenshot: As you can see from the screenshot, no icons appear anywhere in the dashboard, menu, or menu options. Please help with this issue. A: Thank you for all your help. I found the answer and it was very basic and simple. For me the problem was Internet Explorer options not being enabled. Talking with Kentico support is what tipped me off to this fix: In IE 11, Go to Internet Options > Security Tab > Click Custom level > Scroll down until you get to Downloads > Under Font download check Enabled. That was it. Like I said very simple, but on a development server where everything is disabled, it made a huge difference in performance of the Kentico interface. I hope this helps someone else.
[ "stackoverflow", "0033828741.txt" ]
Q: Using Image.ptr(0); with color image in OpenCV I am studying GrabCut in OpenCV (c++) and I stuck with this line coefs = model.ptr<double>(0); mean = coefs + componentsCount; cov = mean + 3*componentsCount; where model is Matrix coefs, mean, and cov are double* componentsCount is a constant integer I wonder what coefs will be? Is it is RGB values or something else? (the result of the following code) model.ptr<double>(0); And what happens in line cov = mean + 3*componentsCount; Thank you for answer!! :) A: The Mat model is not a color image, but the model for the Gaussian Mixture Model. The GMM has these private memmbers: Mat model; double* coefs; double* mean; double* cov; model a single channel double matrix (CV64FC1), with 1 row and number of columns equals to modelSize*componentsCount, where componentsCount = 5 // line 60 modelSize = 13 // 3/*mean*/ + 9/*covariance*/ + 1/*component weight*/ // line 89 This data are stores in the matrix model with this layout: cw0, cw1, cw4, m00, m01, m02, m10, ..., m42, c00, c11, ... ^ ^ ^ coefs = model.ptr<double>(0) ^ mean + 3*componentsCount ^ ^ coefs + componentsCount where: cw<i> is the weight of the i-th component m<i><j> is the j-th dimension mean of the i-th component c<i><j> is the j-th dimension covariance of the i-th component So: coefs = model.ptr<double>(0); // points at the start of the weights into model mean = coefs + componentsCount; // points at the start of the means into model cov = mean + 3*componentsCount; // points at the start of the covariances into model ptr<double>() just return a double* at the beginning of line 0, i.e. the start of the data into the matrix. It's equivalent to (double*)model.data. Basically, coefs, mean and cov are just shortcuts to get the appropriate data into the model.
[ "stackoverflow", "0016782736.txt" ]
Q: Delphi 2010 - Show form at memo seltext Can anyone help me to display (or create) a form positioned (X, Y) in a memo based on the last character typed by the user? Ie, I need a form is displayed whenever the user types in a memo the % character, yet need the form to be positioned immediately adjacent and below this character. I'm using this code: procedure TForm1.memo1KeyPress(Sender: TObject; var Key: Char); if key = #37 then begin form2.Top:=Mouse.CursorPos.Y; form2.left:=Mouse.CursorPos.X; form2.Show; end; end; But this code only show a form based on the cursor position . Is there a way to display and position the form to the right and below where the user entered the% character? A: You need to get the caret position, not the mouse postion .. Try this instead procedure TForm1.Memo1KeyPress(Sender: TObject; var Key: Char); var clientPos: TPoint; begin if key = #37 then begin GetCaretPos(clientPos); clientPos:=Memo1.ClientToScreen(clientPos); with form2 do begin Top := clientPos.Y + 4; Left := clientPos.X; Visible := true; end; end end;
[ "math.stackexchange", "0000708450.txt" ]
Q: Scale a Point onto Plane I'm trying to find the scale factor that scale a point onto plane in 3D Space. I have the following information: Point on a plane: $a = (x_1,y_1,z_1)$ Plane equation: $P\colon Ax + By + Cz +D =0$; therefore, the normal of the plane must be $n=(A,B,C)$. Point in 3D space $b = (x_2,y_2,z_2)$. How we can find a scale factor $s$ that maps the point $b$ to the plane $P$? Thanks for the Help! A: Assuming you are given the point $a$ and normal vector $n$, you get $D$ from the plane equation immediatly. Now for the scaled point $sb=(sx_2, sy_2, sz_2)$ to be on the plane $P$ we need $$ Asx_2+Bsy_2+Csz_2+D=0 $$ which is equivalent to $$ s(Ax_2+By_2+Cz_2)=-D. $$ If $Ax_2+By_2+Cz_2\neq 0$, this has a unique solution. In the case $Ax_2+By_2+Cz_2= 0$ we have $2$ possibilities: If $D\neq 0$ there is no solution to your problem, since $b$ is parallel to the plane but not on it. If $D=0$ the plane goes through the origin and $b$ is already on it, so every $sb$ will be on the plane as well.
[ "graphicdesign.stackexchange", "0000028792.txt" ]
Q: Which of these font communicates "luxury products" better? We are about to create a new luxury fashion brand. We researched many trademark logos, and saw they use different font types. We cannot decide between the two different fonts below. We target people who using luxury leather goods (handbags, belts, wallets), similar to Michael Kors, Furla, Balenciaga or Prada. Which one looks cool, good and suitable for a fashion brand? Would appreciate the input from you knowledgeable graphic artist. A: A typeface tells a story. Whether or not you're consciously aware of it, it has history, character, emotion. Of course, most people don't realize this. It's subconscious but that makes it all the more powerful as a psychological tool. If your mark is going to be primarily typographic, the message of the typeface becomes a much bigger piece of the authenticity of your branding. It needs to align with your story and aspirations. In your example, #1 has a sort of early 20th century New York architectural feel. It's stylish but approachable. It's solid and just a little quirky. #2 is much more serious, somewhat European, and possibly snobbish. We could all tell you what we like but that's not very relevant to your brand. A: This is wildly opinion-based, but I would go for number two; hands down. The proportions are better, the sharpness of the M an As less spiky. Besides.. the top one reminds me a little too much of Futura, and though it is a good font, it is a little dated. At least to me. A: I would say the first font is better for a fashion brand because it is thinner and more angular. These things give it a great feminine distinction and make it more appealing to that audience. It also has the advantage of being bolder and will stand out better when inverted to white against color and will stand off print material well when black.
[ "math.stackexchange", "0002146460.txt" ]
Q: Consistency and asymptotic normality of MLE of $\theta$ in $N(\theta,1)$ when $\theta\ge 0$ Question: Let $X_1,\ldots,X_n$ are iid $\sim N(\theta,1)$, $\theta\ge0$. Compute the MLE of $\theta$. Is the MLE consistent? Is it asymptotically normal? I am able to find the MLE is $\hat{\theta}=\max\{\bar{X},0\}$. (see also The MLE of a $N(\theta, 1)$ distribution ) But I don't know whether it is consistent and asymptotically normal. To show a MLE is consistent, we may use Chebyshev's inequality and we need to show the variance $D\hat{\theta}\to 0$ as $n\to \infty$. I don't know if it is a correct way, since the distribution of $\hat{\theta}$ is a little complicated. And I have no idea about the asymptotic normality. A: If $\theta > 0$, it's easy to see using asymptotics of $\Phi(-\sqrt{n}\theta)$ that $\sqrt{n}(\hat{\theta} - \overline{X}) \to 0$ in distribution, giving us consistency and asymptotic normality. If $\theta = 0$, $|\overline{\theta} - \theta| < |\overline{X} - \theta|$, so we still have consistency, but since $\hat{\theta} - \theta \ge 0$ in this case we can't possibly have asymptotic normality.
[ "math.stackexchange", "0000828651.txt" ]
Q: Uniqueness of solution of a constrained least square problem I am interested in the linear least square problem with the solution constrained to the closed standard simplex: $$ \min_x \|Ax-b\|^2$$ subject to $x_i \ge 0$ and $\| x \|_1 = 1$. More precisely, I want to know which conditions on $A$ provides a unique solution to the problem. I found conditions on the rank of $A$ for equality constraints from chapter 5 of Numerical methods for least square problems by Ake Bjorck, but I don't know if they apply to my case. A: Since $x_i \ge 0$, $\|x\|_1 = \sum_i x_i$, and the feasible region is convex (in fact a simplex). If $A$ is injective on $L = \{u: \sum_i u_i = 0\}$, the objective is strictly convex so the minimizer is unique. On the other hand, in order for the minimizer $p$ to be unique there can't be any nonzero $u \in L$ with $Au = 0$ and $p+u$ feasible. Thus if $u \in L$ and $Au = 0$ there must be some index $i$ such that $p_i = 0$ and $u_i < 0$ (so that $p + t u$ is infeasible for all $t > 0$) and some $i$ such that $p_i = 0$ and $u_i > 0$ (so that $p + t u$ is infeasible for all $t < 0$).
[ "stackoverflow", "0023282987.txt" ]
Q: Hiding a parent div with jQuery i have a problem with jQuery. I have this: And i want that when you click on the black part of the page, the black part and the image dissapear. Here is my code: HTML <div id="fade-wrapper"> <div class="row-1-big"><img src="css/images/galeria/1.jpg"></div> <div class="row-2-big"><img src="css/images/galeria/2.jpg"></div> <div class="row-3-big"><img src="css/images/galeria/3.jpg"></div> <div class="row-4-big"><img src="css/images/galeria/4.jpg"></div> <div class="row-5-big"><img src="css/images/galeria/5.jpg"></div> <div class="row-6-big"><img src="css/images/galeria/6.jpg"></div> <div class="row-7-big"><img src="css/images/galeria/7.jpg"></div> <div class="row-8-big"><img src="css/images/galeria/8.jpg"></div> <div class="row-9-big"><img src="css/images/galeria/9.jpg"></div> </div> JS var r1 = $('.row-1'); //this is for when you click the thumbnail r1.click(function(){ $('#fade-wrapper').show(300); $('.row-1-big').delay(400).show(); }); the problem is that if I add this code: $('#fade-wrapper').click(function(){ $('this').hide(); }); when i click the image (row-1-big) it hides all and I wan't that the content hide just when I click the black part. If you don't understand just tell me. A: If you are looking to click outside the Div wrapper which is the black area then close the whole thing, here is how: //Click on html $('html').click(function(){ //hide $('#fade-wrapper').hide(); }); // prevent the fadeIn area to hide when clicked $('#fade-wrapper').click(function(e){ e.stopPropagation(); })
[ "stackoverflow", "0043835866.txt" ]
Q: Failed to update work status Exception in Python Cloud Dataflow I have a Python Cloud Dataflow job that works fine on smaller subsets, but seems to be failing for no obvious reasons on the complete dataset. The only error I get in the Dataflow interface is the standard error message: A work item was attempted 4 times without success. Each time the worker eventually lost contact with the service. Analysing the Stackdriver logs only shows this error: Exception in worker loop: Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 736, in run deferred_exception_details=deferred_exception_details) File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 590, in do_work exception_details=exception_details) File "/usr/local/lib/python2.7/dist-packages/apache_beam/utils/retry.py", line 167, in wrapper return fun(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 454, in report_completion_status exception_details=exception_details) File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/batchworker.py", line 266, in report_status work_executor=self._work_executor) File "/usr/local/lib/python2.7/dist-packages/dataflow_worker/workerapiclient.py", line 364, in report_status response = self._client.projects_jobs_workItems.ReportStatus(request) File "/usr/local/lib/python2.7/dist-packages/apache_beam/internal/clients/dataflow/dataflow_v1b3_client.py", line 210, in ReportStatus config, request, global_params=global_params) File "/usr/local/lib/python2.7/dist-packages/apitools/base/py/base_api.py", line 723, in _RunMethod return self.ProcessHttpResponse(method_config, http_response, request) File "/usr/local/lib/python2.7/dist-packages/apitools/base/py/base_api.py", line 729, in ProcessHttpResponse self.__ProcessHttpResponse(method_config, http_response, request)) File "/usr/local/lib/python2.7/dist-packages/apitools/base/py/base_api.py", line 599, in __ProcessHttpResponse http_response.request_url, method_config, request) HttpError: HttpError accessing https://dataflow.googleapis.com/v1b3/projects//jobs/2017-05-03_03_33_40-3860129055041750274/workItems:reportStatus?alt=json>: response: <{'status': '400', 'content-length': '360', 'x-xss-protection': '1; mode=block', 'x-content-type-options': 'nosniff', 'transfer-encoding': 'chunked', 'vary': 'Origin, X-Origin, Referer', 'server': 'ESF', '-content-encoding': 'gzip', 'cache-control': 'private', 'date': 'Wed, 03 May 2017 16:46:11 GMT', 'x-frame-options': 'SAMEORIGIN', 'content-type': 'application/json; charset=UTF-8'}>, content <{ "error": { "code": 400, "message": "(2a7b20b33659c46e): Failed to publish the result of the work update. Causes: (2a7b20b33659c523): Failed to update work status. Causes: (8a8b13f5c3a944ba): Failed to update work status., (8a8b13f5c3a945d9): Work \"4047499437681669251\" not leased (or the lease was lost).", "status": "INVALID_ARGUMENT" } } > I assume this Failed to update work status error is related to the Cloud Runner? But since I didn't find any information on this error online, I was wondering if somebody else encountered it and does have a better explanation? I am using Google Cloud Dataflow SDK for Python 0.5.5. A: One major cause of lease expirations is related to memory pressure on the VM. You may try running your job on machines with higher memory. Particularly, a highmem machine type should do the trick. For more info on machine types, please check out the GCE Documentation The next Dataflow release (2.0.0) should be able to handle these cases better.
[ "math.stackexchange", "0003132681.txt" ]
Q: Tseytin transformation example I am trying to understand Tseytin transformation and I can't really find any reliable info on the internet. I pretty much understand the steps until I get to the point I have to convert all substitutions to CNF. If I have this formula (wikipedia example) $\phi :=((p\lor q)\land r)\to (\neg s)$ then substitued formula would be: ${T(\phi ):=(x1\leftrightarrow \neg s)\land (x2\leftrightarrow p\lor q) \land (x3\leftrightarrow x2\land r)\land (x4\leftrightarrow x3\to x1) \land x4}$ What I don't understand is, that when converting this to CNF, do I keep the new variables? Would the resulting formula in CNF be this? ${T(\phi ):=(p \lor q \lor \neg x1) \land (p \lor \neg q \lor x1) \land (\neg p \lor q \lor \neg x1) \land (\neg p \lor \neg q \lor \neg x1) \land (x1 \lor r \lor \neg x2) \land (x1 \lor \neg r \lor x2) \land (\neg x1 \lor r \lor \neg x2) \land (\neg x1 \lor \neg r \lor \neg x2) \land (s \lor \neg x3) \land (\neg s \lor x3) \land (x2 \lor x3 \lor \neg x4) \land (x2 \lor \neg x3 \lor x4) \land (\neg x2 \lor x3 \lor \neg x4) \land (\neg x2 \lor \neg x3 \lor \neg x4) \land x4}$ Is this final CNF formula? Don't I need to resolve introduced variables x(1..4) back to variables from original formula? A: Your expression can be depicted as a logical circuit similar to this one: The four new auxiliary variables help to directly derive the clauses of the CNF: $x1 = \lnot s$ $$(s \lor x1) \land (\lnot s \lor \lnot x1)$$ $x2 = p \lor q$ $$(\lnot p \lor x2) \land (\lnot q \lor x2) \land (p \lor q \lor \lnot x2)$$ $x3 = r \land x2$ $$(r \lor \lnot x3) \land (x2 \lor \lnot x3) \land (\lnot r \lor \lnot x2 \lor x3)$$ $x4 = x1 \land \lnot x3$ $$(x1 \lor \lnot x4) \land (\lnot x3 \lor \lnot x4) \land (\lnot x1 \lor x3 \lor x4)$$ As witten in the question, the final clause to tie $\phi$ to true, just consists of the single literal $x4$. If you translate the CNF clauses in DIMACS format and feed this collection of clauses to a SAT solver, it will return either UNSAT (= no solution exists), UNKNOWN (= no solution found) or a number of solutions. Each solution assigns either true or false to any of the variables. As you are just interested in the primary input variables, you can ignore the assignments to the four switching variables. Note: For your example expression, Tseytin transformation does not really pay off. The expression can be expressed as CNF with just two clauses: $$(\lnot p \lor \lnot r \lor \lnot s \lor \lnot \phi) \land (\lnot q \lor \lnot r \lor \lnot s \lor \lnot \phi)$$
[ "stackoverflow", "0008767622.txt" ]
Q: Issue with converting parameterized SQL to HQL We are using grails-groovy with Hibernate, I have a SQL query like this in my grails controller String markerCalcQuery = "select sum(trans_cnt) as t_count, location from map2_data where "+ "fdate between (:datefrom) and (:dateto) "+ "and res_id=:res_id "+ "group by location ;" res_row=gurculsql.rows(markerCalcQuery,[res_id:res_id,datefrom:format_dateprevious,dateto:format_datenow]); How do I change this query to HQL, I don't have a domain class map2_data, but want to know if I need to create it for converting this query to HQL, or can I convert it without doing that (should use gorm based implementation)? I have many queries right now written for MySQL and I need to convert them to HQL. I have now created the domain class map2_data. So how would the above query change (how to decide the functions... out of findallby, createcriteria, etc) Regards, Priyank A: HQL works on Hibernate entities. If you don't have an entity to map your table, you can't use HQL on this table. That's the principle of an ORM: use objects to represent tables.
[ "stackoverflow", "0037708781.txt" ]
Q: Opening word document, copying specific text, paste into excel spreadsheet I am trying to make a VBA script that opens a word document, looks for a word that looks like "TPXXXX" where "X" are numbers, and then pastes that text into an excel spreadsheet. I can open up the word document, but I am having trouble selecting and finding the text I need. So far for that part I have: Sub Copy() 'Create variables Dim Word As New Word.Application Dim WordDoc As New Word.Document Dim Doc_Path As String Dim WB As Workbook Dim WB_Name As String Doc_Path = "C:\Path\To\File.docx" Set WordDoc = Word.Documents.Open(Doc_Path) 'Find text and copy it (part that I am having trouble with) Selection.Find.ClearFormatting With Selection.Find .Text = "TP" .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = False End With Selection.Find.Execute Selection.EscapeKey Selection.MoveLeft Unit: wdCharacter , Count:=2 Selection.MoveRight Unit: wdCharacter , Count:=4 Selection.Copy 'Open excel workbook and paste WB_Name = Application.GetOpenFilename(",*.xlsx") Set WB = Workbooks.Open(WB_Name) WB.Sheets("Sheet1").Select Range("AB2").Select ActiveSheet.Paste WordDoc.Close Word.Quit End Sub Can anyone give me some pointers? A: Here's the Excel version: Sub CopyTPNumber() 'Create variables Dim Word As New Word.Application Dim WordDoc As New Word.Document Dim r As Word.Range Dim Doc_Path As String Dim WB As Excel.Workbook Dim WB_Name As String Doc_Path = "C:\temp\TestFind.docx" Set WordDoc = Word.Documents.Open(Doc_Path) ' Set WordDoc = ActiveDocument ' Create a range to search. ' All of content is being search here Set r = WordDoc.Content 'Find text and copy it (part that I am having trouble with) With r .Find.ClearFormatting With .Find .Text = "TP[0-9]{4}" .Format = False .MatchCase = False .MatchWholeWord = False .MatchWildcards = True .Execute End With .Copy ' Debug.Print r.Text End With 'Open excel workbook and paste WB_Name = Excel.Application.GetOpenFilename(",*.xlsx") Set WB = Workbooks.Open(WB_Name) WB.Sheets("Sheet1").Select Range("AB2").Select ActiveSheet.Paste WordDoc.Close Word.Quit End Sub
[ "stackoverflow", "0007910333.txt" ]
Q: How would I break the loop in this piece of my program? public static void date1() { int x = 0 ; //integer for looping do // process to follow if length == 5 { Scanner scanner = new Scanner(System.in); try { System.out.println("Please enter the first date "); System.out.println("Please enter the year: "); y1 = scanner.nextInt(); System.out.println("Please enter the month: "); m1 = scanner.nextInt(); System.out.println("Please enter the day: "); d1 = scanner.nextInt(); } catch (InputMismatchException inputMismatchException) { scanner.nextLine(); System.err.println("You must enter intergers. Please try again. "); } x = x + 1 ; // set loop to three attempts } while (x < 3) ; //do process occurs while attempts are under < 4 } i want to break the loop if the all the inputs are proper (integers entered). I am not too sure what command to use to break the loop i created. thanks in advance everybody! A: Put a break command before you close your try{} block. If no exception is thrown, the break command will be executed and exit the loop. A better way to do it, though, is to make a separate method that accepts a single input from the user, then call it three times. This way, you don't have to make the user input the first two numbers again if only the third one wasn't valid: private static int getIntInput(){ while(true){ try{ return scanner.nextInt(); } catch(InputMismatchException e){ System.out.println("You must enter integers. Please try again."); } } } public static void date1(){ int x=0; System.out.println("Please enter the first date "); System.out.println("Please enter the year: "); y1 = getIntInput(); System.out.println("Please enter the month: "); m1 = getIntInput(); System.out.println("Please enter the day: "); d1 = getIntInput(); } You could, of course, make things more fancy... we could add a String input to the getIntInput() method, and then print that string every time we are accepting an input, so the user doesn't forget what he's trying to enter. Or you could clean up the syntax so it works (I think the compiler will complain that getIntInput needs to return an int, the way I typed it up right now...)
[ "stackoverflow", "0052771770.txt" ]
Q: Different results for IRR from numpy.irr and the Excel IRR function I have the following annual cash flows: w=np.array([ -56501, -14918073, -1745198, -20887403, -9960686, -31076934, 0, 0, 11367846, 26736802, -2341940, 20853917, 22166416, 19214094, 23056582, -11227178, 18867100, 24947517, 28733869, 24707603, -17030396, 7753089, 27526723, 31534327, 26726270, -24607953, 11532035, 29444013, 24350595, 30140678, -33262793, 5640172, 32846900, 38165710, 31655489, -74343373, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8727068]) I calculate IRR using np.irr np.irr(w) Out[141]: -0.05393588064654964 When I use IRR function in Excel for the same cash flows, I get 12%. These two functions usually produce the same result. Does anyone know why in this case the results are so different? Thanks! A: For the given cash flows, the IRR is not unique; see Multiple IRRs. Both the numpy and Excel values for r satisfy NPV(r) = 0, where NPV is the net present value. Here's a plot of NPV(r) for the data in w. The red stars mark the IRR values (where NPV(r) is zero). Here's the script that generates the plot: import numpy as np import matplotlib.pyplot as plt w = np.array([ -56501, -14918073, -1745198, -20887403, -9960686, -31076934, 0, 0, 11367846, 26736802, -2341940, 20853917, 22166416, 19214094, 23056582, -11227178, 18867100, 24947517, 28733869, 24707603, -17030396, 7753089, 27526723, 31534327, 26726270, -24607953, 11532035, 29444013, 24350595, 30140678, -33262793, 5640172, 32846900, 38165710, 31655489, -74343373, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8727068]) r_excel = 0.1200963665 r_numpy = np.irr(w) rr = np.linspace(-0.055, 0.16, 500) npvals = np.array([np.npv(r, w) for r in rr]) plt.plot(rr, npvals/1e6, alpha=0.8) plt.plot(r_numpy, 0, 'r*') plt.plot(r_excel, 0, 'r*') plt.grid(True) plt.xlabel('r') plt.ylabel('NPV(r) [millions]') plt.show()
[ "stackoverflow", "0056867422.txt" ]
Q: Unique pointer in base class prohibts instantiation with error "attempting to reference a deleted function" I updated my C++ toolchain from Visual Studio 2013 to Visual Studio 2017/2019. Now I am experiencing a number of compile errors in the form: <source>(13): error C2280: 'OfflineFixture::OfflineFixture(const OfflineFixture &)': attempting to reference a deleted function <source>(8): note: compiler has generated 'OfflineFixture::OfflineFixture' here <source>(8): note: 'OfflineFixture::OfflineFixture(const OfflineFixture &)': function was implicitly deleted because a data member invokes a deleted or inaccessible function 'std::unique_ptr<int,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' A unique pointer is a member of class that has no constructor and destructor. In this case Visual Studio allows to instantiate an object this way: OfflineFixture a{}; // works! But using: auto&& a = OfflineFixture{}; gives above compile error. const auto& a = OfflineFixture{}; also gives above compile error. Please have a look here: https://gcc.godbolt.org/z/XtP40t My question is: Is my code wrong? The given examples compiles using: gcc (9.1 and lower) clang Visual Studio 2013 But it fails in: Visual Studio 2015 Visual Studio 2017 Visual Studio 2019 One way to fix this is to implement a default constructor in OfflineFixture. Minimal example: #include <memory> struct OfflineFixture { void x() const {} int i; std::unique_ptr<int> m_calc; }; int test() { #if 1 const auto&& a = OfflineFixture{}; #else OfflineFixture a{}; #endif a.x(); return 0; } A: Let's make some preliminary points here. In general, the statement: const auto&& a = Foo{}; is perfectly legal in C++. Moreover, it is not true that it is undefined behavior. In fact, this is a perfect example of Reference Initialization with lifetime extension of a temporary. Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifetime of the reference [...]. It continues with some exceptions (I won't quote all of them), but the declaration of a new object is not part of those exceptions. Regarding your class, it appears to be clear the problem is the std::unique_ptr member. Here a minimal example: #include <memory> struct OfflineFixture { std::unique_ptr<int> m_calc; }; void test() { const auto&& a = OfflineFixture{}; // <--- Error in msvc } Somehow, MSVC tries to create a copy of the object. Indeed, the error is about invoking the copy constructor (which is deleted because of std::unique_ptr). Since no copies should be performed here, it appears to be a msvc bug. Note: gcc and clang compile fine with that.
[ "stackoverflow", "0035394706.txt" ]
Q: Using strncpy on struct Let's say I have this student struct defined: struct student { char *name; }; typedef struct student Student Now I have the following function: void add_student(const char *student_name) { // create new student Student *new_s; new_s = malloc(sizeof(Student)); strncpy(new_s->name, student_name, sizeof(new_s->name) - 1) } I want to add the student_name to the name of the new student struct. However because const char and char are different I have to use strncpy. I tried it this way, however I get a segmentation fault, what's wrong? A: You are only allocating memory for the structure new_s in this line new_s = malloc(sizeof(Student)); This includes the variable char* name, which is a pointer to a char. Although, you also need memory to which this pointer will point at. So, you need to allocate memory for the character pointer name inside the structure. // create new student Student *new_s; new_s = malloc(sizeof(Student)); new_s->name = malloc(100); //assuming you need to store a string of len 100
[ "mathoverflow", "0000345447.txt" ]
Q: Is quantum turing machine equivalent classical turing machine? I have the question if quantum computation is intrinsecally different to a classic computation. Thank you all!! A: They are "equivalent" in the sense they compute the same functions. They are not "equivalent" in the stronger sense that the computation time is the same "up to polynomial" (while, say, Turing machine and Church lambda-calculus or Markov's algorithms are equivalent in this stronger sense).
[ "meta.stackexchange", "0000124654.txt" ]
Q: I don't understand why my answer was deleted I saw that my answer to this question: How to check whether a string contains a substring in JavaScript? was deleted. I did check the FAQ to see if I could figure out why, but I sincerely don't get it. It's an old answer that's been there for a couple of years now. My answer was the only one that addressed the actual bug in the question's code, short and to the point, without any link and answers precisely what's wrong with the code. Is this the correct venue to ask for a clarification? It'd be nice to get a comment when something is deleted, so that you don't go wondering what you did wrong. A: Your answer is the result of a ninja edit by the OP (he asks why his indexOf() method doesn't work, which was not part of the original question), so I'll give you the benefit of the doubt. A: And then I deleted it again as a result of another flag. The problem from our perspective is that, in the flag queue, it doesn't look like an answer. The formatting is collapsed and you're left with less than a single sentence. Due to the fact that it appears to be an answer when you view it in context, and that it has been deemed so by many upvotes (ugh, that's a slippery slope if I ever sledded down one), I've undeleted. Even so, we try to encourage answers to be more substantial than this nowadays. Due to the fact that it it appears to be flagbait, I've edited to flesh it out. Hopefully that will prevent this from happening again.
[ "stackoverflow", "0005645904.txt" ]
Q: How to call glDrawElements with static TexCoords and Dynamic Vertices I'm using the glDrawElements call with VBOs to render my scene. The scene is a cloth with vertices and texture coordinates - in this example, I'm rendering a flag. With my scene, the vertices are dynamic which means I need to write to a VBO every frame. Much of my processing is done on the GPU using CUDA, so I'm constantly mapping CPU memory to GPU memory. The texture coordinates, on the other hand, are static. In order to render with glDrawElements (as I understand it), I should interleave the texture coordinates in the vertices VBO and then simply call glTexCoordPointer() and glEnableClientState(). This is not optimal because then I'd need to draw all the texture coordinates with me when I do CPU<-->GPU memory mapping. Is there a way to arrange my vbo such that I can update the vertex data in the vbo without touching the texture data in the vbo? Below is my code for rendering - I have three arrays currently filled: an index array, a vertex array, and a texture array. In the code below, the indexVbo has been mapped to the index array and vbo has been mapped to the vertex array. I now need to incorporate textures. Any insight or suggestions would be much appreciated. glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, flagTexId); glPushMatrix(); glColor3f(1.0, 1.0, 1.0); glVertexPointer(4, GL_FLOAT, 0, 0); glTexCoordPointer(2, GL_FLOAT, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexVbo); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); // Render flag mesh glDrawElements(GL_TRIANGLES, numTriangles * 3, GL_UNSIGNED_INT, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glPopMatrix(); glDisable(GL_TEXTURE_2D); A: You can keep separate VBOs for both vertex attributes. That way, you can even mark the tex-coord one as static, and the other one as dynamic. Whether this is actually faster depends on many factors: driver, memory setup, etc. The benefits of having some part of the data in static memory might outweight the benefits of having the whole vertex on a cache line (when you interleave). But then again, it might not. Benchmark on your target system(s) to be sure. IMO, a good argument for splitting the attributes into different VBOs is that it is the most "natural" representation of your data. But I guess that depends on personal taste and whether you let that influence your programming :-) By the way, it seems like you have a small bug: you need to bind the correct VBO before a gl*Pointer call (also, your offsets and strides are not correct if you're using a single VBO for your vertices). That's also how you bind separate VBOs: just select the right one before the gl*Pointer call: glBindBuffer(GL_ARRAY_BUFFER, vbo_vertex); glVertexPointer(4, GL_FLOAT, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, vbo_texcoord); glTexCoordPointer(2, GL_FLOAT, 0, 0);
[ "stackoverflow", "0010772168.txt" ]
Q: HTML DOM alerting style.width Possible Duplicate: Get element width in px How can I find the width of divA? This code brings up an empty alert popup. <script type="text/javascript"> function DisplayResult(){ width = document.getElementById("divA").style.width; alert(width); } var widthFinder = { find: DisplayResult }; widthFinder.find(); </script> <div id="divA">Alert this string's length in pixels</div> EDIT: This now alerts "null". Still not quite what im hoping for. <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript"> function DisplayResult(){ var width = $("#divA").width(); alert(width); } var widthFinder = { find: DisplayResult }; widthFinder.find(); </script> <div id="divA" style="display:inline; width:100%;">Alert this string's length in pixels</div> </body> </html> A: Your code is set to be executed before the DOM is ready, hence why it doesn't find any element and returns a null value. function DisplayResult(){ //declared function in the document's head, ok var width = $("#divA").width(); alert(width); } $(document).ready(function(){ //function calls here, when the DOM is ready var widthFinder = { find: DisplayResult() }; widthFinder.find(); }); I've wrapped your function call inside the $(document).ready() event which prevent the code from being executed before the DOM is ready. I've also added () to the DisplayResult() to ensure that it's being interpreted as a function call. Try out this JSFiddle example.
[ "stackoverflow", "0006216562.txt" ]
Q: WinAPI mouse move notification for full desktop In WinAPI is there a mouse move notification for the full desktop (full screen) and not for a window only? I would like to receive mouse screen coordinates in my main window procedure. Edit: What I try to do is getting the coordinates from the mouse when dragging from a button in my window to outside that window. A: Not as such, no. If you wanted to do something anywhere on the desktop from within your program, e.g. point somewhere or draw something anywhere, you could capture the mouse and then follow the movement until the mouse button is released. See SetCapture for this. For an example, see this article on MSDN: Drawing Lines with the Mouse Otherwise you can always use Windows hooks to follow mouse movements anywhere.
[ "stackoverflow", "0011873722.txt" ]
Q: how to extract multiple patterns from a line with grep/sed/awk and merge them in output I have a line of the form bla bla bla RequestId=ABCD1234EFGH bla bla bla bla ResponseId=IJKL5678MNOP bla bla bla I need to get both the RequestId and the ResponseId from this line and output them with a seperator. For example, for this particular line it will be ABCD1234EFGH|IJKL5678MNOP I can extract one of the values with grep -oe "RequestId=[0-9|a-z|A-Z|-]*" but how can i get both? A: How about something like this: awk '{ if (!match($0, /RequestId=([-0-9a-zA-Z]*)/)) next; req = (substr($0, RSTART + 10, RLENGTH - 10)); if (!match($0, /ResponseId=([-0-9a-zA-Z]*)/)) next; res = (substr($0, RSTART + 11, RLENGTH - 11)); printf("%s|%s\n", req, res); }' yourFile.txt ?
[ "stackoverflow", "0014980177.txt" ]
Q: IE Button issue There is an issue with the button "learn more" in IE only that causes it to run down the page and distort the layout. Page URL: http://www.mvholisticretreat.com/ CSS: http://www.mvholisticretreat.com/wp-content/themes/nebula/style.css any help would be greatly appreciated. Thank you ! A: issue 1: clean up your code, you have a useless endif in issue 2: you have some styles before your doctype. this is why IE loads by default in quirks mode. fix your doctype declaration and it's almost fixed. To preview issue, in IE9 press F12, and from the quirks mode dropdown chose IE 9 Standards, you'll see how the site gets fixed
[ "stackoverflow", "0009406257.txt" ]
Q: jQuery.noConflict causing issue with jQuery animate I have just installed an element that slides in from the right. After calling jQuery 1.7.1 I have this in my footer: $(document).ready(function() { $('#element').animate({right:'0px'}, 3000).css('overflow', 'visible'); }); See an example here http://jsfiddle.net/7e92Y/11/ The theme I have it installed in is unfortunately quite bloated with tons of other jQuery. But I've narrowed it to exactly one line in all the .js files as to why the above function won't work. var $j = jQuery.noConflict(); If I eliminate that line, the element slides in as expected, but it also breaks other jQuery elements. I have been running around in circles trying to get it to work. Is it something obvious I am missing that I need to do? Thanks for taking a look. A: Adding this as an answer so the question has an answer: change $ to $j in your footer.
[ "stackoverflow", "0043169970.txt" ]
Q: send data from js function to a modal in the same file I have 3 variables declared in a js function and i want to send them to my modal to display their data js: function consulter_salle(id) { $.ajax({ url : "<?php echo site_url('index.php/batiment/list_salle')?>/"+id, type: "POST", dataType: "JSON", success: function(data) { var table_header = "<table>"; var table_footer = "</table>"; var html =""; for (var row in data) { html += "<tr><td>"+ data.id+"</td><td>"+data.libelle +"</td></tr>"; } $('#modal_list').modal('show'); // show bootstrap modal when complete loaded $('.modal-title').text('Test'); }, error: function (jqXHR, textStatus, errorThrown) { alert('Error displaying data'); } }); } my modal : <div class="modal fade" id="modal_list" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h3 class="modal-title">Liste des salles</h3> </div> <div class="modal-body form"> <form action="#" id="form" class="form-horizontal"> <div class="form-body"> </form> </div> <div class="modal-footer"> <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button> <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> </body> </html> the data is a list that i sent it by my controller,and it been verified that the data is recieved , but i can't find a way to send it to the modal. I wonder what to write in the modal-body section! Thank you . A: Here is working example. // Example result, JS Object var result = { id: 12, title: 'My title', content: '<div>My example content</div>' } // your ajax success method function ajaxSuccess(result) { var modal = $('#modal_list'); modal.modal('show'); modal.find('.modal-title').html(result.title); modal.find('.modal-body').html(result.content); } ajaxSuccess(result); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <div class="modal fade" id="modal_list" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h3 class="modal-title">Liste des salles</h3> </div> <div class="modal-body form"> <form action="#" id="form" class="form-horizontal"> <div class="form-body"> </form> </div> <div class="modal-footer"> <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button> <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div>
[ "stackoverflow", "0021318278.txt" ]
Q: Counting symbols and empty lines from input text via gets The program should print the number of empty lines and certain operators from the input text. I got the problem of empty lines fixed but I'm facing issues with the opperators. I guess it is something wrong with the break. I would appreciate any good ideas for fixing the code. Sorry if such a thread already exists but I checked and couldn't get a solution. Thanks in advance! char c,line[300]; int emptyLine = 0; int operators = 0; printf("Input your text and press ctr+Z on a new line when done: \n"); while(gets(line)) { int i = 0;emptyLine++; for (i = 0; i < strlen(line); i++) { if(line[i] == '+'|| line[i] == '-' || line[i] == '/' || line[i] == '*' || line[i] == '%') { operators++; } if (line[i] != '\n' && line[i] != '\t' && line[i] != ' ') { emptyLine--; break; } } } printf("The number of empty lines is: %d",emptyLine); printf("\nThe number of opperators is: %d",operators); A: Try something like this: char c,line[300]; int emptyLine = 0; int operators = 0; printf("Input your text and press ctr+Z on a new line when done: \n"); while(gets(line)) { bool isEmpty = true; // Assume empty line for (int i = 0; 0 != line[i]; i++) { if (!isspace(line[i])) { isEmpty = false; // Line not empty } if (line[i] == '+'|| line[i] == '-' || line[i] == '/' || line[i] == '*' || line[i] == '%') { operators++; } } if (isEmpty) { emptyLine += 1; } } printf("The number of empty lines is: %d",emptyLine); printf("\nThe number of operators is: %d",operators);
[ "stackoverflow", "0039488665.txt" ]
Q: MySQL return no results from select * where varchar="" query I'm having issue with my study project for creating database in MySQL. I've imported data using LOAD to my created table from a CSV file. Now when I'm executing select * from mytable everything show up perfectly, but when I execute select * from bi_jogging.routes as r where r.Creator_Email="[email protected]" I get nothing. The email is there, I've tried different syntax options but it seems to be something else, I suspect something with the varchar format, I really have nothing in mind. For other tables it works fine and others not. A: You can try using the query: select * from bi_jogging.routes as r where r.Creator_Email like "%[email protected]%" If like operator shows the result then there may be white spaces in the email, please double check.. For join try this: select * from bi_jogging.routes as r join bi_jogging.buddies as b on b.Email like '%r.Creator_Email%'
[ "stackoverflow", "0057749105.txt" ]
Q: Image on footer does not stay on the footer and moves when you scroll up/down There's a small icon I want to add at the bottom of the footer and it scrolls up or down when I scroll instead of staying put. I'm not sure if the image might be set up as sticky on a scroll or perhaps and most likely a CSS error. I have tried setting up the image as fixed on the CSS section but what it mostly does is just move the image to the left and it still scrolls up and down. #footer { position: fixed; bottom: 0; left: 0; right: 0; width: 100%; height: 100px; } .page-footer { background: #e85259; } .blurb p { color: #faf9f9; font-weight: 100; } .blurb a { color: #faf9f9; font-weight: 100; } .container-footer { margin: auto; width: 100%; text-align: center; } #footer-images ul { padding: 0; } #footer-images li { list-style: none; margin: 0 10px; display: block; } #footer-images ul { display: flex; justify-content: center; align-items: center; } <!-- Start - Footer --> <!-- Footer --> <!-- Footer --> <footer class="page-footer font-small"> <!-- Footer Links --> <div class="container"> <!-- Grid row--> <div class="row text-center d-flex justify-content-center pt-5 mb-3"> <!-- Grid column --> <div class="col-md-3 blurb mb-3"> <h6 class="text-uppercase font-weight-bold"> <a href="#!">Quienes somos</a> </h6> </div> <!-- Grid column --> <!-- Grid column --> <div class="col-md-3 blurb mb-3"> <h6 class="text-uppercase font-weight-bold"> <a href="#!">Productos</a> </h6> </div> <!-- Grid column --> <!-- Grid column --> <div class="col-md-3 blurb mb-3"> <h6 class="text-uppercase font-weight-bold"> <a href="#!">Sucursales</a> </h6> </div> <!-- Grid column --> <!-- Grid column --> <div class="col-md-3 blurb mb-3"> <h6 class="text-uppercase font-weight-bold"> <a href="#!">Contacto</a> </h6> </div> <!-- Grid column --> </div> <!-- Grid row--> <hr class="rgba-white-light" style="margin: 0 15%;"> <div class="container-footer"> <div id="footer"> <div id="footer-images"> <ul> <img class="img-responsive" width="89px" height="73px" img src="https://imgur.com/UwZrFN9"> </ul> </div> </div> </div> <div class="col-md-8 blurd col-12 mt-5"> </div> <!-- Grid row--> <div class="row d-flex text-center justify-content-center mb-md-0 mb-4"> <!-- Grid column --> <div class="col-md-8 blurb col-12 mt-5"> <p>+(503) 2243-4887</p> <p style="line-height: 1.7rem">Calle Adriatico y avenida rio Amazonas No. 1 Jardines de Guadaluppe, Antiguo Cuscatlan, El Salvador.</p> <p>© Jardin del Pan todos los derechos resevador</p> </div>`enter code here` <!-- Grid column --> </div> <!-- Grid row--> <hr class="clearfix d-md-none rgba-white-light" style="margin: 10% 15% 5%;"> <!-- Grid row--> <div class="row pb-3"> <!-- Grid column --> </footer> <!-- End - Footer --> A: Position: fixed; will make the image stick to the display. I think you're looking for position: absolute; so the image will be stick to its relative parent. In this case, probably the footer container. #footer { position: absolute; bottom: 0; left: 0; right: 0; width: 100%; height: 100px; } .page-footer { background: #e85259; } .blurb p { color: #faf9f9; font-weight: 100; } .blurb a { color: #faf9f9; font-weight: 100; } .container-footer { margin: auto; width: 100%; text-align: center; } #footer-images ul { padding: 0; } #footer-images li { list-style: none; margin: 0 10px; display: block; } #footer-images ul { display: flex; justify-content: center; align-items: center; } <!-- Start - Footer --> <!-- Footer --> <!-- Footer --> <footer class="page-footer font-small"> <!-- Footer Links --> <div class="container"> <!-- Grid row--> <div class="row text-center d-flex justify-content-center pt-5 mb-3"> <!-- Grid column --> <div class="col-md-3 blurb mb-3"> <h6 class="text-uppercase font-weight-bold"> <a href="#!">Quienes somos</a> </h6> </div> <!-- Grid column --> <!-- Grid column --> <div class="col-md-3 blurb mb-3"> <h6 class="text-uppercase font-weight-bold"> <a href="#!">Productos</a> </h6> </div> <!-- Grid column --> <!-- Grid column --> <div class="col-md-3 blurb mb-3"> <h6 class="text-uppercase font-weight-bold"> <a href="#!">Sucursales</a> </h6> </div> <!-- Grid column --> <!-- Grid column --> <div class="col-md-3 blurb mb-3"> <h6 class="text-uppercase font-weight-bold"> <a href="#!">Contacto</a> </h6> </div> <!-- Grid column --> </div> <!-- Grid row--> <hr class="rgba-white-light" style="margin: 0 15%;"> <div class="container-footer"> <div id="footer"> <div id="footer-images"> <ul> <img class="img-responsive" width="89px" height="73px" img src="https://imgur.com/UwZrFN9"> </ul> </div> </div> </div> <div class="col-md-8 blurd col-12 mt-5"> </div> <!-- Grid row--> <div class="row d-flex text-center justify-content-center mb-md-0 mb-4"> <!-- Grid column --> <div class="col-md-8 blurb col-12 mt-5"> <p>+(503) 2243-4887</p> <p style="line-height: 1.7rem">Calle Adriatico y avenida rio Amazonas No. 1 Jardines de Guadaluppe, Antiguo Cuscatlan, El Salvador.</p> <p>© Jardin del Pan todos los derechos resevador</p> </div>`enter code here` <!-- Grid column --> </div> <!-- Grid row--> <hr class="clearfix d-md-none rgba-white-light" style="margin: 10% 15% 5%;"> <!-- Grid row--> <div class="row pb-3"> <!-- Grid column --> </footer> <!-- End - Footer -->
[ "stackoverflow", "0006978723.txt" ]
Q: Symfony2 : How to get form validation errors after binding the request to the form Here's my saveAction code (where the form passes the data to) public function saveAction() { $user = OBUser(); $form = $this->createForm(new OBUserType(), $user); if ($this->request->getMethod() == 'POST') { $form->bindRequest($this->request); if ($form->isValid()) return $this->redirect($this->generateUrl('success_page')); else return $this->redirect($this->generateUrl('registration_form')); } else return new Response(); } My question is: how do I get the errors if $form->isValid() returns false? A: You have two possible ways of doing it: do not redirect user upon error and display {{ form_errors(form) }} within template file access error array as $form->getErrors() A: Symfony 2.3 / 2.4: This function get's all the errors. The ones on the form like "The CSRF token is invalid. Please try to resubmit the form." as well as additional errors on the form children which have no error bubbling. private function getErrorMessages(\Symfony\Component\Form\Form $form) { $errors = array(); foreach ($form->getErrors() as $key => $error) { if ($form->isRoot()) { $errors['#'][] = $error->getMessage(); } else { $errors[] = $error->getMessage(); } } foreach ($form->all() as $child) { if (!$child->isValid()) { $errors[$child->getName()] = $this->getErrorMessages($child); } } return $errors; } To get all errors as a string: $string = var_export($this->getErrorMessages($form), true); Symfony 2.5 / 3.0: $string = (string) $form->getErrors(true, false); Docs: https://github.com/symfony/symfony/blob/master/UPGRADE-2.5.md#form https://github.com/symfony/symfony/blob/master/UPGRADE-3.0.md#form (at the bottom: The method Form::getErrorsAsString() was removed) A: Below is the solution that worked for me. This function is in a controller and will return a structured array of all the error messages and the field that caused them. Symfony 2.0: private function getErrorMessages(\Symfony\Component\Form\Form $form) { $errors = array(); foreach ($form->getErrors() as $key => $error) { $template = $error->getMessageTemplate(); $parameters = $error->getMessageParameters(); foreach($parameters as $var => $value){ $template = str_replace($var, $value, $template); } $errors[$key] = $template; } if ($form->hasChildren()) { foreach ($form->getChildren() as $child) { if (!$child->isValid()) { $errors[$child->getName()] = $this->getErrorMessages($child); } } } return $errors; } Symfony 2.1 and newer: private function getErrorMessages(\Symfony\Component\Form\Form $form) { $errors = array(); if ($form->hasChildren()) { foreach ($form->getChildren() as $child) { if (!$child->isValid()) { $errors[$child->getName()] = $this->getErrorMessages($child); } } } else { foreach ($form->getErrors() as $key => $error) { $errors[] = $error->getMessage(); } } return $errors; }
[ "stackoverflow", "0047767319.txt" ]
Q: How to (horizontally) align text of PDTextField in PDFBox? I have a program that create TextFields inside a PDF-file so it can be used as a form. I would like to have the text I write in the TextFields I created to be centered though. How is that possible? My code currently looks like this: PDTextField textBox = new PDTextField(acroForm); textBox.setPartialName("Field " + j + " " + i); defaultAppearanceString = "/Helv 8 Tf 0 g"; //Textsize: 8 textBox.setDefaultAppearance(defaultAppearanceString); acroForm.getFields().add(textBox); PDAnnotationWidget widget = textBox.getWidgets().get(0); PDRectangle rect = new PDRectangle(inputField.getX(), inputField.getY(), inputField.getWidth(), inputField.getHeight()); widget.setRectangle(rect); widget.setPage(page); widget.setPrinted(true); page.getAnnotations().add(widget); and I thought of an easy function to align text like this: textBox.setAlignment(Alignment.CENTER); but I didn't find it. A: Use the Q flag: textBox.setQ(PDTextField.QUADDING_CENTERED); Other possible values are QUADDING_RIGHT and QUADDING_LEFT (which is the default).
[ "pets.stackexchange", "0000012076.txt" ]
Q: Should I remove rubber bands from delivered flame moss? I purchased some flame moss online for the first time and it arrived rubber-banded to a wire mesh. Do I just throw it in the tank like this or do I have to remove the rubber bands? A: You can do either but it's hard to give specific advice without seeing exactly how it's attached. Most mosses take a long time to attach to whatever they are being mounted to so rubber bands or small zip ties are commonly used to attach them until they can grab hold and spread on their own. As far as the mesh goes, the moss will typically attach to it and eventually cover it completely making a solid carpet. If you don't want a carpet in your tank, you may want to remove it or some of it from the mesh and attach it somewhere else in your tank. Also, you want to be certain it is stainless mesh as most other metal mesh will corrode and leach elements into your tank which could be detrimental to your plants and other inhabitants.
[ "stackoverflow", "0006282819.txt" ]
Q: How to pass parameter when calling a .ascx control from javascript? I am using this line to load the .ascx control after running a few javascript statements __doPostBack('<%=Basket1.ClientID %>', null) I do this then i get to the .ascx.cs file i run the code good..but can i pass parameter using the above line , and if i can how can i retrieve them on the ascx.cs page . I want to do it because even if i refresh the page the .ascx control loads and some code i dont want is executed so i need some check that when it is called from javascript it has some values and run the code . I hope you get what i want to say Thank you A: Ask yourself this: If I look at the flow (not the code, but the business flow), what information do I have when I am running the code one way that I don't when I run it another. If you figure that out, it is what has to be passed to the ASCX control. Then there is the question of when you have to do it. The load of this variable has to be loaded prior to rendering the control. ASCX controls are classes, like any other item in .NET, so setting it up as a property is fairly easy. If you head to a constructor argument, you end up with a dynamic loading issue, so I would not peruse that direction. This page shows user controls with properties, which is an easy way to accomplish what you desire. To be safe, set a default for the property or choose to render an "error" (user friendly) when the property is not set. http://oreilly.com/catalog/progaspdotnet/chapter/ch14.html
[ "stackoverflow", "0043511184.txt" ]
Q: Is there any alternative for loadFromWaypoints in Google Maps API? I want to move a marker through the given path in the map in my hybrid application using Ionic. I got a solution with Google Maps version 2, but I didn't get any replacement for the loadFromWaypoints function in version 3. Thanks in advance. var dirn = new google.maps.DirectionsService; var startpoint = document.getElementById("start").value; var endpoint = document.getElementById("end").value; dirn.loadFromWaypoints([startpoint,endpoint],{getPolyline:true,getSteps:true}); <input id="start" type="text" class="nav-input" placeholder="Your Location" gm-places-autocomplete ng-model="yourLocation"/> <input id="end" type="text" class="nav-input" placeholder="Drop Location" gm-places-autocomplete ng-model="dropLocation"/> A: Hope this will help you: var map; var directionDisplay; var directionsService; var stepDisplay; var markerArray = []; var position; var marker = null; var polyline = null; var poly2 = null; var speed = 0.000005, wait = 1; var infowindow = null; var timerHandle = null; function createMarker(latlng, label, html) { var contentString = '<b>' + label + '</b><br>' + html; var marker = new google.maps.Marker({ position: latlng, map: map, title: label, zIndex: Math.round(latlng.lat() * -100000) << 5 }); marker.myname = label; google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(contentString); infowindow.open(map, marker); }); return marker; } function initialize() { infowindow = new google.maps.InfoWindow({ size: new google.maps.Size(150, 50) }); // Instantiate a directions service. directionsService = new google.maps.DirectionsService(); // Create a map and center it on Manhattan. var myOptions = { zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); address = 'new york'; geocoder = new google.maps.Geocoder(); geocoder.geocode({ 'address': address }, function(results, status) { map.setCenter(results[0].geometry.location); }); // Create a renderer for directions and bind it to the map. var rendererOptions = { map: map }; directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions); // Instantiate an info window to hold step text. stepDisplay = new google.maps.InfoWindow(); polyline = new google.maps.Polyline({ path: [], strokeColor: '#FF0000', strokeWeight: 3 }); poly2 = new google.maps.Polyline({ path: [], strokeColor: '#FF0000', strokeWeight: 3 }); } var steps = []; function calcRoute() { if (timerHandle) { clearTimeout(timerHandle); } if (marker) { marker.setMap(null); } polyline.setMap(null); poly2.setMap(null); directionsDisplay.setMap(null); polyline = new google.maps.Polyline({ path: [], strokeColor: '#FF0000', strokeWeight: 3 }); poly2 = new google.maps.Polyline({ path: [], strokeColor: '#FF0000', strokeWeight: 3 }); // Create a renderer for directions and bind it to the map. var rendererOptions = { map: map }; directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions); var start = document.getElementById("start").value; var end = document.getElementById("end").value; var travelMode = google.maps.DirectionsTravelMode.DRIVING; var request = { origin: start, destination: end, travelMode: travelMode }; // Route the directions and pass the response to a // function to create markers for each step. directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); var bounds = new google.maps.LatLngBounds(); var route = response.routes[0]; startLocation = new Object(); endLocation = new Object(); // For each route, display summary information. var path = response.routes[0].overview_path; var legs = response.routes[0].legs; for (i = 0; i < legs.length; i++) { if (i === 0) { startLocation.latlng = legs[i].start_location; startLocation.address = legs[i].start_address; // marker = createMarker(legs[i].start_location, "start", legs[i].start_address, "green"); } endLocation.latlng = legs[i].end_location; endLocation.address = legs[i].end_address; var steps = legs[i].steps; for (j = 0; j < steps.length; j++) { var nextSegment = steps[j].path; for (k = 0; k < nextSegment.length; k++) { polyline.getPath().push(nextSegment[k]); bounds.extend(nextSegment[k]); } } } polyline.setMap(map); map.fitBounds(bounds); map.setZoom(18); startAnimation(); } }); } var step = 50; // 5; // metres var tick = 100; // milliseconds var eol; var k = 0; var stepnum = 0; var speed = ""; var lastVertex = 1; //=============== animation functions ====================== function updatePoly(d) { // Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow if (poly2.getPath().getLength() > 20) { poly2 = new google.maps.Polyline([polyline.getPath().getAt(lastVertex - 1)]); // map.addOverlay(poly2) } if (polyline.GetIndexAtDistance(d) < lastVertex + 2) { if (poly2.getPath().getLength() > 1) { poly2.getPath().removeAt(poly2.getPath().getLength() - 1); } poly2.getPath().insertAt(poly2.getPath().getLength(), polyline.GetPointAtDistance(d)); } else { poly2.getPath().insertAt(poly2.getPath().getLength(), endLocation.latlng); } } function animate(d) { if (d > eol) { map.panTo(endLocation.latlng); marker.setPosition(endLocation.latlng); return; } var p = polyline.GetPointAtDistance(d); map.panTo(p); var lastPosn = marker.getPosition(); marker.setPosition(p); var heading = google.maps.geometry.spherical.computeHeading(lastPosn, p); icon.rotation = heading; marker.setIcon(icon); updatePoly(d); timerHandle = setTimeout("animate(" + (d + step) + ")", tick); } function startAnimation() { eol = polyline.Distance(); map.setCenter(polyline.getPath().getAt(0)); marker = new google.maps.Marker({ position: polyline.getPath().getAt(0), map: map, icon: icon }); poly2 = new google.maps.Polyline({ path: [polyline.getPath().getAt(0)], strokeColor: "#0000FF", strokeWeight: 10 }); // map.addOverlay(poly2); setTimeout("animate(50)", 2000); // Allow time for the initial map display } google.maps.event.addDomListener(window, 'load', initialize); //=============== ~animation funcitons ===================== var car = "M17.402,0H5.643C2.526,0,0,3.467,0,6.584v34.804c0,3.116,2.526,5.644,5.643,5.644h11.759c3.116,0,5.644-2.527,5.644-5.644 V6.584C23.044,3.467,20.518,0,17.402,0z M22.057,14.188v11.665l-2.729,0.351v-4.806L22.057,14.188z M20.625,10.773 c-1.016,3.9-2.219,8.51-2.219,8.51H4.638l-2.222-8.51C2.417,10.773,11.3,7.755,20.625,10.773z M3.748,21.713v4.492l-2.73-0.349 V14.502L3.748,21.713z M1.018,37.938V27.579l2.73,0.343v8.196L1.018,37.938z M2.575,40.882l2.218-3.336h13.771l2.219,3.336H2.575z M19.328,35.805v-7.872l2.729-0.355v10.048L19.328,35.805z"; var icon = { path: car, scale: .7, strokeColor: 'white', strokeWeight: .10, fillOpacity: 1, fillColor: '#404040', offset: '5%', // rotation: parseInt(heading[i]), anchor: new google.maps.Point(10, 25) // orig 10,50 back of car, 10,0 front of car, 10,25 center of car }; /*********************************************************************\ * * * epolys.js by Mike Williams * * updated to API v3 by Larry Ross * * * * A Google Maps API Extension * * * * Adds various Methods to google.maps.Polygon and google.maps.Polyline * * * * .Contains(latlng) returns true is the poly contains the specified * * GLatLng * * * * .Area() returns the approximate area of a poly that is * * not self-intersecting * * * * .Distance() returns the length of the poly path * * * * .Bounds() returns a GLatLngBounds that bounds the poly * * * * .GetPointAtDistance() returns a GLatLng at the specified distance * * along the path. * * The distance is specified in metres * * Reurns null if the path is shorter than that * * * * .GetPointsAtDistance() returns an array of GLatLngs at the * * specified interval along the path. * * The distance is specified in metres * * * * .GetIndexAtDistance() returns the vertex number at the specified * * distance along the path. * * The distance is specified in metres * * Returns null if the path is shorter than that * * * * .Bearing(v1?,v2?) returns the bearing between two vertices * * if v1 is null, returns bearing from first to last * * if v2 is null, returns bearing from v1 to next * * * * * *********************************************************************** * * * This Javascript is provided by Mike Williams * * Blackpool Community Church Javascript Team * * http://www.blackpoolchurch.org/ * * http://econym.org.uk/gmap/ * * * * This work is licenced under a Creative Commons Licence * * http://creativecommons.org/licenses/by/2.0/uk/ * * * *********************************************************************** * * * Version 1.1 6-Jun-2007 * * Version 1.2 1-Jul-2007 - fix: Bounds was omitting vertex zero * * add: Bearing * * Version 1.3 28-Nov-2008 add: GetPointsAtDistance() * * Version 1.4 12-Jan-2009 fix: GetPointsAtDistance() * * Version 3.0 11-Aug-2010 update to v3 * * * \*********************************************************************/ // === first support methods that don't (yet) exist in v3 google.maps.LatLng.prototype.distanceFrom = function(newLatLng) { var EarthRadiusMeters = 6378137.0; // meters var lat1 = this.lat(); var lon1 = this.lng(); var lat2 = newLatLng.lat(); var lon2 = newLatLng.lng(); var dLat = (lat2 - lat1) * Math.PI / 180; var dLon = (lon2 - lon1) * Math.PI / 180; var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = EarthRadiusMeters * c; return d; } google.maps.LatLng.prototype.latRadians = function() { return this.lat() * Math.PI / 180; } google.maps.LatLng.prototype.lngRadians = function() { return this.lng() * Math.PI / 180; } // === A method which returns the length of a path in metres === google.maps.Polygon.prototype.Distance = function() { var dist = 0; for (var i = 1; i < this.getPath().getLength(); i++) { dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1)); } return dist; } // === A method which returns a GLatLng of a point a given distance along the path === // === Returns null if the path is shorter than the specified distance === google.maps.Polygon.prototype.GetPointAtDistance = function(metres) { // some awkward special cases if (metres == 0) return this.getPath().getAt(0); if (metres < 0) return null; if (this.getPath().getLength() < 2) return null; var dist = 0; var olddist = 0; for (var i = 1; (i < this.getPath().getLength() && dist < metres); i++) { olddist = dist; dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1)); } if (dist < metres) { return null; } var p1 = this.getPath().getAt(i - 2); var p2 = this.getPath().getAt(i - 1); var m = (metres - olddist) / (dist - olddist); return new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m); } // === A method which returns an array of GLatLngs of points a given interval along the path === google.maps.Polygon.prototype.GetPointsAtDistance = function(metres) { var next = metres; var points = []; // some awkward special cases if (metres <= 0) return points; var dist = 0; var olddist = 0; for (var i = 1; (i < this.getPath().getLength()); i++) { olddist = dist; dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1)); while (dist > next) { var p1 = this.getPath().getAt(i - 1); var p2 = this.getPath().getAt(i); var m = (next - olddist) / (dist - olddist); points.push(new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m)); next += metres; } } return points; } // === A method which returns the Vertex number at a given distance along the path === // === Returns null if the path is shorter than the specified distance === google.maps.Polygon.prototype.GetIndexAtDistance = function(metres) { // some awkward special cases if (metres == 0) return this.getPath().getAt(0); if (metres < 0) return null; var dist = 0; var olddist = 0; for (var i = 1; (i < this.getPath().getLength() && dist < metres); i++) { olddist = dist; dist += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i - 1)); } if (dist < metres) { return null; } return i; } // === Copy all the above functions to GPolyline === google.maps.Polyline.prototype.Distance = google.maps.Polygon.prototype.Distance; google.maps.Polyline.prototype.GetPointAtDistance = google.maps.Polygon.prototype.GetPointAtDistance; google.maps.Polyline.prototype.GetPointsAtDistance = google.maps.Polygon.prototype.GetPointsAtDistance; google.maps.Polyline.prototype.GetIndexAtDistance = google.maps.Polygon.prototype.GetIndexAtDistance; html { height: 100%; } body { height: 100%; margin: 0px; font-family: Helvetica, Arial; } <script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script> <div id="tools">start: <input type="text" name="start" id="start" value="union square, NY" />end: <input type="text" name="end" id="end" value="times square, NY" /> <input type="submit" onclick="calcRoute();" /> </div> <div id="map_canvas" style="width:100%;height:90%;"></div>
[ "stackoverflow", "0001602346.txt" ]
Q: How can i monitor cfthread processes? Now that I am using it for backend processing of csv files, and the cf8 standard is limited to ten threads, I want to make sure i won't somehow overload the server... Any suggestions? I am making uniquely named threads, but i am worried about performance...also what if i need to stop a thread, how do i do that? Thank You. A: ColdFusion 9's Server Monitor will allow you to measure server performance such as Memory, Requests and specific Threads. Prior to ColdFusion 9 you needed to use third party utilities such as FusionReactor to monitor threads (www.fusion-reactor.com). While I have not used FusionReactor, it does have a good reputation in the CF community.
[ "space.stackexchange", "0000023435.txt" ]
Q: What is the nature and purpose of the treaty that US (NASA) has signed with Australia? From Australia and the United States sign historic space treaty: In Washington this morning the Turnbull Government signed a treaty with the National Aeronautics and Space Administration (NASA), reaffirming a commitment made by Australia and the United States of America more than 50 years ago to collaborate on space exploration. Ambassador Joe Hockey signed the historic Space Tracking Treaty on behalf of Australia, with the Acting Administrator of NASA, Robert Lightfoot Jr, signing on behalf of the USA at a ceremony at the Australian Embassy in Washington D.C. The Space Tracking Treaty covers civil space facilities owned by NASA and located within Australia, including the Canberra Deep Space Communication Complex (CDSCC) at Tidbinbilla, as well as facilities in Western Australia and the Northern Territory. There is of course a large, critical, and historic collaboration between Australia and the US on space matters, including the Deep Space Network. Is this a renewal, or a change in understanding? Is it related to the imminent formation of the Australian Space Agency (see Open letter to the Australian Government: why Australia can no longer afford not to have a space agency and SIAA White Paper: Advancing Australia in Space), or perhaps the 50th anniversary of the Outer Space Treaty? I'm guessing that the signatories mentioned; director of NASA and Australian ambassador are symbolic - that the treaty proper is between two countries, not two space agencies, and other agreements in the form of contracts are used between the agencies. A: The treaty appears to be called "The Agreement concerning Space Vehicle Tracking and Communications Facilities" Here's a summary page from this pdf. 2010 will mark the 50 th anniversary of treaty-level cooperation between the US and Australia in space vehicle tracking. Australia's cooperation with the US on space-related activities began in 1957 with the establishment of facilities at Woomera in South Australia, to track US satellites. This was broadened to include additional scientific facilities set up by the US National Aeronautics and Space Administration (NASA) in 1960. Since then, the space vehicle tracking and communication relationship between Australia and the US has been the subject of a succession of Agreements and Exchanges of Notes between the two countries. Under these treaties, NASA has spent in excess of $A610 million on space-related activities in Australia since 1960. Significant scientific and economic benefits have been derived from activities conducted under the Agreement, especially through encouraging collaboration between Australian and NASA scientists. The treaty action under consideration further amends and extends the 1980 Program Agreement, which provides for the establishment, operation and maintenance of NASA facilities in Australia that will provide commensurate benefits for Australia. From what I can tell, the original agreement has been modified over the decades by the exchange of "diplomatic notes" between the countries. (An example of these exchanges can be found here.) If there is a current document containing the complete, updated agreement with all the changes, I was unable to find it. The State Department's Jan 1, 2017 Treaties in Force document lists this about the treaty: Agreement concerning space vehicle tracking and communications facilities. Exchange of notes at Canberra May 29, 1980. Entered into force May 29, 1980; effective February 26, 1980. 32 UST 1417; TIAS 9781; 1217 UNTS 237 Amendment and Extensions: July 21, 1981 (TIAS 10198) January 17 and May 2, 1990 (TIAS 12413) August 4, 2000 (2171 UNTS 139) February 25, 2010 August 19, 2011 and January 11, 2012 November 18 and 21, 2013
[ "stackoverflow", "0017397207.txt" ]
Q: Show do you set unique attributes for resources in Puppet when utilizing arrays In Puppet you can use arrays when declaring resources as so: file { ["/tmp/file1", "/tmp/file2"]: ensure => file, } However, as far as I know both file1 and file2 must have the same attributes, content, etc... Is there a way to have file1 and file2 have differing attributes? Something like: myContent = { "/tmp/file1" => "foo", "/tmp/file2" => "bar" } file { ["/tmp/file1", "/tmp/file2"]: ensure => file, content => myContent[name], } So file1 contains foo and file2 contains bar? As far as I know this comes down to being able to tell if the resource is for file1 or file2, at which point options like hashes or inline templates should become viable, but I'm not sure if this is possible. Thanks! A: No, that's not possible. You could use Hiera with create_resources: manifest: create_resources('file', hiera('filez')) Hierafile: --- filez: /tmp/file1: content: foo /tmp/file2: content: bar
[ "stackoverflow", "0053646086.txt" ]
Q: Adjust HTML with javascript I have a personal time keeper I am putting together for work. We are allotted 50 minutes a week, and I wanted to make a fancy way of keeping track of that time. I have a method that works: <!DOCTYPE html> <html lang="en"> <head> <style> #example1 { background-color="#0CD6C7"; } </style> <div id="example2"> <meta charset="utf-8" /> <title> Personal Timer</title> <script type="text/javascript"> function setTimes(info) { var sel = info.split('|'); document.getElementById('time1').value = sel[0]; document.getElementById('time2').value = sel[1]; } </script> </head> <body bgcolor="#0CD6C7"> <div id="example1"> <hr align="left" size="0.5" color="white" width="82%"> <br> <font face="arial"> <input id="time1" value="50:00" size="5"> 50 minutes of personal time per week <br> <input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your personal break<br> <button onclick="document.getElementById('time1').value = timeAddSub('time1','time2',false)">Enter</button> <script type="text/javascript"> // From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30 Number.prototype.padDigit = function() { return (this < 10) ? '0'+this : ''+this; } function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values var tt1 = document.getElementById(id1).value; if (tt1 == '') { return ''; } var t1 = tt1.split(':'); var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; } var t2 = tt2.split(':'); tt1 = Number(t1[0])*60+Number(t1[1]); tt2 = Number(t2[0])*60+Number(t2[1]); var diff = 0; if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; } t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours t1[1] = Math.abs(diff % 60).padDigit(); // form minutes var tt1 = ''; if (diff < 0) { tt1 = '-'; } // check for negative value return document.getElementById("time1").innerHTML = tt1+t1.join(':'); } </script> </font> </body> </div> </html> Enter in the length of the break in the second input field and that time is subtracted from the total. To make it look fancier, I want the total time to appear as only text, not as an input field. This is what I have so far: <!DOCTYPE html> <html lang="en"> <head> <style> </style> <div id="example2"> <meta charset="utf-8" /> <title> Personal Timer</title> <script type="text/javascript"> function setTimes(info) { var sel = info.split('|'); document.getElementById('time1').innerHTML = sel[0]; document.getElementById('time2').value = sel[1]; } </script> </head> <body bgcolor="#0CD6C7"> <div id="example1"> <hr align="left" size="0.5" color="white" width="82%"> <br> <font size="60" face="verdana" color="white"> <p id="time1"><font size="80"><b>50:00</b></p> <font size="3" face="verdana"> <input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your break<br> <button onclick="document.getElementById('time1').value = timeAddSub('time1', 'time2', false)">Enter</button> <script type="text/javascript"> // From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30 Number.prototype.padDigit = function() { return (this < 10) ? '0'+this : ''+this; } function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values var tt1 = document.getElementById(id1).value; if (tt1 == '') { return ''; } var t1 = tt1.split(':'); var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; } var t2 = tt2.split(':'); tt1 = Number(t1[0])*60+Number(t1[1]); tt2 = Number(t2[0])*60+Number(t2[1]); var diff = 0; if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; } t1[1] = Math.abs(diff % 60).padDigit(); // form minutes t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours var tt1 = ''; if (diff < 0) { tt1 = '-'; } // check for negative value return document.getElementById("time1").innerHTML = tt1+t1.join(':'); } </script> </font> </body> </div> </html> I know I need to use innerHTML, but it's just not quite clicking. Any pointers in the right direction would be much appreciated! A: Change the below line var tt1 = document.getElementById(id1).value; to var p = document.getElementById(id1); var tt1 = p.textContent; This is because, value function is applicable only to input tags. For the other plain text tags like p, headings, etc. textContent should be fetched.
[ "stackoverflow", "0041454603.txt" ]
Q: Go XML unmarshal array I am trying to unmarshal a file that looks like this <?xml version="1.0" encoding="UTF-8"?> <houses> <house name="Rhyves Flats 14" houseid="1" entryx="167" entryy="361" entryz="6" rent="0" townid="2" size="17" /> </houses> With the following code // House struct used for houses xml file type House struct { XMLName xml.Name `xml:"houses"` HouseID uint32 `xml:"houseid,attr"` Name string `xml:"name,attr"` EntryX uint16 `xml:"entryx,attr"` EntryY uint16 `xml:"entryy,attr"` EntryZ uint16 `xml:"entryz,attr"` Size int `xml:"size,attr"` TownID uint32 `xml:"townid,attr"` Rent int `xml:"rent,attr"` } // LoadHouses parses the server map houses func LoadHouses(file string, list []House) error { // Load houses file f, err := ioutil.ReadFile(file) if err != nil { return err } // Unmarshal houses file return xml.Unmarshal(f, &list) } This is not returning any error. But the house slice is empty. Everything seems correct, the attrs are set and the XMLName too. A: Your code is missing a definition of the Houses part of the XML. Something like what is shown below and unmarshal on that. type Houses struct { House []House `xml:"house"` }
[ "wordpress.stackexchange", "0000334475.txt" ]
Q: Woocommerce: sorting variable product How do I show variations sorted by quantity in stock? I can override or extend the WC_Product_Variable class, but this solution doesn't seem optimal. What other options are there? A: You can use the woocommerce_get_children filter: function wpse_filter_variations( $variations, $product, $false ) { // Do you sorting here return $variations; } add_filter( 'woocommerce_get_children', 'wpse_filter_variations', 10, 3 );
[ "stackoverflow", "0010195021.txt" ]
Q: Download image from servlet by button click i GWT? I used that code to create the servlet: How to get image with servlet and display it using GWT Image class? And I used that code to create the button: How to download a file via a button click i GWT? The mapping to the servlet in my web.xml file is like that: <servlet-mapping> <servlet-name>MyImageServlet</servlet-name> <url-pattern>*.images</url-pattern> </servlet-mapping> I give the name of the file with a get parameter "name". The probleme is, when I click on the button, the files name is always "servlet.images". How can I do to rename the image with the right name when the user wants to download the image? Thank you. A: In servlet. response.setHeader("Content-Disposition", "attachment;filename=downloadname.txt");
[ "stackoverflow", "0034529525.txt" ]
Q: How to setup SQLite with eclipse for the very first time? I am trying to setup SQLite with eclipse using the documentation: https://wiki.eclipse.org/Connecting_to_SQLite But when I am trying to add new "Generic JDBC" driver, the fields are disabled. I don't know how to proceed. A: From where you are now, you need to select JAR List tab and import the sqlite.jar file which is inside the zip file downloaded in the earlier step. Download from here. Once that is done, you can proceed as per the steps mentioned in the link. Hope it helps.
[ "stackoverflow", "0024949321.txt" ]
Q: Is it possible to link to a div without changing the URL (in HTML)? So, basically, I want people to be able to navigate my website, through links to Divs, but PREVENT the browser from changing the current URL (it adds #divname at the end of the .html file). I have something like this: <div id="modalLogin" class="modalLogin"> <!-- random stuff here --> </div> And somewhere else I have a link to that Div: <a href="#modalLogin"> <img class="btnLogin" src="../images/btnLogin.png" alt="Log in!"/> </a> But, as I mentioned before, whenever they click those kind of links, the URL changes. I'd like to be able to navigate the website WITHOUT that happening. If at all possible, using just HTML (no JavaScript, no jQuery, no AJAX). While we're at it, I've seen entire websites not changing their URL at all (even when I've traced the requests and am clearly navigating through different files), and some don't even show you the 'expected address' (the URL on the bottom left of the browser). How do I do that? Thanks in advance! P.S.: I've searched this website, and apparently all 'similar' questions ask just about the opposite: how TO change the URL. A: I think You Can Use Javascript for This. //Grab your current Url var url = window.location.toString(); //Remove anchor from url using the split url = url.split("#")[0]; SAMPLE JSFIDDLE
[ "stackoverflow", "0043619925.txt" ]
Q: SQL tree path structure length I have the below values: Id | Sum | Tree_path_structure 1 | 10 | /1/2 2 | 30 | /1/3/4 3 | 40 | /1/3/5 4 | 50 | /1/6 For the longest tree path, in the example, id in (2,3) the query should return the small sum and the output should be: Id | Sum | Tree_path_structure 1 | 10 | /1/2 2 | 30 | /1/3/4 4 | 50 | /1/6 I would like a SQL that based on the tree path structure length will return the smallest sum value. A: Oracle Setup: CREATE TABLE your_table ( Id, SUm, Tree_path_structure ) AS SELECT 1, 10, '/1/2' FROM DUAL UNION ALL SELECT 2, 30, '/1/3/4' FROM DUAL UNION ALL SELECT 3, 40, '/1/3/5' FROM DUAL UNION ALL SELECT 4, 50, '/1/6' FROM DUAL; Query: SELECT id, sum, tree_path_structure FROM ( SELECT id, sum, tree_path_structure, CASE WHEN is_Max_Depth = 0 OR sum = MIN( sum ) OVER ( PARTITION BY is_Max_Depth ) THEN 0 ELSE 1 END AS is_Max_Depth_With_Higher_sum FROM ( SELECT id, sum, tree_path_structure, CASE depth WHEN MAX( depth ) OVER () THEN 1 ELSE 0 END AS is_Max_Depth FROM ( SELECT ID, SUM, Tree_Path_Structure, LENGTH( Tree_Path_Structure ) - LENGTH( REPLACE( Tree_Path_Structure, '/' ) ) AS depth FROM your_table ) t ) ) WHERE is_Max_Depth_With_Higher_sum = 0; Output: ID SUM TREE_P ---------- ---------- ------ 1 10 /1/2 4 50 /1/6 2 30 /1/3/4 Update: SELECT id, sum, tree_path_structure FROM ( SELECT id, sum, tree_path_structure, CASE WHEN is_Max_Depth = 0 OR sum = MIN( sum ) OVER ( PARTITION BY root, is_Max_Depth ) THEN 0 ELSE 1 END AS is_Max_Depth_With_Higher_sum FROM ( SELECT id, sum, tree_path_structure, root, CASE depth WHEN MAX( depth ) OVER ( PARTITION BY root ) THEN 1 ELSE 0 END AS is_Max_Depth FROM ( SELECT ID, SUM, Tree_Path_Structure, SUBSTR( Tree_Path_Structure, 1, INSTR( Tree_Path_Structure, '/', 1, 2 ) ) AS root, LENGTH( Tree_Path_Structure ) - LENGTH( REPLACE( Tree_Path_Structure, '/' ) ) AS depth FROM your_table ) t ) ) WHERE is_Max_Depth_With_Higher_sum = 0;
[ "askubuntu", "0000305712.txt" ]
Q: How do I auto mount my partition? I've a partition on /dev/sda2 of 279 GB Ext4 filesystem, but I'm not able to auto mount it on login. I've added the partition entry /dev/sda /home ext4 defaults 0 0 in /etc/fstabt still it does not auto mount. I've even tried to edit the mount options from disks (please see the below screenshot), yet no results. The udisks command works well but the problem is that, it asks a admin password for standard user. So my question is how do I auto mount this partition or at least grant read write permission to standard user so that they can mount this partition using udisks command. Thanks to dschinn1001 I was able to automount my partition by editing the entry in fstab. First I fount the UUID using sudo blkid Then edit the fstab file using sudo /etc/fstab Add the entry in the following format [Device] [Mount Point] [File System Type] [Options] [Dump] [Pass] Device will be your UUID Mount Point will be the location where you want to mount your partition File System Type will be displayed when you run blkid command Options Add the options you need. See options in Fstab for more details. Dump This value will be zero most cases. See Fstab for more details. Pass This value will be zero most cases. See Fstab for more details. So finally this is how my entry looks like. UUID=fe9ab5ba-35ed-49c5-b1d3-9bfc02060867 /media/mount ext4 auto,user,rw,exec 0 0 Save the file and restart your PC. In the options I've mentioned auto which means auto mount user which means grant standard users to mount partition rw read write permission exec Permit the execution of binaries from the filesystem A: partition entry is not quite correct ( /home is in /dev/sda2 ? ) : you wrote: /dev/sda /home ext4 defaults 0 0 ( if you write like that then you should replace /dev/sda with: UUID=number-of-device you can determine UUID-number with command: sudo blkid) but it could look like this too ( in older Linux-Versions): /dev/sda /mnt/ext4 defaults 0 0 or like this: /dev/sda /media/ext4 defaults 0 0 more is explained here : https://help.ubuntu.com/community/AutomaticallyMountPartitions https://help.ubuntu.com/community/Fstab https://help.ubuntu.com/community/UsingUUID
[ "gaming.stackexchange", "0000280076.txt" ]
Q: Does internet speed or computer speed affect the FPS of the server? Does the internet speed or computer speed of the host affect the fps of a minecraft server? If so how to make the fps better without tinkering with the internet speed. A: The host's computer speed or internet speed will influence how many fps the server will be able to handle. One way to improve said fps is to limit the amount of loaded chunks and rendering distance. The host can do that through server configuration for rendering distance, and by limiting any or all objects that allow for chunks to be loaded without the presence of a player (although this should only be an issue with modded servers).
[ "stackoverflow", "0005098789.txt" ]
Q: SharePoint memory leak Does this contain a memory leak? I've been trying to better understand memory leaks, but I can't tell if I have corrected this? If not, how do I correctly dispose of the SPweb object and SPSite object? using (SPWeb oWebsite = new SPSite(webUrl).OpenWeb()) //Open SP Web { SPListCollection collList = oWebsite.Lists; //Open Lists foreach (SPList oList in collList) //For Each List Execute this { if (!oList.Hidden) //If the list is hidden do this else nothing { ListSitesDropDownBox.Items.Add(new ListItem(SPEncode.HtmlEncode(oList.Title), SPEncode.HtmlEncode(oList.Title))); ViewState["Item" + counter] = SPEncode.HtmlEncode(oList.Title); counter++; } } } A: Yep, it does. You dispose of SPWeb but forget disposing of SPSite. The right way to do this: using (var site = new SPSite(webUrl)) using (var web = site.OpenWeb()) { // ... } Note that this is equivalent to: using (var site = new SPSite(webUrl)) { using (var web = site.OpenWeb()) { // ... } } but I omitted braces for outer using to reduce code nesting. The bracing rules are the same as for if. A few stylistic remarks: Please, don't use Systems Hungarian in C# code. Just list. Comments that rephrase the code above don't make any sense. Keep them constructive, i.e. explaining the purpose of the code. Instead of those four comments, you should've written something like that in the beginning: // Populate drop-down list with list names and save them in ViewState
[ "gis.stackexchange", "0000272368.txt" ]
Q: Using cursor in ArcPy gives TypeError: cannot concatenate 'str' and 'Polygon' objects? I have been trying to use arcpy.da.seachcursor to rip through a datasets rows and use each in an intersect analysis like so: with arcpy.da.SearchCursor(in_feature, ['SHAPE@', 'NAME']) as cursor: for f in cursor: data = [] print '...Working on {}'.format(f[1]) for path, subdirs, files in os.walk(in_folder): for i,x in enumerate(files): if x.endswith('.shp'): arcpy.Intersect_analysis(os.path.join(path, x)+';' + f[0], 'in_memory\\r{}'.format(i)) data.append('in_memory\\r{}'.format(i)) arcpy.Merge_management(data, out_folder + '\\out_dataset_{}.shp'.format(name)) arcpy.Delete_management('in_memory\\') it yields the following error code message: TypeError: cannot concatenate 'str' and 'Polygon' objects Upon reviewing how to fix this, I have stumbled upon code like: row[0].overlaps(row2[0]) that is used by da cursors (reference: https://arcpy.wordpress.com/2012/02/01/find-overlapping-features/). This has piqued my interest but I cannot find documentation on the implementation of this data structure. Where do I find it? Are there methods for doing other spatial processes like intersect? Hopefully through this I find out the answer to my error code, but if anyone has a quick bit of knowledge outside of the data structure I am looking for info on, please drop it :) A: Intersect wants a list of inputs so this wont work: arcpy.Intersect_analysis(os.path.join(path, name)+';' + f[0],... Also try copying the polygon object to the in memory workspace and use this as input to the intersection: arcpy.CopyFeatures_management(f[0], r'in_memory\temp') arcpy.Intersect_analysis([os.path.join(path, name), r'in_memory\temp'],.. For this to work you probably need to set arcpy.env.overwriteOutput = True
[ "stackoverflow", "0006607848.txt" ]
Q: Issue with EventTrigger for specific user interface element I am having an issue when using EventTriggers. I have two buttons and two EventTriggers that I want to listen for Click events from those buttons, then the triggers should start a StoryBoard which animates the height of a control. I have no problem with starting the StoryBoards, I simply have a problem with specifying the SourceName of the EventTrigger: <UserControl x:Class="MyWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" > <UserControl.Resources> <Storyboard x:Key="GrowPanel1"> <DoubleAnimation To="400" Duration="0:0:0.75" Storyboard.TargetName="Panel1" Storyboard.TargetProperty="Height" /> </Storyboard> <Storyboard x:Key="GrowPanel2"> <DoubleAnimation To="400" Duration="0:0:0.75" Storyboard.TargetName="Panel2" Storyboard.TargetProperty="Height" /> </Storyboard> </UserControl.Resources> <Grid > <Grid.Triggers> <EventTrigger RoutedEvent="Button.Click" SourceName="TriggerElement1" > <EventTrigger.Actions> <BeginStoryboard Storyboard="{StaticResource GrowPanel1}" /> </EventTrigger.Actions> </EventTrigger> <EventTrigger RoutedEvent="Button.Click" SourceName="TriggerElement2" > <EventTrigger.Actions> <BeginStoryboard Storyboard="{StaticResource GrowPanel2}" /> </EventTrigger.Actions> </EventTrigger> </Grid.Triggers> <Border BorderBrush="HotPink" BorderThickness="2"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <ContentPresenter Panel.ZIndex="20" Grid.Column="1" > <ContentPresenter.Content> <StackPanel Orientation="Horizontal"> <Button x:Name="TriggerElement2" Background="BurlyWood" Width="30" Height="30" VerticalAlignment="Top" /> <Button x:Name="TriggerElement1" Background="Chartreuse" Width="30" Height="30" VerticalAlignment="Top" /> </StackPanel> </ContentPresenter.Content> </ContentPresenter> <Grid Grid.Column="0" Grid.ColumnSpan="2"> <my1:TreeViewNav Name="Panel1" Height="0" VerticalAlignment="Top" /> <my:ListViewNav x:Name="Panel2" Height="0" VerticalAlignment="Top" /> </Grid> </Grid> </Border> </Grid> </UserControl> With this I get a run time error: The most likely causing exception was was: 'System.Windows.Markup.XamlParseException: 'Initialization of 'System.Windows.Controls.Grid' threw an exception.' Line number '23' and line position '6'. ---> System.ArgumentException: Cannot find a FrameworkElement with Name 'TriggerElement1'. at System.Windows.FrameworkElement.FindNamedFrameworkElement(FrameworkElement startElement, String targetName) at System.Windows.EventTrigger.ProcessOneTrigger(FrameworkElement triggersHost, TriggerBase triggerBase) at System.Windows.EventTrigger.ProcessTriggerCollection(FrameworkElement triggersHost) at System.Windows.FrameworkElement.TryFireInitialized() at System.Windows.FrameworkElement.EndInit() at MS.Internal.Xaml.Runtime.ClrObjectRuntime.InitializationGuard(XamlType xamlType, Object obj, Boolean begin) --- End of inner exception stack trace --- Removing the EventTrigger SourceName property fixes the error, but I need to start different StoryBoards depending on which button is clicked. So as far as I know I need to use the SourceName. Why can't WPF find my Button called TriggerElement1? I thought RoutedEvents get bubbled up the visual tree, so as long as the trigger is at a high enough level it should have no naming problems? It has no problem finding the StoryBoard.Target called Panel1. Have I taken the right approach to get two buttons to trigger different storyboards? A: Since your button "TriggerElement1" is inside a ContentPresenter App is unable to locate the button at initalization. Because contentpresentor content will be rendered at runtime. I made few changes to your code which is working fine now... hope this will solve your problem. <UserControl x:Class="WpfApplication1.MyWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"> <UserControl.Resources> <Storyboard x:Key="GrowPanel1"> <DoubleAnimation To="400" Duration="0:0:0.75" Storyboard.TargetName="Panel1" Storyboard.TargetProperty="Height" /> <DoubleAnimation To="0" Duration="0:0:0.75" Storyboard.TargetName="Panel2" Storyboard.TargetProperty="Height" /> </Storyboard> <Storyboard x:Key="GrowPanel2"> <DoubleAnimation To="400" Duration="0:0:0.75" Storyboard.TargetName="Panel2" Storyboard.TargetProperty="Height" /> <DoubleAnimation To="0" Duration="0:0:0.75" Storyboard.TargetName="Panel1" Storyboard.TargetProperty="Height" /> </Storyboard> </UserControl.Resources> <Grid> <Border BorderBrush="HotPink" BorderThickness="2"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <StackPanel Orientation="Horizontal" Grid.Column="1" > <Button x:Name="TriggerElement2" Background="BurlyWood" Width="30" Height="30" VerticalAlignment="Top"> <Button.Triggers> <EventTrigger RoutedEvent="Button.Click"> <EventTrigger.Actions> <BeginStoryboard Storyboard="{StaticResource GrowPanel2}" /> </EventTrigger.Actions> </EventTrigger> </Button.Triggers> </Button> <Button x:Name="TriggerElement1" Background="Chartreuse" Width="30" Height="30" VerticalAlignment="Top" > <Button.Triggers> <EventTrigger RoutedEvent="Button.Click"> <EventTrigger.Actions> <BeginStoryboard Storyboard="{StaticResource GrowPanel1}" /> </EventTrigger.Actions> </EventTrigger> </Button.Triggers> </Button> </StackPanel> <Grid Grid.Column="0" Grid.ColumnSpan="2" VerticalAlignment="Bottom"> <Grid Name="Panel1" Height="0" VerticalAlignment="Top" Background="Red"/> <Grid x:Name="Panel2" Height="0" VerticalAlignment="Top" Background="Blue"/> </Grid> </Grid> </Border> </Grid> </UserControl>
[ "stackoverflow", "0030598146.txt" ]
Q: How to push text from html input into AngularJS array? I'm new to AngularJS - trying to build a pretty vanilla todo-list app. I can't figure out how to push the text value from the input box into the 'todos' array. Here's my code. HTML: <body ng-controller="MainCtrl"> <div class="container"> <div class="main"> <p>Todo App</p> <input ng-model="todoList" type="text" name="input" placeholder="Enter tasks here"> <button ng-click="addTodo()">Add</button> <ul> <li ng-repeat="todo in todos"> {{todo} </li> </ul> </div> </div> </body> JS: var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.todos = [] $scope.todoList = ""; $scope.addTodo = function(){ $scope.todos.push($scope.todoList) } $scope.clearAll = function(){ $scope.todos = [] } }); Thanks in advance! A: I guess it's just a typo in your template, try {{todo}} instead of {{todo} Everything else looks fine Here is completed code: http://plnkr.co/edit/tRGw9UTRVhXvD51lxYjF?p=preview I've also added track by $index statement to allow duplicated todos.
[ "stackoverflow", "0019707797.txt" ]
Q: Avoid Repeating Column Header in Table I am a newbie to JasperReports. When I try to add values to table in the columns the column header and footer are getting repeated. How should I group column header. My jrxml: <?xml version="1.0" encoding="UTF-8"?> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report1" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="551344a1-61b0-419c-92a0-5ebe6f8d4219"> <property name="ireport.zoom" value="1.2100000000000004"/> <property name="ireport.x" value="0"/> <property name="ireport.y" value="0"/> <style name="table"> <box> <pen lineWidth="1.0" lineColor="#000000"/> </box> </style> <style name="table_TH" mode="Opaque" backcolor="#F0F8FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table_CH" mode="Opaque" backcolor="#BFE1FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table_TD" mode="Opaque" backcolor="#FFFFFF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table 1"> <box> <pen lineWidth="1.0" lineColor="#000000"/> </box> </style> <style name="table 1_TH" mode="Opaque" backcolor="#F0F8FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table 1_CH" mode="Opaque" backcolor="#BFE1FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table 1_TD" mode="Opaque" backcolor="#FFFFFF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table 2"> <box> <pen lineWidth="1.0" lineColor="#000000"/> </box> </style> <style name="table 2_TH" mode="Opaque" backcolor="#F0F8FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table 2_CH" mode="Opaque" backcolor="#BFE1FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table 2_TD" mode="Opaque" backcolor="#FFFFFF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <subDataset name="Table Dataset 1" uuid="75c6059a-1e76-45b2-a87c-14792e68956e"> <field name="training" class="java.lang.String"/> <field name="trainingPeriod" class="java.lang.String"/> <field name="traingingAdd" class="java.lang.String"/> <field name="noofgovtorderauth" class="java.lang.String"/> <field name="authapprovingentry" class="java.lang.String"/> <field name="deptTestpassed" class="java.lang.String"/> <field name="athConducTest" class="java.lang.String"/> <field name="monthSptestPassed" class="java.lang.String"/> <field name="yrSpTestPassed" class="java.lang.String"/> <field name="regNo" class="java.lang.String"/> </subDataset> <parameter name="ReportName" class="java.lang.String"/> <parameter name="Date" class="java.lang.String"/> <parameter name="Title" class="java.lang.String"/> <parameter name="SubTitle" class="java.lang.String"/> <parameter name="FooterDetail" class="java.lang.String"/> <parameter name="govtlogo" class="java.lang.String"/> <parameter name="TNWRDLogo" class="java.lang.String"/> <field name="training" class="java.lang.String"> <fieldDescription><![CDATA[training]]></fieldDescription> </field> <field name="trainingPeriod" class="java.lang.String"/> <field name="traingingAdd" class="java.lang.String"/> <field name="noofgovtorderauth" class="java.lang.String"/> <field name="authapprovingentry" class="java.lang.String"/> <field name="deptTestpassed" class="java.lang.String"/> <field name="athConducTest" class="java.lang.String"/> <field name="monthSptestPassed" class="java.lang.String"/> <field name="yrSpTestPassed" class="java.lang.String"/> <field name="regNo" class="java.lang.String"/> <background> <band splitType="Stretch"/> </background> <title> <band height="79" splitType="Stretch"> <frame> <reportElement uuid="fd5eaed7-88e8-4980-8205-6e50cf99ef20" x="0" y="27" width="565" height="52"> <property name="net.sf.jasperreports.export.pdf.tag.h1"/> <property name="net.sf.jasperreports.export.pdf.tag.tr" value="full"/> <property name="net.sf.jasperreports.export.pdf.tag.th" value="full"/> <property name="net.sf.jasperreports.export.pdf.tag.td" value="full"/> </reportElement> <box> <pen lineWidth="0.25"/> <topPen lineWidth="0.25"/> <leftPen lineWidth="0.25"/> <bottomPen lineWidth="0.25"/> <rightPen lineWidth="0.25"/> </box> <textField> <reportElement uuid="d3615141-0461-4665-b5f4-46a10f968d0e" x="174" y="33" width="213" height="19"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font size="8" isBold="true"/> </textElement> <textFieldExpression><![CDATA[$P{SubTitle}]]></textFieldExpression> </textField> <image> <reportElement uuid="34b5159e-3eb2-450a-9536-f79813589d48" x="442" y="2" width="61" height="48"/> <imageExpression><![CDATA[$P{TNWRDLogo}]]></imageExpression> </image> <image> <reportElement uuid="cd0f7d86-105f-44a1-8c27-81feacfba469" x="65" y="0" width="98" height="51"/> <imageExpression><![CDATA[$P{govtlogo}]]></imageExpression> </image> <textField> <reportElement uuid="e8aee322-2336-4637-9a5c-cb51af5995c8" x="174" y="0" width="213" height="32"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font size="14" isBold="true"/> </textElement> <textFieldExpression><![CDATA[$P{Title}]]></textFieldExpression> </textField> </frame> </band> </title> <pageHeader> <band height="35" splitType="Stretch"> <textField> <reportElement uuid="4c89127c-2b66-447e-af83-7ffd210e8a19" x="174" y="5" width="213" height="24"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font size="9" isBold="true"/> </textElement> <textFieldExpression><![CDATA[$P{ReportName}]]></textFieldExpression> </textField> <frame> <reportElement uuid="4ba70858-74c9-48a0-9690-888636570607" x="0" y="0" width="565" height="35"/> <box> <pen lineWidth="0.25"/> <topPen lineWidth="0.25"/> <leftPen lineWidth="0.25"/> <bottomPen lineWidth="0.25"/> <rightPen lineWidth="0.25"/> </box> </frame> </band> </pageHeader> <columnHeader> <band height="23" splitType="Stretch"> <staticText> <reportElement uuid="479cad61-a5be-4318-8e81-850ba6626e59" x="27" y="0" width="100" height="22"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[Training Detail]]></text> </staticText> <staticText> <reportElement uuid="d3474389-b724-4579-81b6-2f5c806aaa25" x="432" y="0" width="100" height="22"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[Special Tests Passed]]></text> </staticText> </band> </columnHeader> <detail> <band height="125" splitType="Stretch"> <componentElement> <reportElement uuid="f2abf631-2415-4ba1-bf93-4b1d458dacbc" key="table 2" style="table 2" x="53" y="44" width="450" height="50"/> <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd"> <datasetRun subDataset="Table Dataset 1" uuid="69dfdbc6-34fc-48ee-8ecd-197cde9b11fb"> <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.JREmptyDataSource(1)]]></dataSourceExpression> </datasetRun> <jr:columnGroup width="450" uuid="7287994d-bc5c-4286-8607-29969a2eb9ef"> <jr:column width="90" uuid="dbd24c78-fb82-47c4-9342-d5a73fb7e000"> <jr:columnHeader style="table 2_CH" height="29" rowSpan="1"> <staticText> <reportElement uuid="74b27263-d281-4136-b674-12bd3a74bd3c" x="0" y="0" width="90" height="29"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[Training]]></text> </staticText> </jr:columnHeader> <jr:detailCell style="table 2_TD" height="30" rowSpan="1"> <textField> <reportElement uuid="be34b5c1-5cd4-43e3-b6f9-0e6f2bbf88db" x="0" y="0" width="90" height="30"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{training}]]></textFieldExpression> </textField> </jr:detailCell> </jr:column> <jr:column width="90" uuid="01a9c90b-46c3-4693-b186-7abc77256f73"> <jr:columnHeader style="table 2_CH" height="29" rowSpan="1"> <staticText> <reportElement uuid="5ada3627-2084-4d79-a923-b6acbeee8058" positionType="Float" stretchType="RelativeToBandHeight" x="0" y="0" width="90" height="29"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[Period / Duration]]></text> </staticText> </jr:columnHeader> <jr:detailCell style="table 2_TD" height="30" rowSpan="1"> <textField> <reportElement uuid="abb64036-38ea-4560-84fd-09dde730c3bc" x="0" y="0" width="90" height="30"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{trainingPeriod}]]></textFieldExpression> </textField> </jr:detailCell> </jr:column> <jr:column width="90" uuid="0865e4a3-5dbe-430a-9c50-90a636ef49ef"> <jr:columnHeader style="table 2_CH" height="29" rowSpan="1"> <staticText> <reportElement uuid="a897110e-f09f-43f3-a53b-aa8450065832" positionType="Float" stretchType="RelativeToBandHeight" x="0" y="0" width="90" height="29"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[Impart Training Address]]></text> </staticText> </jr:columnHeader> <jr:detailCell style="table 2_TD" height="30" rowSpan="1"> <textField> <reportElement uuid="41f45483-1f6d-480c-a59c-96093111ace5" x="0" y="0" width="90" height="30"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{traingingAdd}]]></textFieldExpression> </textField> </jr:detailCell> </jr:column> <jr:column width="90" uuid="8949efe8-7041-49dd-8631-685e8568e6d5"> <jr:columnHeader style="table 2_CH" height="29" rowSpan="1"> <staticText> <reportElement uuid="643bb124-0b66-448d-ade8-c7b540f18eb5" positionType="Float" stretchType="RelativeToBandHeight" x="0" y="0" width="90" height="29"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[No of Government Orders]]></text> </staticText> </jr:columnHeader> <jr:detailCell style="table 2_TD" height="30" rowSpan="1"> <textField> <reportElement uuid="834227d7-673a-4335-b1f8-37b3892125b1" x="0" y="0" width="90" height="30"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{noofgovtorderauth}]]></textFieldExpression> </textField> </jr:detailCell> </jr:column> <jr:column width="90" uuid="7fa15b45-3110-4648-ab41-35fc77c625d6"> <jr:columnHeader style="table 2_CH" height="29" rowSpan="1"> <staticText> <reportElement uuid="cfd20c24-75f4-449e-83ae-38d9e0507728" x="0" y="0" width="90" height="29"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[ Approving Audthority]]></text> </staticText> </jr:columnHeader> <jr:detailCell style="table 2_TD" height="30" rowSpan="1"> <textField> <reportElement uuid="b5e5dec0-46d3-47b5-aefe-5fe2038c94b9" x="0" y="0" width="90" height="30"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{authapprovingentry}]]></textFieldExpression> </textField> </jr:detailCell> </jr:column> </jr:columnGroup> </jr:table> </componentElement> </band> </detail> <columnFooter> <band height="45" splitType="Stretch"/> </columnFooter> <pageFooter> <band height="54" splitType="Stretch"/> </pageFooter> <summary> <band height="42" splitType="Stretch"/> </summary> </jasperReport> A: Try this , It will work for you. <?xml version="1.0" encoding="UTF-8"?> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report1" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="551344a1-61b0-419c-92a0-5ebe6f8d4219"> <property name="ireport.zoom" value="1.0"/> <property name="ireport.x" value="0"/> <property name="ireport.y" value="0"/> <style name="table"> <box> <pen lineWidth="1.0" lineColor="#000000"/> </box> </style> <style name="table_TH" mode="Opaque" backcolor="#F0F8FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table_CH" mode="Opaque" backcolor="#BFE1FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table_TD" mode="Opaque" backcolor="#FFFFFF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table 1"> <box> <pen lineWidth="1.0" lineColor="#000000"/> </box> </style> <style name="table 1_TH" mode="Opaque" backcolor="#F0F8FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table 1_CH" mode="Opaque" backcolor="#BFE1FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table 1_TD" mode="Opaque" backcolor="#FFFFFF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table 2"> <box> <pen lineWidth="1.0" lineColor="#000000"/> </box> </style> <style name="table 2_TH" mode="Opaque" backcolor="#F0F8FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table 2_CH" mode="Opaque" backcolor="#BFE1FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="table 2_TD" mode="Opaque" backcolor="#FFFFFF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> </box> </style> <subDataset name="Table Dataset 1" uuid="75c6059a-1e76-45b2-a87c-14792e68956e"> <field name="training" class="java.lang.String"/> <field name="trainingPeriod" class="java.lang.String"/> <field name="traingingAdd" class="java.lang.String"/> <field name="noofgovtorderauth" class="java.lang.String"/> <field name="authapprovingentry" class="java.lang.String"/> <field name="deptTestpassed" class="java.lang.String"/> <field name="athConducTest" class="java.lang.String"/> <field name="monthSptestPassed" class="java.lang.String"/> <field name="yrSpTestPassed" class="java.lang.String"/> <field name="regNo" class="java.lang.String"/> </subDataset> <parameter name="ReportName" class="java.lang.String"/> <parameter name="Date" class="java.lang.String"/> <parameter name="Title" class="java.lang.String"/> <parameter name="SubTitle" class="java.lang.String"/> <parameter name="FooterDetail" class="java.lang.String"/> <parameter name="govtlogo" class="java.lang.String"/> <parameter name="TNWRDLogo" class="java.lang.String"/> <field name="training" class="java.lang.String"> <fieldDescription><![CDATA[training]]></fieldDescription> </field> <field name="trainingPeriod" class="java.lang.String"/> <field name="traingingAdd" class="java.lang.String"/> <field name="noofgovtorderauth" class="java.lang.String"/> <field name="authapprovingentry" class="java.lang.String"/> <field name="deptTestpassed" class="java.lang.String"/> <field name="athConducTest" class="java.lang.String"/> <field name="monthSptestPassed" class="java.lang.String"/> <field name="yrSpTestPassed" class="java.lang.String"/> <field name="regNo" class="java.lang.String"/> <background> <band splitType="Stretch"/> </background> <title> <band height="114" splitType="Stretch"> <frame> <reportElement uuid="fd5eaed7-88e8-4980-8205-6e50cf99ef20" x="0" y="27" width="565" height="52"> <property name="net.sf.jasperreports.export.pdf.tag.h1"/> <property name="net.sf.jasperreports.export.pdf.tag.tr" value="full"/> <property name="net.sf.jasperreports.export.pdf.tag.th" value="full"/> <property name="net.sf.jasperreports.export.pdf.tag.td" value="full"/> </reportElement> <box> <pen lineWidth="0.25"/> <topPen lineWidth="0.25"/> <leftPen lineWidth="0.25"/> <bottomPen lineWidth="0.25"/> <rightPen lineWidth="0.25"/> </box> <textField> <reportElement uuid="d3615141-0461-4665-b5f4-46a10f968d0e" x="174" y="33" width="213" height="19"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font size="8" isBold="true"/> </textElement> <textFieldExpression><![CDATA[$P{SubTitle}]]></textFieldExpression> </textField> <image> <reportElement uuid="34b5159e-3eb2-450a-9536-f79813589d48" x="442" y="2" width="61" height="48"/> <imageExpression><![CDATA[$P{TNWRDLogo}]]></imageExpression> </image> <image> <reportElement uuid="cd0f7d86-105f-44a1-8c27-81feacfba469" x="65" y="0" width="98" height="51"/> <imageExpression><![CDATA[$P{govtlogo}]]></imageExpression> </image> <textField> <reportElement uuid="e8aee322-2336-4637-9a5c-cb51af5995c8" x="174" y="0" width="213" height="32"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font size="14" isBold="true"/> </textElement> <textFieldExpression><![CDATA[$P{Title}]]></textFieldExpression> </textField> </frame> </band> </title> <pageHeader> <band height="35" splitType="Stretch"> <textField> <reportElement uuid="4c89127c-2b66-447e-af83-7ffd210e8a19" x="174" y="5" width="213" height="24"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font size="9" isBold="true"/> </textElement> <textFieldExpression><![CDATA[$P{ReportName}]]></textFieldExpression> </textField> <frame> <reportElement uuid="4ba70858-74c9-48a0-9690-888636570607" x="0" y="0" width="565" height="35"/> <box> <pen lineWidth="0.25"/> <topPen lineWidth="0.25"/> <leftPen lineWidth="0.25"/> <bottomPen lineWidth="0.25"/> <rightPen lineWidth="0.25"/> </box> </frame> </band> </pageHeader> <columnHeader> <band height="23" splitType="Stretch"> <printWhenExpression><![CDATA[$V{REPORT_COUNT} == 1]]></printWhenExpression> <staticText> <reportElement uuid="479cad61-a5be-4318-8e81-850ba6626e59" x="27" y="0" width="100" height="22"> <printWhenExpression><![CDATA[$V{REPORT_COUNT} == 1]]></printWhenExpression> </reportElement> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[Training Detail]]></text> </staticText> <staticText> <reportElement uuid="d3474389-b724-4579-81b6-2f5c806aaa25" x="432" y="0" width="100" height="22"> <printWhenExpression><![CDATA[$V{REPORT_COUNT} == 1]]></printWhenExpression> </reportElement> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[Special Tests Passed]]></text> </staticText> </band> </columnHeader> <detail> <band height="125" splitType="Stretch"> <componentElement> <reportElement uuid="f2abf631-2415-4ba1-bf93-4b1d458dacbc" key="table 2" style="table 2" x="53" y="44" width="450" height="50"/> <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd"> <datasetRun subDataset="Table Dataset 1" uuid="69dfdbc6-34fc-48ee-8ecd-197cde9b11fb"> <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.JREmptyDataSource(1)]]></dataSourceExpression> </datasetRun> <jr:columnGroup uuid="7287994d-bc5c-4286-8607-29969a2eb9ef" width="450"> <jr:column uuid="dbd24c78-fb82-47c4-9342-d5a73fb7e000" width="90"> <jr:columnHeader style="table 2_CH" height="29" rowSpan="1"> <staticText> <reportElement uuid="74b27263-d281-4136-b674-12bd3a74bd3c" x="0" y="0" width="90" height="29"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[Training]]></text> </staticText> </jr:columnHeader> <jr:detailCell style="table 2_TD" height="30" rowSpan="1"> <textField> <reportElement uuid="be34b5c1-5cd4-43e3-b6f9-0e6f2bbf88db" x="0" y="0" width="90" height="30"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{training}]]></textFieldExpression> </textField> </jr:detailCell> </jr:column> <jr:column uuid="01a9c90b-46c3-4693-b186-7abc77256f73" width="90"> <jr:columnHeader style="table 2_CH" height="29" rowSpan="1"> <staticText> <reportElement uuid="5ada3627-2084-4d79-a923-b6acbeee8058" positionType="Float" stretchType="RelativeToBandHeight" x="0" y="0" width="90" height="29"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[Period / Duration]]></text> </staticText> </jr:columnHeader> <jr:detailCell style="table 2_TD" height="30" rowSpan="1"> <textField> <reportElement uuid="abb64036-38ea-4560-84fd-09dde730c3bc" x="0" y="0" width="90" height="30"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{trainingPeriod}]]></textFieldExpression> </textField> </jr:detailCell> </jr:column> <jr:column uuid="0865e4a3-5dbe-430a-9c50-90a636ef49ef" width="90"> <jr:columnHeader style="table 2_CH" height="29" rowSpan="1"> <staticText> <reportElement uuid="a897110e-f09f-43f3-a53b-aa8450065832" positionType="Float" stretchType="RelativeToBandHeight" x="0" y="0" width="90" height="29"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[Impart Training Address]]></text> </staticText> </jr:columnHeader> <jr:detailCell style="table 2_TD" height="30" rowSpan="1"> <textField> <reportElement uuid="41f45483-1f6d-480c-a59c-96093111ace5" x="0" y="0" width="90" height="30"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{traingingAdd}]]></textFieldExpression> </textField> </jr:detailCell> </jr:column> <jr:column uuid="8949efe8-7041-49dd-8631-685e8568e6d5" width="90"> <jr:columnHeader style="table 2_CH" height="29" rowSpan="1"> <staticText> <reportElement uuid="643bb124-0b66-448d-ade8-c7b540f18eb5" positionType="Float" stretchType="RelativeToBandHeight" x="0" y="0" width="90" height="29"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[No of Government Orders]]></text> </staticText> </jr:columnHeader> <jr:detailCell style="table 2_TD" height="30" rowSpan="1"> <textField> <reportElement uuid="834227d7-673a-4335-b1f8-37b3892125b1" x="0" y="0" width="90" height="30"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{noofgovtorderauth}]]></textFieldExpression> </textField> </jr:detailCell> </jr:column> <jr:column uuid="7fa15b45-3110-4648-ab41-35fc77c625d6" width="90"> <jr:columnHeader style="table 2_CH" height="29" rowSpan="1"> <staticText> <reportElement uuid="cfd20c24-75f4-449e-83ae-38d9e0507728" x="0" y="0" width="90" height="29"/> <textElement textAlignment="Center" verticalAlignment="Middle"> <font isBold="true"/> </textElement> <text><![CDATA[ Approving Audthority]]></text> </staticText> </jr:columnHeader> <jr:detailCell style="table 2_TD" height="30" rowSpan="1"> <textField> <reportElement uuid="b5e5dec0-46d3-47b5-aefe-5fe2038c94b9" x="0" y="0" width="90" height="30"/> <textElement textAlignment="Center" verticalAlignment="Middle"/> <textFieldExpression><![CDATA[$F{authapprovingentry}]]></textFieldExpression> </textField> </jr:detailCell> </jr:column> </jr:columnGroup> </jr:table> </componentElement> </band> </detail> <columnFooter> <band height="45" splitType="Stretch"/> </columnFooter> <pageFooter> <band height="54" splitType="Stretch"/> </pageFooter> <summary> <band height="42" splitType="Stretch"/> </summary> </jasperReport> Enjoy....
[ "stackoverflow", "0031408394.txt" ]
Q: Disallow function template instantiation with iterator parameter I have a function template which takes a templated parameter: template <class R> RefT<R> make_ref(R& res) { return RefT<R>(&res); } I either want to prevent R from being any kind of iterator, or, if this is easier, I want to have a overload that the compiler will prefer to use for iterators which calls make_ref again with the iterator dereferenced. Best approach would be combining the two, so the compiler prefers using iterator specific overload, and refuses to use the non-specific version. I would like consumers of the code to be able to call make_ref(something) without having to think about whether the something is an iterator or not - I just need to do something different if it is, and if that's not possible, give a useful error message to the consumer. A: First the traits (you may have to tweak it with your requirements): template <typename T> auto is_iterator_impl(T* it) -> decltype(**it, ++(*it), (*it) == (*it), std::true_type()); template <typename T> auto is_iterator_impl(...) -> std::false_type; template <typename T> using is_an_iterator = decltype(is_iterator_impl<T>(0)); Note: using std::iterator_traits<IT> may be a good alternative. With SFINAE, you may do template <class R> std::enable_if_t<!is_an_iterator<R>::value, RefT<R>> make_ref(R& res) { return RefT<R>(&res); } template <class R> std::enable_if_t<is_an_iterator<R>::value && !std::is_pointer<R>::value, RefT<R>> // you may want to change return type make_ref(R& res) { // Implementation for iterator } template <class R> std::enable_if_t<std::is_pointer<R>::value, RefT<R>> // you may want to change return type make_ref(R& res) { // Implementation for iterator } Note: as you want to manage pointer differently, I also use std::is_pointer in addition to the custom is_an_iterator. Note: The conditions should not have overlap, else you have conflict. Live Demo
[ "cs.stackexchange", "0000071087.txt" ]
Q: Solving the 10 players duel game Players #1 to #10 with hit probabilities $0.1,0.2,...,0.9,1$ (which are common knowledge) take part in a shooting game. Rules of the game: Players from #1 to #10 take turns to fire at each other. After round one, survivors repeat the circle (still in the order of #1 to #10). The game lasts many rounds until only one player survives. Players are rational and each calculates to maximize his survival probability. Question: What is each player's optimal choice of target in his turn, when all 10 players are alive? And what are their respective survival probabilities? (Technically, I'm looking for a pure strategy subgame perfect Nash equilibrium, where the players follow deterministic strategies. Barring the very unlikely circumstance of ties, in which firing at one or the other player yields the same survival probability for the shooter, such an equilibrium is unique.) My problem is I don't know how to write a tractable program to solve it. Let's consider 4 players with probabilities $(p_1,p_2,p_3,p_4)$. In this case, my reasoning is that the problem is solved by the following equations: $s_{i1}^4 = p_1*$(i's survival probability after 1 hits his target) $+ (1-p_1) * s_{i2}^4$ $s_{i2}^4 = p_2*$(i's survival probability after 2 hits his target) $+ (1-p_2) * s_{i3}^4$ $s_{i3}^4 = p_3*$(i's survival probability after 3 hits his target) $+ (1-p_3) * s_{i4}^4$ $s_{i4}^4 = p_4*$(i's survival probability after 4 hits his target) $+ (1-p_4) * s_{i1}^4$ for $i=1,2,3,4$, where $s_{ij}^4$ denotes i's survival probability when it's j's turn to fire, with 4 player alive. Notice that after a play hits his target, there's only 3 players left. So if we already know the 3 players case, the above equations can be solved. But I have no idea how to define a suitable structure and sub-programs to implement these thought... or maybe this is not the best way to look at the problem? A: Robert Israel's answer on Math Overflow provides the key insight: If $S$ is the set of players remaining alive and it is player $j$'s turn, player $j$ should shoot at the player $k$ such that, if $k$ dies, the remaining set gives $j$ the best survival chances. This enables us to build a dynamic programming algorithm, as Robert Israel states. I'll explain in a bit more detail how that works. Represent a configuration of the game by $(S,j)$, where $S$ is the set of players remaining alive and $j$ is the player whose turn it is to shoot next. Define $f_i(S,j)$ to be $i$'s probability of survival, under the equilibrium strategy for all (under optimal play), in configuration $(S,j)$. Then the insight above means that in configuration $(S,j)$, player $j$ should shoot at the player $k$ such that $f_j(S\setminus\{k\},j+1)$ is as large as possible. (As a conventional notation, when I write $(S,j+1)$, you should interpret $j+1$ as the next person to shoot after $j$, given that players $S$ are alive.) Based on this, we can write recursive equations for $f$: $$f_i(S,j) = p_j \cdot f_i(S \setminus \{g(S,j)\}, j+1) + (1-p_j) \cdot f_i(S,j+1)$$ where $$g(S,j) = \arg \max_k p_j(S \setminus \{k\}, j+1).$$ We'll start by calculating the values of $f_i(S,j)$ and $g(S,j)$ for all $S$ where $|S|=1$. Then, we'll calculate the values of $f_i(S,j)$ and $g(S,j)$ for all $S$ where $|S|=2$. Then, we'll calculate the values of $f_i(S,j)$ and $g(S,j)$ for all $S$ where $|S|=3$. At the $k$th stage, to calculate the $f$-values, we solve a system of linear equations in $k^2 \times {n \choose k}$ unknowns. (The unknowns are the terms $f_i(S,j)$ where $|S|=k$ and $i,j \in S$. Note that at this point $f_i(S \setminus \{\text{anything}\},j$ is known, since the first argument to $f$ will be a set of size $k-1$, which we've already calculated in the previous stage.) In your problem, $n=10$, so the $k$th stage involves solving a system of linear equations in $k^2 \times {10 \choose k}$ unknowns. This has a maximum at $k=6$, where we have 7560 unknowns. The system of linear equations can be solved using Gaussian elimination, which takes cubic time. In particular, Gaussian elimination on a $7560 \times 7560$ matrix is entirely feasible on a computer (probably it will take at most seconds). Therefore, this should provide an efficient algorithm to compute the survival probabilities and strategy you are looking for.
[ "stackoverflow", "0011696078.txt" ]
Q: Python - converting a list of tuples to a list of strings I have a list of tuples that looks like this: [('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')] What is the most pythonic and efficient way to convert into this where each token is separated by a space: ['this is', 'is the', 'the first', 'first document', 'document .'] A: Very simple: [ "%s %s" % x for x in l ] A: Using map() and join(): tuple_list = [('this', 'is'), ('is', 'the'), ('the', 'first'), ('first', 'document'), ('document', '.')] string_list = map(' '.join, tuple_list) As inspectorG4dget pointed out, list comprehensions are the most pythonic way of doing this: string_list = [' '.join(item) for item in tuple_list]
[ "stackoverflow", "0033720538.txt" ]
Q: Testing angular controller in Karma Me and my team have been having a problem setting up a controller test with the Karma test runner on Jasmine. app/app.js buyItApp = angular.module('buyItApp', ['ionic']); app/controllers/userSearchCtrl.js buyItApp.controller("userSearchCtrl", function($http, $scope) { var self = this; self.searchQuery = function(searchData) { $( "ion-spinner").toggle(true); $http({ method: 'GET', url: 'http://productfeedtest.wandoso.com/?keyword=' + searchData }).then(function successCallback(response) { $( "ion-spinner").toggle(false); $scope.showResultsCount = true $scope.items = response.data.items; $scope.isOffer = response.data.is_special_offer; $scope.resultsCount = response.data.items.length; $scope.searchQuery = searchData; }, function errorCallback(response) { $scope.searchResults = "server error!" }); } }); test/karma.conf.js module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], files: [ 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.1/angular.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.1/angular-mocks.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.1/angular-scenario.js', '../public/javascripts/app/*.js', '../public/javascripts/app/controllers/*.js', 'unit/userSearchCtrl.spec.js', 'unit/*.spec.js' ], exclude: [ ], preprocessors: { }, reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['PhantomJS'], singleRun: false, concurrency: Infinity }) } test/unit/userSearchCtrl.spec.js describe('userSearchCtrl', function() { var $rootScope, $scope, $controller, userSearchCtrl; beforeEach(module('buyItApp')); beforeEach(inject(function(_$rootScope_, _$controller_){ $rootScope = _$rootScope_; $scope = $rootScope.$new(); $controller = _$controller_; userSearchCtrl = $controller('userSearchCtrl', {'$rootScope' : $rootScope, '$scope': $scope}); })); it('should exist', function() { expect(userSearchCtrl).toBeDefined(); }); }); The failing test result http://textuploader.com/5jo6b Most notably: Expected undefined to be defined. at /Users/Harry/Dropbox/Dev/buyIt/test/unit/userSearchCtrl.spec.js:16 PhantomJS 1.9.8 (Mac OS X 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.004 secs / 0.007 secs) It looks like Karma cannot find the controller, however after checking the code and reviewing other projects it is not so clear what the issue is. A: As the error > http://errors.angularjs.org/1.5.0-beta.1/$injector/modulerr?p0=buyItApp&p1=Error: > [$injector:modulerr] > http://errors.angularjs.org/1.5.0-beta.1/$injector/modulerr?p0=ionic&p1=Error: > [$injector:nomod] > http://errors.angularjs.org/1.5.0-beta.1/$injector/nomod?p0=ionic explicitly says, it can't find ionic module which is loaded in buyItApp. Because it wasn't included in Karma files.
[ "stackoverflow", "0021089582.txt" ]
Q: Amazon RDS Endpoint internal How can I make ec2 instance communicate with rds instance on aws by internal ip address or dns? I only see public dns like xxx.cehmrvc73g1g.eu-west-1.rds.amazonaws.com:3306 Will internal ipaddress will be faster than public dns? Thanks A: A note for posterity, ensure that you enable DNS on the VPC Peering link! Enabling DNS Resolution Support for a VPC Peering Connection To enable a VPC to resolve public IPv4 DNS hostnames to private IPv4 addresses when queried from instances in the peer VPC, you must modify the peering connection. Both VPCs must be enabled for DNS hostnames and DNS resolution. To enable DNS resolution support for the peering connection Open the Amazon VPC console at https://console.aws.amazon.com/vpc/. In the navigation pane, choose Peering Connections. Select the VPC peering connection, and choose Actions, Edit DNS Settings. To ensure that queries from the peer VPC resolve to private IP addresses in your local VPC, choose the option to enable DNS resolution for queries from the peer VPC. If the peer VPC is in the same AWS account, you can choose the option to enable DNS resolution for queries from the local VPC. This ensures that queries from the local VPC resolve to private IP addresses in the peer VPC. This option is not available if the peer VPC is in a different AWS account. Choose Save. If the peer VPC is in a different AWS account, the owner of the peer VPC must sign into the VPC console, perform steps 2 through 4, and choose Save. A: You can use the "Endpoint" DNS name. It will resolve to the internal IP when used within the VPC and resolves to a public ip when used outside of your AWS network. You should never use the actual IP address because the way the RDS works it could possibly change in the future. If you ping it from your EC2 (on the same VPC) server you can verify this. It is amazing to see the amount of down votes I've got given that my answer is the only correct answer, here is 2 other sources: https://forums.aws.amazon.com/thread.jspa?threadID=70112 You can use the "Endpoint" DNS name. It will resolve to the internal IP when used within EC2. https://serverfault.com/questions/601548/cant-find-the-private-ip-address-for-my-amazon-rds-instance2 The DNS endpoint provided in the AWS console will resolve to the internal IPs from within Amazon's network. A: Check out the AWS EC2 docs: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-instance-addressing.html#concepts-private-addresses. It doesn't appear that this necessarily applies to RDS, however.
[ "meta.stackoverflow", "0000360452.txt" ]
Q: Ambiguous [textbuffer] I'm talking about textbuffer. Current status: Carried by 16 questions. 9 of them uses it as a component in GTK 6 of them uses it as a (computationally) generic buffer that's intended to store text One last question that I don't know whatever its author thinks this tag is for First apprearance: Nov 23, 2010 Has neither a wiki nor an excerpt As it currently is, slightly more than a half of the questions uses it as a GTK component. Since GTK TextBuffer cannot have another name, and there's no need for a tag for a general buffer whose only relationship with textbuffer is its intention (whatever a buffer stores makes no difference to the computer), I suggest removing this tag from the 7 irrelevant questions, renaming it to gtk-textbuffer and making this a synonym to that, as well as adding necessary excerpt to direct further askers away from adding this tag unless their question is about GTK TextBuffer. In case the SO community thinks this tag is used too infrequently, burninating it is also a fine solution. I agree that a frequency of less than 2 Q per year is absolutely too low. Side note: These three questions (A, B, C) seem to have some internal relationship as they contain very similar code. A: In the meantime, there was 1 new question about text buffer again related to GTK. 4 out of the 6 questions which you mention were being used as "generic buffer that's intended to store text", were all by one user who was writing a text buffer class. They seem to be separate questions, so I just removed the tag from it (it seemed a bit suspicious, and I dug a bit, but that's mod related and not tag related). Among the 2 other questions, I closed and deleted one, and retagged the other. Finally I renamed the tag as gtk-textbuffer. The next step is to add a tag wiki.
[ "civicrm.stackexchange", "0000002820.txt" ]
Q: Changes not saving when using other contact's address In our Joomla 3.4.1/CiviCRM 4.6.3 setup, we heavily depend on setting up households and linking people to them. For instance, if you become a contributor, the entire family is entitled to discounts, so we link the contribution to the household rather than individual people. Furthermore it helps us with duplicate entry of address information for people of the same household. The situation is so that we create a household, then create contacts and link the contacts to the household using the "Use another contact's address" feature. Recently however, after having done our initial data-entry and linking contacts to households in the above manner, I noticed that I could no longer edit most of my contact's information once their address was linked to another one. In order to test this, I logged onto the demo site and created a fresh household and a contact. Set the contact's (home) address to that of the household using the "Use another contact's address" option and saved the contact. Next I tried to edit the contact (using the 'Edit' button) and tried to enter an external ID. Upon clicking 'Save', CiviCRM says it has updated the contact, but in fact no change is visible. I currently employ one of two workarounds: 1) For fields where it is possible to get an in place 'Ajax' edit-field, I use those because when I use that the change does get saved. 2) I temporarily uncheck 'Use another contact's address', make all my changes and save, go to Edit again and re-check (and select) the household address. Of course, workaround 2 is kind of cumbersome, but unfortunately the only solution for fields that don't have an Ajax-type edit option such as External ID and contact photo. Considering that the demo site behaves the same as my own installation, I'm inclined to submit a but-report to the Jira-tracker, but I would like to know if anyone else is seeing this same issue. A: This has been confirmed as bug CRM-16588. Please consider marking this as the accepted answer, so that future Stack Exchange users with this issue can find the bug status to identify when the bug has been fixed.
[ "stackoverflow", "0024758566.txt" ]
Q: How to get correct return an array for ajax? I'm using the api dataTable and ajax. I generate an array like this: [['1','2','3'],['4','5','6']] On my return from ajax, and does not work in dataTable, but if I copy this array and put in: success: function (result) { result = [['1','2','3'],['4','5','6']]; } Example script: jQuery.ajax({ url: "<?php echo Mage::getSingleton('adminhtml/url')->getUrl('pagseguro/adminhtml_ajax'); ?>", type: "POST", data: { form_key: "<?php echo Mage::getSingleton('core/session')->getFormKey();?>", days: getDays }, success: function(result) { if (result != "") { jQuery('#htmlgrid').dataTable().fnClearTable(true); jQuery('#htmlgrid').dataTable().fnAddData(result); //jQuery('#htmlgrid').dataTable().fnStandingRedraw(); } blockModal(0); }, error: function() { blockModal(0); } }); Works, already tried dozens of ways to return in json array and do not know why to return and php does not work with the array placed physically in the script works. Example 1 php: print_r($array) = array ([0] => Array ( [date] => 15/07/2014 [id_magento] => #100000031 [status_magento] => Pendente) [1] => Array ( [date] => 15/07/2014 [id_magento] => #100000030 [status_magento] => Pendente)) Processing $array code: foreach ($array as $info) { $i = 1; $dataSet .= ($j > 1) ? ",[" : "["; foreach ($info as $item) { $dataSet .= (count($info) != $i) ? "'" . $item . "'," : "'" . $item . "'"; $i++; } $dataSet .= "]"; $j++; } $dataSet .= "]"; echo $dataSet; Example 2 php: echo json_encode($array); A: Acoording to your code you've posted. There are a PHP function and a HTTP header which you should read about. Function json_encode() Header Content-Type: application/json So you end up with something like // Tell browser it'll receive JSON data header('Content-Type: application/json'); // Parses your array as a valid JSON string echo json_encode($array);
[ "stackoverflow", "0041789461.txt" ]
Q: Regex: Ignore trailing whitespace in capturing group I am writing a simple config file parser in C++11 and want to use a regex to pick out the key=value pairs from a text file. I want to be able to support comments in this file, denoted by a # symbol. So far I have the following: ^(\w+)\s*=\s*([^#]+) This matches an alphanumeric parameter name starting at the beginning of the line, allows for optional whitespace around the = character and then captures everything up to a comment symbol. This seems to work quite well, except for in the following example: param_1 = test with comment # comment The second capturing group captures the whitespace between the end of the parameter value and the # symbol. Is there anyway I can get this to ignore any trailing whitespace in the second capturing group? A: This regex works with your example : ^(\w+)\s*=\s*([^#\n]+?)\s*(?=#|$) It is your original regex, modified to not be greedy for the second group, and match until whitespaces before a # or end-of-line are found. Here's an example.
[ "codereview.stackexchange", "0000007682.txt" ]
Q: Dynamic association generation in ActiveRecord I'm developing a Rails-based web interface/API for a large, vendor-supplied, legacy Oracle database. One of the constraints is that I can't change the schema other than adding views, because it still has to support the vendor's application. The table for customer data has a limited number of columns, and extended attributes are stored in customer_def_field_value. These attributes are defined in customer_def_field_def. so I end up with the classes: class FieldDef < ActiveRecord::Base set_table_name 'customer_def_field_def' set_primary_key :customer_def_field_def_id set_sequence_name 's_customer_def_field_def' alias_attribute :field_def_id, :customer_def_field_def_id has_many :field_values def symbol self.title.parameterize('_').to_sym end end class FieldValue < ActiveRecord::Base set_table_name 'customer_def_field_value' set_primary_keys :cust_id, :customer_def_field_def_id set_sequence_name :autogenerated alias_attribute :field_def_id, :customer_def_field_def_id belongs_to :customer, :foreign_key => :cust_id belongs_to :field_def, :foreign_key => :customer_def_field_def_id end In order to get associations on Customer for each of the 'custom fields', I have this code in the Customer class: FieldDef.find_each do |field| has_one field.symbol, :class_name => 'FieldValue', :foreign_key => :cust_id, :conditions => proc{ "customer_def_field_def_id = #{field.id}"} accepts_nested_attributes_for field.symbol delegate :field_value, :to => field.symbol, :prefix => true delegate :field_value=, :to => field.symbol, :prefix => true attr_accessor ('set_' + field.symbol.to_s).to_sym end This works like a charm, but it queries the DB every time a Customer is instantiated in order to generate the method definitions. It hasn't been a performance issue... yet. New custom field types aren't added very often, so I think I might be able to do this in an initializer rather than in my model, and just restart the application if new fields have to be added... but I wanted to get some feedback. Thanks! A: I think the query of the database would only happen once in production mode (the class would get cached, in development mode, the class gets reloaded every request that references a Customer object). You can confirm this by setting: config.log_level = :debug in your production.rb file and seeing if the query runs more than once. It might be worth having an after_save callback for FieldDef that does the same thing as the "FieldDef.find_each do |field|" block you have so you don't have to restart the server when new FieldDefs are created.
[ "stackoverflow", "0026649180.txt" ]
Q: 'Show' segue in Xcode 6 presents the viewcontroller as a modal in iOS 7 I have two view controllers in my iPhone application (built with swift) built with Xcode 6.1 and uses storyboards. The first view controller is embedded in a navigation controller in the storyboard and the segue for the second view controller is a 'Show' segue. When the application is run, it properly shows the transition as a push in iOS 8.x, but in iOS 7.x it appears as a modal without the navigation bar. My application requirement is to show the transition as a push regardless of whether it's iOS 7 or iOS 8. Any ideas to get this working as push in both versions of the iOS? I saw a related post where this issue is mentioned, but could not find a solution to the problem: Adaptive segue in storyboard Xcode 6. Is push deprecated? Any help is appreciated... Thanks A: This solution is different from the others in the following ways: It includes a method to examine and verify the issue The cause of the issue is traced to the source (a change in the segue type) The solution is very simple (delete and recreate a new segue) Please note the requirements in the text I just gave a very detailed SO answer that fully explains what is happening and why, but the simple solution is you can delete the Segue that is not pushing and then recreate it on the storyboard. The reason is that there is likely a broken bit of xml in the segue (see extended answer for example/instructions how to confirm this issue). After you confirm that you have at least one UINavigationController within the view hierarchy, be sure that the segue is NOT a manual segue and does NOT have an action associated with it (by viewing the segue in the storyboard as Source Code). Delete the existing segue and then Ctrl-drag from a UIView/UIControl to the target view controller and if custom action is needed intercept the call to destination controller in prepareForSegue. Also to confirm that this solution works for you please do the following: Verify that your initial view controller (with the arrow on it) is a UINavigationController and that it has a normal content view controller as it's root view controller. (or that you embed your initial view controller inside of a UINavigationController) Read my extended comments on an earlier response to a very similar question (linked above). A: It's possible that you have assigned the Initial View Controller to your UIViewController instead of the UINavigationController. Also, select your UIViewController and check that the "Is Initial View Controller" option is unchecked. A: Here is the workaround for that. It looks like a bug in Xcode for iOS 7. You need to create a dummy UINavigationController and link all your free UIViewControllers to this navigation controller. Worked for me.
[ "stackoverflow", "0055372245.txt" ]
Q: Multiple Bar charts on the same X-axis and Y-axis in Plotly I'm trying to plot multiple bar charts on the same x-axis and y-axis. I do not want stacked or grouped bar charts. I just want to have multiple bar charts side by side with a long x-axis where x-axis ticks repeat based on the number of bar charts and y-axis which is shared along bar charts and is placed on the leftmost side of the graph. Here is my code but it does not produce the output what I want import plotly.offline as pyo import plotly.graph_objs as go from plotly import tools trace1 = go.Bar( x=[1, 2, 3], y=[10, 11, 12] ) trace2 = go.Bar( x=[1, 2, 3], y=[100, 110, 120], ) trace3 = go.Bar( x=[1, 2, 3], y=[1000, 1100, 1200], ) fig = tools.make_subplots(rows=3, cols=1, specs=[[{}], [{}], [{}]], shared_xaxes=True, shared_yaxes=True, vertical_spacing=0.001) fig.append_trace(trace1, 3, 1) fig.append_trace(trace2, 2, 1) fig.append_trace(trace3, 1, 1) fig['layout'].update(height=600, width=600, title='') pyo.plot(fig, filename='bar-charts-with-shared-axis.html') Any help would be appreciated A: If I correctly understand, you want that: Code: import plotly.offline as pyo import plotly.graph_objs as go from plotly import tools trace1 = go.Bar( x=[1, 2, 3], y=[10, 11, 12] ) trace2 = go.Bar( x=[1, 2, 3], y=[100, 110, 120], ) trace3 = go.Bar( x=[1, 2, 3], y=[1000, 1100, 1200], ) fig = tools.make_subplots(rows=1, cols=3, shared_xaxes=True, shared_yaxes=True, vertical_spacing=0.001) fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) fig.append_trace(trace3, 1, 3) fig['layout'].update(height=600, width=600, title='') pyo.plot(fig, filename='bar-charts-with-shared-axis.html')
[ "stackoverflow", "0023293052.txt" ]
Q: Blinking Alpha Animation With no fade effect I'm trying to implement a Blink Animation. This code makes a view to blink fade in and fade out: AlphaAnimation blink = new AlphaAnimation(0.0f, 1.0f); blink.setDuration(500); blink.setStartOffset(0); //changing it makes more than one animation appear in different time stamps. blink.setRepeatMode(Animation.REVERSE); blink.setRepeatCount(Animation.INFINITE); I have two issues: setStartOffset(n); --> Changing n makes more than one animation appear in different time stamps. Not synced. I want it to be synced, all animations should appear and dissappear at same time. I do not want fade in or fade out, simply visible & gone with few millisecond delay. Is there any other Class of Animation that i had to use, or i had to make a custom animation. Pls. help. A: For animation without the fading you can create your own custom Interpolator: import android.view.animation.Interpolator; public class StepInterpolator implements Interpolator { float mDutyCycle; public StepInterpolator(float dutyCycle) { mDutyCycle = dutyCycle; } @Override public float getInterpolation(float input) { return input < mDutyCycle ? 0 : 1; } } Then set the interpolator in the Animation object: blink.setInterpolator(new StepInterpolator(0.5f)); A: So, my answer ... it's a class that toggles visibility of a view in a certain interval. Of course it can be solved differently, maybe you get some inspiration... public static class ViewBlinker { private Handler handler = new Handler(); private Runnable blinker; public ViewBlinker(final View v, final int interval) { this.blinker = new Runnable() { @Override public void run() { v.setVisibility(v.getVisibility()==View.VISIBLE?View.INVISIBLE:View.VISIBLE); handler.postDelayed(blinker, interval); } }; } public void startBlinking() { handler.post(blinker); } public void stopBlinking() { handler.removeCallbacks(blinker); } } and you use it like this : ViewBlinker blinker = new ViewBlinker(YOUR_BLINK_VIEW, YOUR_BLINK_INTERVAL); blinker.startBlinking(); and when your view is finished blinking, call blinker.stopBlinking();
[ "stackoverflow", "0039869932.txt" ]
Q: Windbg disassembler address resolution I was analysing a complete memory dump and I applied Windbg uf command to see what a function does 0: kd> uf profsvc!CUserProfileService::_RegisterGPNotification This is the part of the output. I wonder why the address in parentheses is different than the address of profsvc!CUserProfileService::_RegisterGPNotification+0x44 which should be 000007fe fb149276 but is 000007fe fb155019. When I try to unassembled the address 000007fe fb155019 with u it points to profsvc!CUserProfileService::_RegisterGPNotification+0x44: I’m really puzzled, any help deeply appreciated. OUTPUT from WinDBG …. profsvc!CUserProfileService::_RegisterGPNotification+0x2e: 000007fe`fb14925e ba01000000 mov edx,1 000007fe`fb149263 488bc8 mov rcx,rax 000007fe`fb149266 ff157c410200 call qword ptr [profsvc!_imp_RegisterGPNotification (000007fe`fb16d3e8)] 000007fe`fb14926c 85c0 test eax,eax 000007fe`fb14926e 0f84a5bd0000 je profsvc!CUserProfileService::_RegisterGPNotification+0x44 (**000007fe`fb155019**) profsvc!CUserProfileService::_RegisterGPNotification+0x40: 000007fe`fb149274 33db xor ebx,ebx 000007fe`fb149276 eb00 jmp profsvc!CUserProfileService::_RegisterGPNotification+0x66 (000007fe`fb149278) Branch profsvc!CUserProfileService::_RegisterGPNotification+0x66: 000007fe`fb149278 488b0d31b00200 mov rcx,qword ptr [profsvc!WPP_GLOBAL_Control (000007fe`fb1742b0)] 000007fe`fb14927f 488d052ab00200 lea rax,[profsvc!WPP_GLOBAL_Control (000007fe`fb1742b0)] 000007fe`fb149286 483bc8 cmp rcx,rax 000007fe`fb149289 740a je profsvc!CUserProfileService::_RegisterGPNotification+0x94 (000007fe`fb149295) Branch 0: kd> u 000007fe`fb155019 profsvc!CUserProfileService::_RegisterGPNotification+0x44: 000007fe`fb155019 ?? ??? ^ Memory access error in 'u 000007fe`fb155019' A: This is due to optimization, see the following MSDN article: https://msdn.microsoft.com/en-us/library/windows/hardware/ff541382(v=vs.85).aspx
[ "pm.stackexchange", "0000002782.txt" ]
Q: How can you limit the hours entered for a specific task in Microsoft Project Server? I have projects where I want a task to have a set number of hours charged to it. If three people are charging to the project, 8 hours a day, and I specify that the project can only have 40 hours charged to it. Then all three of them can charge the first day, and then two of them will charge the next day, but the third one will have to charge to another task. Is this possible? A: I cannot find any way to do this in Microsoft Project Server 2007. I do not have a Microsoft Project Server 2010 installation so I can't tell you for that system. However, In my experience tightly linking your project management tracking system to your billing system like this not a good idea. I have always viewed project management systems as ways to estimate, track my estimates to reality, and improve my estimates for the next time. Client billing and getting paid for my work was a discrete process. Even when the team's time sheet system was used to track project execution, I would adjust the billing and not the project tracking.
[ "stackoverflow", "0004254509.txt" ]
Q: difference between the following In order to prevent another command windows from showing, I have tried the following two methods 1) StartInfo.UseShellExecute = true; StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 2) StartInfo.UseShellExecute = false; Is there any pros and cons of those usage? A: There are many advantages of setting StartInfo.UseShellExecute to false. One of which is if you can redirect standard input,standard output and standard error and read those streams. This is very useful when something goes wrong. By reading standard error stream you can determine whether any error had occured or not. For more information on shellExecute follow this link About StartInfo.WindowStyle property, if we keep it to false command prompt pops up when process starts. If your application has nice,rich UI and then suddenly one black window pops up, it will annoy users plus some users might try to close command prompt before process exits.. and there are many more reasons for keeping window hidden.
[ "stackoverflow", "0041299288.txt" ]
Q: Firebase Storage: String does not match format 'base64': Invalid character found I'm working on a react-native and I need to upload an image to Firebase using Firebase Storage. I'm using react-native-image-picker to select the image from the phone which gives me the base64 encoded data. When I try to upload the image to Firebase it gives me the error Firebase Storage: String does not match format 'base64': Invalid character found but I already checked if the string is a valid base64 string with regex and it is! I already read a few answers from here but I tried all that. Here's my code: function uploadImage(image){ const user = getCurrentUser(); const refImage = app.storage().ref(`profileImages/${user.uid}`); refImage.putString(image, 'base64').then(() => { console.log('Image uploaded'); }); } The image picker: ImagePicker.showImagePicker(ImageOptions, (response) => { if (response.didCancel) { console.log('User cancelled image picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { uploadImage(response.data); } }); A: if image is a base64 data URL you can use 'data_url' parameter and metadata: function uploadImage(image){ const user = getCurrentUser(); const refImage = app.storage().ref(`profileImages/${user.uid}`); refImage.putString(image, 'data_url', {contentType:’image/jpg’}).then(() => { console.log('Image uploaded'); }); } A: you need to remove this string from your image variable "data:image/jpeg;base64,. need only data A: image.substring(23) function uploadImage(image){ const user = getCurrentUser(); const refImage = app.storage().ref(`profileImages/${user.uid}`); refImage.putString(image.substring(23), 'base64').then(() => { console.log('Image uploaded'); }); }
[ "stackoverflow", "0050936869.txt" ]
Q: Intercepting HttpErrorResponse and redirecting user to login page I'm trying to redirect the user to the login page every time the login fails. I've set up an interceptor to handle Http responses: export class HttpInterceptor implements HttpInterceptor { intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(request).do((event: HttpEvent<any>) => {}, (err: any) => { if (err instanceof HttpErrorResponse) { console.log("http error intercepted") } }); } } However, the error I get is "property do does not exist on type observable>". I'm also confused as to how I would redirect the user back to the login page from the interceptor. How can I address this? Any help would be much appreciated, thank you! A: Here is an example of what you are trying to accomplish, but this uses pipe and the newer tap operator, which is the replacement for the do operator. import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; @Injectable() export class HttpInterceptor implements HttpInterceptor { intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(request).pipe( tap( event => event instanceof HttpResponse ? 'succeeded' : '', error => { if (error instanceof HttpErrorResponse) { console.log('http error intercepted') } }) ); } } FYI: This compiles, but I have not tested it.
[ "stackoverflow", "0015128046.txt" ]
Q: How do you create a templates folder when you're working with Flask? http://flask.pocoo.org/docs/quickstart/#a-minimal-application When the instructions under "Rendering Templates" directs you to create a templates folder, where exactly do you make it? In your project directory? And how? Thanks! A: If you had read a bit further down in the link you pasted, you would have found: Flask will look for templates in the templates folder. So if your application is a module, this folder is next to that module, if it’s a package it’s actually inside your package: Case 1: a module: /application.py /templates /hello.html Case 2: a package: /application /__init__.py /templates /hello.html The most common is case 1 - for which you simply create a directory called templates and add your templates there. Nothing special about it.
[ "stackoverflow", "0018876471.txt" ]
Q: Oracle Code to insert data into table that doesn't exist I am trying to insert data into a table in Oracle database. Data already exists, but not all of the data, and I can't just delete the data and reinsert it all. Is there a way to insert data into the table (without knowing what data I am missing). My script is running, but no data is actually inserting (and I do know there is data missing. I intentionally took data out to test its re-insertion.) Insert into item (item, descr) select distinct a.SUBORD, a.SUBORD_DESCR FROM EXIDE.UDT_BOM a, item b where b.item = a.subord and not exists (select b.item from item b, exide.udt_bom a where a.subord = b.ITEM) A: If I follow what you're doing, you can use the merge statement for this: merge into item i using (select subord, subord_descr from exide.udt_bom) u on (i.item = u.subord) when not matched then insert (item, descr) values (u.subord, u.subord_descr); SQL fiddle demo. This also has the advantage that if the udt_bom has new descriptions for existing items, you can update those in the item table too: merge into item i using (select subord, subord_descr from exide.udt_bom) u on (i.item = u.subord) when matched then update set descr = u.subord_descr when not matched then insert (item, descr) values (u.subord, u.subord_descr); Another fiddle.
[ "stackoverflow", "0059795494.txt" ]
Q: bison grammar execution order I have a grammar like this: A : a B {int i = 0; printf("%d",i);}; B: and b B {i++; printf("%d",i);} | %empty ; input a and b and b and b output : 1230 my question is : how to change the order of execution to have 0123 A: Use left recursion instead of right recursion. Bison executes actions exactly in the way you tell it to. Each non-terminal's action is executed exactly as soon as the non-terminal is completed. If you use a right-recursive rule: B: "and" b B then the outer B's action, which prints the semantic value of b, executes after the inner B's action, which prints the semantic values of the bs which follow. A much more natural way to write that grammar, which has the further advantage of producing correct associativity, is: A: a | A "and" b Moreover, the actions in that grammar will execute left-to-right, because the inner A's action is executed as soon as it is complete, which is before the associated b has even been seen.
[ "math.stackexchange", "0000203485.txt" ]
Q: How to define difference quotients for Sobolev functions There is a definition for difference quotients of Sobolev functions I do not understand. Let $U\subset\Omega\subset\mathbb{R}^n$ be open sets such that the closure of $U$ is compact in $\Omega$ and let $h\in\mathbb{R}$ with $0<|h| < \mbox{dist}(U,\partial\Omega)$. Then one defines a function $\partial^h_i u$ on $U$ by $\partial_i^h u(x) := \frac{u(x+he_i) - u(x)}{h}$, (where $e_1,\dots,e_n$ is the standard basis of $\mathbb{R}^n$), see e.g. [1]. But how can one even define this? One must be able to evaluate $u$ at $x$ and $x+he_i$, but since $u$ is only an $L^p$-function, point evaluation is not even well defined. One needs higher regularity, I assume - an unique continuous representative of $u$ which can be evaluated. But no mention of such higher regularity is made in [1] (and the other texts on PDEs I'm reading) where such difference quotients are used. So I guess that no such higher regularity is needed after all? Am I missing something obvious here? Why can one define $\partial_i^h u$ in such a way? Could you please give me a hint why this definition works or recommend me some literature on this? Thank you in advance! Reference: [1] Lawrence C. Evans, "Partial Differential Equations", 5.8.2. There, Evans defines $\partial_i^hu$ for 'locally summable functions' but uses it for $W^{1,p}$ functions. A: To avoid any discussion of representatives and equivalences, one can introduce translation operators $\tau_h f = f(\cdot +he_i)$. This operator is originally defined on continuous functions, but is immediately seen to be bounded on $W^{1,p}$ (and on pretty much every un-weighted function space), though some care needs to be taken with the domain of the function (it's best to consider functions on $\mathbb R^n$ first). Thus, $\tau_h$ uniquely extends to a bounded operator on $W^{1,p}$. The operator-based approach also allows one to handle the issue of boundary values (traces), where the equivalence classes do not help much. A: This actually doesn't define $\partial_i^hu$ as an usual function, but as an equivalence class of functions. It is well-defined, as if $u_1=u_2$ almost everywhere, $u_1(x+he_i)=u_2(x+he_i)$ for almost every $x$ which gives that $\partial_i^hu_1(x)=\partial_i^hu_2(x)$ for almost every $x$.
[ "stackoverflow", "0061478290.txt" ]
Q: How can I open a local PDF file using a SwiftUI button? I want to display a local PDF file through a new view when I tap a button. I tried doing that using a UIViewRepresentable WebView but it's not working (I have worked with WebView only through NavigationList). I leave my code, but feel free to suggest better option if the WebView is not the most optimal. ButtonView import SwiftUI struct ResumeView: View { let sfSymbol: String let text: String let fileUrl = Bundle.main.path(forResource: "Resume", ofType: "pdf") var body: some View { RoundedRectangle(cornerRadius: 25) .fill(Color.white) .frame(height: 50.0) .overlay( HStack { Image(systemName: sfSymbol) .foregroundColor(.init(red: 0.20, green: 0.33, blue: 0.55, opacity: 1.00)) Button(action: { WebView(urlString: self.fileUrl) }) { Text(text) .foregroundColor(.black) } }) } } WebView import Foundation import SwiftUI import WebKit struct WebView: UIViewRepresentable { let urlString: String? func makeUIView(context: Context) -> WKWebView { return WKWebView() } func updateUIView(_ uiView: WKWebView, context: UIViewRepresentableContext<WebView>) { if let safeUrlString = urlString { if let url = URL(string: safeUrlString) { let request = URLRequest(url: url) uiView.load(request) } } } } A: Using PDFKit we load local PDF file. Please try below code. import SwiftUI struct ResumeView: View { .... let fileUrl = Bundle.main.url(forResource: "Resume", withExtension: "pdf")! var body: some View { .... Button(action: { PDFKitView(url: self.fileUrl) }) { Text(text) .foregroundColor(.black) } .... } } PDFKitView import PDFKit struct PDFKitView: View { var url: URL var body: some View { PDFKitRepresentedView(url) } } struct PDFKitRepresentedView: UIViewRepresentable { let url: URL init(_ url: URL) { self.url = url } func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType { let pdfView = PDFView() pdfView.document = PDFDocument(url: self.url) pdfView.autoScales = true return pdfView } func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) { // Update the view. } }
[ "stackoverflow", "0014659008.txt" ]
Q: Google Places AutocompleteService filtering by country I'm setting up a custom autocomplete field where I show locations from Google Places and events from my database that match the search query. For this reason, I'm using the Google Places Autocomplete Service to get the query predictions rather than plugging in the Places Autocomplete directly into my textfield. The problem is I can't figure out how to filter Places Autocomplete suggestions by country using the AutoComplete service. I've tried: var service = new google.maps.places.AutocompleteService(null, { types: ['cities'], componentRestrictions: {country: "au"} }); but it still shows autocomplete options from Germany and France:( Any suggestions? A: You need to pass the restrictions when you call the service, not when you create it. Here: //create service service = new google.maps.places.AutocompleteService(); //perform request. limit results to Australia var request = { input: 'Brisbane', componentRestrictions: {country: 'au'}, }; service.getPlacePredictions(request, callback); A: You can specify types, and componentRestrictions using AutocompletionRequest. Here is an example - var service = new google.maps.places.AutocompleteService(); service.getPlacePredictions({ input: query, types: ['geocode'], componentRestrictions:{ country: 'us' } }, function (predictions, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { var results = document.getElementById('results'); for (var i = 0, prediction; prediction = predictions[i]; i++) { results.innerHTML += '<li>' + prediction.description + '</li>'; } } });
[ "ru.stackoverflow", "0000665152.txt" ]
Q: Как отключить "тень" при свайпе? Когда тянешь пальцем экран вертикально, дотягиваешь до края и тянешь дальше, начинает проявляться полукруглая тень. Есть ли возможность её отключить? A: Нашёл ответ. В ScrollView: android:overScrollMode="never"
[ "stackoverflow", "0039318110.txt" ]
Q: Invoke jQuery from action form From a HTML form, I invoke a jQuery method, triggering an alert message and make an image become visible, but the image disappears after a second? This is my form: <form action= "jquery.php" method="post" > <label for="farfar">Farfar:</label> <input type="text" placeholder="farfar" name="farfar"> <input type="submit" value="Tilføj"> </form> In the file jquery.php, I have the following script: $(document).ready(function(){ $("form").submit(function(){ alert("Submitted"); $(".ff").show(); }); }); And I have made a PHP script: <?php $farfar = $_POST['farfar']; ?> The image is a class (outside the script): img class ="ff" src="human.png"... In my CSS file, I have set the current value on images. img { display: none; position: relative; } Now, when I load the page and give the form a value, the jQuery is properly invoked, the alert message is shown and the image shows. But only for 1 second or so, then it disappears again. What am I doing wrong? and how can I make the image stay on the screen? A: The reason your image disappears is that your page POSTs and that changes the content of the page. I am not sure which URL you're POSTing your for to but you could try POSTing the form to self, then might work. Or you could also use jQuery to POST the form via async so the page does not load.
[ "stackoverflow", "0022847927.txt" ]
Q: Access/Excel VBA: Getting the two dates corresponding to last week I think I can do this with a loop but since I am using this in conjunction with MS Access I wondered if there was a quick way to do this. Right now it is April 3rd, 2014. I want to be able to return the dates corresponding to the Sunday and Saturday that bookend the previous week. So for example that would be March 23rd (Sunday) through March 29th (Saturday) last week. A: In Excel formulae: =TODAY()-WEEKDAY(TODAY())-6 'Sunday of last week =TODAY()-WEEKDAY(TODAY()) 'Saturday of last week =TODAY()-WEEKDAY(TODAY())+6 'Friday of current week In VBA: Date()-Weekday(Date())-6 'Sunday of last week Date()-Weekday(Date()) 'Saturday of last week Date()-Weekday(Date())+6 'Friday of current week
[ "stackoverflow", "0058032753.txt" ]
Q: :host background color not set, but font size increased? In this demo apply the following CSS to the :host element, or <hello>, the font size is increased, but the background color is not changed. Thoughts: styles: [` :host { font-size: 2rem; background-color: yellow; }`] }) A: Custom elements are displayed inline by default in the browser. Just add display: block.
[ "stackoverflow", "0042769432.txt" ]
Q: How to save the background colour to local storage? I'm using a select box with font sizes and a colour picker to allow a user to select a preferred header background colour as well as the font size. The font size is saving to the local storage as expected and updating when the page is re-visited (although I'd prefer it to be already changed rather than animating to the new size). However, I've done the backfground colour the exact same way but when I change the colour, it works once but returns back to it's previous colour when the oage is re-opened. HTML: <header class="siteHeader"> <div id="container"> <select id="change_font_size"> <option value="225">225</option> <option selected value="250">250</option> <option value="300">300</option> <option value="350">350</option> </select> <p style="float: left;">A+/-</p> <input type="color" id="colour_picker"> <p style="float: right;">Background colour:</p> </div> <nav> <ul> <li><a href="menu.html">MENU</a></li> <li><a href="burritos.html">BURRITOS</a></li> <li><a href="index.html"><img class="header-image" src="assets/Headerlogo1.png"></a></li> <li><a href="contact.html">CONTACT</a></li> <li><a href="about.html">ABOUT</a></li> </ul> </nav> </header> JS: $(document).ready(function () { var font_size = localStorage.getItem("font_size"); $('.siteHeader').css("font-size", font_size + "%"); var background_colour = localStorage.getItem("background_colour"); $('.siteHeader').css("background-color", background_colour); $("#change_font_size").change(function () { var font_size = $(this).val(); $('.siteHeader').css("font-size", font_size + "%"); localStorage.setItem("font_size", font_size); }); $('#colour_picker').change(function () { var background_colour = $(this).val(); $('.siteHeader').css("background-color", background_colour); localStorage.setItem("background_color", background_colour); }); }); A: You're setting it as "background_color" and attempting to retrieve it as "background_colour".
[ "stackoverflow", "0057084646.txt" ]
Q: Could Android EditText be target of XSS when loading a text? Is there any unsafe strings that may be placed into an EditText using setText() ? Recently our app was subject to a security Scanner and EditTexts loading a text from another EditText raised an Reflected XSS alert. I understand that this may be a vulnerability on webviews and websites in general that may alter the constructed HTML DOMS or even execute javascript. I imagine the only way this may affect an android app is if the second EditText's text is processed later in a way the programmer isn't expecting. A: Is there any unsafe strings that may be placed into an EditText using setText() ? Not really. As you note, there may be problems in how you use what the user fills into the EditText, but the EditText itself is not scriptable and so is not really a vehicle for attack. Recently our app was subject to a security Scanner and EditTexts loading a text from another EditText raised an Reflected XSS alert. I am not aware of any XSS attacks relevant to Android native UIs (outside of WebView). After all, "XSS" is shorthand for "cross-site scripting", and there are no "sites" for Android native UIs. IMHO, many online security scanners are snake oil.