source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0019539781.txt" ]
Q: How to do unit testing in efficient way The following is my method User UpdateUser(User user) { } Whenever To test this method, I do testing like following. Nearly I wrote 20 to 30 test cases. In that, I used following method. For each testcase I've created User object and give necessary input and also give wrong input to check and finally I'll delete user details which is updated in DB. for example [TestMethod] void test1() { try { // Here will call updateUser and do necessarry check } finally { // here I'll delete user details from DB } } [TestMethod] void test2() { try { // Here will call updateUser and do necessarry check } finally { // here I'll delete user details from DB } } Is that Correct way of unit testing ? Because, If i use TestInitialize, that's also called for each test cases. Am I doing in correct way or is there any other method ? A: No, this is not a correct way, because this is no longer unit testing, but rather integration tests. Unit testing should NEVER touch the database. but instead use mocks and stubs to imitate the behavior. If your question is about integration tests, then it's kinda opinion based. It depends on your needs and preferences, as long as it does what you need. I've seen multiple approaches how to handle a situation like this. The most important thing to do is to be consistent. Once you choose one approach, stick with it until the project is finished, so you don't mix multiple programming styles.
[ "stackoverflow", "0027313964.txt" ]
Q: Flush Mode hibernate utility I try to understand the difference between different hibernate FlushMode. For this, I created a small example of insertion. session.beginTransaction(); session.setFlushMode(FlushMode.AUTO);// I tried ALWAYS AND MANUAL for (int i = 1; i < 4; i++) { Stock stock = new Stock(); stock.setStockId(i); stock.setStockCode("code-"+i); stock.setStockName("name-"+i); session.save(stock); System.out.println("entity saved"); } session.getTransaction().commit(); The problem I always have the same behavior as if the flushMode is set to COMMIT. entity saved entity saved entity saved insert into stock (STOCK_CODE, STOCK_NAME, STOCK_ID) values (?, ?, ?) insert into stock (STOCK_CODE, STOCK_NAME, STOCK_ID) values (?, ?, ?) insert into stock (STOCK_CODE, STOCK_NAME, STOCK_ID) values (?, ?, ?) while I was expecting to have entity saved insert into stock (STOCK_CODE, STOCK_NAME, STOCK_ID) values (?, ?, ?) entity saved insert into stock (STOCK_CODE, STOCK_NAME, STOCK_ID) values (?, ?, ?) entity saved insert into stock (STOCK_CODE, STOCK_NAME, STOCK_ID) values (?, ?, ?) Anyone have an explanation why I have always the same result? A: What I found, after several test, is that session does not happen before every query beacause the purpose of the Hibernate session is to minimise the number of writes to the database, so it will avoid flushing to the database if it thinks that it isn’t needed even explicitly calling session.flush(). This is confirmed in org.hibernate.Session docs Except when you explicitly flush(), there are absolutely no guarantees about when the Session executes the JDBC calls, only the order in which they are executed. However, Hibernate does guarantee that the Query.list(..) will never return stale or incorrect data. Finally to see the difference between the flush modes, do not act on a single entity because hibernate thinks that it will not be useful to flush. So I added a Query in my loop to force Hibernate to flush. The code below does not flush although the mode used is ALWAYS session.beginTransaction(); session.setFlushMode(FlushMode.ALWAYS ); for (int i = 1; i < 4; i++) { Stock stock = new Stock(); stock.setStockId(i); stock.setStockCode("code-"+i); stock.setStockName("name-"+i); session.save(stock); System.out.println("entity saved"); } session.getTransaction().commit(); output : entity saved entity saved entity saved insert into stock (STOCK_CODE, STOCK_NAME, STOCK_ID) values (?, ?, ?) insert into stock (STOCK_CODE, STOCK_NAME, STOCK_ID) values (?, ?, ?) insert into stock (STOCK_CODE, STOCK_NAME, STOCK_ID) values (?, ?, ?) Now, if I add after the System.out.println("entity saved"); Query query = session.createQuery("from StockDailyRecord"); query.list(); The output will be : entity saved insert into stock (STOCK_CODE, STOCK_NAME, STOCK_ID) values (?, ?, ?) select stockdaily0_.STOCK_REC_ID as STOCK_RE1_1_ from stock_daily_record stockdaily0_ entity saved insert into stock (STOCK_CODE, STOCK_NAME, STOCK_ID) values (?, ?, ?) select stockdaily0_.STOCK_REC_ID as STOCK_RE1_1_ from stock_daily_record stockdaily0_ entity saved insert into stock (STOCK_CODE, STOCK_NAME, STOCK_ID) values (?, ?, ?) select stockdaily0_.STOCK_REC_ID as STOCK_RE1_1_ from stock_daily_record stockdaily0_
[ "stackoverflow", "0043971876.txt" ]
Q: How to make next repeated values as a blank if the value appears greater then 3 times I have a data frame as below. In the data frame the value "45" repeating/appears for "A" greater than 3 times and also same for "67" for "B", Now needs to make them as "Blank/NA" for those which are repeating / frozen greater than 3 times ("New_value") Name Value New_Value A 24 24 A 45 45 A 45 A 45 A 45 A 45 A 93 93 A 19 19 A 10 10 B 29 29 B 67 67 B 67 B 67 B 67 C 201 201 C 993 993 C 396 396 A: FWIW, here is another data.table solution using rleid() instead of duplicated(). Note that the OP requested to make next repeated values as a blank if the value appears greater then 3 times. This implies that for a Value which is repeated exactly two times no blanks should appear in the result. I've amended my sample data set to include the case of exactly two repetitions of the same value. Edit: The OP hasn't made it clear whether he is counting repetitions of the same Value in the given sequence regardless of Name or if he is counting repetitions in the sequence per Name group. See also this comment. In addition, the OP hasn't specified what result he expects if there's a sequence of repeated Values but with a change in Name. Therefore, I've modified my sample data set to include the additional use cases as well: DT # Name Value # 1: A 24 # 2: A 24 # 3: A 45 # 4: A 45 # 5: A 45 # 6: A 45 # 7: A 45 # 8: A 93 # 9: A 19 #10: A 19 #11: A 10 #12: B 29 #13: B 67 #14: B 67 #15: B 67 #16: B 67 #17: C 201 #18: C 993 #19: C 396 #20: A 19 #21: A 19 #22: C 19 #23: B 29 #24: B 67 #25: B 67 #26: B 67 #27: B 67 #28: C 67 #29: C 67 #30: C 67 #31: C 67 # Name Value As in the other answers, NA is taken for blank. library(data.table) setDT(DT)[, New := Value[.N < 3], by=rleid(Value)][rowid(rleid(Value)) == 1L, New := Value] DT # Name Value New # 1: A 24 24 # 2: A 24 24 # 3: A 45 45 # 4: A 45 NA # 5: A 45 NA # 6: A 45 NA # 7: A 45 NA # 8: A 93 93 # 9: A 19 19 #10: A 19 19 #11: A 10 10 #12: B 29 29 #13: B 67 67 #14: B 67 NA #15: B 67 NA #16: B 67 NA #17: C 201 201 #18: C 993 993 #19: C 396 396 #20: A 19 19 #21: A 19 NA #22: C 19 NA #23: B 29 29 #24: B 67 67 #25: B 67 NA #26: B 67 NA #27: B 67 NA #28: C 67 NA #29: C 67 NA #30: C 67 NA #31: C 67 NA # Name Value New The first expression copies Value for all RLE groups with one or two repetitions. All RLE groups with more repetitions get NA. The second expressions copies Value only for the first row in each RLE group. Note that each sequence of repeated values is treated separately regardless of Name but the change of A to C in row 22 and ofB to C in row 27 is being ignored. This can be further improved to copy only if not already copied: setDT(DT)[, New := Value[.N < 3], by=rleid(Value) ][is.na(New) & rowid(rleid(Value)) == 1L, New := Value] In case the change in Name is expected to "restart" Value as well this variant could be used (credits to Jaap): setDT(DT)[, New := Value[.N < 3], by = rleid(Name, Value) ][is.na(New) & rowid(rleid(Name, Value)) == 1L, New := Value][] # Name Value New # 1: A 24 24 # 2: A 24 24 # 3: A 45 45 # 4: A 45 NA # 5: A 45 NA # ... #18: C 993 993 #19: C 396 396 #20: A 19 19 #21: A 19 19 #22: C 19 19 #23: B 29 29 #24: B 67 67 #25: B 67 NA #26: B 67 NA #27: B 67 NA #28: C 67 67 #29: C 67 NA #30: C 67 NA #31: C 67 NA # Name Value New Note the difference in rows 21, 22, and 27. Data DT <- structure(list(Name = c("A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "C", "C", "C", "A", "A", "C", "B", "B", "B", "B", "B", "C", "C", "C", "C"), Value = c(24L, 24L, 45L, 45L, 45L, 45L, 45L, 93L, 19L, 19L, 10L, 29L, 67L, 67L, 67L, 67L, 201L, 993L, 396L, 19L, 19L, 19L, 29L, 67L, 67L, 67L, 67L, 67L, 67L, 67L, 67L)), .Names = c("Name", "Value"), row.names = c(NA, -31L), class = "data.frame") Note that rows 1 and 8 have been duplicated w.r.t. the OP's data set to cover the case of exactly two repetitions and that a fews rows have been added at the end.
[ "stackoverflow", "0016694140.txt" ]
Q: how to slow down listing hover effect using jquery i am a poor programmer can some 1 help me out with this problem.when i mouseover on "when you click here" rest of the ul slides down when i mouse out slide up up till here its working good .but when i mouseover on mu ul "we" text it needs to stay and when i mouse out from the text "we" it should slide up.but in my code when i mouseover on text "we" it stays when i mouse out it stays back insted of sliding up.can any one help me please.here is js fiddle for my code <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script src="http://code.jquery.com/jquery-1.7.1.js"></script> <script type="text/javascript"> $(document).ready(function(){ //alert('fdsafdasfdas'); $("#aaaaa").mouseover( function() { //alert('ssss'); var lis = $(this).next('ul').find('li'); $(lis).each(function(index) { var li = $(this); setTimeout(function() { li.slideDown(1000); }, 10 * index); }); }); $("#aaaaa").mouseout( function() { //alert('ssss'); var bu=$(this).next('ul').find('li'); $(bu).each(function(index) { var bu1 = $(this); setTimeout(function() { bu1.slideUp(1000); }, 10 * index); }); }); $("#dropdown").mouseout( function() { //alert('out'); var bu=$(this).next('ul').find('li'); $(bu).each(function(index) { var bu1 = $(this); setTimeout(function() { bu1.slideUp(1000); }, 10 * index); }); }); $("#bag").mouseenter( function() { $("#aaaaa").mouseout( function() { //alert('opopopopopopo'); var bu=$(this).next('ul').find('li'); $(bu).each(function(index) { var bu1 = $(this); setTimeout(function() { bu1.stop(1000); }, 10 * index); }); }); //alert('ssss'); setTimeout(function() { bu1.delay(5000); }, 10 * index); }); $("#bag").mouseout( function() { var bu=$(this).next('li'); $(bu).each(function(index) { var bu1 = $(this); setTimeout(function() { bu1.slideUp(1000); }, 10 * index); }); }); }); </script> #dropdown li { display:none; } <div id="dropdown" style="width:200px; border:solid 1px #000;"> <div id="aaaaa">when you click here</div> <ul id="bag" style="width:200px;position:relative;top:-10px;"> <li id="bag">We</li> <li id="bag">We</li> <li id="bag">We</li> <li id="bag">We</li> <li id="bag">We</li> </ul> </div> A: What about this? <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#aaaaa").mouseenter( function() { $("#bag").slideDown(1000); }); $("#aaaaa").mouseleave( function() { $("#bag").slideUp(1000); }); }); </script> Here the clean code lines (incl HTML): http://jsfiddle.net/LFKxF/11/
[ "superuser", "0000096242.txt" ]
Q: Unprotect a Word Document Possible Duplicate: Can’t edit a specific document in Word 2007 How do I remove the password protection (unprotect) on a Word document if I don't know the password? (i.e. The protection provided by Tools > Unprotect Document) A: One possible solution. I think there are others as well. Open a protected document in MS Word Save as "Web Page (*.htm; *.html)", close Word Open html-document in any Text-Editor Search <w:UnprotectPassword> tag, the line reads something like that: <w:UnprotectPassword>ABCDEF01</w:UnprotectPassword> (password is already in hex-format) Keep the "password" in mind Open original document (.doc) with any hex-editor Search for hex-values of the password, which is stored in reverse order. (e.g. If password is 0xAB 0xCD 0xEF 0x01. Then the password is in the .doc file as 0x01 0xEF 0xCD 0xAB) Overwrite all 4 double-bytes with 0x00, Save, Close Open document with MS Word, Select "Tools / Unprotect Document" (password is blank) A: Save the file in Rich text format RTF Open the file with WordPad Save the RTF file with a different name Open the new RTF file with Word Save the document as a word document Delete the two rtf files
[ "superuser", "0000806720.txt" ]
Q: How to Delete Mac from PC I just got to know that it is illegal to run Mac OS X on my PC. I already have Windows 8.1 installed, and I just formatted the Mac OS X HDD Drive. When I boot my computer on it takes me to the Mac OS X Boot Loader and it says boot failed and says no Operating System found, but when I put my USB on, it takes me to Niresh Menu, where I can select my Drive to boot Windows 8.1. I am in need of serious help. A: You could repair the Windows Bootloader from the Advanced Startup Options. Here is a tutorial on how to enter the Advanced Startup. The easiest way should be to boot from a Windows 8 installation media (DVD or bootable USB drive). Then, select Troubleshooting and look for something like 'Startup repair'. The process should be able to repair the Bootloader, so your computer can boot on Windows 8. Hope this helps !
[ "stackoverflow", "0025224020.txt" ]
Q: solve Equation a+b+c+d=a*b*c*d Hello i am trying to solve this equation for a programming problem that states that you need to do a complete search algorithm to find this results. However an O(N^4) algorithm takes a lot of time, since the range for each value of A,B,C, and D, is (0,2000] . so we can say A<=B<=C<=D i want to make my algorithm faster translating it to a O(n^3) solution. For doing that i am taking into account certain things with A,B and C to make the algorithm runs a little faster (prunning). But the main issue is to take out the search of D, i have read some solutions for a similar problem and the way they find D derivating it from A+B+C=A*B*C is really confusing, can somebody explain to me the O(N^3) solution to this problem? thanks a lot! A: The equation A * B * C * D == A + B + C + D has just one solution 1 1 2 4 So time complexity is O(1). Since A <= B <= C <= D, A + B + C + D <= 4 * D hence A * B * C * D <= 4 * D and A * B * C <= 4 Therefore, it is enough to check just a few combinations: for(int a = 1; a <= 4; a++) for(int b = a; b <= 4; b++) for(int c = b; c <= 4; c++) { // a*b*c*d == a+b+c+d // => d == (a+b+c) / (a*b*c - 1) if(a * b * c - 1 != 0 && (a + b + c) % (a * b * c - 1) == 0) { int d = (a + b + c) / (a * b * c - 1); if (d >= c) Console.WriteLine("{0} {1} {2} {3}", a, b, c, (a + b + c) / (a * b * c - 1)); } } A: Equivalently d = (a+b+c)/(abc-1). Now just walk over all values of a, b, and c, seeing which ones return an integer value for d. Furthermore a+b+c < abc-1 when a,b,c >= 2. Should shorten your search time quite a bit...
[ "stackoverflow", "0057378957.txt" ]
Q: How to compose (combine) several function calls with arguments My full question sound this way: How to compose (combine) several function calls with arguments without using partial. Right now current code below works fine, but I need to call partial every time any additional argument is provided: from functools import partial def pipe(data, *funcs): for func in funcs: data = func(data) return data def mult(data, amount=5, bias=2): return data*amount + bias def divide(data, amount, bias=1): return data/amount + bias result = pipe(5, mult, partial(divide, amount=10) ) print(result) # 3.7 But I would like to partial to be called inside of pipe function. So calling should start looking this way: result = pipe(5, mult, divide(amount=10) ) A: Here's an implementation that may help you. It's a decorator to use on functions so that you can create partial function by calling the function itself, rather than partial(func, ...): from functools import partial, wraps def make_partial(func): @wraps(func) def wrapper(*args, **kwargs): return partial(func, *args, **kwargs) return wrapper With any function that you want your behaviour with, decorate it like so: @make_partial def divide(data, amount, bias=1): return data/amount + bias Now you can call pipe as you describe as calling divide(amount=10) now returns a partial too. result = pipe(5, mult, divide(amount=10)) It would be difficult to make the partial call within pipe as you would somehow need to pass in the desired function and its default arguments without calling it. This method tries to eliminate this and keep your existing functions clean. The only other way I can suggest is that you pass a list of functions, a list of lists of partial args and a list of dicts of keyword arguments. Your function signature would be pipe(data, funcs, args, kwargs). def pipe(data, funcs, args, kwargs): for func, arg_list, kwarg_list in zip(funcs, args, kwargs): data = partial(func, *arg_list, **kwarg_list)(data) return data To call pipe, it gets a bit more complicated: result = pipe( 5, [mult, divide], [[], []], [{}, {'amount': 10}] )
[ "stackoverflow", "0031829312.txt" ]
Q: Bootstrap dropdown clipped by overflow:hidden container, how to change the container? Using bootstrap, I have a dropdown menu(s) inside a div with overflow:hidden, which is needed to be like this. This caused the dropdowns to be clipped by the container. My question, how can I solve this clipping issue, e.g. change the container of all dropdowns inside my project to be body, with lowest cost possible? this is an example of the code: http://jsfiddle.net/0y3rk8xz/ A: if anyone interested in a workaround for this, bootstrap dropdown has a show.bs.dropdown event you may use to move the dropdown element outside the overflow:hidden container. $('.dropdown').on('show.bs.dropdown', function() { $('body').append($('.dropdown').css({ position: 'absolute', left: $('.dropdown').offset().left, top: $('.dropdown').offset().top }).detach()); }); there is also a hidden.bs.dropdown event if you prefer to move the element back to where it belongs once the dropdown is closed: $('.dropdown').on('hidden.bs.dropdown', function() { $('.bs-example').append($('.dropdown').css({ position: false, left: false, top: false }).detach()); }); Here is a working example: http://jsfiddle.net/qozt42oo/32/ A: Change the div property to overflow:visible;, or Set Position:absolute; on .dropdown class like .bs-example .dropdown{position:absolute;} See the Working Code: http://jsfiddle.net/guruWork/3x1f8ng5/ A: My solution was to use static positioning on the dropdown. I had the dropdown inside a bootstrap table with overflow hidden. <div class="table" style="overflow: hidden;"> <div class="dropdown" style="position: static;"> <div class="dropdown-menu">...</div> </div> </div> It didn't work with your fiddle, however. So I'm not sure if my solution had something to do with bootstrap tables. Regardless, perhaps it will give someone something new to try.
[ "ru.stackoverflow", "0000396415.txt" ]
Q: Php и unixtime? Пишу echo $unixtime = time("2015.2.2 8:00:00")*1000; возвращает 1422866907000, а это Mon, 02 Feb 2015 08:46:50 GMT В чем проблема? A: $unixtime = strtotime("2015-02-02 20:00:00")*1000;
[ "stackoverflow", "0012765540.txt" ]
Q: Session returning null even though i can see the values public class BaseController : Controller { public string UserId { set; get; } public string AccessToken { set; get; } private readonly IUnitOfWork _unit; public BaseController(IUnitOfWork unit) { _unit = unit; } protected override void OnActionExecuting(ActionExecutingContext filterContext) { UserId = Session["_UserId"] as string; AccessToken = Session["_AccessToken"] as string; // ...... } } Even though AccessToken returns value. UserId is coming as null even though I can debug and see that there is a value in Session object. I m setting them in session: Session.Add("_UserId", user.Id); Session.Add("_AccessToken", user.AccessToken); What s going on? A: UserId = Session["_UserId"] as string; Looks like the value for the key "_UserId" is not a string - hence you get null as result.
[ "stackoverflow", "0060112762.txt" ]
Q: how to continue text under image in column in bootstrap html i am creating a box with bootstrap, like following: <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <style> .addonscard { width: 100%; height: 181px; padding: 2%; border: 1px solid #efefef; } .addonsimage { width: 100%; } .add-on-add-unit { color: #30ac15; border: 1px solid #30ac15; } .add-on-add-unit { font-size: 14px; line-height: 20px; padding: 2px 12px 2px 10px; border-radius: 10px; display: inline-block; } .add-on-add-unit { color: #30ac15; border: 1px solid #30ac15; } .addonsdesc { font-size: 13px; } </style> <section class="addons"> <div class="container"> <div class="row"> <div class="col-md-5"> <div class="addonscard"> <div class="row"> <div class="col-md-4"> <img class="addonsimage" src="test1.jpg" /> </div> <div class="col-md-8"> <h4>This is Heading</h4> <p>Price</p> <a href="" class="add-on-add-unit">+ Add</a> <p class="addonsdesc">Standard photography at best value to turn make lifetime memories from your party. Photographer will be available for maximum 3 hours. 150 - 200 soft copies will be delivered through CD within 10 working days from the event date.</p> </div> </div> </div> </div> </div> </div> as you can see the text is going out of the box, i want the text to be like a continuation under image , something like below: because both image and text is on different columns, am not able to put it like this, am new to bootstrap, can anyone please tell me how to accomplish this. thanks in advance A: You have a specific height in .addonscard. If you are giving specific height then you have to give overflow property. I have added overflow property in my answer. Hope this helps. <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <style> .addonscard { width: 100%; height: auto; padding: 2%; border: 1px solid #efefef; overflow:auto; } .addonsimage { width: 100%; } .add-on-add-unit { color: #30ac15; border: 1px solid #30ac15; } .add-on-add-unit { font-size: 14px; line-height: 20px; padding: 2px 12px 2px 10px; border-radius: 10px; display: inline-block; } .add-on-add-unit { color: #30ac15; border: 1px solid #30ac15; } .addonsdesc { font-size: 13px; } </style> <section class="addons"> <div class="container"> <div class="row"> <div class="col-md-5"> <div class="addonscard"> <div class="row"> <div class="col-md-4"> <img class="addonsimage" src="test1.jpg" /> </div> <div class="col-md-8"> <h4>This is Heading</h4> <p>Price</p> <a href="" class="add-on-add-unit">+ Add</a> <p class="addonsdesc">Standard photography at best value to turn make lifetime memories from your party. Photographer will be available for maximum 3 hours. 150 - 200 soft copies will be delivered through CD within 10 working days from the event date.</p> </div> </div> </div> </div> </div> </div>
[ "webapps.stackexchange", "0000092797.txt" ]
Q: How can a URL be linked to a text in a YouTube comment? I know that links can be posted in comments made below YouTube videos, but some addresses are very long and look quite ugly. I may use a URL shortening service to shorten the link, but this is a complication. Is it possible to hide a link behind a visible clickable text? A: To make moderation easier, it is not possible to link a custom text to a URL in Youtube comments. Only plain links are clickable, such as: https://www.example.com/xxxxxxx http://www.example.com/xxxxx/yyyyy www.example.com/ example.com
[ "electronics.stackexchange", "0000195261.txt" ]
Q: Is this layout good? (RF - 2.45 GHz) I finished laying out HACK, my first RF (2.45 GHz) layout. The sensitive part is the connection between the IC (Atmel SAM R21G18A), the balun (Johanson 2450BM15A0015), and the PCB antenna (copied from a TI app note, thank you Texas Instruments!). I followed the suggested schematic for the SAM R21 XPlained pro with regards to the connection from chip to balun and from balun to antenna. The schematic part is here: Before laying out, I used an edge-coupled microstrip differential impedance calculator to find a width of the two traces from IC to balun that was near 100 Ohms, while I used a coplanar waveguide calculator to find a width of the trace from balun to PCB antenna that was near 50 Ohms. My values are: Er:4.5 (FR4 PCB) PCB width: 1 mm Copper (trace) thickness: 1 oz/ft^2 Traces distance or ground plane distance: 7 mils And I got 24 mils for the 100 Ohms differential traces from IC to balun, and 55 mils for the 50 Ohms trace from balun to antenna. The layout is here: I also placed vias to ground near the 50 Ohms trace at 1/20th of the wavelength, then I also stitched the ground planes. Before I send this out for the first run of prototypes (low budget, so the less revisions the better), can you please tell me if the math I did is correct (did I use the correct formulas?), and if this layout would perform well? Thanks guys. Cheers, Mick A: Have you read the following: Atmel AT02865 RF Layout with Microstrip ? It deals with exactly what you are doing, same chip and same balun. One of the key parameter is the FR4 dielectric thickness between the RF ground plane and the microstrips. You have listed yours as 0.18mm (7 mils). In the Atmel app note, it uses an example of 0.25mm (10 mils) FR4 dielectric thickness. So the example is a little different, but is close enough that you can apply all the considerations while adjusting for the small dimensional differences accordingly. Since the traces are sitting on top of a ground plane, you cannot use the coplanar waveguide model for the transmission lines. Using the microstrip model and dielectric thickness of 0.18mm, I get approx 0.3mm for 50-ohm line. Also, you do want to isolate the microstrip lines from other elements of your design. For example, a quote directly from the Atmel app note page 10 - For microstrip designs the copper pour on layer-1 should be kept away from the transmission line. The underlying Layer-2 ground plane needs to be the dominant ground reference to minimize variables. A keep-away distance of 4x the dielectric thickness will reduce the parasitic effects of copper pour to less than 1%. In other words the gap between the microstrip transmission line and copper pour on layer-1 should be 40 mils or more. If you look at the balanced 100-ohm connection between the SAMR21 IC and the Balun, it ends up looking more like a "T" shape dipole antenna than a transmission line. I don't think there is anyway to make that better, so just make that connection as short as possible. Also for the same consideration of the preceding quote, I would probably take away that asymmetric ground pour. Also, I would move the antenna to the left so the tail of antenna at the right is closer to the ground plane.
[ "stackoverflow", "0024061088.txt" ]
Q: Avoid repeating for loop for different code execution I have a condition let's assume for example Animal = {Dog,Cat,Elephant} Now I want to make a for loop with if conditions in it (not a simple for loop), inside this for loop I do some code based on the animal type for example: for(int i=0;i<100;i++) { if(some conditions on i) { for(int j =0;j<100;j++) { if(some condition on j) { switch(animaltype) { case Dog: //call function 1 case Cat: //call function 2 case Elephant: //call function 3 } } } } } So for performance optimization in case of large loops I made the switch-case outside the for loop so the code became something like this: switch (animaltype) { case Dog : for(int i=0;i<100;i++) { if(some conditions on i) { for(int j =0;j<100;j++) { if(some condition on j) { //call function 1 } } } } //------------- case Cat : for(int i=0;i<100;i++) { if(some conditions on i) { for(int j =0;j<100;j++) { if(some condition on j) { //call function 2 } } } } //---------------------- case Elephant : for(int i=0;i<100;i++) { if(some conditions on i) { for(int j =0;j<100;j++) { if(some condition on j) { //call function 3 } } } } } The problem here is that I repeated the code 3 times (or as the number of cases) and this violates the once and only once principle of the Software Design. I tried to pass a delegate but the 3 functions that I supposed to call have different arguments, can anyone tell me a neat solution to this case? EDIT I mean by "different arguments" that they do not take the same number of arguments. For example: function1(string s,int age) function2(float height,bool CanMove) function3(int legs,string name,string place) A: Try something like this: void ExecuteLoop(Func callback) { for(int i=0;i<100;i++) { if(some conditions on i) { for(int j =0;j<100;j++) { if(some condition on j) { callback(); } } } } } switch (animaltype) { case Dog: ExecuteLoop(dogCallback); break; case Cat: ExecuteLoop(catCallback); break; case Elephant: ExecuteLoop(elephantCallback); break; } This will allow you to consolidate the loop into a method, while varying what is actually executed. It is unclear when you say: ...but the 3 functions that I supposed to call have different arguments... what you mean. I assume one of two things: The three methods you intend to call have different values passed as their arguments. or The three methods you intend to call have a different number of arguments passed to them. Either way, you can solve this by building on the previous solution. Something like this: switch (animaltype) { case Dog: ExecuteLoop(() => { dogCallback(1, 2, 3); }); break; case Cat: ExecuteLoop(() = > { catCallback( "argument 1", "arg 2" ); }); break; case Elephant: ExecuteLoop(() => { elephantCallback(i, j, k); }); break; } This uses lambdas that accept no parameters (thus matching the requirement of the ExecuteLoop method) but call a method that accepts any number of variable type arguments.
[ "stackoverflow", "0006514423.txt" ]
Q: How can I play a recorded sound using a local notification? I have an app that requires that the user record their own message to be played back at some future time. My intent was to do that using UILocalNotification. Unfortunately, it seems that the sound associated with the local notif has to be stored in the main bundle but the user cannot make a recording and save it in the bundle. How do I get a user recorded sound file to be played via local notification? Alternatively - is there a way if the app is not running to capture the local notification (without waiting for the user to respond to an alert) and then play the desired soundfile? Thanks! A: You can assign a (custom) sound to a UILocalNotification by setting its property as follows: localNotification.soundName = @"MySoundFile.wav"; Unfortunately, according to the reference, it is not possible to use a sound file that is not stored in the main bundle or is declared by apple: For this property, specify the filename (including extension) of a sound resource in the application’s main bundle or UILocalNotificationDefaultSoundName to request the default system sound. See also UILocalNotification Class Reference #soundName A: I think this is possible for ios 9, this is what apple documentation says: For remote notifications in iOS, you can specify a custom sound that iOS plays when it presents a local or remote notification for an app. The sound files can be in the main bundle of the client app or in the Library/Sounds folder of the app’s data container. I tested saving a sound into the Library/Sounds folder then using it with a local notification and it worked fine on iOS 9, after that I tried the same on iOS 8 and it didn't work, so my conclussion was that this is possible for iOS 9 only You can access the library directory in this way: let fileManager = NSFileManager.defaultManager() let libraryPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] let soundsPath = libraryPath + "/Sounds" You have to create the directory if it doesn't exist: fileManager.createDirectoryAtPath(soundsPath, withIntermediateDirectories: false, attributes: nil) and you can then save your sounds there.
[ "meta.stackexchange", "0000050413.txt" ]
Q: Is this a fake Stack Overflow Facebook page? If not, what is it? According to this question, the official Facebook page for Stack Overflow is this one, with 2,400+ fans. So what's this Facebook page? I do find the "Related Global Posts" on the imposter page absolutely hysterical though... (source: gitlin.name) Related Global Posts Donna EvansI Keep Getting This Darn Message Popping Saying----Message From Web Page Stack Overflow @ Line 28 What The Hell Is This Anyone Know Help Me Thanks a few seconds ago Diane Bookwalter HELP I keep getting a pop up that say "Stack overflow at line28" and then I can't do anything. I can't click off and I have to just restart the computer from here ?? Any idea what's going on ?? Thanks 6 minutes ago · View Feedback (6) Mitzi Cotton OMG THIS FRIKKIN OUT OF MEMORY AND STACK OVERFLOW ERRORS ARE MAKING ME CRA....................................ZY!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 9 minutes ago · Comment · Like · View Feedback (4) Karen Conner JUST WONDERING WHEN MY "OUT OF MEMORY" AND "STACK OVERFLOW" ERRORS WILL BEGIN TO POP UP AGAIN :-( 10 minutes ago · View Feedback (3) Ann Wilson Belford what is stack overflow? and what dose it mean 16 minutes ago EDIT: It's all OK now, I altered the duplicate page so it looks correct now: (source: gitlin.name) A: In seriousness, one of the Stack Overflow administrators needs to contact Facebook and tell them that they are the real stack overflow and that page is an imposter. A: I'm not sure what all the real vs fake stuff is about. I started the 'page' on FB and the 'group' on LinkedIn just after the original beta. Chris started the 'group' on FB around the same time (confusingly FB has both groups and pages). I asked a question (back before meta even existed) and Chris and I traded admin rights. Ultimately that question became community and then moved to meta. I'm still an admin for the FB page and the LinkedIn group. Neither is strictly official, although there's now a marketing person from StackExchange on the admin lists for both pages. The 'fake' page is just the one Facebook auto-generates for wikipedia entries, it's been reported as a duplicate, but FB typically isn't quick with these things. The related global posts is just pattern matching, I'd expect them to be fairly nonsensical. A: Much better. The freehand circles are a significant improvement and help mitigate the terrible mess on that page. That sparkly unicorn looks a little sick, though.
[ "stackoverflow", "0010540666.txt" ]
Q: Error when compiling simple Qwt program on Mac OSX 10.7.4 I'm trying to get the following c++ program using Qwt v. 6.0.1 to work: #include <cmath> #include <QApplication> #include <qwt_plot.h> #include <qwt_plot_curve.h> int main(int argc, char **argv) { QApplication a(argc, argv); QwtPlot plot(QwtText("CppQwtExample1")); plot.setGeometry(0,0,640,400); plot.setAxisScale(QwtPlot::xBottom, 0.0, 2.0*M_PI); plot.setAxisScale(QwtPlot::yLeft, -1.0, 1.0); QwtPlotCurve sine("Sine"); std::vector<double> xs; std::vector<double> ys; for (double x=0; x<2.0*M_PI; x+=(M_PI/10.0)) { xs.push_back(x); ys.push_back(std::sin(x)); } sine.setData(&xs[0], &ys[0], xs.size()); sine.attach(&plot); plot.show(); return a.exec(); } and the .pro file looks like: TEMPLATE = app TARGET = CppQwtExample1 QMAKEFEATURES += /usr/local/qwt-6.0.1/features CONFIG += qwt INCLUDEPATH += /usr/local/qwt-6.0.1/lib/qwt.framework/Headers LIBS += -L/usr/local/qwt-6.0.1/lib/qwt.framework/Versions/6/ \ -lqwt SOURCES += qwtTest.cpp However, when I now try to do qmake make I get the error: ld: library not found for -lqwt collect2: ld returned 1 exit status make: * [qwtTest.app/Contents/MacOS/qwtTest] Error 1 I surely miss something here. Any help is greatly appreciated. A: LIBS += -L/usr/local/qwt-6.0.1/lib/qwt.framework/Versions/6/ -lqwt This is wrong. Due to the naming conventions of Mac OS X frameworks, the dynamic library inside qwt.framework isn't named "libqwt.dylib" (which the linker requires), but simply "qwt". Use LIBS += -F/usr/local/qwt-6.0.1/lib -framework qwt instead.
[ "stackoverflow", "0003478707.txt" ]
Q: Python midi out to FruityLoops Studio im working on a project and i want to create a virtual midi input with python to flstudio (fruityloops) i have googled a bit but all the modules i could find was about creating midi files which is not my issue. so what module should i use for midi i/o with python? A: Ahmet, I recommend MIDI Yoke for this. Building a virtual MIDI device driver is no easy task, and it isn't something you'll be doing with Python. http://www.midiox.com/myoke.htm Edit 2011: Some things have changed in the last year. I recommend using Tobias Erichsen's driver, which allows you to create virtual ports and send data to them. If you can use a DLL, you can use his driver. The info is here: http://www.tobias-erichsen.de/rtpMIDI.html Contact him for the API.
[ "stackoverflow", "0022860782.txt" ]
Q: CS0103: The name 'Encoding' does not exist in the current context I have a webapplication running on framework 3.5 and is installed on multiple clients, working perfectly. Except this one client... where all webservices that the application provide fail with the following error message: Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS0103: The name 'Encoding' does not exist in the current context Source Error: Line 100: string EscapedFileName { Line 101: get { Line 102: return HttpUtility.UrlEncode(FileName, Encoding.UTF8); Line 103: } Line 104: } Source File: c:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\DefaultWsdlHelpGenerator.aspx Line: 102 Google points me toward the application might be targeting the client version of the framework or the system missing the system.web dll. I've checked that both this possibilities are not the cause... Any ideas? A: Try to use the namespace using System.Text; A: Check your web.config for any <clear /> elements for the namespaces. Also, check your App Pool settings. If possible, can you create a new App Pool and try again?
[ "stackoverflow", "0056292442.txt" ]
Q: How to detect if 2 admins update a table row at the same time in php The website i'm developing has an admin page to add products to the database or edit existing products in the database. If 2 admins want to edit the same product the second admin should get an alert that the product has already been/is now being updated. How could I detect in php/sql when 2 admins try to edit the same product? I haven't really tried anything because I have no idea what to try or where to start. here's how my function looks for updating a product in the database: //I know this is a VERY unsafe function, this website will never go online! FUNCTION updateProduct($data) { include_once 'dbconn.php'; try { $conn = connectToDb(); if ($data['imageChanged'] == false) { $query = "SELECT img_url FROM products WHERE product_id=".$data['productId']; $result = mysqli_query($conn, $query); if ($result == false) { throw new Exception('Failed to execute: '. $query . 'Error: '. mysqli_error($conn)); } $imgUrl = mysqli_fetch_row($result)[0]; } else { $imgUrl = $data['image']; } $query2 = "img_url='".$imgUrl."'"; $query = "UPDATE products SET product_name='".$data['productName']."', product_desc='".$data['productDesc']."', price=".$data['price'].", ". $query2 . " WHERE product_id=".$data['productId']; $result = mysqli_query($conn, $query); if ($result == false) { throw new Exception('Failed to execute: '. $query . 'Error: '. mysqli_error($conn)); } } finally { mysqli_close($conn); } } edit: storing the old data after an update is made is not needed nor is storing the updates being made(regarding the question this might be a duplicate of). The thing I would like to know is: if admin_1 is updating a row, and admin_2 is trying to update the same row at the time admin_1's transaction is still ongoing, how can my script detect that this is happening? A: This is usually done by adding a version column that is updated every time the row changes. Before updating the row, check if the value is still the same as when the row was last read: SELECT img_url, version FROM products WHERE product_id = ?; -- Suppose this returns ('https://example.com/foo.jpg', 1) -- Remember that the current version is 1. Later: BEGIN; SELECT version FROM products WHERE product_id = ? FOR UPDATE; -- Check if version is still 1. If it's not, someone modified the row (execute ROLLBACK in this case). -- Otherwise: UPDATE products SET img_url = ?, version = version + 1 WHERE product_id = ?; COMMIT; If for whatever reason transactions are not available, an alternative is to use a simple compare-and-swap: UPDATE products SET img_url = ?, version = version + 1 WHERE product_id = ? AND version = 1; If the number of updated rows is zero, the row has been modified in the meantime. Arguably, this is slightly quicker than the SELECT FOR UPDATED followed by UPDATE. However, having the conflicting version of the row enables much richer user feedback. With an author column you can tell who updated the row, for instance, not just that it happened.
[ "stackoverflow", "0000909343.txt" ]
Q: Reading dynamically allocated arrays into lists Currently, I have been reading lists of data from a binary data file programmatically as follows: tplR = (double*) malloc(sampleDim[0]*sizeof(double)); printf("tplR = %d\n", fread(tplR, sizeof(double), sampleDim[0], dfile)); However, as I want to use find_if() function on those lists, I would need to get tplR into a list type in stl. In terms of general C++ programming practice, is it usually good practice to make tplR into a list only when I really have to? If I do make another member variable, for example, tplRList, what would be the easiest way of pushing all sampleDim[0] number of double precision entries into tplRList from tplR? Pushing them one by one until the incremental counter is equal to sampleDim[0]? Thanks in advance. A: You can use find_if with the array like this: bool equals(int p) { return p == 9; } int main(int argc,char *argv[]) { int a[10]; for(int i = 0; i < 10; ++i) { a[i] = i; } int* p = std::find_if(a, a+10, equals); cout<<*p; return 0; }
[ "stackoverflow", "0055798148.txt" ]
Q: TypeScript and Redux: Why do I need to add ` | undefined` to my Reducer state type? Why can I not just type my reducer simply like this, without adding " | undefined" to my redux state type? const reducer: Reducer<ReduxState> = function(state: ReduxState, action: any) ... Extra context:::: This works OK: export const reducer: Reducer<ReduxState | undefined> = function ( state: ReduxState | undefined, action: any ) { return state } export default reducer However, it doesnt when taking away state parameter "undefined" from fxn: export const reducer: Reducer<ReduxState | undefined> = function ( state: ReduxState, action: any ) { return state } export default reducer Which gives an error of: Type '(state: ReduxState, action: any) => ReduxState' is not assignable to type 'Reducer<ReduxState | undefined, AnyAction>'. Types of parameters 'state' and 'state' are incompatible. Type 'ReduxState | undefined' is not assignable to type 'ReduxState'. Type 'undefined' is not assignable to type 'ReduxState'.ts(2322) Or this: export const reducer: Reducer<ReduxState> = function ( state: ReduxState | undefined, action: any ) { return state } export default reducer which gives an error msg of: Type '(state: ReduxState | undefined, action: any) => ReduxState | undefined' is not assignable to type 'Reducer<ReduxState, AnyAction>'. Type 'ReduxState | undefined' is not assignable to type 'ReduxState'. Type 'undefined' is not assignable to type 'ReduxState'.ts(2322) And lastly, this doesn't work either: import {ReduxState, ReduxAction, ReduxActionType} from './types' import {Reducer} from 'redux' export const reducer: Reducer<ReduxState> = function ( state: ReduxState, action: any ) { return state } export default reducer With an error msg of : Type '(state: ReduxState, action: any) => ReduxState' is not assignable to type 'Reducer<ReduxState, AnyAction>'. Types of parameters 'state' and 'state' are incompatible. Type 'ReduxState | undefined' is not assignable to type 'ReduxState'. Type 'undefined' is not assignable to type 'ReduxState'.ts(2322) TL; DR: Typescript isn't happy with my Reducer unless I specifically allow "ReduxState | undefined" type in both the Reducer<ReduxState|undefined> and function(state: ReduxState | undefined). A: Because for the initial state, the previous state is undefined. Therefore your function has to be able to deal with state being undefined, thats what the first error tells you. The second version doesn't work, because you return state, and that can be undefined (as you don't check if it is not defined), and therefore the return type of that function (which is the generic argument to Reducer) also have to be possible undefined. You could guard against that: if(state === undefined) return { /*...*/ }; else return state; then Reducer<ReduxState> would describe the type correctly.
[ "stackoverflow", "0029712319.txt" ]
Q: How to use fgetl in Matlab? I am trying to understand how I can use fgetl to read from a file. Here is a sample .txt file: 0: 2.14 +++ 1.70 +++ 1.57, 28.2 1: 1.20 +++ 1.44 +++ 2.97, 28.6 2: 1.47 +++ 2.32 +++ 4.01, 29.1 3: 1.41 +++ 4.58 +++ 2.95, 29.0 4: 0.33 +++ 1.28 +++ 0.41, 28.8 5: 0.04 +++ 1.07 +++ 0.00, 28.6 6: 0.03 +++ 1.07 +++ 0.00, 28.4 7: 0.03 +++ 1.07 +++ 0.00, 28.1 8: 0.03 +++ 1.08 +++ 0.00, 27.9 9: 0.03 +++ 1.07 +++ 0.00, 27.8 10: 0.04 +++ 1.07 +++ 0.00, 27.6 and here is my code: fid = fopen('test.txt'); tline = fgetl(fid); while ischar(tline) disp(tline) A=sscanf(tline,'%d: %f +++ %f +++ %f, %f'); tline = fgetl(fid); end fclose(fid); But it does not work (it is obvious that I have no idea what I am doing). I want matrix A to be like this: 0 2.14 1.70 1.57 28.2 1 1.20 1.44 2.97 28.6 ... Please note that I can do this using some other methods but the point of this question is that I need to understand how to do this using fgetl. A: You have it pretty much all worked out. What you are missing is an index to store the output of every call to sscanf and that's it. Doing so, here is what I get: clear clc fid = fopen('Mymatrix.txt'); tline = fgetl(fid); %// Initialize counter k = 1; while ischar(tline) %// Store in a cell array, just in case the outputs are of different size. A{k}=sscanf(tline,'%d: %f +++ %f +++ %f, %f'); tline = fgetl(fid); k = k+1; end %// Convert to numeric array. This part would need some tuning if the outputs were of different size A = cell2mat(A).' fclose(fid); And the final output looks like this: A = 0 2.1400 1.7000 1.5700 28.2000 1.0000 1.2000 1.4400 2.9700 28.6000 2.0000 1.4700 2.3200 4.0100 29.1000 3.0000 1.4100 4.5800 2.9500 29.0000 4.0000 0.3300 1.2800 0.4100 28.8000 5.0000 0.0400 1.0700 0 28.6000 6.0000 0.0300 1.0700 0 28.4000 7.0000 0.0300 1.0700 0 28.1000 8.0000 0.0300 1.0800 0 27.9000 9.0000 0.0300 1.0700 0 27.8000 10.0000 0.0400 1.0700 0 27.6000
[ "stackoverflow", "0033858089.txt" ]
Q: Use one waypoint as destination in Gmaps Api I'm using gmaps Api to make a route for a person who have to visit a list of markets (my waypoints) to take note of their stocks. I'm using the user's house location for the origin of the route and the location of the markets as my waypoints. The problem is that I don't know which waypoint is the route's destination because I set the property optimization = true when call the the direction service, but the api needs a destination to trace the route. What I need is a way to tell the api to use the last waypoint of my optimized route as a destination. A: You could make multiple requests to the directions service, one with each possible waypoint as the final destination, pick the shortest resulting distance. proof of concept fiddle code snippet: var map; var directionsServices = []; var directionsDisplays = []; // constant "start" address var start = "Paramus, NJ"; // list of possible candidate destinations/waypoints (must be < 9) var locations = ["67 E Ridgewood Ave, Paramus, NJ 07652", "450 Rochelle Ave, Rochelle Park, NJ 07662,", "720 River Rd, New Milford, NJ 07646", "280 Main St, New Milford, NJ 07646", "469 Passaic St, Hackensack, NJ 07601", "91 Broadway, Elmwood Park, NJ 07407", "206 Market St, Saddle Brook, NJ 07662" ]; var routes = []; function initialize() { var map = new google.maps.Map( document.getElementById("map_canvas"), { center: new google.maps.LatLng(37.4419, -122.1419), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }); document.getElementById('info').innerHTML += "<u><b>intermediate results:</b></u><br>"; getDirections(start, locations, map); } google.maps.event.addDomListener(window, "load", initialize); function getDirections(start, waypoints, map) { var requests = []; var request = { origin: start, optimizeWaypoints: true, travelMode: google.maps.TravelMode.DRIVING }; for (var j = 0; j < waypoints.length; j++) { var waypts = []; for (var i = 0; i < waypoints.length; i++) { if (i != j) { waypts.push({ location: waypoints[i], stopover: true }); } } requests[j] = {}; requests[j].destination = waypoints[j]; requests[j].waypoints = waypts; requests[j].origin = start; requests[j].optimizeWaypoints = true; requests[j].travelMode = google.maps.TravelMode.DRIVING; setTimeout(function(request, j) { sendDirectionsRequest(request, j, map); }(requests[j], j), 3000 * j); } } function sendDirectionsRequest(request, index, map) { var directionsService = new google.maps.DirectionsService(); directionsServices.push(directionsService); directionsService.route(request, function(response, status) { if (status === google.maps.DirectionsStatus.OK) { var route = response.routes[0]; routes.push(route); var distance = 0; var duration = 0; for (var i = 0; i < route.legs.length; i++) { distance += route.legs[i].distance.value; duration += route.legs[i].duration.value; } route.distance = distance; route.duration = duration; route.index = index; document.getElementById('info').innerHTML += (routes.length - 1) + " dist:" + (route.distance / 1000).toFixed(2) + " km dur:" + (route.duration / 60).toFixed(2) + " min dest:" + index + " loc:" + locations[index] + " waypt order:" + route.waypoint_order + "<br>"; if (routes.length == locations.length) { routes.sort(sortFcn); var directionsDisplay = new google.maps.DirectionsRenderer({ map: map, polylineOptions: { strokeOpacity: 0.9, strokeWeight: 4, strokeColor: "black", zIndex: 10 } }); directionsDisplay.setDirections(response); directionsDisplay.setMap(map); document.getElementById('info').innerHTML += "<u><b>shortest result:</b></u><br>" + routes[0].index + " dist:" + (routes[0].distance / 1000).toFixed(2) + " km dur:" + (routes[0].duration / 60).toFixed(2) + " min dest:" + routes[0].index + " loc:" + locations[index] + " waypt order:" + routes[0].waypoint_order + "<br>"; } } else { window.alert('Directions request failed due to ' + status); } }); } function sortFcn(a, b) { if (a.distance > b.distance) return 1; else if (a.distance < b.distance) return -1; else return 0; } html, body, #map_canvas { height: 100%; width: 100%; margin: 0px; padding: 0px } <script src="https://maps.googleapis.com/maps/api/js"></script> <div id="info"></div> <div id="map_canvas"></div>
[ "stackoverflow", "0024090328.txt" ]
Q: Display an image inline with imagepng() I've consulted the PHP manual to try and invert the colors of an image, but I can't get the image to display the way I need it to. Essentially, within a WordPress loop, I need to take an image, invert it, and then set the background image of a div to that inverted image. Here's my code so far: <? if (have_rows("slideshow")): while (have_rows("slideshow")): the_row(); $icon = get_sub_field("icon"); $image = get_sub_field("image"); ?> <button data-slide="<? echo $image["url"] ?>"> <div class="icon" style="background-image:url('<? echo $icon["url"] ?>');"> <? function negate($im) { if (function_exists("imagefilter")) { return imagefilter($im, IMG_FILTER_NEGATE); } for ($x = 0; $x < imagesx($im); ++$x) { for ($y = 0; $y < imagesy($im); ++$y) { $index = imagecolorat($im, $x, $y); $rgb = imagecolorsforindex($index); $color = imagecolorallocate($im, 255 - $rgb["red"], 255 - $rgb["green"], 255 - $rgb["blue"]); imagesetpixel($im, $x, $y, $color); } } return(true); } $im = imagecreatefrompng($icon["url"]); if ($im && negate($im)) { echo "Image successfully converted to negative colors."; imagepng($im); imagedestroy($im); } ?> <!--<span style="background-image:url('img/icon-circle-white.png');"></span>--> </div><!--/.icon--> <div class="caption"> <h2><? the_sub_field("title"); ?></h2> <? the_sub_field("caption"); ?> </div><!--/.caption--> </button> <? endwhile; endif; ?> This works, but it spits out a bunch of weird characters instead of the image. It seems to me that the problem is imagepng() requires header("Content-type: image/png");, but I can't do that because this is within a WordPress loop, not a separate file. My idea is to externalize the image inversion stuff, and run that separate PHP against every image that I specify in the loop (ex: <img src="/invert.php?url=<? $icon['url'] ?>" />. Unfortunately I don't know how to do that. Is this possible? A: One solution is to deploy the image-data inline like so: <?php //... $im = imagecreatefrompng($icon["url"]); if ($im && negate($im)) { echo "Image successfully converted to negative colors."; //read the imagedata into a variable ob_start(); imagepng($im); $imgData=ob_get_clean(); imagedestroy($im); //Echo the data inline in an img tag with the common src-attribute echo '<img src="data:image/png;base64,'.base64_encode($imgData).'" />'; } //... ?> This does have some downsides: The entire computaion is done on every Page refresh Browsers do not cache the imagedata and will therefore always download the entire image Hope this helps.
[ "stackoverflow", "0011988457.txt" ]
Q: Check Session variable and Redirect to login page before page load How can I check a variable and redirect to another page before the page loads using ASP.NET? I'm aware of the life cycle, and PageInit() sounds like it would be right, but I can't seem to find anywhere to put the code without and error within Visual Studio. I can't put the onpageinit="" within the first line of my page declaration. Am I suppose to put it somewhere different? My page declaration looks like: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="dashboard.aspx.cs" Inherits="dashboard" MasterPageFile="~/Design.master" %> This is the code that I want to run on the page load: // Check if the user is logged in, if not send them to the login page if (session.logged_in == false) { // Redirect the user to the login page Response.Redirect("login.aspx"); } A: You have to override the OnInit method of the page. Place this just above (order doesn't matter, but I believe organization is important) your Page_Load event in your code behind... protected override void OnInit(EventArgs e) { base.OnInit(e); // your code goes here } Also, depending on what you are trying to accomplish, I would suggest looking into FormsAuthentication. With that you can simply specify secure folders and a login page and .NET handles kicking the visitor to the login page if they are not authenticated.
[ "stackoverflow", "0052934343.txt" ]
Q: How can I plug a prediction of X into BernoulliNB.predict_proba? I have a Python script that, given an observed class (X) and some columns of binary (Y), predicts a class (Pred_X). It then predicts the probability of each class (Prob(1), etc). How could I get the probability of only the observed class (Prob(X)) please? import pandas as pd from sklearn.naive_bayes import BernoulliNB BNB = BernoulliNB() # Data df_1 = pd.DataFrame({'X' : [1,2,1,1,1,2,1,2,2,1], 'Y1': [1,0,0,1,0,0,1,1,0,1], 'Y2': [0,0,1,0,0,1,0,0,1,0], 'Y3': [1,0,0,0,0,0,1,0,0,0]}) # Split the data df_I = df_1 .loc[ : , ['Y1', 'Y2', 'Y3']] S_O = df_1['X'] # Bernoulli Naive Bayes Classifier A_F = BNB.fit(df_I, S_O) # Predict X A_P = BNB.predict(df_I) df_P = pd.DataFrame(A_P) df_P.columns = ['Pred_X'] # Predict Probability A_R = BNB.predict_proba(df_I) df_R = pd.DataFrame(A_R) df_R.columns = ['Prob_1', 'Prob_2'] # Join df_1 = df_1.join(df_P) df_1 = df_1.join(df_R) A: thanks @jezrael: # Rename the columns after the classes of X classes = df_1['X'].unique() df_R.columns = [classes] # Look up the predicted probability of X df_1['Prob_X'] = df_R.lookup(df_R.index, df_1.X)
[ "stackoverflow", "0042584093.txt" ]
Q: Error in installing psycopg2==2.6.1 I'm trying to run pip install psycopg2==2.6.1 but I get the error of In file included from psycopg/psycopgmodule.c:27:0: ./psycopg/psycopg.h:30:20: fatal error: Python.h: No such file or directory compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 and Failed building wheel for psycopg2 and finally Command "/home/arpan/ArpanMangal/virtualenvmnts/Heroku/heroku-arpan/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-Hs26Hx/psycopg2/ setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace ('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-Y6fwIc-record/install-record.txt --single-version-externally -managed --compile --install-headers /home/arpan/ArpanMangal/virtualenvmnts/ Heroku/heroku-arpan/include/site/python2.7/psycopg2" failed with error code 1 in /tmp/pip-build-Hs26Hx/psycopg2 I am installing psycopg2=2.6.1 as a part of requirment.txt file for deploying my app on Heroku. Is there any way to fix it? A: You need to install the following dependencies sudo apt-get install python-dev libxml2-dev libxslt1-dev zlib1g-dev
[ "stackoverflow", "0029490756.txt" ]
Q: How can I use a UITextView in SpriteKit? So I have this UITextView in my game, and I want to make it more dynamic by adding SKAction animations and having it interact with physics. The former I did in kind of a hacky way which I'm not quite satisfied with, the latter I haven't done as I haven't a clue how to. This is how I did the SKActions: I made a couple of ivars: -textViewContent (NSString) -textViewSize (CGRect) -textView (UITextView) -fakeTextView (SKSpriteNode) Called by didMoveToView: -(void)createTextView { textViewContent = @"foo"; textViewSize = CGRectMake(CGRectGetMidX(self.frame)-(self.frame.size.width/4), CGRectGetMidY(self.frame)-(self.frame.size.height/4), self.frame.size.width/2, self.frame.size.height/2); textView = [[UITextView alloc]initWithFrame:textViewSize]; textView.backgroundColor = [SKColor orangeColor]; textView.text = textViewContent; textView.textColor = [SKColor whiteColor]; textView.textAlignment = NSTextAlignmentLeft; textView.font = [UIFont fontWithName:@"Code-Pro-Demo" size:25]; textView.layer.zPosition = -1; textView.alpha = 0; textView.editable = NO; fakeTextView = [SKSpriteNode spriteNodeWithColor:[SKColor orangeColor] size:CGSizeMake(self.frame.size.width/2, self.frame.size.height/2)]; fakeTextView.position = CGPointMake((self.frame.size.width*1.5),CGRectGetMidY(self.frame)); [self addChild:fakeTextView]; [self textViewEntersScene]; } -(void)textViewEntersScene{ SKAction *wait = [SKAction waitForDuration:0.5]; SKAction *moveIn = [SKAction moveToX:(self.frame.size.width/2) - 100 duration:0.3]; SKAction *moveBackSlightly = [SKAction moveToX:self.frame.size.width/2 duration:0.2]; SKAction *displayTextView = [SKAction runBlock:^{ textView.alpha = 1; }]; SKAction *hideFakeTextView = [SKAction runBlock:^{ fakeTextView.hidden = YES; }]; [fakeTextView runAction:[SKAction sequence:@[wait,moveIn,moveBackSlightly,displayTextView,hideFakeTextView]]]; } As you can probably tell, the possibilities are very limited. Is there a better way of achieving this or something similar? A: I created a class to display and scroll text. You can do a straight copy and paste for the .h and .m files once you create a new SKNode class. Basically the class displays SKLabelNodes and scrolls them up if there is more than 1 line. Lines appear for a set time, move up if additional lines are added and then fade out. It's pretty generic stuff so feel free to use and modify the code in any project you want. To use the class, import the header and use this code (example): TextBubble *myBubble = [[TextBubble alloc] init]; [myBubble createBubbleWithText:@"Hello this is a very nice day to go fishing and have a cold beer." textSize:24 maxLineLength:20]; myBubble.position = CGPointMake(300, 300); [self addChild:myBubble]; TextBubble Header File #import <SpriteKit/SpriteKit.h> @interface TextBubble : SKNode -(instancetype)init; -(void)createBubbleWithText:(NSString *)textString textSize:(int)textSize maxLineLength:(int)maxLineLength; @end TextBubble Implementation File #import "TextBubble.h" @implementation TextBubble { NSMutableArray *linesArray; } - (instancetype)init { self = [super init]; if (self) { linesArray = [[NSMutableArray alloc] init]; } return self; } -(void)createBubbleWithText:(NSString *)textString textSize:(int)textSize maxLineLength:(int)maxLineLength { NSMutableString *passedText = [[NSMutableString alloc] initWithString:textString]; NSMutableString *currentLine = [[NSMutableString alloc] init]; unsigned long characterCounter = 0; BOOL keepGoing = true; while (keepGoing) { NSRange whiteSpaceRange = [passedText rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]]; if(whiteSpaceRange.location != NSNotFound) { characterCounter += whiteSpaceRange.location+1; if(characterCounter <= maxLineLength) { [currentLine appendString:[passedText substringWithRange:NSMakeRange(0, whiteSpaceRange.location+1)]]; [passedText setString:[passedText substringWithRange:NSMakeRange(whiteSpaceRange.location+1, [passedText length]-whiteSpaceRange.location-1)]]; } else { [currentLine setString:[currentLine substringWithRange:NSMakeRange(0, [currentLine length]-1)]]; SKLabelNode *myNode = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"]; myNode.text = [NSString stringWithString:currentLine]; myNode.fontSize = textSize; myNode.fontColor = [SKColor blueColor]; myNode.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeCenter; myNode.verticalAlignmentMode = SKLabelVerticalAlignmentModeCenter; myNode.zPosition = 0; [linesArray addObject:myNode]; characterCounter = 0; [currentLine setString:@""]; } } else { [currentLine appendString:passedText]; SKLabelNode *myNode = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"]; myNode.text = [NSString stringWithString:currentLine]; myNode.fontSize = textSize; myNode.fontColor = [SKColor blueColor]; myNode.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeCenter; myNode.verticalAlignmentMode = SKLabelVerticalAlignmentModeCenter; myNode.zPosition = 0; [linesArray addObject:myNode]; keepGoing = false; } } if([linesArray count] == 1) { SKAction *block0 = [SKAction runBlock:^{ SKLabelNode *myNode = [linesArray objectAtIndex:0]; myNode.alpha = 0.0; [self addChild:myNode]; [myNode runAction:[SKAction fadeAlphaTo:1.0 duration:0.5]]; }]; SKAction *wait1 = [SKAction waitForDuration:2.5]; SKAction *block1 = [SKAction runBlock:^{ SKLabelNode *myNode = [linesArray objectAtIndex:0]; [myNode runAction:[SKAction fadeAlphaTo:0.0 duration:0.5]]; }]; SKAction *wait2 = [SKAction waitForDuration:0.5]; SKAction *block2 = [SKAction runBlock:^{ [[linesArray objectAtIndex:0] removeFromParent]; }]; [self runAction:[SKAction sequence:@[block0, wait1, block1, wait2, block2]]]; } if([linesArray count] == 2) { float heightCounter = 0.0; for (int i = 0; i<[linesArray count]; i++) { SKAction *wait0 = [SKAction waitForDuration:(2.0 * i)]; SKAction *block0 = [SKAction runBlock:^{ SKLabelNode *myNode = [linesArray objectAtIndex:i]; myNode.alpha = 0.0; myNode.position = CGPointMake(0, 0); [self addChild:myNode]; [[linesArray objectAtIndex:i] runAction:[SKAction fadeAlphaTo:1.0 duration:0.5]]; }]; SKAction *wait1 = [SKAction waitForDuration:1.5]; heightCounter += 30; SKAction *block1 = [SKAction runBlock:^{ [[linesArray objectAtIndex:i] runAction:[SKAction moveToY:heightCounter duration:0.5]]; }]; SKAction *block2 = [SKAction runBlock:^{ [[linesArray objectAtIndex:i] runAction:[SKAction fadeAlphaTo:0.0 duration:0.5]]; }]; SKAction *wait2 = [SKAction waitForDuration:0.5]; SKAction *block3 = [SKAction runBlock:^{ [[linesArray objectAtIndex:i] removeFromParent]; }]; [self runAction:[SKAction sequence:@[wait0, block0, wait1, block1, wait1, block2, wait2, block3]]]; heightCounter = 0; } } if([linesArray count] >= 3) { float heightCounter = 0.0; for (int i = 0; i<[linesArray count]; i++) { SKAction *wait0 = [SKAction waitForDuration:(1.5 * i)]; SKAction *block0 = [SKAction runBlock:^{ SKLabelNode *myNode = [linesArray objectAtIndex:i]; myNode.alpha = 0.0; myNode.position = CGPointMake(0, 0); [self addChild:myNode]; [[linesArray objectAtIndex:i] runAction:[SKAction fadeAlphaTo:1.0 duration:0.5]]; }]; SKAction *wait1 = [SKAction waitForDuration:1.5]; heightCounter += 30; SKAction *block1 = [SKAction runBlock:^{ [[linesArray objectAtIndex:i] runAction:[SKAction moveToY:heightCounter duration:0.5]]; }]; heightCounter += 30; SKAction *block5 = [SKAction runBlock:^{ [[linesArray objectAtIndex:i] runAction:[SKAction moveToY:heightCounter duration:0.5]]; }]; SKAction *block2 = [SKAction runBlock:^{ [[linesArray objectAtIndex:i] runAction:[SKAction fadeAlphaTo:0.0 duration:0.5]]; }]; SKAction *wait2 = [SKAction waitForDuration:0.5]; SKAction *block3 = [SKAction runBlock:^{ [[linesArray objectAtIndex:i] removeFromParent]; }]; [self runAction:[SKAction sequence:@[wait0, block0, wait1, block1, wait1, block5, wait1, block2, wait2, block3]]]; heightCounter = 0; } } } @end
[ "retrocomputing.stackexchange", "0000006472.txt" ]
Q: What's a good way to implement this "fade" effect on C64 See the beginning of https://www.youtube.com/watch?v=hmfLBAtGAKk. Here's a screenshot: It basically clears characters pixel by pixel both horizontally and vertically. Use sprites for the pixel by pixel cover and then clear complete characters at the right time? Or is there another way to do this? A: You could do the sides with sprites, and clearing the characters at the right time, as you have said. But the top and bottom, I would use something more like raster bars to do the top and bottom. I would first prepare a tileset which is all blank, so that the characters won't show. Then, when I get to the right scanline, (the one I want to cut off at the bottom that is), I would just set the background colour to be the same as the border, and also point the character map to this "invisible tileset". And obviously set the colour and characters back up again where you want to characters to show, at the top. I think this is the fastest way. It'll leave enough time for you to do your decrunch or precalcs or whatever. A: The most simple way is to copy the lores screen on a hires screen (using the charactersetrom) and then just clear the pixels...
[ "ru.stackoverflow", "0000782176.txt" ]
Q: Высота дочернего элемента jquery Добрый день! Столкнулась с проблемой: У меня есть блок с кнопкой, по нажатию на который - блок с кнопкой пропадает и запускается видео. И есть непосредственно блок с видео, у которого есть атрибут poster: Постер представляет собой изображение с определенной высотой. Высоту блока с кнопкой я реализовала через абсолютное позиционирование. Т.е. получается, что до момента запуска видео, у меня высота блока с кнопкой = высоте постера. Возникает проблема, когда я нажимаю на кнопку. Получается, что постер пропадает и начинает подгружаться видео, из-за чего происходит прыжок. А мне нужно от этого прыжка избавиться, сразу задать высоту, которая = высоте видео. Мне нужно от этого прыжка избавиться. Пробовала стилями, не получается. var blockHeight = $('video').height(); $('.button-block').css('height',blockHeight); HTML: <video id='homepage-video' preload="metadata" poster="http://www.designstickers.com.ua/images/png/cv-22.jpg" data-video-id=""></video> <div id="main-poster" data-mp4=""> <div id='button' class="height-video"> <button class="text-uppercase">Press </button> </div> </div> Style: .main-poster { display: block; position: absolute; top: 0; left: 0; right: 0; bottom: 0; } A: Примерно вот так var video = $('.video'); var blockHeight = video.height(); var blockWidth = video.width(); var block = $('.block'); $(block).css({ 'height': video.height(), 'width': video.width() }); $('.button-block').on('click', function() { $(this).addClass('hidden'); video.removeClass('hidden'); }) .block { background: #000; display: flex; justify-content: center; align-items: center; } .video { height: 250px; width: 250px; } .hidden { display: none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="block"> <video id='homepage-video' class="video hidden" preload="metadata" poster="http://www.designstickers.com.ua/images/png/cv-22.jpg" data-video-id=""></video> <button class="button-block">Press</button> </div>
[ "stackoverflow", "0054172394.txt" ]
Q: The rattle Annotation option doesn't seem to work rattle version 5.2.0 (or 5.2.5) doesn't seem to annotate graphs under the Explorer tab - Distributions - Box Plot. I can recode it and get the desired look but click / unclicking Annotate doesn't seem to do any thing. RStudio version 1.1.463, R version 3.5.1, rattle version 5.2.0 MIght there be another library I'm missing? Jeff A: In this case the solution was to uncheck Advanced Graphics under the Settings drop down.
[ "math.stackexchange", "0003011221.txt" ]
Q: Conditional expectation of exponential rv Let $ X $~$Expo(\lambda)$. Find $E(X|X < 1) $. I can find the conditional diaribution of$X|X<1$ and then evaluate the sum. But the question wants me to find the solution using law of total expectation and i don't know how to do it without using calculus. Any help would be appreciated! A: \begin{align}E[X]&=E[X|X>1]P(X>1)+E[X|X<1]P(X<1) \\ &=(1+E[X])P(X>1)+E[X|X<1]P(X<1)\end{align} Where I have used the memoryless property. Hopefully you can take it from here.
[ "stackoverflow", "0057945481.txt" ]
Q: How to declare the TypeScript types of a React Context initial state? I've been struggling to declare the TypeScript types of an initial state of a React Context with our errors. It'll store a list of items, and the initial state should be an empty array. I've tried many options like using an interface instead of a type, using an object to declare the types of items and setItems, declaring the type exactly as it's inferred, even trying to bypass de type declaration altogether, and I've finally managed to make it work like this: type Props = [any, any]; export const ListContext = createContext<Partial<Props>>([]); export const ListProvider = (props: any) => { const [items, setItems] = useState([]); return ( <ListContext.Provider value={[items, setItems]}> {props.children} </ListContext.Provider> ); }; I'm not sure if it's the correct way (using any doesn't look like it), and I don't fully understand why it works either. How can I improve it? Thanks in advance. A: This is the way I approach it: type Item = { example_prop: number; }; interface ContextProps { items: Item[]; setItems: Function; } export const ListContext = createContext<ContextProps>({ items: [], setItems: () => null }); interface Props { some_prop: string; } export const ListProvider: React.ComponentType<Props> = props => { const { some_prop } = props; // This is here just to illustrate const [items, setItems] = useState<Item[]>([]); return ( <ListContext.Provider value={{ items, setItems }}> {props.children} </ListContext.Provider> ); }; As you can see I'm passing an object through the Context. The initial state of this object is set to an empty array and a function which returns null; these two values will be overriden and won't actually pass but are required. The Props from the component I included some_prop, just to serve as an example. Let me know if something is not clear.
[ "math.stackexchange", "0001816115.txt" ]
Q: What is the number of columns of matrix A Given that: $$Ax = (2,4,2)^T$$ and a complete solution is $$x=(2,0,0)^T+c(1,1,0)^T+d(0,0,1)^T$$ How do I know that $A$ is a $3 \times 3$ matrix? Obviously, A has $3$ rows, we also know that the null space is $2$ dimensional. But I cannot use this information to obtain the number of columns of $A$: $$\dim N(A) + C(A^T) = n$$ and $$\dim N(A^T)+C(A) = m$$ A: If $A$ is an $m \times n$ matrix, then in the equation $Ax = b$: $b$ must be a vector on $m$ entries, and $x$ must be a vector on $n$ entries. We may thereby infer from the equation and given solution that $A$ is a $3 \times 3$ matrix (that is, both $m$ and $n$ are $3$).
[ "stackoverflow", "0047267316.txt" ]
Q: onLayout not called in react native I am trying to detect the width change with this code class MyClass extends Component { onLayout(event) { const {x, y, height, width} = event.nativeEvent.layout; const newHeight = this.state.view2LayoutProps.height + 1; const newLayout = { height: newHeight , width: width, left: x, top: y, }; this.setState({ view2LayoutProps: newLayout }); alert('ok'); } the the onLayout function is never called. Is something wrong with the code? I found the code in this website. A: Did you ever add onLayout to a component that MyClass renders? It's not a lifecycle method on the React.Component instance (like componentDidMount), it's an event from another component that you can capture by providing an onLayout callback property to the other component. It's a feature of the react-native builtin components. class MyClass extends Component { onLayout(event) { const {x, y, height, width} = event.nativeEvent.layout; const newHeight = this.state.view2LayoutProps.height + 1; const newLayout = { height: newHeight , width: width, left: x, top: y, }; this.setState({ view2LayoutProps: newLayout }); alert('ok'); } render() { return ( <View onLayout={e => this.onLayout(e)} /> ) } }
[ "stackoverflow", "0043255427.txt" ]
Q: SQL Server 2014: Re-Create System view master.dbo.spt_values On my test SQL Server 2014 installation, I was "cleaning" the master database. With the following command, I was checking which user objects there are: SELECT 'DROP ' + CASE WHEN [sys].[all_objects].type IN ('AF','FN','FS','FT','IF','TF') THEN 'FUNCTION ' WHEN [sys].[all_objects].type IN ('D','C','F','PK','UQ') THEN 'CONSTRAINT ' WHEN [sys].[all_objects].type IN ('IT','S','U') THEN 'TABLE ' WHEN [sys].[all_objects].type IN ('P','PC','RF','X') THEN 'PROCEDURE ' WHEN [sys].[all_objects].type IN ('TA','TR') THEN 'TRIGGER ' WHEN [sys].[all_objects].type = 'R' THEN 'RULE ' WHEN [sys].[all_objects].type = 'SN' THEN 'SYNONYM ' WHEN [sys].[all_objects].type = 'TT' THEN 'TYPE ' WHEN [sys].[all_objects].type = 'V' THEN 'VIEW ' END + SCHEMA_NAME(sys.[all_objects].[schema_id]) + '.' + OBJECT_NAME(object_id) + '; ' as [Command], OBJECT_NAME(object_id) as [ObjectName], [sys].[all_objects].[type_desc] as [TypeDesc], [sys].[all_objects].[type] as [Type], SCHEMA_NAME(sys.[all_objects].[schema_id]) as [Schema] FROM sys.[all_objects] WITH (NOLOCK) WHERE SCHEMA_NAME(sys.[all_objects].[schema_id]) like '%dbo%' One of the results was the view spt_values. Command | ObjectName | TypeDesc | Type | Schema ------------------------|------------|----_-----|------|------- DROP VIEW dbo.spt_values; spt_values VIEW V dbo As it was not one of the views I knew, I deleted it (along with other objects). Later that day, I wanted to check the properties of a database in SSMS 2016 and got the following error: After some searching, I found that I could recreate the missing view with the script u_tables.sql (which is in the SQL Server installation folder on your server). Information from here: https://ashishgilhotra.wordpress.com/tag/u_tables-sql/ The code in that script to create the view is the following: create view spt_values as select name collate database_default as name, number, type collate database_default as type, low, high, status from sys.spt_values go EXEC sp_MS_marksystemobject 'spt_values' go grant select on spt_values to public go Already when looking at the code, I doubted that it would work, as there is no sys.spt_values table anywhere to be found. As expected I get the error Msg 208, Level 16, State 1, Procedure spt_values, Line 6 Invalid object name 'sys.spt_values'. On my other server with SQL Server 2008 on it, there is a table master.dbo.spt_values (but no view)! After some more searching, I found that I could just create a table with the same name.. Link here https://www.mssqltips.com/sqlservertip/3694/fix-invalid-object-name-masterdbosptvalues-when-viewing-sql-server-database-properties/ Now I create a table with the values from another SQL Server 2014 installation, and everything seems to be working again. But, it is not correct! When I check the new created object on the test server with this command select [name] , [type], [type_desc] from sys.objects where name like 'spt_v%' It shows a user_table object. On my other server, it shows a view... So, my question is: How can I create the view spt_values which gets its data from a table spt_values? A: Ok, after some fiddling arround, I found the solution.. The table sys.spt_values is in the ressources database (mssqlsystemresource). This database is only accessible when the SQL Service is started in single user mode.. To re-create the view I had to do the following steps: Stop all SQL Services 2. Start the SQL Service in single user mode Open a DOS Command prompt and start the sqlservice with the switch -m sqlservr.exe -sSQLT01 –m Connect SSMS to the instance Just connect the query window, but not the Object Explorer window. The service only accepts one single connection! If there is a problem, you can see it in the DOS Window where the service is running. Delete the wrong table spt_values As I created a table spt_values on the master database, I have to delete it first use master go drop table dbo.spt_values 5. Create the view Now I finally can create the view dbo.spt_values, which points to the table sys.spt_values use master go create view spt_values as select name collate database_default as name, number, type collate database_default as type, low, high, status from sys.spt_values go EXEC sp_MS_marksystemobject 'spt_values' go grant select on spt_values to public go 6. Check the dbo.spt_values object use master select schema_name(schema_id), object_id('spt_values'), * from sys.objects where name like 'spt_v%' It should show a view now Query the view dbo.spt_values and the table sys.spt_values Just for the fun of it... You can now query the table sys.spt_values, which is in the ressources database use mssqlsystemresource Select * from sys.spt_values And you can query the view dbo.spt_values, which is in the master database use master Select * from dbo.spt_values 8. Restart the services You can now quit the DOS window with the SQL Service running and start the SQL Services. Or you just restart the whole server Hope this post will help others in the future
[ "stackoverflow", "0018625457.txt" ]
Q: Asset Pipeline failing when deploying to Heroku When I deploy to Heroku I get this error messages: Connecting to database specified by DATABASE_URL rake aborted! could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? The curious thing is that this only started to happen after I add gem 'impressionist' to the Gemfile. Locally there are not any problems. Commenting out the gem resolves it for deployment. The error received from Heroku is well documented, but nothing there gives me any clue to what is causing the fail. The Impressionist gem is fairly popular, and I haven't seen any similar issues deriving from it, so I'm skeptical that the gem is the root to the problem. Update Here's the complete Gemfile, just to show that it's a normal app that works fine in deployment (until the above mentioned gem is added). source 'https://rubygems.org' gem 'rails', '3.2.13' gem 'bcrypt-ruby', '3.0.1' gem 'jquery-rails', '2.2.1' gem 'impressionist' # gem 'will_paginate' group :assets do gem 'sass-rails', '~> 3.2.6' gem 'uglifier', '>= 1.3.0' gem 'jquery-ui-rails' end group :development, :test do gem 'quiet_assets' gem 'webrick', '~> 1.3.1' gem 'sqlite3', '1.3.7' gem 'hirb' end group :production do gem 'thin' gem 'pg', '0.12.2' end A: The 'issue' was that Impressionist sets up db configuration on the fly, Therefore it needs to load a DB adapter. Let's use ActiveRecord as an example. When it tries to load ActiveRecord::Base it raises an exception that Heroku informs you with that message, because you're not connected to the DB yet. Devise has had this issue plataformatec/devise#1339 I added cancan gem and removed impressionist and it raised the same error. Fortunately there is a solution: # config/application.rb # Forces application to not load models or access the DB when precompiling # assets config.assets.initialize_on_precompile = false Thanks :)
[ "stackoverflow", "0055008632.txt" ]
Q: Django pass parameters I'm trying to pass pk key urlpatterns = [ path('api/products', ProductAPI.as_view()), path('api-admin/products/', ProductAdminAPI.as_view()), url(r'^api-admin/products/(?P<pk>[0-9]\d+)', ProductAdminAPI.as_view()), ] with this URL localhost:8000/api-admin/products/3/ but I'm getting 404 A: Your expression (?P<pk>[0-9]\d+) is wrong. You need at least 2 digits to match the expression, since you first ask a character [0-9] and then a digit \d. Remove either [0-9] or \d.
[ "tex.stackexchange", "0000549343.txt" ]
Q: How do I change this tikz picture? I looked up and took a code to draw a cube but now I'm not able to centre it. I want to further divide the cube into smaller sections like this: It's okay if I can draw just the lines instead of the minicubes to represent the division. Here is my image: I'm also not able to add labels to the image where I want them. I want to be able to provide labels for all three axes based on my requirement. Here is my code, could you help me out? \newcommand{\Depth}{5} \newcommand{\Height}{5} \newcommand{\Width}{5} \begin{tikzpicture} \centering \coordinate (O) at (0,0,0); \coordinate (A) at (0,\Width,0); \coordinate (B) at (0,\Width,\Height); \coordinate (C) at (0,0,\Height); \coordinate (D) at (\Depth,0,0); \coordinate (E) at (\Depth,\Width,0); \coordinate (F) at (\Depth,\Width,\Height); \coordinate (G) at (\Depth,0,\Height); \draw[] (O) -- (C) -- (G) -- (D) -- cycle;% Bottom Face \draw[] (O) -- (A) -- (E) -- (D) -- cycle;% Back Face \draw[] (O) -- (A) -- (B) -- (C) -- cycle;% Left Face \draw[] (D) -- (E) -- (F) -- (G) -- cycle;% Right Face \draw[] (C) -- (B) -- (F) -- (G) -- cycle;% Front Face \draw[] (A) -- (B) -- (F) -- (E) -- cycle;% Top Face \end{tikzpicture} A: Just define a pic that you place via nested loops. The coloring can be done via \ifnums. The most cumbersome part is to punch in the texts from a screen shot. \documentclass[tikz,border=3mm]{standalone} \definecolor{pft}{RGB}{150,198,145} \begin{document} \begin{tikzpicture}[node font=\sffamily,nodes={text depth=0.25ex}, scale=4/3, pics/block/.style={code={ \tikzset{block/.cd,#1}% \def\pv##1{\pgfkeysvalueof{/tikz/block/##1}}% \colorlet{cc}{\pv{color}}% \draw[fill=cc] (-\pv{a}/2,-\pv{a}/2,-\pv{a}/2) -- (\pv{a}/2,-\pv{a}/2,-\pv{a}/2) -- (\pv{a}/2,\pv{a}/2,-\pv{a}/2) -- (-\pv{a}/2,\pv{a}/2,-\pv{a}/2) -- cycle; \draw[fill=cc!70!black] (-\pv{a}/2,-\pv{a}/2,-\pv{a}/2) -- (-\pv{a}/2,-\pv{a}/2,\pv{a}/2) -- (-\pv{a}/2,\pv{a}/2,\pv{a}/2) -- (-\pv{a}/2,\pv{a}/2,-\pv{a}/2) -- cycle; \draw[fill=cc!60!black] (-\pv{a}/2,-\pv{a}/2,-\pv{a}/2) -- (-\pv{a}/2,-\pv{a}/2,\pv{a}/2) -- (\pv{a}/2,-\pv{a}/2,\pv{a}/2) -- (\pv{a}/2,-\pv{a}/2,-\pv{a}/2) -- cycle; }},block/.cd,a/.initial=1,color/.initial=gray!40] \path[transform shape] foreach \Z in {0,...,3} {foreach \X in {0,...,3} {foreach \Y in {0,...,3} {\pgfextra{% \ifnum\Z=3 \edef\mycolor{blue!70!black} \ifnum\Y=2 \edef\mycolor{pft} \fi \ifnum\X=1 \ifnum\Y=2 \edef\mycolor{orange} \else \edef\mycolor{yellow} \fi \fi \else \edef\mycolor{gray!40} \ifnum\X=1 \edef\mycolor{yellow} \fi \ifnum\Y=2 \edef\mycolor{pft} \fi \fi} (\X,\Y,\Z) pic{block={color=\mycolor}}}}}; % y axis \path foreach \X [count=\Y] in {Laptop,Mobile,TV,Tablet} {(-0.7,-1+\Y,3.5) node[rotate=90,anchor=south]{\X}}; \draw[orange!30!yellow,-stealth,ultra thick] (-1.5,-0.5,3.5) -- node[pos=0,sloped,above right,font=\large,black]{PRODUCTS} ++ (0,4.2,0); % x axis \path foreach \X [count=\Y] in {USA,Asia,Australia,Europe} {(-1+\Y,-0.7,3.5) node[anchor=north,text height=0.8em]{\X}}; \draw[orange!30!yellow,-stealth,ultra thick] (-0.5,-1.5,3.5) -- node[pos=0,sloped,below right,font=\large,black]{GEOGRAPHY} ++ (4.2,0,0); % z axis \path foreach \Y in {1,...,4} {(3.5,-0.5,4-\Y) node[anchor=north west,text height=0.8em]{$Q_{\Y}$}}; \draw[orange!30!yellow,-stealth,ultra thick] (4,-1.5,3.5) -- node[pos=0,sloped,below right,font=\large,black]{time} ++ (0,0,-4.2); \end{tikzpicture} \end{document} If you are wondering whether one can use a more realistic projection, the answer is yes. And here is a version with full cubes. \documentclass[tikz,border=3mm]{standalone} \definecolor{pft}{RGB}{150,198,145} \begin{document} \begin{tikzpicture}[node font=\sffamily,nodes={text depth=0.25ex}, scale=4/3, pics/block/.style={code={ \tikzset{block/.cd,#1}% \def\pv##1{\pgfkeysvalueof{/tikz/block/##1}}% \colorlet{cc}{\pv{color}}% \draw[fill=cc] (-\pv{a}/2,-\pv{a}/2,-\pv{a}/2) -- (\pv{a}/2,-\pv{a}/2,-\pv{a}/2) -- (\pv{a}/2,\pv{a}/2,-\pv{a}/2) -- (-\pv{a}/2,\pv{a}/2,-\pv{a}/2) -- cycle; \draw[fill=cc!70!black] (-\pv{a}/2,-\pv{a}/2,-\pv{a}/2) -- (-\pv{a}/2,-\pv{a}/2,\pv{a}/2) -- (-\pv{a}/2,\pv{a}/2,\pv{a}/2) -- (-\pv{a}/2,\pv{a}/2,-\pv{a}/2) -- cycle; \draw[fill=cc!60!black] (-\pv{a}/2,-\pv{a}/2,-\pv{a}/2) -- (-\pv{a}/2,-\pv{a}/2,\pv{a}/2) -- (\pv{a}/2,-\pv{a}/2,\pv{a}/2) -- (\pv{a}/2,-\pv{a}/2,-\pv{a}/2) -- cycle; \draw[fill=cc!70!black] (\pv{a}/2,-\pv{a}/2,-\pv{a}/2) -- (\pv{a}/2,-\pv{a}/2,\pv{a}/2) -- (\pv{a}/2,\pv{a}/2,\pv{a}/2) -- (\pv{a}/2,\pv{a}/2,-\pv{a}/2) -- cycle; \draw[fill=cc!60!black] (-\pv{a}/2,\pv{a}/2,-\pv{a}/2) -- (-\pv{a}/2,\pv{a}/2,\pv{a}/2) -- (\pv{a}/2,\pv{a}/2,\pv{a}/2) -- (\pv{a}/2,\pv{a}/2,-\pv{a}/2) -- cycle; \draw[fill=cc] (-\pv{a}/2,-\pv{a}/2,\pv{a}/2) -- (\pv{a}/2,-\pv{a}/2,\pv{a}/2) -- (\pv{a}/2,\pv{a}/2,\pv{a}/2) -- (-\pv{a}/2,\pv{a}/2,\pv{a}/2) -- cycle; }},block/.cd,a/.initial=1,color/.initial=gray!40] \path[transform shape] foreach \Z in {0,...,3} {foreach \X in {0,...,3} {foreach \Y in {0,...,3} {\pgfextra{% \ifnum\Z=3 \edef\mycolor{blue!70!black} \ifnum\Y=2 \edef\mycolor{pft} \fi \ifnum\X=1 \ifnum\Y=2 \edef\mycolor{orange} \else \edef\mycolor{yellow} \fi \fi \else \edef\mycolor{gray!40} \ifnum\X=1 \edef\mycolor{yellow} \fi \ifnum\Y=2 \edef\mycolor{pft} \fi \fi} (\X,\Y,\Z) pic{block={color=\mycolor}}}}}; % y axis \path foreach \X [count=\Y] in {Laptop,Mobile,TV,Tablet} {(-0.7,-1+\Y,3.5) node[rotate=90,anchor=south]{\X}}; \draw[orange!30!yellow,-stealth,ultra thick] (-1.5,-0.5,3.5) -- node[pos=0,sloped,above right,font=\large,black]{PRODUCTS} ++ (0,4.2,0); % x axis \path foreach \X [count=\Y] in {USA,Asia,Australia,Europe} {(-1+\Y,-0.7,3.5) node[anchor=north,text height=0.8em]{\X}}; \draw[orange!30!yellow,-stealth,ultra thick] (-0.5,-1.5,3.5) -- node[pos=0,sloped,below right,font=\large,black]{GEOGRAPHY} ++ (4.2,0,0); % z axis \path foreach \Y in {1,...,4} {(3.5,-0.5,4-\Y) node[anchor=north west,text height=0.8em]{$Q_{\Y}$}}; \draw[orange!30!yellow,-stealth,ultra thick] (4,-1.5,3.5) -- node[pos=0,sloped,below right,font=\large,black]{time} ++ (0,0,-4.2); \end{tikzpicture} \end{document} Please note that pgfplots has a 3d cube plot mark, which you could use to get similar plots in a more structured way.
[ "stackoverflow", "0033533949.txt" ]
Q: Find the number of non-decreasing and non-increasing subsequences in an array I am attempting to complete a programming challenge from Quora on HackerRank: https://www.hackerrank.com/contests/quora-haqathon/challenges/upvotes I have designed a solution that works with some test cases, however, for many the algorithm that I am using is incorrect. Rather than seeking a solution, I am simply asking for an explanation to how the subsequence is created and then I will implement a solution myself. For example, with the input: 6 6 5 5 4 1 8 7 the correct output is -5, but I fail to see how -5 is the answer. The subsequence would be [5 5 4 1 8 7] and I cannot for the life of me find a means to get -5 as the output. Problem Statement At Quora, we have aggregate graphs that track the number of upvotes we get each day. As we looked at patterns across windows of certain sizes, we thought about ways to track trends such as non-decreasing and non-increasing subranges as efficiently as possible. For this problem, you are given N days of upvote count data, and a fixed window size K. For each window of K days, from left to right, find the number of non-decreasing subranges within the window minus the number of non-increasing subranges within the window. A window of days is defined as contiguous range of days. Thus, there are exactly N−K+1 windows where this metric needs to be computed. A non-decreasing subrange is defined as a contiguous range of indices [a,b], a<b, where each element is at least as large as the previous element. A non-increasing subrange is similarly defined, except each element is at least as large as the next. There are up to K(K−1)/2 of these respective subranges within a window, so the metric is bounded by [−K(K−1)/2,K(K−1)/2]. Constraints 1≤N≤100,000 days 1≤K≤N days Input Format Line 1: Two integers, N and K Line 2: N positive integers of upvote counts, each integer less than or equal to 10^9 Output Format Line 1..: N−K+1 integers, one integer for each window's result on each line Sample Input 5 3 1 2 3 1 1 Sample Output 3 0 -2 Explanation For the first window of [1, 2, 3], there are 3 non-decreasing subranges and 0 non-increasing, so the answer is 3. For the second window of [2, 3, 1], there is 1 non-decreasing subrange and 1 non-increasing, so the answer is 0. For the third window of [3, 1, 1], there is 1 non-decreasing subrange and 3 non-increasing, so the answer is -2. A: Given a window size of 6, and the sequence 5 5 4 1 8 7 the non-decreasing subsequences are 5 5 1 8 and the non-increasing subsequences are 5 5 5 4 4 1 8 7 5 5 4 5 4 1 5 5 4 1 So that's +2 for the non-decreasing subsequences and -7 for the non-increasing subsequences, giving -5 as the final answer.
[ "dsp.stackexchange", "0000040312.txt" ]
Q: Why does python's scipy.signal.dimpulse introduce delay in impulse response? Consider a simple linear, time invariant system of the form: $y_k = cy_{k-1} + (1-c)x_k$ The impulse response of this system can be computed by either dimpulse or by applying lfilter to a vector composed of a one followed by zeros: import scipy.signal as sp_signal import numpy as np Ts = 1 c = 0.9 A = [1, -c] B = [1-c] time, imp_resp1 = sp_signal.dimpulse((B, A, Ts)) x = np.zeros(100) x[0] = 1 imp_resp2 = sp_signal.lfilter(B, A, x) print(imp_resp1[0][:5,0]) print(imp_resp2[:5]) which yields: array([ 0. , 0.1 , 0.09 , 0.081 , 0.0729]) [ 0.1 0.09 0.081 0.0729 0.06561] Why does dimpulse introduce a one-sample delay in the impulse response? A: In lfilter the transfer function is described in decreasing powers of z, as shown below copied from the python doc for signal.lfilter: -1 -M b[0] + b[1]z + ... + b[M] z Y(z) = -------------------------------- X(z) -1 -N a[0] + a[1]z + ... + a[N] z While the parameters B and A in dimpulse are represented in increasing powers of z as described in the doc for signal.TransferFunction: If (numerator, denominator) is passed in for *system, coefficients for both the numerator and denominator should be specified in descending exponent order (e.g. s^2 + 3s + 5 or z^2 + 3z + 5 would be represented as [1, 3, 5]) Along with the following example given for: $$\frac{z^2+3z+3}{z^2+2z+1}$$ Contruct the transfer function with a sampling time of 0.1 seconds: H(z)=z2+3z+3z2+2z+1 H(z)=z2+3z+3z2+2z+1 >>>>signal.TransferFunction(num, den, dt=0.1) TransferFunctionDiscrete( array([ 1., 3., 3.]), array([ 1., 2., 1.]), dt: 0.1 ) So in your case, for dimpulse: $$H_1(z)=\frac{1-0.9z^{-1}}{0.1}$$ And for lfilter: $$H_2(z)=\frac{z-0.9}{0.1}$$ So $$H_1(z)= H_2(z)z^{-1}$$ And mystery solved!
[ "stackoverflow", "0000695263.txt" ]
Q: How to display placeholder value in WPF Visual Studio Designer until real value can be loaded I'm an experienced C# developer but a WPF newbie. Basic question (I think) that I can't find an answer to by web searching. Here's the simplified use case... I want to display a string in a WPF TextBlock. So I write some C# code in codebehind of my XAML control... public class MyCoolControl : UserControl { public void InitializeMyCoolControl() { this.DataContext = "SomeStringOnlyAvailableAtRuntime"; // Perhaps from a database or something... } } And I set up my XAML like this: <UserControl ... snip...> <!-- Bind the textblock to whatever's in the DataContext --> <TextBlock Text="{Binding}"></TextBlock> </UserControl> Works great, I can see the value "SomeStringOnlyAvailableAtRuntime" when I execute my application. However, I don't see anything at Design Time using Visual Studio 2008's XAML Designer. How can I see a placeholder value (anything) for the textblock at design time? Thanks! -Mike A: I often use FallbackValue on the binding to have something to look at while I design user controls. For example: <TextBlock Text={Binding Path=AverageValue, FallbackValue=99.99} /> However, since FallbackValue is not just applied at design time, this might not be appropriate if you want to use FallbackValue at run time for other reasons.
[ "stackoverflow", "0056816837.txt" ]
Q: Column div moving below the column div with largest height above I am using PHP loop to create and display articles (as 'col' divs) from the MySQL database. If I use 3 "col-6" divs, the 3rd one moves below both the above divs. I want it to stay just close to the div above it(the first col-6 div in this case). How can I achieve this? I have figured out that this is a problem with bootstrap columns. Also, I cannot use absolute positioning in this case. while($row=mysqli_fetch_array($run_query)){ echo '<div class="col-md-6 col-xl-4 blogColumn">'; echo '<a class="articleLink" href="show.php?blogId=';echo $row['id'].'" target="_blank">'; echo '<article>'; echo '<header>'; if($row['file_id']==null){ echo '<img class="img-fluid rounded focus" src="https://i.ibb.co/ZNDm012/logo.jpg"/>'; } else{ $fileId=$row['file_id']; $q="SELECT * FROM uploads WHERE id='$fileId'"; $run_q=mysqli_query($con,$q) or die(mysqli_error($con)); $res=mysqli_fetch_array($run_q); $path="uploads/".$res['name']; if($res['type']=='image'){ echo '<img class="img-fluid rounded focus" src="'.$path.'"/>'; } else { echo '<video class="articleVideo" src="'.$path.'" controls="controls">'; echo '</video>'; } } echo '<h2>'.$row['title'].'</h2>'; echo '</header>'; echo '<p>'.substr($row['description'],0,100).'... Read More'.'</p>'; echo '</article>'; echo '</a>'; echo '<hr/>'; echo '</div>';}?>``` A: The full width of the page is defined by col-12. So if you want to have 3 same width columns next to each other use col-md-4 <div class="col-md-4">...</div> <div class="col-md-4">...</div> <div class="col-md-4">...</div> This will result in 3 equal width columns next to each other.
[ "electronics.stackexchange", "0000496232.txt" ]
Q: Help deriving the transfer function of an LC circuit? I have the LC circuit below. I believe (but I'm not certain) that this is a 3rd order filter. Since there are two capacitors and 1 inductor. The circuit is a passive low pass pi filter. The component values have been chosen so that the cutoff frequency is 15kHz. The input is from a signal generator with a source impedance of 50ohms (the resistor shown). I need to derive a transfer function for the circuit but I'm not sure how, since I don't know the order of the system. The Bode plots of the system are below: Can anyone help me derive the transfer function of the system using these Bode plots? A: If you do the algebra (it's amazing what folk will do in lock-down of course) you get the following transfer function: - $$H(s) = \dfrac{1}{s^3LC_1C_2R + s^2LC_2 + sR(C_1+C_2) + 1}$$ And just to demonstrate that is correct I used micro-cap 12 and the following circuit: - Inside the red box is the input AC voltage that can be swept from low to high frequencies. To the left of that is the conventional circuit formed by R, L, C1 and C2. To the right we have micro-caps 12's Laplace function solver. Both circuits are fed from V1 (red box). Comparing both bode plots we get identical overlapping results: - If this helps then that's good. If you require the derivation of the above TF then ask. I don't suppose it hurts to post my reasonably legible hand calcs: - A: This transfer function can be obtained using brute-force analysis or the fast analytical circuit techniques known as FACTs. For the brute-force approach, you can consider a Thévenin generator featuring the first \$RC\$ filter driving the \$LC\$ network. If you do the maths ok, you should find: Then you develop all the terms and rearrange to form a 3rd-order polynomial to reveal resonant and cutoff frequencies. The other option is to use the FACTs which will lead you to the coefficients values in one shot, without equations and the risk to make mistakes while developing the above expression. Just go through the time constants determination as shown in the below drawing and you find the transfer function very quickly: Assemble the time constants in a Mathcad sheet and try to factor the 3rd-oder polynomial with a 1st-order filter dominating the low-frequency response: And finally you can plot the ac response. Please note the divergence of the factored expression. This is because the \$RC\$ cutoff frequency is too close to the double poles incurred by the \$LC\$ filter. Increasing \$R_1\$ to 100 \$\Omega\$ gives a better fit:
[ "stackoverflow", "0022988900.txt" ]
Q: Neo4j enterprise backup Windows 7 I'm trying to run an Neo4j-database online-backup. I am using a Windows 7-machine and Neo4j enterprise 2.0.1. I'm pretty new to all that database stuff, so I need pretty precise advice. So far I have tried various steps to run the backup: I created a clear directory for the backup (C:\Users\Tobi\Desktop\neo_backup) I typed the following statement into the Neo4j command box: ./neo4j-backup -from single://localhost:7474 -to C:\Users\Tobi\Desktop\neo_backup. But, despite the red help box dropping down, nothing happens. I also tried some slightly different statements (i.e. using the IP-address etc.) What am I doing wrong? Could someone give me some advice? A: You have to run this from your Windows command line, execute cmd from the start menu, navigate (cd c:\your\path\to\neo) to the Neo4j installation directory and run it from there. Also I think at least on Windows it's called Neo4jBackup.bat (but I'm not sure, having no Windows)
[ "dba.stackexchange", "0000005176.txt" ]
Q: What is the purpose of SET NULL in Delete/Update Foreign Keys constraints? I am probably being narrow minded, but if I create a foreign key constraint and a row gets updated or deleted, I lose that connection if the child table's column gets set to NULL. What is the purpose of intentionally keeping these orphaned rows? A: Whether set null is useful or not depends on what you have chosen null to mean in the particular context - with all the confusion and opinion around null IMO the sensible approach is for the DBA to Choose (and document) what it means for each nullable field Make sure it means one thing only With those rules, consider the following use case: You have a table 'shop' (eg individual premises) You have a table 'retailer' (eg chains) The 'shop' table has a lookup field referring to the key of 'retailer' You have defined null to represent an independent shop (ie one that is not part of a chain) A 'retailer' closes branches to the point that you consider its shops to be independent In this case, an on delete set null makes sense. There are other ways of modelling these business rules but this is the simplest and if it accurately fits the facts that you care about in the real world, I suggest it is perfectly ok
[ "stackoverflow", "0009822187.txt" ]
Q: What kind of model & controller should I use in ASP MVC 3, if I want a dynamic dropdown from db? I've been looking for hours the solution. I've 3 models atm. Priority: using System; using System.Collections.Generic; namespace IssueReportManagementTest.Models { public class Priority { public int ID { get; set; } public string Name { get; set; } } } Category: using System; using System.Collections.Generic; namespace IssueReportManagementTest.Models { public class Category { public int ID { get; set; } public string Name { get; set; } } } And the problem is that I've a Issue model and I want dynamic dropdowns from the other models. Issue using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace IssueReportManagementTest.Models { public class Issue { [Key] public int IssueID { get; set; } public DateTime Added { get; set; } public DateTime Modiefied { get; set; } public virtual Category Category { get; set; } public IEnumerable<Category> Categories { get; set; } public virtual Priority Priority { get; set; } public IEnumerable<Category> Priorities { get; set; } [Required] public string Title { get; set; } [Required] [DataType(DataType.MultilineText)] public string Description { get; set; } } } Is this correct? And what do I need in the Controller if I want to get dropdowns from priorities and categories. And yes they're stored in the database. A: This is what I have taken from my scenario, you can modify and adapt it to fit in with your code. On my view I have a dropdown that displays the different banks. My action method where I set the dropdown's values from the database: public ActionResult MyActionMethod() { MyViewModel viewModel = new MyViewModel { Banks = bankRepository.GetAll() } return View(viewModel); } This is what my view model looks like (just a partial view): public class MyViewModel { public int BankId { get; set; } public IEnumerable<Bank> Banks { get; set; } } Here is my Bank class: public class Bank { public int Id { get; set; } public string Name { get; set; } public bool IsActive { get; set; } } This is my dropdown's code in the view: <td>Bank:</td> <td> @Html.DropDownListFor( x => x.BankId, new SelectList(Model.Banks, "Id", "Name", Model.BankId), "-- Select --" ) @Html.ValidationMessageFor(x => x.BankId) </td> I hope this helps. It doesn't do anything fancy, it just populates a dropdown. Shout if you need more clarification.
[ "superuser", "0000379435.txt" ]
Q: Hyperlink to open a script We have several Windows desktops used by different individuals with several .bat files stored in a common location (say E: drive) in every machine. I am in the process of setting up a web-page in our intranet site with hyperlinks to run each batch file. As machine names change from PC to PC I am not able to use a hyperlink something like this: \\chethan-PC\e$\scripts\one.bat I tried using localhost and 127.0.0.1 in place of PC name but it did not help. Hence I am interested to know if there is any way to achieve this objective. One alternative I could think of, is to have scripts in a server. But this is not feasible in our case as users will be making modifications on local copies. A: Try this for an address: file:///E:/scripts/one.bat
[ "stackoverflow", "0020845159.txt" ]
Q: Match all characters up to a capture group, excluding the capture group I have a pattern blah_blah_blah_blah_19292_blah_m32.jpg I want to match everything up to _mXX while excluding the _mXX. I have ^(.*[_m]) but this is inclusive. Can't seem to get the capture group excluded. What am I missing? rubular link http://www.rubular.com/r/0Ls12Z6GH7 A: You can use positive lookahead for that: /^.*?(?=_m[0-9]+)/ Will match blah_blah_blah_blah_19292_blah in your input string. Online Demo: http://www.rubular.com/r/abgW0Q1gjX Referece: Lookarounds in regex Quoting from above link: q(?=u) matches a q that is followed by a u, without making the u part of the match. The positive lookahead construct is a pair of parentheses, with the opening parenthesis followed by a question mark and an equals sign.
[ "stackoverflow", "0037478154.txt" ]
Q: What are the requirements for audio output in Chrome on Android? I'm using code from here: https://github.com/TwilioDevEd/video-quickstart-php to develop a webRTC web app. The example application, when running successfully on 2 browsers, creates the following HTML: <div id="remote-media"> <audio src="blob:https%3A//myAddress.com/8a537e34-9ab2-4bea-a85d-61e5f80b585c"></audio> <video src="blob:https%3A//myAddress.com/22b23b46-9021-4f15-9ab5-ffb78fec2d48"></video> </div> <div id="local-media"> <audio src="blob:https%3A//myAddress.com/740c8e33-cc60-4d1e-b1fe-2c23742e618d"></audio> <video src="blob:https%3A//myAddress.com/3105d4a2-cd71-4408-8b7c-771cba677829"></video> </div> It works on Chrome and Firefox on a PC, and works on Firefox on Android. Chrome on Android connects, there is video and audio input which is visible and audible on the remote browser, and there is video output - the video streamed from the remote browser. THE PROBLEM: there is no audio output. I have tried $("audio").autoplay="true"; in the javascript that creates the <audio> element. I have opened other web pages from the same Chrome installation on the same device (eg. YouTube) and I have audio and video. What am I missing? A: "On iOS, and Chrome for Android, autoplay doesn’t work; users must tap the screen to play the video." source: https://developers.google.com/web/fundamentals/design-and-ui/media/video/quick-reference?hl=en#autoplay My solution: <button id="audioOn" onclick="$('#remote-media > audio')[0].play()">Cant hear? Click me!</button>
[ "stackoverflow", "0003392641.txt" ]
Q: jQuery password strength plugin: Retrieving password's strength I'm working on a legacy groovy project that uses jQuery's password strength validator plugin. It works great. However, a new requirement arrived today, indicating that the form should not be submited if the strength of the password is below good (this is an arbitrary value) Is there any way to achieve this? Possibly via javascript? Ajax solutions are welcome to. Thanks in advance. A: I see two ways of doing it: Check class of warning, it is something like ".password_strength_1", so strength is in its name. Just edit plugin :) It won't hurt.
[ "diy.stackexchange", "0000169352.txt" ]
Q: Induction cooktop connection I have a new induction cooktop Bosch PIF645BB1E rated at 7.4 kW. According to its documentation it should be connected with 5 wires (2 phases, 2 neutrals and 1 PE wire). From a former flat renter I have a power outlet with 5 dedicated 2.5 mm2 wires (3 phases, 1 neutral wire and 1 PE wire). I think that I can connect 2 phases to 2 phases, PE wire to PE wire and 2 neutrals to just 1 neutral wire, but I am not sure that just one 2.5 mm2 neutral wire is enough in this case. Is it OK to connect it like this or I need thicker wires for this cooktop? Thank you for your answers! Edit: Sorry, I forgot to mention that I live in Germany and voltage is 230/400 V. Also I attached photos of back side of the cooktop with connection diagrams and photo of my power outlet. A: What you've described is the correct way to do this. As the currents in the two phase wires are fed from different phases, they do not add together fully, and so the neutral will not be overloaded.
[ "stackoverflow", "0040154672.txt" ]
Q: "ImportError: file_cache is unavailable" when using Python client for Google service account file_cache I'm using a service account for G Suite with full domain delegation. I have a script with readonly access to Google Calendar. The script works just fine, but throws an error (on a background thread?) when I "build" the service. Here's the code: from oauth2client.service_account import ServiceAccountCredentials from httplib2 import Http import urllib import requests from apiclient.discovery import build cal_id = "[email protected]" scopes = ['https://www.googleapis.com/auth/calendar.readonly'] credentials = ServiceAccountCredentials.from_json_keyfile_name('my_cal_key.json', scopes=scopes) delegated_credentials = credentials.create_delegated('[email protected]') http_auth = delegated_credentials.authorize(Http()) # This is the line that throws the error cal_service = build('calendar','v3',http=http_auth) #Then everything continues to work normally request = cal_service.events().list(calendarId=cal_id) response = request.execute() # etc... The error thrown is: WARNING:googleapiclient.discovery_cache:file_cache is unavailable when using oauth2client >= 4.0.0 Traceback (most recent call last): File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/__init__.py", line 36, in autodetect from google.appengine.api import memcache ImportError: No module named 'google' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 33, in <module> from oauth2client.contrib.locked_file import LockedFile ImportError: No module named 'oauth2client.contrib.locked_file' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 37, in <module> from oauth2client.locked_file import LockedFile ImportError: No module named 'oauth2client.locked_file' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/__init__.py", line 41, in autodetect from . import file_cache File "/Users/myuseraccount/anaconda3/lib/python3.5/site-packages/googleapiclient/discovery_cache/file_cache.py", line 41, in <module> 'file_cache is unavailable when using oauth2client >= 4.0.0') ImportError: file_cache is unavailable when using oauth2client >= 4.0.0 What's going on here and is this something that I can fix? I've tried reinstalling and/or upgrading the google package. A: I am a bit late to the party here but I had a similar problem today and found the answer here Solution to only the error : file_cache is unavailable when using oauth2client >= 4.0.0 Solution: change your discovery.build() to have the field cache_discovery=False i.e discovery.build(api, version, http=http, cache_discovery=False) EDIT: As @Chronial says this will disable the cache. A solution that does not disable the cache can be found here A: The code head of module "google-api-python-client" said... install_requires = [ 'httplib2>=0.9.2,<1dev', 'oauth2client>=1.5.0,<5.0.0dev', <<============= 'six>=1.6.1,<2dev', 'uritemplate>=3.0.0,<4dev', ] So, I have uninstalled oauth2client version 4.0.0 Then, I have downloaded oauth2client 1.5.2 in a tar.gz file from offial python site https://pypi.python.org/pypi/oauth2client/1.5.2 I have installed this downloaded file so I have 1.5.2 version of oauth2client Package Version ------------------------ --------- certifi 2016.9.26 discovery 0.0.4 distribute 0.7.3 future 0.16.0 google-api-python-client 1.5.5 httplib2 0.9.2 oauth2client 1.5.2 pefile 2016.3.28 pip 9.0.1 pyasn1 0.1.9 pyasn1-modules 0.0.8 PyInstaller 3.2 pypiwin32 219 requests 2.11.1 rsa 3.4.2 setuptools 28.8.0 six 1.10.0 uritemplate 3.0.0 After that, ALL is working OK again and there is no warning message.
[ "stackoverflow", "0034540762.txt" ]
Q: How to find size of query result I have the following query in rails: records = Record.select('y_id, source') .where(:source => source, :y_id => y_id) .group(:y_id, :source) .having('count(*) = 1') I get the following output if I puts records: [#<Record source: "XYZ", y_id: 10000009>, #<Record source: "XYZ", y_id: 10000070>] This looks like there are 2 elements in the output array. But when I try to do records.size I get: {[10000009, "XYZ"]=>1, [10000070, "XYZ"]=>1} Why doesn't records.size print 2 when records is an array having 2 elements? Is the group by query result behaving differently for some reason? What should I do to get the size of records A: I could be on the wrong track but I think the issue is to do with the way .size works. Size will automatically try to determine whether to call .count or .length. These behave in the followings ways: .count performs a SQL COUNT .length calculates the length of the resultant array However on occassion .size will return a hash (as it has decided to use .count) So your solution may be to use .length which will return an integer. A: You can get it using : results.length The size method uses the sql count method which behaves this way.
[ "ru.stackoverflow", "0000537918.txt" ]
Q: Как создать SQL запрос без конструктора в Laravel 5.2? Мне не нужно делать запрос вида SELECT или INSERT, я понимаю, что конструктором это сделать проще и лучше. Однако мне необходимо запустить процедуру находящеюся на MsSQL Server. Можно ли это осуществить конструктором? Если нет, то как можно по холопски руками прописать запрос в Laravel 5.2? A: Иные запросы к БД Используйте метод statement фасада DB: DB::statement('drop table users');
[ "stackoverflow", "0012863616.txt" ]
Q: Printing PDF in jsp in iframe contents I have researched several options for printing a pdf inside an iframe and none seem to be working. Simple Details: I get some search parameters from a user. I do a database search and then use Apachi FOP to generate a PDF of the results. They are directed to a webpage that has a print and cancel button. When the user clicks the Print button, it will open a window displaying the PDF. A print dialog will open up for the user to print the PDF. The PDF file is deleted from the server. The windows close Advanced Details: This only needs to work on IE8. The FOP integration does not use any XSLT translations. It only uses a StringReader of the inputted FOP XML formatted as a string The window displaying the PDF is actually two JSP pages. The first page: Has an iframe with the second JSP page as a source Runs a printPDF() function on load that prints the PDF in the iframe The second page: Uses Java BufferedOutputStream and ServletOutputStream Will delete the file after outputting Uses out = pageContent.pushBody(); Here is part of the first jsp page (the run that calls the print function): <body onload='printPDF()'> <table> <tr> <td class="content"> <% // get myfilename from the myfile parameter on the URL String myfile = request.getParameter("myfile"); out.print("<iframe src='fc_view_letter.jsp?myfile="+ myfile + "' id='pdfFrame'></iframe>"); %> </td> </tr> </table> <script> function printPDF() { var id = 'pdfFrame'; var iframe = document.frames ? document.frames[0] : document.getElementById(id); var ifWin = iframe.contentWindow || iframe; ifWin.focus(); ifWin.printPage(); //ifWin.print(); } </script> </body> Here is most of the second JSP Page (the one that shows the pdf): <%@ page session="false" %> <%@ page import="java.io.*" %> <%@ page import="java.net.URLDecoder" %> <html> <head> </head> <body> <% String myfile = request.getParameter("myfile"); String myfiledecoded = ""; myfiledecoded = URLDecoder.decode(myfile, "UTF8"); String myfilename = myfiledecoded; String extension; int dotPos = myfilename.lastIndexOf(".")+1; extension = myfilename.substring(dotPos); int slashPos = myfilename.lastIndexOf("/")+1; String secondparam = "filename=" + myfiledecoded.substring(slashPos); response.setContentType("application/pdf"); response.setHeader("Content-Disposition", secondparam); try { ServletOutputStream sout = response.getOutputStream(); response.setHeader("Content-Disposition", secondparam); File file = new File(myfilename); FileInputStream fstream = new FileInputStream(file); BufferedInputStream bis = null; bis = new BufferedInputStream(fstream); BufferedOutputStream bos = null; bos = new BufferedOutputStream(sout); byte[] buff = new byte[1024]; int bytesRead; while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } bis.close(); bos.close(); sout.flush(); sout.close(); //file.delete(); } catch (Exception e) { System.out.println("Exception Occured...................." ); } out.clear(); out = pageContext.pushBody(); %> </body> </html> What I think is the issue: I'm thinking that the buffer eliminates all of the html and only displays the PDF. Or at least it does that in IE. When I looked in Firefox it embedded the PDF file. Maybe I cannot grab the contents of the iframe because it is no longer HTML. Here are my sources so far: Javascript Print iframe contents only How to open print dialog after pdf generated? http://www.ehow.com/how_7352227_use-javascript-print-pdf.html http://www.webmasterworld.com/forum91/4086.htm how to print pdf inside embed/iframe using javascript Printing contents of a dynamically created iframe from parent window A: What I ended up doing was generating the PDF then using iText I added some print JavaScript that ran when the PDF loaded
[ "stackoverflow", "0031018575.txt" ]
Q: Failed to resolve only recyclerview i have a strange error this is my error Capture Big Size Image here I had to install Support Repository and Support Libray but recyclerview is not found If I click on "Install repository and sync project" , show this window and finish,project clean, but still same error Search of hard work, but it does not solve thanks i already seen here Question Try 21.0.1,2,3,+ still same error A: You have a typo in your dependency, a dot instead of the colon after the group ID. It should say: compile 'com.android.support:recyclerview-v7:21.0.0' ^ Also, consider using the latest versions (22.2.0) instead of 21.0.0.
[ "stackoverflow", "0003884264.txt" ]
Q: Django: "reverse" many-to-many relationships on forms The easiest example of the sort of relationship I'm talking about is that between Django's Users and Groups. The User table has a ManyToMany field as part of its definition and the Group table is the "reverse" side. A note about my constraints: I am not working with the Admin interface at all nor is that an option. Now, onto the programming problem. I need to write a form that is used to edit MyGroup instances, defined simply as the following: class MyGroup( Group ): some_field = models.CharField( max_length=50 ) I want to be able to have a form page where I can edit both some_field and which users are members of the group. Because I'm working with a model, a ModelForm seems obvious. But I cannot figure out how to get Django to include the users because it is on the reverse side of the User-Group relationship. Ideally, I'd like the display widget for specifying the users to be like the one for specifying permissions that is found on the User and Group pages within Admin. A: I never found a great way to do this. I ended up writing custom forms that manage creating the fields and specifying an appropriate queryset on them. For the display portion of the question, there is a way to use the SelectFilter (a.k.a. horizontal filter) on regular pages. One page with instructions I found is here, and there was another that was helpful, but I can't seem to re-located it. I'm considering writing up a more thorough guide to both parts of this process. If anyone is interested please let me know, it'll give me the push to actually get it done.
[ "stackoverflow", "0015902762.txt" ]
Q: JTree selection on mouse release I'm using a JTree to generate some tab for my application. Every time I select a node on right panel I load a new page. I'd like to generate the node selection event on mouse release. A: Although it has significant user interface implications, you might look at the approach shown in JTree select on mouse release. It replaces all instances of MouseListener in the tree with a listener that forwards the desired mouse events to the original.
[ "stackoverflow", "0059650444.txt" ]
Q: How to write Date in C# I don't know how to write date time in C#, more specific which is a default format of date-time. I have two classes. One is Student and the second one is DiplomiraniStudent (which means a student who gets graduated). Class student have properties ime (engl. first name), prezime (engl. last name), jmbag is a special id for students, imeObrUstanove (engl. name of an educational institution), nazivStudija (engl. name of study), datUpisStudija (engl. date when a student enrolled in study) and second class inherits first class. Second class DiplomiraniStudent has just one property which is datZavrStudija (engl. date when the student graduated). In first class I write method which return a formatted string, and in the second class, I write override method. In Program I don't know how to write date-time. It's called an error in date-time format. I don't know should I specify the format of date ore there is some format which .NET framework allready use. Here is my code. Class Student using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Vjezba_4 { class Student { public string ime { get; set; } public string prezime { get; set; } public string jmbag { get; set; } public string imeObrUstanove { get; set; } public string nazivStudija { get; set; } public DateTime datUpisStudija { get; set; } public Student(string Ime, string Prezime, string Jmbag, string ImeObrUstanove, string NazivStudija, DateTime DatUpisStudija) { this.ime = Ime; this.prezime = Prezime; this.jmbag = Jmbag; this.imeObrUstanove = ImeObrUstanove; this.nazivStudija = NazivStudija; this.datUpisStudija = DatUpisStudija; } public Student() {} public virtual string PodaciOStudentu() { return String.Format(this.ime, this.prezime, this.jmbag, this.imeObrUstanove, this.nazivStudija, this.datUpisStudija); } } } Class Diplomirani Student using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Vjezba_4 { class DiplomiraniStudent:Student { public DateTime datZavrStudija { get; set; } public DiplomiraniStudent(string Ime, string Prezime, string Jmbag, string ImeObrUstanove, string NazivStudija, DateTime DatUpisStudija, DateTime DatZavrStudija): base(Ime, Prezime, Jmbag, ImeObrUstanove, NazivStudija, DatUpisStudija) { this.datZavrStudija = DatZavrStudija; } public DiplomiraniStudent() {} public override string PodaciOStudentu() { return String.Format(this.ime, this.prezime, this.jmbag, this.imeObrUstanove, this.nazivStudija, this.datUpisStudija, this.datZavrStudija); } } } Program using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Vjezba_4 { class Program { static void Main(string[] args) { Student student = new Student("Jakov", "Jaki", "549900871", "Veleučilište Velika Gorica", "Održavanje računalnih sustava", 17.07.2018); DiplomiraniStudent dipstudent = new DiplomiraniStudent("Mate", "Matić", "Veleučilište Velika Gorica", "Održavanje računalnih sustava", 19.07.2014, 25.06.2019); Console.WriteLine(student.PodaciOStudentu()); Console.WriteLine(student.ime); Console.WriteLine(student.prezime); Console.WriteLine(student.jmbag); Console.WriteLine(student.imeObrUstanove); Console.WriteLine(student.nazivStudija); Console.WriteLine(student.datUpisStudija); Console.WriteLine(); Console.WriteLine(dipstudent.PodaciOStudentu()); Console.WriteLine(dipstudent.ime); Console.WriteLine(dipstudent.prezime); Console.WriteLine(dipstudent.jmbag); Console.WriteLine(dipstudent.imeObrUstanove); Console.WriteLine(dipstudent.nazivStudija); Console.WriteLine(dipstudent.datUpisStudija); Console.WriteLine(dipstudent.datZavrStudija); } } } A: You want to use DateTime.ToString like so: DateTime.Now.ToString("MM/dd/yyyy") A list of available formats is here. EDIT: After seeing the constructor call you are using for Student I've concluded that you're simply not passing a DateTime; there is no shorthand way to initialize a DateTime object as there is for most number types. You need to use the actual DateTime constructor as MX D stated: new DateTime(2018, 07, 17) A: To create your students, you can use the DateTime constructor that takes in a year, month, and day: Student student = new Student("Jakov", "Jaki", "549900871", "Veleučilište Velika Gorica", "Održavanje računalnih sustava", new DateTime(2018, 7, 17)); DiplomiraniStudent dipstudent = new DiplomiraniStudent("Mate", "Matić", "Veleučilište Velika Gorica", "Održavanje računalnih sustava", new DateTime(2014, 7, 19), new DateTime(2019, 6, 25)); Then, when outputting the datetime as a string, you can use dat.ToShortDateString() (or dat.ToLongDateString(), or you could specify a custom string format using dat.ToString(customFormatString)). For example: public override string PodaciOStudentu() { return $"{ime} {prezime} {jmbag} {imeObrUstanove} {nazivStudija} " + $"{datUpisStudija.ToShortDateString()} {datZavrStudija.ToShortDateString()}"); } For more information on DateTime string formats, check out Standard DateTime Format Strings and Custom DateTime Format Strings
[ "ru.stackoverflow", "0000194401.txt" ]
Q: Рисование дуги заданного угла по кругу (на C# - WPF) Дан круг радиуса R (радиус задается пользователем). Также задается градус, число от 0 до 360. Надо нарисовать дугу вот этого заданного угла. 360 полный круг, 180 половина, это понятно. Делал через CombinedGeometry (GeometryCombineMode: Intersect) - делал PathFigure из LineSegment, ArcSegment, LineSegment в такой последовательности. С использованием Transform, крутил линии и между ними рисовался этот ArcSegment. Извините код, который написал не могу привести здесь, под рукой нет. Обобщенно выглядит так - надо нарисовать дугу заданного угла, т.е. дан круг, дуга будет представлять часть круга. Вот думаю, без всех этих CombinedGeometry, используя в основном один ArcSegment можно будет реализовать аккуратно. Может кто сталкивался с такой задачкой. A: Можно сделать проще, без поворотов, только придётся немного вспомнить тригонометрию. Вот вам пример, с углами в 60 градусов: <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel> <Path Stroke="Red" StrokeThickness="2"> <Path.Data> <PathGeometry Figures="M 100 100 l 100 0 a 100 100 60 0 1 -50 86.6 z"/> </Path.Data> </Path> <Path Stroke="Red" StrokeThickness="2"> <Path.Data> <PathGeometry> <PathGeometry.Figures> <PathFigure StartPoint="100,100" IsClosed="True"> <LineSegment Point="200,100"/> <ArcSegment Point="150,186.6" RotationAngle="60" Size="100,100" IsLargeArc="False" SweepDirection="Clockwise"/> </PathFigure> </PathGeometry.Figures> </PathGeometry> </Path.Data> </Path> </StackPanel> </Page> Получаются такие дуги:
[ "stackoverflow", "0036720661.txt" ]
Q: How to exclude a maven dependency if in the parent project exists a newer version of it I am working with a Maven project where I have spring framework dependency version 3.2.3.RELEASE and I have to import this project into many others but in some of them I am using spring 4. How can I exclude this dependency (spring 3) only in case that the project that uses mine has the same or newer version of spring and in those who hasn't use mine? A: One thing you can do is to manually exclude unwanted dependencies: <dependency> <groupId>com.your.project</groupId> <artifactId>project-name</artifactId> <version>1.0.0</version> <exclusions> <exclusion> <artifactId>org.springframework</artifactId> <groupId>spring-core</groupId> </exclusion> </exclusions> </dependency> But that can get quite verbose. It may help if you elaborate a bit more on the problem description as it is not clear to me what exactly are you trying to solve or achieve. For instance if you include a dependency A which has a dependency B in version 1.0 and then you include B in your pom in 1.1 Maven will use only 1.1. I recommend reading up on it a bit here: https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Transitive_Dependencies
[ "math.stackexchange", "0003396324.txt" ]
Q: Tricky Differentials Question Let variables x, y and z be linked by the two relationships: $$ \begin{split} f(x, y, z) &= −x^2 &+ y^2 &+ z^2 &− 1 &= 0\\ g(x, y, z) &= 3x^3 &+ y^3 &+ 2z^3 &− 6 &= 0 \end{split} $$ Derive conditions on the differentials $dx$, $dy$, and $dz$ if the functions $f$ and $g$ are kept at these values. If $y = 1$, find the two points with values of $x$ and $z$ satisfying $f = g = 0$. To be perfectly honest, I don't know where to start with this question. Never seen anything like it before. Any advice/ help would be appreciated. Thanks. A: You treat $x,y,z$ as variables that depend on a fourth variable $t$, and differentiate the equation with respect to $t$. For example, look at your equation $$-x^2+y^2+z^2-1=0.$$ Apply the differentiation $\frac{d}{dt}$ to both sides of the equation to see that $$\frac{d}{dt}(-x^2+y^2+z^2-1)=\frac{d}{dt}0,\\-2x\frac{dx}{dt}+2y\frac{dy}{dt}+2z\frac{dz}{dt}=0.$$ It looks like implicit differentiation, because it is. Multiply the last equation by $dt$ to see that $$-2xdx+2ydy+2zdz=0.$$ You then do the same thing again for the equation $g=0$. I leave it to you. In general, if you are given a function $F$ and an equation $F(x,y,z)=0$, the condition on the differentials is the equation $$\frac{\partial F}{\partial x}dx+\frac{\partial F}{\partial y}dy+\frac{\partial F}{\partial z}dz=0.$$ You can extend this idea to any number of variables.
[ "math.stackexchange", "0001318552.txt" ]
Q: Using second derivative to find a bound for the first derivative Let $f$ be a twice differentiable function on $\left[0,1\right]$ satisfying $f\left(0\right)=f\left(1\right)=0$. Additionally $\left|f''\left(x\right)\right|\leq1$ in $\left(0,1\right)$. Prove that $$\left|f'\left(x\right)\right|\le\frac{1}{2},\quad\forall x\in\left[0,1\right]$$ The hint we were given is to expand into a first order Taylor polynomial at the minimum of $f'$. So I tried doing that: As $f'$ is differentiable, it is continuous, and attains a minimum at $\left[0,1\right]$. Thus we can denote $x_{0}$ as the minimum, and expending into a Taylor polynomial of the first order around it gives us, for some $c$ between $x$ and $x_0$. $$T_{x_{0}}\left(x\right)=f\left(x_{0}\right)+f'\left(x_{0}\right)\left(x-x_{0}\right)+\frac{f''\left(c\right)}{2}\left(x-x_{0}\right)^{2}$$ Now at $x=0$ we have $$T_{x_{0}}\left(0\right)=f\left(x_{0}\right)-x_{0}f'\left(x_{0}\right)+x_{0}^{2}\frac{f''\left(c\right)}{2}=0$$ And at $x=1$ we have $$T_{x_{0}}\left(0\right)=f\left(x_{0}\right)+\left(1-x_{0}\right)f'\left(x_{0}\right)+\left(1-x_{0}\right)^{2}\frac{f''\left(c\right)}{2}=0$$ and I'm pretty much stuck here.. So I tried a different approach using Mean Value Theorem directly, by Rolle's I know the derivative is $0$ somewhere (as $f(0)=f(1)$), suppose at $x_0$, so by mean value theorem $\frac{f'(x)}{x-x_0} =f''(c)\leq1$ for some $c$ and $f'(x)<x-x_0$. But using this approach as well I'm not sure how to proceed, as this gives me the desired propety only in $1/2$ environment around $x_0$... Any help? A: You were on the right track, but, as I suggested, the hint should have been to expand about the point $x_0$ where $|f'(x_0)|$ is a maximum. Fix any $x_0\in [0,1]$ and, using Taylor's Theorem, write $$f(x)=f(x_0) + f'(x_0)(x-x_0) + \frac12 f''(c)(x-x_0)^2\quad\text{for some $c$ between $x_0$ and $x$.}$$ Plugging in $x=0$ and $x=1$ respectively, we arrive at $$f'(x_0) = \frac12\big(f''(c_1)x_0^2 - f''(c_2)(1-x_0)^2\big) \quad\text{for some $c_1$ and $c_2$}.$$ Therefore $|f'(x_0)|\le \dfrac12\big(x_0^2 + (1-x_0)^2\big) \le \dfrac12$, since $x_0\in [0,1]$ is arbitrary.
[ "stackoverflow", "0035984678.txt" ]
Q: use OpenCV with Clion IDE on Windows I'm actually looking for a way to create apps with OpenCV with Clion from JetBrains. I've installed OpenCV with Choco, so I have all the stuff in C:\opencv this is my projet with Clion CMakeLists.txt: cmake_minimum_required(VERSION 3.3) project(test) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") include_directories("C:\\opencv\\build\\include\\") FIND_PACKAGE( OpenCV REQUIRED core highgui imgproc) set(OpenCV_FOUND TRUE) set(SOURCE_FILES main.cpp) add_executable(prog ${SOURCE_FILES}) and the main.cpp: #include <opencv2/opencv.hpp> int main() { cv::Mat img = cv::imread("./test.jpg", -1); cv::imshow("Mon image", img); cv::waitKey(0); return 0; } and the response to build is : undefined reference to `cv::imread(cv::String const&, int)' and undefined errors for all OpenCV functions Do you know why it doesn't works? A: First of all, you need CMake. Then you need a compiler of your choise (MinGW, Visual Studio, ...). Download the OpenCV source files. Link Unpack to C:\opencv (or a folder of your choice) Open CMake and select source (directory of 2.) and build for example C:\opencv\mingw-build or C:\opencv\vs-x64-build. Choose one accoring your configuration. Click Configure and select the generator according to you compiler. MinGW Makefiles in case of MingGW or Visual Studio ... if you are using Visual Studio and so on ... (If you experience problems with MinGW, ensure that the minGW/bin directory is added to the evironment path labelled, 'PATH') Wait for the configuration to be done, edit your properties of your needs (in my case I don't need tests, docs and python). Click Configure again. When everything is white click Generate else edit the red fields. Open cmd and dir to build directory of 3. If you chose Visual Studio open the generated solution. Compile the library. Run mingw32-make (or mingw64-make) or build the BUILD_ALL project from the generated solution in Visual Studio if your choosen compiler is MSVC. This takes a while. Once it is done, run mingw32-make install (or mingw64-make install). If you've choosen Visual Studio you need to build the INSTALL project. This creates an install folder, where everything you need for building your own OpenCV apps is included. To system PATH add C:\opencv\mingw-build\install\x86\mingw\bin Restart your PC. Set up CLion: You need to download FindOpenCV.cmake and add it to project-root/cmake/. CMakeLists.txt: project(test) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") # Where to find CMake modules and OpenCV set(OpenCV_DIR "C:\\opencv\\mingw-build\\install") set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/") find_package(OpenCV REQUIRED) include_directories(${OpenCV_INCLUDE_DIRS}) add_executable(test_cv main.cpp) # add libs you need set(OpenCV_LIBS opencv_core opencv_imgproc opencv_highgui opencv_imgcodecs) # linking target_link_libraries(test_cv ${OpenCV_LIBS}) main.cpp: #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> int main(int argc, char** argv) { if(argc != 2) { std::cout << "Usage: display_image ImageToLoadAndDisplay" << std::endl; return -1; } cv::Mat frame; frame = cv::imread(argv[1], IMREAD_COLOR); // Read the file if(!frame) // Check for invalid input { std::cout << "Could not open or find the frame" << std::endl; return -1; } cv::namedWindow("Window", WINDOW_AUTOSIZE); // Create a window for display. cv::imshow("Window", frame); // Show our image inside it. cv::waitKey(0); // Wait for a keystroke in the window return 0; } Build and run main.cpp. All Paths depend on the setup you make in 2. and 3. You can change them if you like. UPDATE 1: I updated the post for using a compiler of you choice. SUGGESTION: Using a package manager like Conan makes life much easier.
[ "meta.stackoverflow", "0000359866.txt" ]
Q: The challenge of burninating [hackerrank] Let me preface this by saying I do have a bias against "code challenge" sites. With that out of the way, here goes. Does it describe the contents of the questions to which it is applied? and is it unambiguous? In one use case, it tags questions from hackerrank, it doesn't describe the contents of the questions, it describes the origins of the questions. In another use case, it tags questions about hackerrank itself. Is the concept described even on-topic for the site? The second use case is off-topic. Does the tag add any meaningful information to the post? No. The first use case adds zero information. The second use case is off-topic anyways Does it mean the same thing in all common contexts? As far as I am aware, it always refers to the site. There are 32 questions under the tag as of this post's writing. There is no tag wiki at all, leading to further misuse, and also an indication there is no clear idea on how and when the tag should be used. Of the on-topic questions, I don't see any that suffers from the removal of the tag. Digging around for a bit, I came across The Death of Meta Tags and realized it fits the bill pretty nicely. hackerrank is indeed a meta tag and should be removed. Progress All hackerrank have been removed. The questions have either sensible answers/discussions, closed or is pending to be closed. A: In addition to the points mentioned in the question, I'd like to talk about a couple more. In my experience, a lot of questions pertaining to Hackerrank are from users trying to figure out why their code could not pass the last X test cases. Hackerrank does not provide exception tracebacks on hidden test cases. This puts a majority of these questions in the "Off-topic" category, lacking MCVEs. Other times, it's users copy pasting a wall of text from the question on the website and asking "how can this problem be solved?", which almost always ends up being Too Broad, owing to the sheer size of the problem statement (as are many of the questions on Hackerrank). For the small minority of questions that are of good quality, there is nothing the tag can do to clarify the content or topic of the question that another tag cannot do. So, in short, this needs to go.
[ "ell.stackexchange", "0000132328.txt" ]
Q: Is "tripe" also used as a single-word exclamation? I'd like to know whether a construction with "Tripe!" as for example in "He is very active on StackExchange!" "Tripe! He doesn't even know about the existence of StackExchange!" is possible and common. So far I've only seen "tripe" in exclamations with other words ("This is utter tripe!" etc.) The dictionaries I've consulted haven't answered that for me, and search engines ignore the exclamation mark, which makes it hard to find any examples. EDIT: I've added a wrong statement before the "Tripe!" to make it clearer. A: Based on that "tripe" is an informal word for ideas, suggestions, or writing that are stupid, silly, or have little value and is closely related to the meanings of "crap", "bullshit", "nonsense", "lies", "bosh", "hogwash", it can be used in such a way. Frankly speaking, many such words, expletive or not, can be used standalone with an exclamation mark. Bullshit! I didn't do it! or That's bullshit! I didn't do it! Crap! What in the heavens happened here? Lies! I've never told him that! or That's lies! I've never told him that! Nonsense! This can't be true! Tripe! That wasn't so! Consider this: The exclamation mark is used to express exasperation, astonishment, or surprise, or to emphasise a comment or short, sharp phrase. In professional or everyday writing, exclamation marks are used sparingly if at all.
[ "apple.stackexchange", "0000299605.txt" ]
Q: Reset apple id password immediately I just upgraded IOS and I needed to enter icloud password during upgrade and I can't remember my apple ID password and followed password reset page - https://iforgot.apple.com/password/verify/appleid After few crazy overlapping text in captcha retries I reached the final page where it says I'll receive email or text after 24 hours. After more than 12 hours I received email that says "An account recovery request was made for your Apple ID" and I'll receive another text or phone call to reset password on "8 October 2017 at 08:50:09 GMT+8" and today is 25th September. Does everyone really need to wait that long or am I not using the right forgot password page? A: Not sure which device you are using. So I list some methods to reset your Apple ID. On iPhone, iPad, or iPod touch You need to have iOS 10 or newer. Select "Settings". Select your account name, then Password & Security, and finally Change Password. For iOS 10.2 or older iOS, it's the same but first, you must select "iCloud". On Mac Open the Apple menu, then "System Preferences", then click "iCloud". Select "Account Details". Click "Forgot Apple ID or password". Click "Security", then "Reset Password". Before you can change your Apple ID password, you'll be asked to enter the password for your Mac.
[ "stackoverflow", "0058061651.txt" ]
Q: Printing a series of dataframes in a for loop I have a list of dataframes in the following form: [dfs] = [df1, df2, df3, ..... dfn] I want to print the head of each dataframe in the list through a for loop. I tried with both the print command, and writing directly the df, but all I get is an ugly looking array and not in the form of a dataframe. See below, thanks. for i in range (0, int(max_range_v)): dfs[i] with the above I get nothing. I also tried the following: i = 1 dfs[i].head() this works, but when i embed it in the loop it doesnt work anymore. How can i fix it? Ideally i would like to get something the outcome like a good looking dataframe printed through pandas. Can't reproduce it here.... well i don't know how to do it. A: To print two dataframe with the same format as pandas you can use this library: from IPython.display import display display(df1.head()) display(df2.head()) And for case you just have to do this function in your loop
[ "stackoverflow", "0013032109.txt" ]
Q: jQuery add video on link click I am attempting to write a jQuery script where whenever a link is clicked on a certain page, a video is appended to the body, the video plays, and THEN it goes to the link's intended target. So far, this is what I have: HTML <body> <div id="videoHolder"> <a href="http://www.google.com">Google, as an example</a> </div> </body> jQuery window.onbeforeunload=function(event) { $("#videoHolder").html( '<video width="600" height="600" autoplay="autoplay">' + '<source src="images/doors.mp4" type="video/mp4"></source>' + '</video>'); setTimeout('window.location.href=' + $('a').attr(href), 5000); } A: You need to prevent the link from redirection first, I've modified your code to make it work below <html> <head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript"> $(function() { $('a').click(function(event) { // prevent the navigation from happening event.stopImmediatePropagation(); event.preventDefault(); // play the video $("#videoHolder").html( '<video width="600" height="600" autoplay="autoplay">' + '<source src="http://www.html5rocks.com/en/tutorials/video/basics/Chrome_ImF.mp4" type="video/mp4"></source>' + '</video>'); // redirect the user var url = $(this).attr('href'); setTimeout(function() { window.location = url }, 5000); }); }); </script> </head> <body> <div id="videoHolder"> <a href="http://www.google.com">Google, as an example</a> </div> </body> </html>
[ "stackoverflow", "0011224531.txt" ]
Q: PHP Checking input with isset In order to check if an input field is empty or has any value, will the following both methods work in same way? Or is any of them better than other? if ($options['url']) { .. } Or if ( isset ($options['url']) && ($options['url']!="") ) { .. } A: Without checking with isset() you will get at least a notice message if $options is not an array or the index url does not exist. So isset() should be used. You could also use if (! empty($options['url'])) { ... } Empty() checks for any false value (like an empty string, undefined, etc...).
[ "ell.stackexchange", "0000187975.txt" ]
Q: How to construct complex sentence (with reasons) using neither and nor. I would like to write a complex sentence using neither and nor. For example: This method is neither fast, as it requires long times to give the result, nor simple as it requires three main challenges steps. Is this a correct way to use neither and nor with a sentence includes reasons? A: It’s a little awkward, but not incorrect (though I think you need a comma before the second “as”).
[ "stackoverflow", "0045055985.txt" ]
Q: Reference Error: "UrlShortener" is not defined sheets google I'm trying this code: function onOpen() { SpreadsheetApp.getUi() .createMenu("Shorten") .addItem("Go !!","rangeShort") .addToUi() } function rangeShort() { var range = SpreadsheetApp.getActiveRange(), data = range.getValues(); var output = []; for(var i = 0, iLen = data.length; i < iLen; i++) { var url = UrlShortener.Url.insert({longUrl: data[i][0]}); output.push([url.id]); } range.offset(0,1).setValues(output); } but It has an error: in line 12 Reference Error: "UrlShortener" is not defined A: Inside the Google Script, go to Resources > Advanced Google Services and enable the URL Shortener API.
[ "stackoverflow", "0037617200.txt" ]
Q: Unit test a method with mocking I want to unit test this method. I know i need to mock the mxbean, but i have no idea how to do that. Could someone show me how to unit test this method please? @Override public int compare(Long threadId1, Long threadId2) { ThreadMXBean mxbean = ManagementFactory.getThreadMXBean(); return Long.compare(mxbean.getThreadCpuTime(threadId2), mxbean.getThreadCpuTime(threadId1)); } A: As it is, it can't effectively be mocked. You need to move the local variable to a field. ThreadMXBean mxbean = ManagementFactory.getThreadMXBean(); @Override public int compare(Long threadId1, Long threadId2) { return Long.compare(mxbean.getThreadCpuTime(threadId2), mxbean.getThreadCpuTime(threadId1)); } Now you can reassign the field to a mock in your test (I'll be using Mockito, but other frameworks exist as well): @Test public void yourTestMethod(){ YourClass yourClass = new YourClass(); ThreadMXBean mock = Mockito.mock(ThreadMXBean.class) Mockito.when(mxbean.getThreadCpuTime(1L)).thenReturn(1); Mockito.when(mxbean.getThreadCpuTime(2L)).thenReturn(2); yourClass.mxbean = mock; assertThat(yourClass.compare(1L, 2L), is(-1)); } But it's even nicer to use the Mockito JUnit Runner and have Mockito create mocks automatically: @RunWith(MockitoJUnitRunner.class) public class YourTest{ @InjectMocks YourClass yourClass = new YourClass(); @Mock ThreadMXBean mock; @Test public void yourTestMethodDoesntNeedToCreateMocksAnymore(){ Mockito.when(mxbean.getThreadCpuTime(1L)).thenReturn(1); Mockito.when(mxbean.getThreadCpuTime(2L)).thenReturn(2); assertThat(yourClass.compare(1L, 2L), is(-1)); } } Finally: test get more readable if you replace all Mockito.* calls with static imports, e.g. MyFoo foo = mock(MyFoo.class); when(foo.bar()).thenReturn(baz);
[ "ru.stackoverflow", "0000931407.txt" ]
Q: Объявление переменных вне main функции Правильно ли объявлять переменные вне main функции? Я хочу сделать это, для того чтобы мои переменные были глобальными, но правильно ли такое решение? Есть ли какие-то подводные камни? A: Глобальные переменные в большинстве случаев нарушают инкапсуляцию. К ним открыт неконтролируемый доступ отовсюду. В большом проекте при обилии глобальных переменных возникает путаница в именах. Глобальную переменную же видно отовсюду, надо, чтобы отовсюду было понятно, зачем она. Глобальные переменные в большинстве случаев нарушают принцип инверсии зависимостей (или делают возможным его нарушение). Глобальные переменные ухудшают масштабируемость проекта. Глобальные переменные ухудшают читаемость кода (в каком-то конкретно взятом месте непонятно, нужна ли какая-то конкретная глобальная переменная, или нет). Глобальные переменные приводят к трудноуловимым ошибкам. Примеры: нежелательное изменение её значения в другом месте/другим потоком, ошибочное использование глобальной переменной для промежуточных вычислений из-за совпадения имен, возвращение функцией неправильного значения при тех же параметрах (оказывается, она зависима от глобальной переменной, а ее кто-то поменял). Глобальные переменные создают большие сложности при использовании модульного тестирования. Глобальные переменные увеличивают число прямых и косвенных связей в системе, делая её поведение труднопредсказуемым, а её саму - сложной для понимания и развития. Из этого ответа.
[ "stackoverflow", "0013593124.txt" ]
Q: Jenkins running multiple batch files at once I'm looking for a way to either pause Jenkins or have Jenkins complete a task from a batch file before starting another batch process. Basically what I want is something similar to running: start /wait batchfile.bat but when I run this Jenkins just hangs and the process never actually completes. When I run something like this: run %startpath%\firstbatch.bat run %startpath%\secondbatch.bat Jenkins runs both batch files in different threads and this causes a big problem for me. I need the batch processes to complete because they cook and copy assets. The final batch that gets triggered zips the assets and sends them on their way, but if the assets aren't done being copied, the zip starts without all the files in the directory. The only other way I can think of around this is to have each batch in a different build and adding a quiet period to Jenkins but that would just be a guess to how long the batch scripts are actually running for. Thanks in advance. A: Try using "call batchfile.bat" That should block until the batch file is done running.
[ "stackoverflow", "0045353460.txt" ]
Q: Unevaluated chunk in knitr generates a line break The following Rnw file produces the output shown below. Is there a clean way to prevent the line break in section 2? Of course, this is just a minimal reproducible example; I don't want to remove the unevaluated chunk, which is programatically evaluated or not in my real issue. \documentclass{article} <<setup, include=FALSE>>= knitr::opts_chunk$set(echo = FALSE) @ \begin{document} \section{eval TRUE} <<results='asis'>>= cat("Hello.") @ <<eval=TRUE, results='asis'>>= cat("How are you?") @ What's your name? \section{eval FALSE} <<results='asis'>>= cat("Hello.") @ <<eval=FALSE, results='asis'>>= cat("How are you?") @ What's your name? \end{document} Edit I have one solution so far: <<results='asis'>>= cat("Hello.") if(FALSE) cat("How are you?") @ What's your name? But I'm wondering whether there's a simpler one, which does not require to group the chunks in a single one like this. A: Interestingly, regardless of all options, knitr apparently prints at least a newline for each chunk (even if eval = FALSE, echo = FALSE, results = "hide"). Therefore, the following is just a workaround, but probably a cleaner workaround than the one in the question: Use if in the chunk (in lieu of the chunk option eval) but print % if the chunk is not supposed to be evaluated. This will make TEX ignore the line. \documentclass{article} <<setup, include=FALSE>>= knitr::opts_chunk$set(echo = FALSE) showIt <- FALSE @ \begin{document} \section{eval FALSE} <<results='asis'>>= cat("Hello.") @ <<results='asis'>>= if(showIt) { cat("How are you?") } else { cat("%") } @ What's your name? \end{document}
[ "es.stackoverflow", "0000061592.txt" ]
Q: Problema con RecyclerView y Lista en Android Buenas. Estoy intentando descargar una serie de datos de internet. Para ello, mediante un webservice lleno una lista de objetos. Esta lista la envío al RecycleAdapter para que las muestre en el RecyclerView. Pero al hacerlo, me sale este problema. El caso es que esa lista SI esta llena, y no se que puede pasar. La linea donde dice que esta el error es aqui. Otra cosa curiosa, es que cuando inicio la aplicación, al principio si empieza a mostrar la lista, pero al segundo y poco desaparece y crashea mostrando el error que os he enseñado antes. AÑADO: public void cargarBatallas(){ final LinearLayoutManager layoutManager = new LinearLayoutManager(ctx); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); RecyclerView rviewtimeline = (RecyclerView)this.findViewById(R.id.recyclerView); rviewtimeline.setLayoutManager(layoutManager); //sTextView txtEmpty = (TextView)findViewById(R.id.emptyTimeline); //listTimeLine.setEmptyView(txtEmpty); List<Batalla> batallaList = new ArrayList<Batalla>(); BatallasRecyclerAdapter recyclerAdapter = new BatallasRecyclerAdapter(batallaList); rviewtimeline.setAdapter(recyclerAdapter); GetBatallas getAsync = new GetBatallas(this, key_session, rviewtimeline , GetBatallas.GET_TIMELINE, null, recyclerAdapter); getAsync.execute(); } OnPostExecute (Despues de descargar datos y llenar list) @Override protected void onPostExecute(Object result) { // TODO Auto-generated method stub super.onPostExecute(result); Log.d(msg, "probando"); if(batallaList != null){ Log.d(msg, "probando1"); adapterRecycler.setData(batallaList); adapterRecycler.notifyDataSetChanged();}} Clase Adapter: public class BatallasRecyclerAdapter extends RecyclerView.Adapter<BatallasRecyclerAdapter.BatallaViewHolder>{ List<Batalla> listBatalla; public BatallasRecyclerAdapter(List<Batalla> listBatalla){ this.listBatalla = listBatalla; } public void setData(List<Batalla> listBatalla){ this.listBatalla = listBatalla; } @Override public int getItemCount() { // TODO Auto-generated method stub return listBatalla.size(); } @Override public void onBindViewHolder(BatallaViewHolder viewHolder, int position) { // TODO Auto-generated method stub viewHolder.txtUsuario1.setText(listBatalla.get(position).getUsuario1()); viewHolder.txtUsuario2.setText(listBatalla.get(position).getUsuario2()); } @Override public BatallaViewHolder onCreateViewHolder(ViewGroup parent, int arg1) { // TODO Auto-generated method stub View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.molde_lista, parent, false); BatallaViewHolder holder = new BatallaViewHolder(v); return holder; } public static class BatallaViewHolder extends RecyclerView.ViewHolder{ TextView txtUsuario1; TextView txtUsuario2; public BatallaViewHolder(View itemView) { super(itemView); // TODO Auto-generated constructor stub txtUsuario1 = (TextView)itemView.findViewById(R.id.txtUsuario1); txtUsuario2 = (TextView)itemView.findViewById(R.id.txtUsuario2); } } } A: En este caso el problema es que la clase BatallasRecyclerAdapter no esta instanciada correctamente, al llamar el mètodo setData() marca error ya que la instancia tiene valor null. Este es un ejemplo, pero necesitas agregar la clase porque probablemente reciba valores para inicializaciòn. BatallasRecyclerAdapter RecycleAdapter = new BatallasRecyclerAdapter(); El código correcto para inicializar serìa: @Override protected void onPostExecute(Object result) { // TODO Auto-generated method stub super.onPostExecute(result); Log.d(msg, "probando"); if(batallaList != null){ Log.d(msg, "probando1"); adapterRecycler = new BatallasRecyclerAdapter(batallaList); //adapterRecycler.setData(batallaList); adapterRecycler.notifyDataSetChanged(); } }
[ "softwareengineering.stackexchange", "0000201192.txt" ]
Q: Where should the processing to structured XML be done? I have been given the task of redeveloping an "in house" solution to make it expandable and easier to maintain and administer. The original solution had been hashed together over time using PHP as more requirements were added, and the need to expand is expected into the foreseeable future. The solution, gathers many different files such as word documents and varying structures of XML document, from different "locations" and converts each into a specifically structured XML documents which get sent on via a web service. To add to the mix, some of the original XML files are retrieved from the same "location" but have varying levels of processing that are required depending on where they are from before that (identified by a "customer" field in the XML) My intention is to make the new solution as modular as possible so that processing can be suspended at the individual "customer" or "location" level without affecting anything else. While I have many puzzles to overcome and questions to answer, the question that is keeping me up at night at the moment is "Where should the processing to the structured XML be done?" At present it is done per "customer" but as you can imagine, it leads to a lot of duplicated code. Maybe it is unavoidable, due to the "customer" specific processing required sometimes but sanity tells me there must be a better way. A: My advice would be to invest in learning XSLT (I found a decent tutorial from the perspective of a PHP programmer here). While it's true you could probably accomplish the same thing using only PHP, it could get quite messy. To describe XSLT briefly, in XSLT you define a list of rules which are activated according to the specificity of the XPath used to describe which nodes are affected (very specific nodes described by the xpath have higher priority over more generic rules). It allows you to transform XML into anything, including XML which, you guessed it, means you can perform separate operations if you wish. You can also define rules which activate only when certain nodes are available so for example, if you wanted to apply transform using the customer or location, you simply wouldn't provide information pertaining to anything else, and the corresponding rule does not activate. If you wanted to move the logic to the web service, XSLT is supported in virtually any language that supports XML itself. In any case, this should offer a clean solution that allows you to use a proper technology for handling these types of situations.
[ "stackoverflow", "0026752604.txt" ]
Q: SSRS - multiple matrix tables in one Report (Grouped) I am trying to find a way to pass in a parameter that can have multiple values (customer codes). These customer values then show a matrix table: X column: Months Y column: Years Turnover figures in the body. So this bit was easy. Now I want to be able to pass in more than one customer code and the matrix churns out a new table per customer, ideally when exported to excel it will show one matrix per sheet. I know the easy answer to this is to just keep running the report over and over for each customer but this question is a matter of interest to see if this is possible. Thanks in advance to all that can help A: try with matrix inside tablix .. i just tried creating a similar report with employee/deprtment tablix report grouping done on department Second, matrix report filtering done by department (take parameter) add a row inside group in tablix report and add a matrix report as subreport in that.. pass the parameter department value in subreport ....
[ "stackoverflow", "0061075567.txt" ]
Q: Vanilla JS remove class from previous selection Im working with this part of code <div class="single-select"> <div class="single-title"> <p class="title">User answear</p> <img src="../resources/chevron-down.svg" alt=""> </div> <ul id="single-select-dropdown"> <li class="option" id="option1">answear 1 <img src="../resources/checkmark.svg" alt=""></li> <li class="option" id="option2">answear 2 <img src="../resources/checkmark.svg" alt=""></li> <li class="option" id="option3">answear 3 <img src="../resources/checkmark.svg" alt=""></li> </ul> </div> const dropdownOptions = document.querySelectorAll('.single-select .option'); dropdownOptions.forEach(option => option.addEventListener('click', handleOptionSelected)); function handleOptionSelected(e) { const newValue = e.target.textContent + ' '; const titleElem = document.querySelector('.single-title .title'); titleElem.textContent = newValue; e.target.classList.add('active') } Everytime when i choose option JS should add to class list class 'active'. The point is that only single option can have this class on it. Can someone help me how to remove it everytime when i choose other option? A: Wrap the callback in an anonymous function: //... option.addEventListener('click', function(e) { handleOptionSelected(e); }); //... Then add a the following before the callback: //... //option.addEventListener('click', function(e) { dropdownOptions.forEach(option => option.classList.remove('active')); // handleOptionSelected(e); //}); //... Now whenever the user clicks an option, all options will remove the class .active -- then the callback handleOptionSelected() will add .active to the clicked option. Demo Note: A CSS pseudo-element was added to demonstrate that there is only one .option.active at a time. const dropdownOptions = document.querySelectorAll('.single-select .option'); dropdownOptions.forEach(option => { option.addEventListener('click', function(e) { dropdownOptions.forEach(option => option.classList.remove('active')); handleOptionSelected(e); }); }); function handleOptionSelected(e) { const newValue = e.target.textContent + ' '; const titleElem = document.querySelector('.single-title .title'); titleElem.textContent = newValue; e.target.classList.add('active'); } .option::after { content: ' 'attr(class) } <div class="single-select"> <div class="single-title"> <p class="title">User answear</p> <img src="../resources/chevron-down.svg" alt=""> </div> <ul id="single-select-dropdown"> <li class="option" id="option1">answear 1 <img src="../resources/checkmark.svg" alt=""></li> <li class="option" id="option2">answear 2 <img src="../resources/checkmark.svg" alt=""></li> <li class="option" id="option3">answear 3 <img src="../resources/checkmark.svg" alt=""></li> </ul> </div>
[ "ru.stackoverflow", "0000806927.txt" ]
Q: Добавление в связующую таблицу (many to many) через JDBC? Есть бд, в ней 2 сущности и связь many to many, создаю DAO для crud операций, далее возникает вопрос, я хочу создать developer и добавить ему skill. Как мне добавить данные в таблицу skills_developers? /*Create table developers*/ CREATE TABLE developers ( id INT NOT NULL PRIMARY KEY, name VARCHAR(100) NOT NULL salary VARCHAR(100) NOT NULL ); /*Create table skills*/ CREATE TABLE skills ( id INT NOT NULL PRIMARY KEY, name VARCHAR(100) NOT NULL ); /*Create table skill_developers with links*/ CREATE TABLE skills_developers ( dev_id INT NOT NULL, sk_id INT NOT NULL, FOREIGN KEY (dev_id) REFERENCES developers (id), FOREIGN KEY (sk_id) REFERENCES skills (id) ); public void addDevSkills(String dev_name, String sk_name) { String sql = "INSERT INTO skills_developers (dev_id, sk_id) " + "SELECT developers.id, skills.id " + "FROM developers, skills " + "WHERE d.name = ? AND s.name = ?"; try (Connection connection = ApplicationJDBC.getConnection()) { PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, developer.getFullName()); preparedStatement.setString(2, skill.getName()); } catch (SQLException e) { e.printStackTrace(); } } Почему не добавляет в таблицу?? A: INSERT INTO skills_developers (dev_id, sk_id) SELECT d.id, s.id FROM developers d, skills s WHERE d.name = '?' AND s.name = '?'; В параметрах передаём фамилие персоны и фамилие его умелки. PS. И неплохо бы сделать ALTER TABLE skills_developers ADD PRIMARY KEY (dev_id, sk_id); Ну так, чтобы случайно два раза не добавить...
[ "stackoverflow", "0014617960.txt" ]
Q: Rails activation route I am learning rails and routing has me wanting to jump off the roof. I am confused on how to go about routing my activation at this point. I have the following currently in my user routing: resources :users, only: [:new,:create,:show]. Now I want a route to Users#activate like this www.app.com/users/activate/:a_long_token. Now I know I can just simply do a match '/activate/:auth_token', to: 'users#activate but I am not sure whether this is convention. I was reading this guide on user authentication but it seems its routing is rails 2. Can I do something to add the route mentioned above by simply adding something to the resource itself. By that I mean doing something like (I know this won't work) resource :users do member do get :activate end end A: rails3 guide http://guides.rubyonrails.org/ http://guides.rubyonrails.org/routing.html resources :users do collection do get "activate/:a_long_token" => "users#activate", as: :activate end end rake routes outputs this activate_users GET /users/activate/:a_long_token(.:format) users#activate
[ "stackoverflow", "0031658712.txt" ]
Q: Entity Framework Raw SQL query selecting unknown columns (unknown return type) I'm having trouble running raw sql against an entity dataset when I dont know the type that needs to be returned. The scenario is that the page generates the sql on the fly, based on the options the user selects (Building both the 'Select' and 'Where' part of the statements) then tries to pull them using: string sSQL = "SELECT " + sSelect + " FROM dbo.Staff "; if (!string.IsNullOrWhiteSpace(sWhere)) { sSQL += "WHERE " + sWhere; } DAL.AcdmContext ds = new DAL.AcdmContext(); var resultSet = ds.Database.SqlQuery(sSQL).ToList(); It seems to be that it can't use an anonymous type for the resultset. The problem is that because the select statement is generated on the fly, I can't generate a class or similar for the resultset beforehand - there's too many combinations. I can pull a query of every column, or with one column by var resultSet = ds.Database.SqlQuery<string>(sSQL).ToList(); but I cant find a way to do it with any other number of columns - i've tried as <string[]> and IEnumerable<string> My last thought is to pull the whole set of columns and filter it to what I need after the fact, but that just seems wasteful. Is there a better solution? (Oh, and before anyone says, I know I should be using params in the query - I temporarily took them out to try and get this working) Thanks! A: There maybe a possible solution to do the query the way your trying to do http://www.codeproject.com/Articles/206416/Use-dynamic-type-in-Entity-Framework-SqlQuery But even if it works i seriously advise against it, building a query like that is horrible even if you use params. Much better to just map the entity normally and use LINQ to Entities to generate the query for you. Yes it will bring columns you don't need but unless you are selecting many thousands or millions of records it probably wont have much of an impact on performance and it will much better (and much more maintainable) code and linq to entities will, if I'm not mistaken, take care security problems like Sql Injection
[ "stackoverflow", "0002516665.txt" ]
Q: How can I monitor the rendering time in a browser? I work on an internal corporate system that has a web front-end using Tomcat. How can I monitor the rendering time of specific pages in a browser (IE6)? I would like to be able to record the results in a log file (separate log file or the Tomcat access log). EDIT: Ideally, I need to monitor the rendering on the clients accessing the pages. A: In case a browser has JavaScript enabled one of the things you could do is to write an inline script and send it first thing in your HTML. The script would do two things: Record current system time in a JS variable (if you're lucky the time could roughly correspond to the page rendering start time). Attach JS function to the page onLoad event. This function will then query the current system time once again, subtract the start time from step 1 and send it to the server along with the page location (or some unique ID you could insert into the inline script dynamically on your server). <script language="JavaScript"> var renderStart = new Date().getTime(); window.onload=function() { var elapsed = new Date().getTime()-renderStart; // send the info to the server alert('Rendered in ' + elapsed + 'ms'); } </script> ... usual HTML starts here ... You'd need to make sure that the page doesn’t override onload later in the code, but adds to the event handlers list instead. A: The Navigation Timing API is available in modern browsers (IE9+) except Safari: function onLoad() { var now = new Date().getTime(); var page_load_time = now - performance.timing.navigationStart; console.log("User-perceived page loading time: " + page_load_time); }
[ "stackoverflow", "0009419710.txt" ]
Q: Invalid object name SQL Server 2008 R2 - Stored procedure I am attempting to alter an existing stored procedure with the command ALTER 'name_of_stored"procedure' however the name is highlighted in red noting it is an invalid object. I am able to execute the command successfully however am wanting to know why SQL Server 2008 R2 notes it as an error. A: It's SSMS, not SQL Server. If it's an error against the database engine you'll know it (it wouldn't execute the command successfully). Solution You need to refresh the Intellisense cache (Ctrl + Shift + R). Or you can go to Edit -> IntelliSense -> Refresh Local Cache. A: Create a stored procedure by using CREATE PROCEDURE, not ALTER PROCEDURE. A: Intellisense doesn't refresh as quickly as you create new objects. You need to refresh the cache (Ctrl + Shift + R). Or, maybe, don't rely on Intellisense and only worry if the execution fails.
[ "academia.stackexchange", "0000145952.txt" ]
Q: Can PhD students turn down teaching assistantships? This question deals with PhD programs which guarantee their students funding via teaching assistantships in the US. In order to have more time for themselves (e.g., for PhD research, or for working a higher-paying part-time job), are PhD students normally allowed to decline teaching assistantships, as long as they're willing to forgo the department's stipend? In addition to losing the stipend, are there other disadvantages to declining a TA position? (E.g., would tuition no longer be free?, could the department be frustrated?, etc.) A: Turning down a teaching assistant position in your position is probably a very poor idea. The renumeration for working as a TA normally covers both the a stipend and your graduate tuition. If you do not have some other form of support (research assistantship or fellowship), you will have to pay your own way entirely. This is normally financially prohibitive, although there are sometimes exceptions. Moreover, some doctoral programs (such as my own) actually require that students spend a certain time working as TAs. The teaching is considered a part of their professional training. So even students who might have other ways of funding their entire graduate education may have to spend a certain amount of time teaching. A: If not explicitly forbidden by other stipulations this can indeed be perfectly acceptable and in your interest. However, my recommendation is to tread carefully. For example, doing so might be frowned upon by the department because they need TAs which can lose you significant goodwill. Or your supervisor disapproves because they think you are refusing an important opportunity to mature as a teacher and scientist. Thus you should definitely take into account whether there are any (local) drawbacks. If in doubt, talk to your supervisor! We on the internet cannot tell you what those are.
[ "stackoverflow", "0022250730.txt" ]
Q: Converting Ruby Hash into YAML for locales that already exist There are lots of locales files on my application and they all are in .rb files using the Ruby Hash. What I want is simple: there is a way to convert them all into .yml with no stress? Can be an online converter (I already searched about it but without success) or even a Ruby trick. What I already have tried For test proposals, I copied an entire code of a .rb and used .to_yml after that. The result? Inline scripting – in this case, there's something that can I do? A: Why not right a script in Ruby? require "yaml" File.write(destination_yaml_file, YAML.dump(eval(File.read(original_ruby_file))))
[ "stackoverflow", "0043333025.txt" ]
Q: Polymer 2.0: polymer 1.0 hybrid elements not working in polymer 2.0? New to polymer 2.0! Polymer 1.0 elements don't work correctly with polymer 2.0. What to do? Can someone please provide a link for polymer 2.0 starter kit which also has new polymer 2.0 compatible elements. So that i can setup a new project for polymer 2.0 from scratch and work without any hassle. I have bower installed, so bower code for setting new polymer 2.0 project is welcome. thanks for help. A: well, is it so hard to type upgrade guide polymer into google search bar ? of course Polymer 1.x elements won't work in 2.0 because there is completely new syntax and different way of creating elements, styling them and so on. You can see all changes here: https://www.polymer-project.org/2.0/docs/upgrade If your project isn't big or you just trying to play with polymer it's better to start from scratch. use official Polymer documentation but switch to Polymer 2.0
[ "stackoverflow", "0034115289.txt" ]
Q: get value from viewbag property in javascript i need to assign value from viewbag property to javascript variable I have gone through some of the posts and created the code as per that .. var selectedID = null; @if (ViewBag.Section != null) { <script type="text/javascript"> selectedID =ViewBag.Section ; </script> } But the Problem is that it is not accepting the ViewBag Property inside script and displaying syntax error . Most of the posts has this format of solution , I have tried solution like : 1. @{selectedID =ViewBag.Section ;} 2. @if(ViewBag.DoAboutTab != null) { var doAboutTab ="something"; } else { var doAboutTab ="something_else"; } this solution is not assigning value to variable outside the @{} code I am able to set constant value but not Viewbag Property by this solution 3.selectedID = '@ViewBag.Section' !== @ViewBag.Section; this solution is also no working when @ViewBag.Section is null how can I fix the script problem? A: <script type="text/javascript"> var selectedID = @Html.Raw(Json.Encode(ViewBag.Section)); </script> If ViewBag.Section is not defined then you will get: <script type="text/javascript"> var selectedID = null; </script> and if for example ViewBag.Section equals to Some nasty escaped " string then you will get a properly encoded value which will not break your javascript: <script type="text/javascript"> var selectedID = "Some nasty escaped \" string"; </script>
[ "stackoverflow", "0037651727.txt" ]
Q: Savinging and generating AVMetadataMachineReadableCodeObject Swift I'm having some serious issues here trying to save a AVMetadataMachineReadableCodeObject in Swift. I'm using this library: https://github.com/yeahdongcn/RSBarcodes_Swift, but it has terrible documentation. Basically, I can scan fine and can handle that scan and future scans to build a "Scan History" type screen... The problem comes in when I restart the application - my Scan History is empty (obviously). I need to save these scans locally somehow but I'm not sure how to do that. I've tried saving the attributes of a scan but rebuilding it after app restart is proving to be just as tricky. I've tried saving them as custom objects (which would be ideal and is possible - except for the AVMetadataMachineReadableCodeObject part as I get errors like non-property etc) I'm approaching the point where I think I should try something like Realm but I've never used it before. A: You can't easily save AVMetadataMachineReadableCodeObject to Core Data, because it's not a supported type and does not conform to NSCoding. Switching to Realm won't make any difference, because it has the same restrictions (it can't just save an AVMetadataMachineReadableCodeObject). The reasons are similar-- in both cases AVMetadataMachineReadableCodeObject isn't a subclass of the appropriate type, and it's not one of the supported property types. What you need to do depends on how exactly your scan history UI is supposed to look. Saving the AVMetadataMachineReadableCodeObject is almost certainly not the best approach, though (you might be able to add NSCoding through a Swift extension but it's probably the wrong answer even if it works). There are a couple of possibilities: Save the data represented by the scanned code instead of the code itself. You get this from the stringValue property of AVMetadataMachineReadableCodeObject. When you want to show the scan history, generate new images to display. This is straightforward using Core Image-- COQRCodeGenerator, CIAztecCodeGenerator, CICode128BarcodeGenerator, and CIPDF417BarcodeGenerator are all built in. Take a photo at the same time as you scan the image, and display the photo as the scan history entry. Include the stringValue of the scanned code in the UI so that people can see what the image represents.
[ "stackoverflow", "0023552879.txt" ]
Q: Writing Angular Unit Tests After the App is Written? I've inherited a medium sized angular app. It looks pretty well organized and well written but there's no documentation or unit tests implemented. I'm going to make an effort to write unit tests posthumously and eventually work in e2e tests and documentation via ngdoc. I'm wondering what the best approach to writing unit tests is after the fact. Would you start with services and factories, then directives etc or some other strategy? I plan on using Jasmine as my testing framework. I should also mention that I've only been with the code for a few days so I'm not 100% sure how everything ties together yet. A: At the end of the day what you need to know is that your software works correctly, consistently, and within business constraints. That's all that matters, and TDD is just a tool to help get you there. So, that's the frame of mind from which I'm approaching this answer. If there are any known bugs, I'd start there. Cover the current, or intended, functionality with tests and work to fix the bugs as you go. After that, or if there aren't any currently known bugs, then I'd worry about adding tests as you begin to maintain the code and make changes. Add tests to cover the current, correct functionality to make sure you don't break it in unexpected ways. In general, writing tests to cover things that appear to be working, just so that you can have test coverage, won't be a good use of time. While it might feel good, the point of tests is to tell you when something is wrong. So, if you already have working code and you never change it, then writing tests to cover it won't make the code any less buggy. Going over the code by hand might uncover as yet undiscovered bugs, but that has nothing to do with TDD. That doesn't mean that writing tests after the fact should never be done, but exhaustive tests after the fact seems a bit overkill. And if none of that advice applies to your particular situation, but you want to add tests anyway, then start with the most critical/dangerous parts of the code - the pieces that, if something goes wrong you're going to be especially screwed, and make sure those sections are rock-solid.
[ "stackoverflow", "0015109099.txt" ]
Q: Expand UITableView cell in UITableViewstylePlain I want to expand tableview cell on it's click. There is a tableview in which two cells are expandable and others are not. I need when i click on expandable cell it should show cells under it and on clicking again it should hide. There is a image below defining this. How can i achieve this functionality, please guide for the above. Thanks in advance. A: Here is the complete Tutorial with Expandable UITableView Here’s the code snip for that. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if ([self tableView:tableView canCollapseSection:indexPath.section]) { if (!indexPath.row) { // only first row toggles exapand/collapse [tableView deselectRowAtIndexPath:indexPath animated:YES]; NSInteger section = indexPath.section; BOOL currentlyExpanded = [expandedSections containsIndex:section]; NSInteger rows; NSMutableArray *tmpArray = [NSMutableArray array]; if (currentlyExpanded) { rows = [self tableView:tableView numberOfRowsInSection:section]; [expandedSections removeIndex:section]; } else { [expandedSections addIndex:section]; rows = [self tableView:tableView numberOfRowsInSection:section]; } for (int i=1; i<rows; i++) { NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i inSection:section]; [tmpArray addObject:tmpIndexPath]; } UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; if (currentlyExpanded) { [tableView deleteRowsAtIndexPaths:tmpArray withRowAnimation:UITableViewRowAnimationTop]; cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeDown]; } else { [tableView insertRowsAtIndexPaths:tmpArray withRowAnimation:UITableViewRowAnimationTop]; cell.accessoryView = [DTCustomColoredAccessory accessoryWithColor:[UIColor grayColor] type:DTCustomColoredAccessoryTypeUp]; } } } } as shown below picture This and this one solution also help you to understand how to manage Expandable TableView A: Okay, what I'm thinking is, The titles, Events, Overhead and Friends would be the custom UIView with UIImageView for background, UILabel for title, and UIButton for expand. So basically - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView having return count of the titles you've. - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section having return UIView for each titles. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section having count of the rows within that title. You may need to maintain an array for this. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; having height of the cell item - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section initially it should be 0 (zero) for all sections, when user tap on expand, it should be increase with respect to number of rows * cell height within that section. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath You may need some good logic for setting all rows for expansion Your expansion buttons actions something like, - (void) expandSection:(UIButton *)sender; that you can identify which section to be expand using sender.tag, so don't forget to add tag properly. You may need an int in .h file for store the current section, and can be use in - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section datasource method. A: I think What you want is already given by Apple. You can take a look at Sample Code provided by Apple under the title of Table View Animations and Gestures.
[ "stackoverflow", "0041299385.txt" ]
Q: Where to define a QuerySet in Django I want to define a queryset. In the shell it is all fine and I can filter the column I want with: pat1 = Patient.objects.get(pk=1) pat1.examinationgeometry_set.filter(examination='FIRST') now I want to define a QuerySet out of it but I don't know where to define it and how. In the Views, Templates, Models? And how do I write it? I know that I have to define it with a function but is there any function from django for it? Idea behind this queryset is to show all of the results in my database from the first examination. So in my template I have sth like this: {% if Patient.examinationgeometry_set.filter(examination='FIRST') %} {% for geo in patient.examinationgeometry_set.all %} <li> x: {{ geo.x }}<br/> c: {{ geo.c }} <br/> b: {{ geo.b}}<br/> n: {{ geo.n}}<br/> </li> {% endfor %} {% endif %} I am thankful for every hint! A: Querysets should be made in the view, not in the template, given your code, it should be something like this: view.py: def my_view: patients = Patient.objects.all() context = {"patients": patients} return render(request, "template_path", context) template.html: {% for patient in patients %} {% for geo in patient.examinationgeometry_set.all %} {% if geo.examination == 'FIRST' %} <li> x: {{ geo.x }}<br/> c: {{ geo.c }}<br/> b: {{ geo.b}}<br/> n: {{ geo.n}}<br/> </li> {% endif %} {% endfor %} {% endfor %} A better option is to make a python property for your patient model like this: class Patient(stuff): # your model stuff @property def first_examinationgeometry_set(): # maybe this should use .get() instead of filter? return self.examinationgeometry_set.filter(examination="FIRST") and now call this in the template(same view as first example): {% for patient in patients %} {% with geo=patient.first_examinationgeometry_set %} <li> x: {{ geo.x }}<br/> c: {{ geo.c }}<br/> b: {{ geo.b}}<br/> n: {{ geo.n}}<br/> </li> {% endwith %} {% endfor %}
[ "stackoverflow", "0034936154.txt" ]
Q: Google MDL - Creating card in jquery shows only text - no background or border I have the following code which creates an MDL Card on the fly var resultsHolder = $('#resultsHolder'); var gridHolder = $('<div>',{ 'class' : 'mdl-grid' }); var card = $('<div>',{ 'class' : 'mdl-card.mdl-shadow--2dp data-display' }); var title = $('<div>',{'class' : 'mdl-card__title'}); var h4 = $('<h4>'); var supportingText = $('<div>',{'class' : 'mdl-card__supporting-text'}); var supportingPara = $('<div>',{'class' : 'projectDesc'}); h4.append($('#projectName').val()); title.append(h4); supportingPara.append($('#projectDesc').val()); supportingText.append(supportingPara); card.css('width','100%'); card.append(title); card.append(supportingText); gridHolder.append(card); resultsHolder.prepend(gridHolder); componentHandler.upgradeElement(resultsHolder); While the contents of the new card appears. None of the border or background appears. I have seen the following link How can I update/refresh Google MDL elements that I add to my page dynamically? but using any of the following; componentHandler.upgradeDom(); componentHandler.upgradeElement(); pass the class of the card holder - $('#resultsHolder') None seem to make a difference. So how can I make my full card appear. A: Eventually managed it not with JQuery but using raw JavaScript to create the elements. So a revised version which creates a card, title, supporting text and actions is as follows; var resultsHolder = document.getElementById('resultsHolder'); var gridHolder = document.createElement('div'); var card = document.createElement('div'); var title = document.createElement('div'); var h4 = document.createElement('h4'); var supportingText = document.createElement('div'); var supportingPara = document.createElement('p'); var cardActions = document.createElement('div'); var detailButton = document.createElement('button'); try { // assign classes gridHolder.className = 'mdl-grid'; card.className = "mdl-card mdl-shadow--2dp data-display"; title.className = 'mdl-card__title'; supportingText.className = 'mdl-card__supporting-text'; supportingPara.className = 'projectDesc'; cardActions.className = 'mdl-card__actions mdl-card--border mdl-typography--text-right'; detailButton.className = 'mdl-button mdl-js-button mdl-js-ripple-effect'; // add special styles card.style.width = '100%'; // card.style.opacity = '0'; // add text h4.innerHTML = $('#projectName').val(); supportingPara.innerHTML = $('#projectDesc').val(); detailButton.innerHTML = 'Details'; // build the title title.appendChild(h4); // build the supporting text supportingText.appendChild(supportingPara); // build the actions cardActions.appendChild(detailButton); // build the card card.appendChild(title); card.appendChild(supportingText); card.appendChild(cardActions); gridHolder.appendChild(card); resultsHolder.insertBefore(gridHolder,resultsHolder.firstChild); // now upgrade components so they are handled correctly by mdl componentHandler.upgradeDom(gridHolder); } catch(e) { alert( e ); }
[ "codereview.stackexchange", "0000056092.txt" ]
Q: Searching all diagonals of a 2D M x M array I've started writing a piece of code to help me search for an object in all the objects found in the diagonals of an M x M 2D array. Though the code works, I'd like to know if there is a way I can improve on it or there exists a different technique I could use to achieve the same result with fewer lines of code. I just don't want to re-invent the wheel. // board must be a square matrix bool allDiagonals(string[] board, string strToFind) { string s = ""; for (int col = board[0].Length - 1; col >= 0; col--) { int row = 0; int j = col; s = ""; while (j <= board[0].Length - 1) { s += board[row++][j++]; } if (s.Contains(strToFind)) return true; } for (int row = board.Length - 1; row > 0; row--) { int colmin = 0; s = ""; for (int i = row; i < board.Length; i++) { s += board[i][colmin++]; } if (s.Contains(strToFind)) return true; } for (int col = 0; col <= board[0].Length - 1; col++) { int row = 0; int j = col; s = ""; while (j >= 0) { s += board[row++][j--]; } if (s.Contains(strToFind)) return true; } for (int row = board.Length - 1; row > 0; row--) { s = ""; int colmax = board[0].Length - 1; //scan from bottom right to main diagonal for (int i = row; i < board.Length; i++) { s += board[i][colmax--]; } if (s.Contains(strToFind)) return true; } return false; } A: This reminds me of what I wrote a while ago for my Tic Tac Toe Ultimate game. In case I get anything wrong, here is a relevant part of my original code: // Scan diagonals for a winner: Bottom-right for (int yy = 0; yy < board.getSizeY(); yy++) { newWin(conds, consecutive, loopAdd(board, 0, yy, 1, 1)); } private static List<Winnable> loopAdd(HasSub<? extends Winnable> board, int xx, int yy, int dx, int dy) { List<Winnable> winnables = new ArrayList<>(); Winnable tile; do { tile = board.getSub(xx, yy); xx += dx; yy += dy; if (tile != null) winnables.add(tile); } while (tile != null); return winnables; } When making this in C#, you can return IEnumerable<char>. The idea of the method is to start at a specific point and to iterate until you're outside the valid area. I think it's a bad idea that you're currently using String concatenation first, and then checking if the string contains the char. Instead you can indeed as Carsten points out in the comments use a state machine for that. It only needs to be about an int really that keeps track of how many consecutive matches you've had so far, and when it reaches a non-match it starts over at zero. When it reaches the string length, it returns true. Anyways, back to the main part, here's what I would try to do: private IEnumerable<char> loopOver(string[] board, Point position, Point delta) { char value; while (true) { if (!charIsInsideBoard(board, position)) break; value = getCharInBoard(board, position); position.x += delta.x; position.y += delta.y; yield return value; } } Whenever I'm using C#, I love using the wonderful yield keyword. private boolean contains(IEnumerable<char> loop, string searchFor) { int matches = 0; foreach (char ch in loop) { if (ch == searchFor[matches]) { matches++; } else { matches = 0; if (ch == searchFor[matches]) { matches++; } } if (matches == searchFor.Length) { return true; } } return false; } Then in your allDiagonals method (which really could be renamed to searchAllDiagonals) all you need to do is to call the contains and loopOver methods a couple of times. boolean searchAllDiagonals(string[] board, string searchFor) { boolean result = false; for (int i = 0; i < board[0].Length; i++) { result = result || contains(loopOver(board, new Point(i, 0), new Point(1, 1), searchFor); } for (int i = 0; i < board.Length; i++) { result = result || contains(loopOver(board, new Point(0, i), new Point(1, 0), searchFor); } ... } Please note that I have not tested this code, and as I haven't done any C# development since last time I might have mixed something up. I also might have mixed up X and Y, but that happens for me in Java too every now and then. Other Suggestions: Don't use i and j when you're using nested loops. row and col are so much better, or x and y. I myself use xx and yy sometimes for loops when I already have another x / y variable. As your variable is named board, what do I know, perhaps your whole point is to check for a winner in a Tic Tac Toe game. If a game is your context, then I'd recommend not using string[]. Use a BoardField[][] variable instead, or preferably wrap such a 2D array in a Board class (which can contain the charIsInsideBoard and getCharInBoard methods). A: Let me tell you something about strings. In .NET, String is an immutable type -- it can only be set when it's created, and it can't be changed. The only way to change it is to create an entirely new string which has the desired content. String concatenation doesn't change the original string; it creates a new string. Repeated string concatenation is very time and space inefficient, as the whole string has to get copied each time. But what about when you need to build a string up from pieces? .NET also provides the StringBuilder class, which is mutable: you can change it however you like, most notably, it's efficient to add pieces onto the end of it. However you don't actually need to do either of these; using a state machine is the right way to do things. Don't repeat yourself. You have practically the same code written four times (even though you accomplish the same thing in different ways), to search the 45,135,215, and 305 diagonals. You need to find some way to refactor that so the code is only written once. Simon's idea (passing dx and dy) is a good one. I also wonder if it would be profitable to build the state machine (lexer) to simultaneously search for the target string and its reversal, so that way you only need to run over two diagonals.
[ "stackoverflow", "0060679161.txt" ]
Q: Stripe + NextJs - window is not defined I'm trying to use Stripe in NextJs https://github.com/stripe/react-stripe-elements/blob/master/README.md#server-side-rendering-ssr I keep getting the error "window is not defined". Am I missing something? The code is at the link above. A: "window is not defined" is shown due to the fact that your code is server-side rendered and can't access the global window object because that is something only a client will understand. move your code inside lifecycle methods as they run only on the client-side.
[ "stackoverflow", "0042623360.txt" ]
Q: Charge with Stripe only when specific option selected I have a Schedule model with current enum: enum delivery_option: { drop_off: 'drop_off', pick_up: 'pick_up' } Here's the Schedules controller create action: (which charges $25 for both options) def create @schedule = Schedule.new(schedule_params) amount = 25 * 100 customer = Stripe::Customer.create( email: params[:stripeEmail], card: params[:stripeToken] ) charge = Stripe::Charge.create( customer: customer.id, amount: amount, description: 'Rails Stripe customer', currency: 'usd' ) end When User creates a Schedule he can choose either pick_up or drop_off. I need to charge User for $25 ONLY for pick_up option. How do I do this? A: If you want to charge to customer for specific option, then yu can put condition like following Create one method def create @schedule = Schedule.new(schedule_params) amount = 25 * 100 customer = Stripe::Customer.create( email: params[:stripeEmail], card: params[:stripeToken] ) create_charge(customer, amount, 'Rails Stripe customer', 'usd') if schedule_params[:delivery_option] == "pick_up" end private def create_charge(customer, amt, desc, currency) Stripe::Charge.create( customer: customer.id, amount: amt, description: desc, currency: currency ) end