source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0026951715.txt" ]
Q: Android Studio - how was this resource file structure trick achieved? I was checking out the Google I/O app source code in Android studio, and I came across this IDE layout of the res/ folder - how was this achieved? But if I look at my filesystem at the actual file structure, it's the conventional values/styles.xml, values-v17/styles.xml, values-v21/styles.xml arrangement. How can I achieve this in my own app? A: This is the "android" project view, where the group together different files in order to minimise file differences vs folder differences. This is default in Android 0.9.x A: In 0.8.4, they added the "Android project view", which is what you're seeing. In 0.8.12, it is the default, but presumably only for new projects, which is why I was not seeing it in my fiddling with 0.8.14 today. It is also the default in the parallel 0.9.x series in the canary channel.
[ "stackoverflow", "0005657800.txt" ]
Q: Python Desktop Program Using Web APIs I have a very random request from a client wanting a desktop based program that can retrieve information from web based APIs such as Google Analytics, SEOMoz and other similar services. They then want parts or all of these results stored in a central location. They have said they DO NOT want a web application at all, but they do want the ability to have the data stored on a "server" (read, server version of the desktop client) on their LAN. The program should be able to run on Windows. Linux and OS X support would be nice. I have some programming experience and am semi-familiar with Python so I was thinking about using it. My problem is that I am unsure about the communication between clients/servers on the LAN and the communication between the client and web based APIs. 1) Is this even possible? If so, what are good places to look for resources on the API integration and network communication/any good examples? 2) Any suggestions/tips on what to look out for (e.g, common mistakes, major security issues)? 3) Any ways that would be better than what I have outlined above? 4) Database, what would be good options? I would like to make this as independent as possible and more or less self contained (relying on a minimal amount of installed software). Thanks for any and all input! A: yes, urllib, urllib2 and urlparse are the core python libs for reading to/from urls. I would suggest PyQt for the gui framework (pyGTK, wxWidgets and tkinter would be fine also, they all run fine on the three os's you've mentioned). PyQt includes everything you would need, without reaching into any other library. It includes network access controls, QUrl for url parsing and construction and plenty of GUI tools for displaying the data. nothing out of the norm, except see [1] in 4 see 1 about PyQt. But what you're going to end up doing is crafting the urls you want to access (including all get/post parameters), sending the data, listening for the data, parse data, place in db. Client would just query db, get results, filtering/ordering/management would be done in the gui code. QtDeclarative might be a good choice for allowing users to craft their own queries (Thought of but never implemented this yet), which you can execute too. I would suggest postgres, mysql, or any db, relational or not (see mongodb, but don't think PyQt supports it yet, but you can use any python lib with pyqt nicely). Then you can store the data there, have the clients query it and have a client sit on the server, that has extra functionality to query the sites and insert the data Though this might be better served as cli tool that gets the data and inserts into the db (so you can run it on a cron job if wanted). You would only need to develop the client code and database schema. [1] Remember db's can have multiple clients and users directly connect to a database server. The only real caveat is configuring the server to listen only on the lan to receive the client, and the users permissions are set correctly. This is just cosmetically different from connecting a webapp to the db. You're just granting more users and clients access. Your biggest problem should be figuring out how to deal with the tediousness of GUI Programming :P
[ "stackoverflow", "0031370585.txt" ]
Q: Format table cells according to datatype using Jinja2/Bootstrap I'm trying to automate a manual task where, every day, a colleague logs in to various systems, cuts/pastes chunks of data into an email, and then sends it to a group of people. I'm using Jinja2 for the template engine, and Bootstrap to make it look beautiful. Here's what's been done so far: https://gist.github.com/alexwoolford/ac342289bb90c5dda524 Some of the columns are percentages, some are counts, and some are dollars. For percentages, I'd like to multiply the value by 100, round to two decimal places, and add a percent sign (e.g. 0.34567 would be displayed as 34.57%). For counts, I'd like to comma separate the thousands (e.g. 1234567 would be displayed as 1,234,567). For dollars, I'd like to add a dollar sign, round to the nearest whole integer, and comma separate the thousands (e.g. 2345.67 would be displayed as $2,346). Ideally, I'd like to simply add a class to the table cells in the template like this: <td class='percent'>{{ row.some_percent_val }}</td> <td class='count'>{{ row.some_count }}</td> <td class='dollar'>{{ row.some_dollar_value }}</td> What would I need to do to the Jinja2 template to format the columns correctly? A: css is not going to give you what you want. You'll need to use the jinja filter system. Some of the built filters like format can probably get you most of the way there. But you may need to create some custom ones. For example you could do this to get a nice dollar display: <td class='dollar'>{{ "${:,.2f}" | format (row.some_dollar_value)}}</td> if you prefer, you can use all the built in python methods on the string variable: {{ "${:,.2f}".format (row.some_dollar_value)}} Documentation for creating your own custom filters can be found here: http://jinja.pocoo.org/docs/dev/api/#custom-filters
[ "stackoverflow", "0027399537.txt" ]
Q: Assertion failure in [CustomNavigationController popToViewController:transition:] I want to pop view controllers until the desired view controller is at the top of the navigation stack. I'm doing it this way: UIViewController *aViewController = [self.navigationController.viewControllers objectAtIndex:lViewControllerIndex]; [self.navigationController popToViewController:aViewController animated:YES]; From the debugger I can see that aViewController is <MainViewController: 0x79ea3b10> and self.navigationController.viewControllers is <MainViewController: 0x79ea3b10>, <FirstViewController: 0x79eb2630>, <SecondViewController: 0x7b258f10> Currently I'm in SecondViewController and I want to go back to MainViewController But it crashes, the crash message is the following: ***** Assertion failure in -[CustomNavigationController popToViewController:transition:], /SourceCache/UIKit_Sim/UIKit-2935.137/UINavigationController.m:4912** How can I correctly go back by popping multiple view controller ? UPDATED [1]: I was not clear, I don't need a way how to pop to root view controller, I need a way how to pop multiple view controllers. Above, it was only an example going from SecondViewController to MainViewController UPDATED [2]: Stack trace: 0 CoreFoundation 0x030a81e4 __exceptionPreprocess + 180 1 libobjc.A.dylib 0x02e218e5 objc_exception_throw + 44 2 CoreFoundation 0x030a8048 +[NSException raise:format:arguments:] + 136 3 Foundation 0x00c7d4de -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116 4 UIKit 0x01a45ab8 -[UINavigationController popToViewController:transition:] + 918 5 UIKit 0x01a4571d -[UINavigationController popToViewController:animated:] + 56 6 Isi For You 0x000a14b7 -[DetailViewController breadcrumbItemPressedAtIndex:] + 327 7 Isi For You 0x000c4460 -[ListHeaderViewController breadcrumbView:didTapItemAtIndex:] + 144 8 Isi For You 0x00094772 -[BTBreadcrumbView didTapItemAtIndex:] + 162 9 Isi For You 0x0009480f -[BTBreadcrumbView tapItemButton:] + 143 10 libobjc.A.dylib 0x02e33880 -[NSObject performSelector:withObject:withObject:] + 77 11 UIKit 0x018fe3b9 -[UIApplication sendAction:to:from:forEvent:] + 108 12 UIKit 0x018fe345 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 61 13 UIKit 0x019ffbd1 -[UIControl sendAction:to:forEvent:] + 66 14 UIKit 0x019fffc6 -[UIControl _sendActionsForEvents:withEvent:] + 577 15 UIKit 0x019ff243 -[UIControl touchesEnded:withEvent:] + 641 16 UIKit 0x0193dddd -[UIWindow _sendTouchesForEvent:] + 852 17 UIKit 0x0193e9d1 -[UIWindow sendEvent:] + 1117 18 UIKit 0x019105f2 -[UIApplication sendEvent:] + 242 19 Isi For You 0x00434244 -[CustomUIApplication sendEvent:] + 100 20 UIKit 0x018fa353 _UIApplicationHandleEventQueue + 11455 21 CoreFoundation 0x0303177f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15 22 CoreFoundation 0x0303110b __CFRunLoopDoSources0 + 235 23 CoreFoundation 0x0304e1ae __CFRunLoopRun + 910 24 CoreFoundation 0x0304d9d3 CFRunLoopRunSpecific + 467 25 CoreFoundation 0x0304d7eb CFRunLoopRunInMode + 123 26 GraphicsServices 0x042cc5ee GSEventRunModal + 192 27 GraphicsServices 0x042cc42b GSEventRun + 104 28 UIKit 0x018fcf9b UIApplicationMain + 1225 29 Isi For You 0x000449e2 main + 82 30 libdyld.dylib 0x038796d9 start + 1 ) A: That error usually occurs when the View Controller you are trying to pop to is not in the navigation stack. Although in your case it would seem that you view controller is in fact there... You can use popToRootViewControllerAnimated: to pop to your "root". [self.navigationController popToRootViewControllerAnimated:YES];
[ "stackoverflow", "0023076769.txt" ]
Q: SQL Query to return matches I have this query below: SELECT ied.[Reference] ,Count(*) AS 'Hits' FROM dbo.ItemExportDefinition ied WITH (NOLOCK) LEFT JOIN dbo.[Hits] WH WITH (NOLOCK) ON ied.[Reference] COLLATE DATABASE_DEFAULT = CASE WHEN CHARINDEX('&', WH.QUERY, 0) = 0 THEN SUBSTRING(WH.QUERY, 4, 30) WHEN CHARINDEX('&', WH.QUERY, 0) > 0 THEN SUBSTRING(SUBSTRING(WH.QUERY, 0, CHARINDEX('&', WH.QUERY)), 4, 100) ELSE WH.QUERY END GROUP BY ied.[Guide Web Reference] ORDER BY Hits DESC It returns these values: ESC7730AE5 273697 ES4904A3EA 152392 ES0C69E6B9 11829 ES2413515E 5653 ESBA042518 1144 ES193DFEC8 1067 ESBF086D49 77 ES0AA87194 25 ESIXVY6881 9 ESE77AEF31 4 ES4087624D 3 ESF8BD9328 2 What I want is that I want to get the results where the count is 0. So for example it look like this: ESC7730AE5 273697 ES4904A3EA 152392 ES0C69E6B9 11829 ES2413515E 5653 ESBA042518 1144 ES193DFEC8 1067 ESBF086D49 77 ES0AA87194 25 ESIXVY6881 9 ESE77AEF31 4 ES4087624D 3 ESF8BD9328 2 ESF8BD9328A 0 ESF8BD932832 0 ESF8BD932888 0 Thanks. A: Change Count(*) AS 'Hits' on Count(WH.QUERY) AS 'Hits' Count(*) counts all rows, Count() - count amount of values in (except NULLs)
[ "stackoverflow", "0034869754.txt" ]
Q: Visual Studio Prerequisites installs already installed packages I am using VS 2015 where there is no prerequisite for Visual C++ Redistributable for visual studio 2012. So I created a custom bootstrapper and stored in the VS bootstrapping folder. package.xml <Package xmlns="http://schemas.microsoft.com/developer/2004/01/bootstrapper" Name="DisplayName" Culture="Culture" > <Strings> <String Name="DisplayName">Visual C++ 2012 Runtime Libraries (x86)</String> <String Name="Culture">en</String> <String Name="AdminRequired">You do not have the permissions required to install Visual C++ 2012 Runtime Libraries (x86). Please contact your administrator.</String> <String Name="InvalidPlatformWin9x">Installation of Visual C++ 2012 Runtime Libraries (x86) is not supported on Windows 95. Contact your application vendor.</String> <String Name="InvalidPlatformWinNT">Installation of Visual C++ 2012 Runtime Libraries (x86) is not supported on Windows NT 4.0. Contact your application vendor.</String> <String Name="GeneralFailure">A failure occurred attempting to install Visual C++ 2012 Runtime Libraries (x86).</String> <String Name="VCRedistExe">https://download.microsoft.com/download/1/6/B/16B06F60-3B20-4FF2-B699-5E9B7962F9AE/VSU_4/vcredist_x86.exe</String> </Strings> </Package> Here is the product.xml <?xml version="1.0" encoding="utf-8" ?> <Product xmlns="http://schemas.microsoft.com/developer/2004/01/bootstrapper" ProductCode="Microsoft.Visual.C++.12.0.x86" > <PackageFiles> <PackageFile Name="vcredist_x86.exe" HomeSite="VCRedistExe" PublicKey="3082010a0282010100e8af5ca2200df8287cbc057b7fadeeeb76ac28533f3adb407db38e33e6573fa551153454a5cfb48ba93fa837e12d50ed35164eef4d7adb137688b02cf0595ca9ebe1d72975e41b85279bf3f82d9e41362b0b40fbbe3bbab95c759316524bca33c537b0f3eb7ea8f541155c08651d2137f02cba220b10b1109d772285847c4fb91b90b0f5a3fe8bf40c9a4ea0f5c90a21e2aae3013647fd2f826a8103f5a935dc94579dfb4bd40e82db388f12fee3d67a748864e162c4252e2aae9d181f0e1eb6c2af24b40e50bcde1c935c49a679b5b6dbcef9707b280184b82a29cfbfa90505e1e00f714dfdad5c238329ebc7c54ac8e82784d37ec6430b950005b14f6571c50203010001" /> </PackageFiles> <InstallChecks> <MsiProductCheck Property="VCRedistInstalled" Product="{6C772996-BFF3-3C8C-860B-B3D48FF05D65} "/> </InstallChecks> <Commands Reboot="Defer"> <Command PackageFile="vcredist_x86.exe" Arguments=' /q:a ' > <InstallConditions> <BypassIf Property="VCRedistInstalled" Compare="ValueGreaterThanOrEqualTo" Value="3"/> <!-- Block install if user does not have admin privileges --> <FailIf Property="AdminUser" Compare="ValueEqualTo" Value="false" String="AdminRequired"/> </InstallConditions> <ExitCodes> <ExitCode Value="0" Result="Success"/> <ExitCode Value="3010" Result="SuccessReboot"/> <DefaultExitCode Result="Fail" FormatMessageFromSystem="true" String="GeneralFailure" /> </ExitCodes> </Command> </Commands> </Product> The setup downloads and installs the Visual c++ redistributable for visual studio 2012. But the problem is that even after it installs it, it I run the setup again it again downloads and tries to install the C++ redistribution. I thin the problem lies in the product.xml . Any way to resolve this?? A: After small research I found that "Visual C++ 2012 Runtime Libraries (x86)" has version 11.0, not 12.0 as you mention. Try this in your product.xml: <Product xmlns="http://schemas.microsoft.com/developer/2004/01/bootstrapper" ProductCode="Microsoft.Visual.C++.11.0.x86" > Or see this answer if it still doesn't work: Missing prerequisites for Visual C++ in Visual Studio 2012
[ "stats.stackexchange", "0000192126.txt" ]
Q: $\mathbb{P}(A_1)≤\mathbb{P}(A_1)$ in Boole's inequality ($n=1$) proof? Why does this proof use $≤$ in the $n=1$ (induction base case) case for Boole's inequality, when in fact it's an equality? That is, why claim, $\mathbb{P}(A_1)≤\mathbb{P}(A_1)$, when it should be a "$=$"? The induction base case generally should be such that it's a "step" that can be generalised to $n$. The $n+1$ case uses a more sophisticated reasoning to display that there's really a "$\le$". A: Note that the statement in the proof is true. Your statement that $P(A_1)=P(A_1)$ is also true and is stronger than the statement in the proof. However, the method of proof they used is induction. In an induction proof, one states the "base case" (here it's $n=1$), then assumes it to be true for $n$, then proves that if it is true for $n$, then it is true for $n+1$. It doesn't make sense to write $P(A_1)=P(A_1)$ as the base case because, although that is correct, that does not flow with the argument made. The proof attempts to show that the probability of the union of a finite collection of events is less than or equal to the union of the probabilities of those events. The proof is not attempting to establish equality, so to start your proof by establishing equality in the base case is an illogical and inappropriate step.
[ "stackoverflow", "0037872561.txt" ]
Q: HTML: Add elements dynamically using JS Working with HTML5, I have created a simple table that consists of a series of pair fields (Activity log, time). I've been searching on the web how to dynamically create fields using Javascript, but I've only found how to create one field at a time (using getElementById). The thing is that I'd like to create a series of tags. Meaning, when the user clicks on "add another field", I'd like that JS generates another row on the table, with a pair of fields, instead of having to hard code the complete table (the snippet below only has two rows, but I'd probably need 10-15 rows). The snippet of the code for the table appears below. Using CSS the page looks as it's on the screen shot. screenshot: I'd appreciate any help. Thanks in advance. <!DOCTYPE html> <html> <head lang="en"> <meta charset="utf-8"> <title>Activity Log</title> <link href="styles.css" rel="stylesheet"> <script type="text/javascript" language="javascript" src="script.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="leftcol"> <form name='mainForm' id='mainForm' method="get" action="http://www.randyconnolly.com/tests/process.php"> <fieldset> <legend>Input Activity Logs</legend> <table id=tracklist> <tr> <th colspan="3">Track List: </th> </tr> <tr> <td>1</td> <td><label>Activity Log: </label><br/><input type="text" name="actlog1" class="required"></td> <td><label>Time: </label><br/><input type="time" name="time1" class="required"></td> </tr> <tr> <td>2</td> <td><label>Activity Log: </label><br/><input type="text" name="actlog2" class="required"></td> <td><label>Time: </label><br/><input type="time" name="time2" class="required"></td> </tr> </table> <input type="submit" /> </fieldset> </form> </div> </div> </div> </body> </html> A: You can use the .innerHTML += method wired up to an "Add Activity" button. Each time you click the button a new table row is added with the correct index numbers. Here is a fully working example - for the sake of simplicity and having only one file, I've included the javascript directly in the HTML code: <!DOCTYPE html> <html> <head lang="en"> <meta charset="utf-8"> <title>Activity Log</title> <script> // Wait until the window finishes loaded before executing any script window.onload = function() { // Initialize the activityNumber var activityNumber = 3; // Select the add_activity button var addButton = document.getElementById("add_activity"); // Select the table element var tracklistTable = document.getElementById("tracklist"); // Attach handler to the button click event addButton.onclick = function() { // Add a new row to the table using the correct activityNumber tracklistTable.innerHTML += '<tr><td>' + activityNumber + '</td><td><label>Activity Log: </label><br/><input type="text" name="actlog' + activityNumber + '" class="required"></td><td><label>Time: </label><br/><input type="time" name="time' + activityNumber + '" class="required"></td></tr>'; // Increment the activityNumber activityNumber += 1; } } </script> </head> <body> <div class="container"> <div class="row"> <div class="leftcol"> <form name='mainForm' id='mainForm' method="get" action="#"> <fieldset> <legend>Input Activity Logs</legend> <table id="tracklist"> <tr> <th colspan="3">Track List: </th> </tr> <tr> <td>1</td> <td><label>Activity Log: </label><br/><input type="text" name="actlog1" class="required"></td> <td><label>Time: </label><br/><input type="time" name="time1" class="required"></td> </tr> <tr> <td>2</td> <td><label>Activity Log: </label><br/><input type="text" name="actlog2" class="required"></td> <td><label>Time: </label><br/><input type="time" name="time2" class="required"></td> </tr> </table> <input type="submit" /> </fieldset> </form> <button id="add_activity">Add Activity</button> </div> </div> </div> </body> </html>
[ "stackoverflow", "0024393499.txt" ]
Q: Exception Handling for specific condition - Best Practice I have following code in DAO method : public void someMethod() throws CustomException { try { ... do something ... }catch(Exception e) { if(e.getCause() instanceOf org.hibernate.ConstraintViolationException && e.getMessage().contains("child record found")) { throw new CustomException("Child records found."); }else { throw new CustomException("Unable to update."); } } } In service layer : public void someMethod() throws CustomException { dao.someMethod(); } And in Controller : public ResponseObject someMethod() { ResponseObject response = new ResponseObject(); try { service.someMethod(); response.setMessage("success"); }catch(CustomException e) { response.setMessage(e.getMessage()); } return response; } Am I going correctly as per BEST PRACTICES ? What else I can do to make it proper ? Any help appreciated! A: A few things I noticed. First, use exceptions only for exceptional conditions. Put another way, exceptions should be the exception, not the norm. From what it looks like, "ConstraintViolationException" is something that is going to be expected a lot. Exceptions make the code uglier, harder to debug, and reduce JVM optimizations that greatly speed up program execution. Second, you should only use checked exceptions (exceptions that don't extend from RuntimeException) if the caller can be reasonable expected to recover. In your case, the caller doesn't do anything to recover except give the client an error message. By throwing a checked exception, you force the caller to handle the exception in a catch clause or propagate it outwards. (Both are these pitfalls are detailed in Joshua Bloch's excellent book, "Effective Java".) Third, in your exception handling, you try to parse the error message. This can be very problematic because third parties often change their error messages, because they are not a part of the API. Once this happens, you're code is broken. Another minor problem in your exception handling is that tie your JPA implementation to hibernate. What if later you want to change to EclipseLink? There is a way to address all these issues. Get rid of the exception handling in your DAO. Add the following method to your DAO: boolean childRecordExists(Record record) Then, in your controller, have something like: if (service.childRecordExists()){ response.setMessage("Failed. A child record exists"); //a useful error message for the user, as you know *exactly* why failure happened } else { service.someMethod(); response.setMessage("Success"); } You will need some sort of exceptionHandler in the controller. (If you're using Spring MVC, you can just add it as another method using the ExceptionHandler annotation.) This would address things that are truly exceptions (things that are out of the ordinary for the everyday user experience, and things that the user can't fix.)
[ "stackoverflow", "0057839166.txt" ]
Q: How to manage lifetime of CString in a Vec? Is there a better or more idiomatic way to handle the lifetime of a CString in a Vec other than using into_raw()? Here's my code: // This fails because the CString gets dropped and then what is pointed to is invalid and invalidates required_layers let required_layers: Vec<*const c_char> = vec!( CString::new("VK_LAYER_LUNARG_standard_validation").expect("CString err A").as_ptr(), ); // This works because ss0 stays alive, but is going to be error-prone as dropping ss0 somewhere invalidates required_layers let ss0 = CString::new("VK_LAYER_LUNARG_standard_validation").expect("CString err A"); let required_layers: Vec<*const c_char> = vec!( ss0.as_ptr(), ); // This works, but now requires from_raw() to retake ownership to avoid leaks let required_layers: Vec<*const c_char> = vec!( CString::new("VK_LAYER_LUNARG_standard_validation").expect("CString err A").into_raw(), ); A: You can just store the actual CString objects: let a = vec![ CString::new("VK_LAYER_LUNARG_standard_validation").expect("CString err A") ]; And if what you actually need is a contiguous array of pointers, perhaps for passing to a C function that is expecting that sort of thing, you can create a second vector holding the pointers from the strings in the first. let b: Vec<*const c_char> = a.iter().map(|cstr| { cstr.as_ptr() }).collect(); The first vector will outlive the second, and it will properly drop the contained CString objects when it is dropped itself.
[ "stackoverflow", "0039756473.txt" ]
Q: Using foreach loop with Query Builder in Yii 2 For some reason this isn't working. The error I get is "Undefined index: cu_id" for the line $cu_id = $rows['cu_id']; I think I'm just totally using the querybuilder wrong with the foreach loop. Any help with the proper syntax for this? Thanks! $query = new Query; $query->select('cu_id')->from('cu_emails')->where(['creator_id' => $user_id, 'email' => $email]); foreach ($query as $rows) { $cu_id = $rows['cu_id']; echo"CU ID: $cu_id<br /><br />"; } Also I'm on the Yii 2 framework in case anyone missed that. A: You query not run. $query->all() and then foreach records or $query->one() and get data from one record $query = new Query; $query->select('cu_id')->from('cu_emails')->where(['creator_id' => $user_id, 'email' => $email]) $results = $query->all(); foreach ($results as $rows) { $cu_id = $rows['cu_id']; echo"CU ID: $cu_id<br /><br />"; }
[ "stackoverflow", "0040988751.txt" ]
Q: LibGdx falling object I am trying to code a LibGDX game. Currently i am trying to make add an image that falls from the top of the screen to the bottom then reappears over the screen and falls again, I also need to find a way that can detect collision with a player (which I will have to learn how to properly add a player next) . The problem is I don't have any experience in this part of Libgdx i am still fairly new. This is what i have tried so far, Image image; public Beam(Image image) { this.image = image; image.setPosition(LevelSmash.HEIGHT, LevelSmash.WIDTH); } public void update(){ image.setY(image.getY() - 1); } public void draw(SpriteBatch sb){ sb.begin(); //Draw image? sb.end(); } I already know it is very bad, I don't know which LibGDX classes to use, I was wondering if it was Body or something? EDIT Updated Code public class Beam extends Sprite{ Image image; Body body; public Beam(World world) { BodyDef bodyDef = new BodyDef(); bodyDef.type = BodyDef.BodyType.DynamicBody; bodyDef.position.set(100, 300); body = world.createBody(bodyDef); CircleShape circle = new CircleShape(); circle.setRadius(20f); FixtureDef fixtureDef = new FixtureDef(); fixtureDef.shape = circle; fixtureDef.density = 0.5f; fixtureDef.friction = 0.4f; fixtureDef.restitution = 0.6f; Fixture fixture = body.createFixture(fixtureDef); circle.dispose(); body.setUserData(this); setRegion(new Texture("beam.png")); } public void update(float dt){ } public Body getBody(){ return body; }} A: I think you should stay away from box2d for now. It seems like overkill to use it for this project. Here is an example of how you could solve it: Beam.class: public class Beam{ private Rectangle bound; private TextureRegion texture; private float weight = 10; //or gravity or however you want to think about it public Beam(float x, float y, float width, float height){ texture = new Texture(Gdx.files.internal("beam.png")); bound = new Rectangle(x,y,width,height); } public void update(float delta){ bound.y -= weight*delta; } public Rectangle getBound(){ return bound; } public Texture getTexture(){ return texture; } } You get the beam to the top of the screen by just changing the bound.y beam.getBound().y = newValue; You can do this on the object itself or by whereever it makes sense in you game. Then when you add a player you give that object a bound too and you can do simple collision with: if( player.getBound().overlaps(beam.getBound())){ //collision } The bound is a Rectangle object from libgdx. It holds an x and y coordinate and a width and height. Using a Rectangle makes moving the object and collision detection very simple. EDIT: Drawing the texture from render(): public void render(float delta){ ... beam.update(delta); spriteBatch.begin(); spriteBatch.draw(beam.getTexture(), beam.getBound().x, beam.getBound().y); spriteBatch.end(); } Or have beam draw itself: public void render(float delta){ ... beam.update(delta); spriteBatch.begin(); beam.draw(spritebatch); spriteBatch.end(); } in the beam class: public void draw(SpriteBatch spriteBatch){ spriteBatch.draw(texture, bound.x, bound.y); }
[ "stats.stackexchange", "0000329730.txt" ]
Q: Feature Maps vs Channels in CNN What's the difference between feature maps and channels in Convolutional Neural Network. I understand that number feature maps is determined by number of filters. I'm thinking that both of these terms refer to the same thing. Am I right? A: Yes, both are same. Each channel after the first layer of a CNN is a feature map. Before the first layer of CNN, RGB images have 3 channels (red, green & blue channels).
[ "stackoverflow", "0058166002.txt" ]
Q: How to add caption & subtitle using plotly method in python I'm trying to plot a bar chart using plotly and I wanted to add a caption and subtitle.(Here you can take any example of your choice to add caption and subtitle) My code for plotting the bar chart: import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Bar(x=["Apple", 'Mango', 'Banana'], y=[400, 300, 500])) fig.show() A: Use fig.update_layout(title_text='Your title') for your caption. There's no built-in option for subtitles. But you can get the desired effect by moving the x-axis labels to the top and at the same time insert an annotation at the bottom right. I've tried with other y-values as well, but there doesn't seem to be a way to get the annotations outside the plot itself. You could also change the fonts of the caption and subtitle to make them stand out from the rest of the labels. Plot: Code: import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Bar(x=["Apple", 'Mango', 'Banana'], y=[400, 300, 500])) fig.update_layout(title=go.layout.Title(text="Caption", font=dict( family="Courier New, monospace", size=22, color="#0000FF" ))) fig.update_layout(annotations=[ go.layout.Annotation( showarrow=False, text='Subtitle', xanchor='right', x=1, xshift=275, yanchor='top', y=0.05, font=dict( family="Courier New, monospace", size=22, color="#0000FF" ) )]) fig['layout']['xaxis'].update(side='top') fig.show()
[ "stackoverflow", "0037993160.txt" ]
Q: canvas.getContext is not a function I have written a simple template for a AngularJs directive: <div class="circle"> <canvas></canvas> </div> My directive has the following look: MobileApp.directive('circle', function () { return { restrict: 'E', scope: true, link: function (scope, elem, attrs) { ... var canvas = elem.find('canvas'); var ctx = canvas.getContext('2d'); ... } } }); And the usage of that is simple enough: <circle/> I am getting an error when trying to call a method getContext('2d'): TypeError: canvas.getContext is not a function The canvas instance is selected and its JSON representation looks { "0": {}, "length": 1, "prevObject": { "0": {}, "context": {}, "length": 1 }, "context": {}, "selector": "canvas" } I have already read about all related questions here, but the answer hasn't been found. Any help would be appreciated. Thanks. A: I create a little plunker. In your sample i don't understand the relation between directive and template. Have you missing to add template property ? What i do in plunker : Define template : return { restrict: 'E', scope: true, template: '<div><canvas></canvas></div>', link: function (scope, elem, attrs) { var canvas = elem.find('canvas'); console.log(canvas); var ctx = canvas[0].getContext('2d'); console.log(canvas, ctx); } } Get canvas from the object that return by find method : var ctx = canvas[0].getContext('2d'); And the use : <circle></circle>
[ "stackoverflow", "0000886495.txt" ]
Q: How do I get the Application Name from either SQL Server connection string or the IIS application name using C#? How do I get the Application Name from an SQL Server connection string in the web.config file. I want to use to log escalated error messages from a web application into the Windows Event Log. Maybe there is a better way of doing this, ie using the IIS/Web application name? Thanks Mark A: What does the connection string look like? DbConnectionStringBuilder is good for parsing and inspecting connection-string values by key: DbConnectionStringBuilder db = new DbConnectionStringBuilder(); db.ConnectionString = connectionString; Console.WriteLine(db["Application Name"]); otherwise you can get various details from the http server variables.
[ "stackoverflow", "0016772558.txt" ]
Q: What is ffmpeg, avcodec, x264? From wiki, I read that FFmpeg is a free software project that produces libraries and programs for handling multimedia data. The most notable parts of FFmpeg are libavcodec, an audio/video codec library used by several other projects, libavformat, an audio/video container mux and demux library, and the ffmpeg command line program for transcoding multimedia files. So ffmpeg is a wrapper of avcodec? And I often hear that people encode video with x264 using ffmpeg. So ffmpeg is also a wrapper of x264? How are they related ? A: First of all, to clear up some terms: FFmpeg is a software project with lots of people involved, a Wiki, a bug tracker, some funding, etc. ffmpeg is one of the tools they offer (others are ffplay and qt-faststart, for example). Libav is a fork of the FFmpeg project, which supplies the avconv binary. They both develop independently, but FFmpeg usually merges commits from Libav—not the other way 'round. (Some might say Libav suffers from NIH). Some distributions decided to ship Libav instead of FFmpeg programs, notably Ubuntu, which caused a bit of confusion in the transition period where the Libav command was still named ffmpeg. Now Ubuntu uses the "real" ffmpeg again. The ffmpeg tool is, like you said, a command line wrapper for a number of libraries designed for handling multimedia content. These include: libavcodec, for encoding and decoding of audio, video and subtitle bitstreams libavformat, for muxing and demuxing containers libavfilter, for applying a variety of filters on audio, video and subtitles libswscale, which scales images and video or resamples audio libavresample, which was originally pushed to Libav and later integrated into FFmpeg. See this thread for more about the history. While the FFmpeg developers often provide their own encoders and decoders, you can enable third party libraries that have wrappers in libavcodec, in order to "glue" together FFmpeg and, say, x264, which is the most popular H.264 encoder. This is often done when there's simply no point in "reinventing the wheel", which would be the case if one decided to write a new H.264 encoder with the goal to be better than x264. In other cases, some libraries may not be shipped with an ffmpeg build due to licensing reasons, such as libfaac—in that case, ffmpeg offers a native AAC encoder. Common external encoders include: libx264 libvpx (for VP8 and VP9 video) libfaac, libfdk-aac, libvo-aacenc for AAC audio libmp3lame libvorbis libxvid For all of those you will find the wrappers under libavcodec, e.g. for libx264, the file libx264.c provides the necessary code to push the video from the FFmpeg-internal format to the x264 encoder, and then pass that on to libavformat to write it into a file. The actual encoding is done through libx264. As mentioned before, other encoders such as the one for MPEG-4 are native to FFmpeg and do not rely on external libraries at all. Finally, there are several programs that make use of FFmpeg tools and libraries, be it by providing an ffmpeg executable, or by picking parts of the libavcodec and libavformat libraries. This is allowed per the license and makes FFmpeg the most popular collection of multimedia tools today.
[ "stackoverflow", "0058146228.txt" ]
Q: Infinite recursion for parsing arithmetic expressions using a recursive descent parser I am trying to create my own recursive descent parser in python, but when my parser runs into a rule concerning arithmetic expressions, it surpasses the python recursion limit. Here is the grammar: Term --> Factor {( "+" | "-" ) Factor} Factor --> Grouping {( "*" | "/" | "%" ) Grouping} Grouping --> Expression | "(" Expression ")" | "-" Factor Expression --> Integer | Float | Tuple | ID | Term The curly braces in the grammar denote that they can repeat (but also is optional), and are implemented using a while loop in my parser. I feel that what is causing this is the fact that a Grouping rule can be and Expression (whcih can recur over and over because the right side of the Factor and Term rule are optional). What I am asking is: Is there a way to implement the left recusion with a recursive descent parser or eliminate it in my grammar somehow? EDIT: I was browsing around and iit seem this type of recursion is called indirect left recursion, perhaps this has something to do with it? A: As you observe, the infinite recursion is the result of the infinite loop Expression ⇒ Term ⇒ Factor ⇒ Grouping ⇒ Expression which must be broken. But it's a simple transcription error; Expression needs to start from the top, in a hierarchy of syntactic precedence: Expression ⇒ Term {( "+" | "-" ) Term} Term ⇒ Factor {( "*" | "/" | "%" ) Factor} Factor ⇒ Item | "-" Factor Item ⇒ Integer | Float | Tuple | ID | "(" Expression ")"
[ "stackoverflow", "0015629370.txt" ]
Q: Possible to have DbContext Ignore Migration/Version data in Database? I have an application that uses two separate models stored in a single database. The first model is set up with migrations and is the one that has created the migrations data in the database. The second is a very simple model that needs no model validation at all - the tables it uses exist and are of the proper structure. The second Context works fine in a separate database with the same table structure. The problem is it fails when running in the same database with the first model since it does provide some sort of model validation. It complains that the context has changed since the last update, but of course the the migrations data does not contain anything about the second context's tables. Is it possible to turn off the meta data validation for the context, and just let the second context work against the tables as is, since I know that works? in the context constructor but that has no effect. A: The solution is to use implement a "do nothing" database initializer that basically does nothing. public class QueueMessageManagerContextInitializer : IDatabaseInitializer<QueueMessageManagerContext> { protected void Seed(QueueMessageManagerContext context) { } public void InitializeDatabase(QueueMessageManagerContext context) { // do nothing Seed(context); } } To use in one time startup code then: [ClassInitialize()] public static void MyClassInitialize(TestContext testContext) { //Database.SetInitializer<QueueMessageManagerContext>(new DropCreateDatabaseIfModelChanges<QueueMessageManagerContext>()); Database.SetInitializer<QueueMessageManagerContext>(new QueueMessageManagerContextInitializer()); } Simple but non-obvious solution. Edit: Even simpler solution: Just pass NULL to the SetInitializer() method: Database.SetInitializer<QueueMessageManagerContext>(null);
[ "stackoverflow", "0022098791.txt" ]
Q: jQuery AJAX/POST not sending data to PHP So I have this problem for a while now, and I know there are countless questions on this topic, believe me I tried every solution possible but still does not work. This is the simplest of examples which in my case is not working jQuery: $.ajax({ url: "ajax/add-user.php", type: "POST", data: {name: 'John'}, success: function(data){ console.log(data); } }); PHP echo json_encode($_POST); That's it. I always get back an empty array as a response. I tried with serialize() for the data: but the response is always empty. I get no errors whatsoever, just an empty array when I should get the posted values. If, for example, in php I try to echo some hard-coded variables I get them, but the $_POST and $_GET don't work. Any solution or methods of how I can identify the problem ? Thank you. EDIT/SOLUTION Ok, so it seems the problem was with .htaccess which rewrites the url and removes the extension. In the network tab indeed the request was moved permanently. Removing the .php extension from the ajax url: solved it. Thank you and sorry for wasting time. Cheers A: You need to set the data type as json in ajax call. JQUERY CODE: $.ajax({ url: "ajax/add-user.php", type: "POST", dataType:'json', data: {name: 'John'}, success: function(data){ console.log(data); } }); At the same time verify your backend code(php), whether it can accept json data ? If not, configure the header as below: PHP CODE: /** * Send as JSON */ header("Content-Type: application/json", true); Happy Coding : A: I recently came across this issue but because of other reasons: My POST data was redirected as 301 My Server request was GET I did not get my POST data My reason - I had a url on the server registered as: http://mywebsite.com/folder/path/to/service/ But my client was calling: http://mywebsite.com/folder/path/to/service The .htaccess on the server read this as a 301 GET redirect to the correct URL and deleted the POST data. The simple solution was to double check the url path. @C.Ovidiu, @MarcB - Both of you guys saved me lots of hours in debugging! A: Why not use jQuery.post? $.post("ajax/add-user.php", {name: 'John'}, function(response){ console.log(response); } ); Then in your PHP you could save the input like so: if(isset($_POST["name"])) { $name= $_POST["name"]; file_put_contents("name.txt", $name) header('HTTP/1.1 200 OK'); } else { header('HTTP/1.1 500 Internal Server Error'); } exit;
[ "stackoverflow", "0007556272.txt" ]
Q: rails 3.1 - auto compile SASS before browser refresh I used to run compass -watch to ensure my Sass files compiled as soon as they were modified. Now though, thanks to the asset pipeline, code auto-compiles (if changes are detected) when the view is refreshed in the browser. There's a time-cost associated with this, especially if you frequently modify your Sass files. I'm spending half my development time waiting on views to refresh. I'm wondering if there's a way to compile sass before a page refresh in rails 3.1. I tried the sass-guard gem but it doesn't seem to do what I want in rails 3.1. Perhaps there's another way? A: fixed this using guard-livereload - now my code changes take effect before I've even switched from text-editor to browser, which cuts down on RSI-inducing mouse movements considerably
[ "serverfault", "0000138598.txt" ]
Q: Check existance of domain accounts with Powershell script Is there a Powershell cmdlet or script to query Active Directory if a given domain account (such as "myDomain\myUser") exists? A: This is what we use to validate accounts. It relies of course on Import-Module ActiveDirectory and either a 2008 R2 DC, or a DC running ADWS: function validateUser { param( [string]$username ) # If the username is passed without domain\ if(($username.StartsWith("domain\")) -eq $false) { $user = Get-ADUser -Filter { SamAccountName -eq $username } if (!$user) { return $false } else { return $true } } elseif(($username.StartsWith("domain\")) -eq $true) { $username = ($username.Split("\")[1]) $user = Get-ADUser -Filter { SamAccountName -eq $username } if (!$user) { return $false } else { return $true } } } $userCheck = validateUser -username smith02 if($userCheck -eq $true) { do stuff } else { user doesn't exist } A: Old question, I know, but I feel I need to add this bit here because none of the previous answers use any form of error handling. Also, if you need to support users from multiple domains, you will have to query the correct domain controller (or query the Global Catalog and specify the DN of a directory partition). $Domainname = 'ABC' $Username = 'Administrator' Try { $DomainController = Get-ADDomainController -DomainName $DomainName -Discover -ErrorAction Stop Get-ADUser -Identity $Username -Server $DomainController -ErrorAction Stop # user account exists } Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] { # no error, user account does not exist } Catch { # Domain controller not found, domain unreachable, authentication failure or another error occurred }
[ "cs.stackexchange", "0000053376.txt" ]
Q: Is Post's correspondence problem recognizable? I want to know whether Post Correspondence Problem (PCP) is recognizable. I learnt how to demonstrate the undecidability of PCP. I thought to use the similar approach for recognizability too i.e. to considering MPCP and show whether it is recognizable. I am not sure if it is a good approach. A: We can recognize acceptable inputs of PCP by exhaustively checking all valid possibilities (preferably by non-deterministic TM). That is it!. If the input is acceptable then the TM will stop, if it is not then the TM may not stop. Thus PCP is an RE language. Recognizability should not be confused with decidability. We can do the same with deterministic TM by essentially simulating each thread of NDTM one step at a time.
[ "stackoverflow", "0021170952.txt" ]
Q: Basic side to side movement in Corona/Lua I've been trying for hours to get my character to move side to side. The basic aim of the game is to have the character jump up crates. I have the sprite code to make him move all around the screen but I can't make it so he only moves on the X. local touchX, touchY local touchScreen = function(e) --print(e.phase, e.x, e.y) if e.phase == "began" then touchX = e.x touchY = e.y elseif e.phase == "moved" then --spriteAsh.x = spriteAsh.x + (e.x - touchX) --spriteAsh.y = spriteAsh.y + (e.y - touchY) local difX = e.x - touchX local difY = e.y - touchY spriteAsh:applyForce(difX *50, difY * 50, spriteAsh.x, spriteAsh.y) touchX = e.x touchY = e.y elseif e.phase == "ended" then end end Runtime:addEventListener("touch", touchScreen) local updateGame = function(e) local seq local velX, velY = spriteAsh:getLinearVelocity() print (velX, velY) if math.abs (velX) >= math.abs (velY) then --horizonal if velX > 0 then seq ="right_run" else seq = "left_run" end else if velY > 0 then seq = "down_run" else seq = "up_run" end end if spriteAsh.sequence ~= seq then spriteAsh:setSequence(seq) spriteAsh:play() end end Runtime:addEventListener("enterFrame", updateGame) A: You are applying a force in both x and y, so my first guess is that motion will occur along both axes. Don't apply a force in the y direction: spriteAsh:applyForce(difX *50, 0, spriteAsh.x, spriteAsh.y) Note that the place you apply a force makes a difference, just as it would in reality: if you push on a stick at its center, the whole stick moves, but if you push at one end (perpendicular to it) it will rotate, very differet. Note also that you are applying a force. Force changes current motion. If there already is motion along y due to some other factor, putting 0 force will not cancel out the y motion. If you really want to constrain y motion it may be worthwhile setting the velocity to 0 at every frame (in update()).
[ "stackoverflow", "0032310504.txt" ]
Q: Laravel: calling controller method from another location In my Laravel app I have the following controller that takes the instance of Elastic search as a first parameter and then another variable: use Elasticsearch\Client; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class AngularController extends Controller { public function selectRandom(Client $es, $numRows) { # ...search params here $results = $es->search($searchParams); return $results; } } I need to call the method of the controller above from another controller, I do it like this: class HomeCtrl extends Controller { public function index() { $featured = new AngularController(); return $featured->selectRandom(12); } } I get the following error Argument 1 passed to App\Http\Controllers\AngularController::selectRandom() must be an instance of Elasticsearch\Client, integer given I'm not well versed in OOP. Do I call it incorrectly? Because I though the method I call would take instance that is injected in controller, not from where I call it. A: When you are calling a method from your Controller to another Controller that means you are doing wrong. For this purpose you should use service. Create a class in app\Services Utility.php use Elasticsearch\Client; class Utility { public function selectRandom(Client $es, $numRows) { # ...search params here $results = $es->search($searchParams); return $results; } } and just inject this class to your controller
[ "stackoverflow", "0016554757.txt" ]
Q: Set ImageView from SDcard to match_parent height? So I have an ActionDialog that saves a signature. When I set the ImageView to the new captured signature it is way too tall. Below I will illustrate the problem Right now at default the screen looks like this (textview)-(--edittext--)-(space)- (textview)-(--edittext--)-(space)- (textview)-(imageview)-(button)- after the user clicks the button it asks for a signature, saves the signature, then replaces the default ImageView with the new bitmap. However it ends up looking like this (textview)-(--edittext--)-(space)- (textview)-(--edittext--)-(space)- (textview)-(imageview)-(button)- I'm unsure why this is happening. Here is the XML Layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/twoglobe_line" android:gravity="center" android:orientation="vertical" > <LinearLayout android:id="@+id/sigll3" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/textView3" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="@string/title" android:textAppearance="?android:attr/textAppearanceSmall" /> <EditText android:id="@+id/editText2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="2" android:ems="10" > <requestFocus /> </EditText> <Space android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout> <LinearLayout android:id="@+id/sigll1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/textView1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="@string/print_name" android:textAppearance="?android:attr/textAppearanceSmall" /> <EditText android:id="@+id/editText1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="2" android:ems="10" > <requestFocus /> </EditText> <Space android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" /> </LinearLayout> <LinearLayout android:id="@+id/sigll2" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/textView2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="@string/signature" android:textAppearance="?android:attr/textAppearanceSmall" /> <ImageView android:id="@+id/sig_image" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="2" android:src="@drawable/sig" /> <Button android:id="@+id/signature" style="?android:attr/borderlessButtonStyle" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:text="@string/sign" /> </LinearLayout> </LinearLayout> </ScrollView> I would like to make it so that the new bitmap is the same height as the button and textview next to it. Or as much as possible. Thanks for any help you can offer A: use this to get the pixels to scale the image to according to the textview or whatever per device, then scale the bitmap accordingly public static int dpToPixels(Context context, float dp) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dp * scale + 0.5f); } then in your code after this like this Bitmap bmp = BitmapFactory.decodeFile(mysig .getAbsolutePath()); bmp = Bitmap.createScaledBitmap(bmp,bmp.getWidth(),dpToPixels(this,20)); //or some dp
[ "stackoverflow", "0009802932.txt" ]
Q: objective-c how to save variable name and value I have five integers.I added all integers to a mutableArray and shuffled it. int A = 1; int B = 2; int C = 3; int D = 4; int E = 5; myArray = [2,1,3,5,4]; //shuffled array is it possible to get variable names of each integer in the array? please help me. A: In this case NSDictionary would be feasible, you can store both the Variable Names and their Values: NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"A",@"2",@"B",@"3",@"C",@"4",@"D",@"5",@"E", nil]; Now you can fetch all the keys of the dictionary like: NSArray *arr = [dict allKeys]; // which will be [A,B,C,D,E] And you can fetch the values for those keys like: for (int i=0; i<arr.count; i++) { NSLog(@"%@",[dict valueForKey:[arr objectAtIndex:i]]); // Will print 1,2,3,4,5 }
[ "electronics.stackexchange", "0000467986.txt" ]
Q: Cover element on LED component From time to time I come across a solution in which uses an LED as in below picture: This particular component is placed inside the module located in car interior. Button backlight application. The base LED [PLCC-2 Package] is blue color LED. The top cover material changes the light to white, so I assume this cover material is actually a phosphorus layer. This is a common approach of achieving white color but usually the phosphorus layer is integrated inside the PLCC-2 package (The die is sunk in phosphorus line on below picture.) What is the purpose of this additional cover? My guesses are: Specially mixed phosphorus layer is added to finished LED in order to achieve exact white color coordinates. Manufacturing process improvement: one line for blue and white LEDs with additional process for white. Is there any LED expert that could confirm this? A: I received confirmation from LED supplier: This solution results in better light homogeneity than die sinking method. It is very rare because it's patent protected.
[ "stackoverflow", "0059496329.txt" ]
Q: How to insert the value into query? Do I need to insert the variable in sum(orderdets.quantity) into another variable? $order = Order::with('customer','product') ->select( 'orders.id', 'orders.customer_id', 'orderdets.product_id', DB::raw('SUM(orderdets.quantity)')) ->get(); A: Try This $orders = Order::with('customer','product')->select('orders.id', 'orders.customer_id', 'orderdets.product_id', DB::raw('SUM(orderdets.quantity) as sum'))->get(); dd($orders);
[ "stackoverflow", "0022515159.txt" ]
Q: Phaser js php leaderboard I am building a game using the Phaser js framework. Its an endless runner and i have just started.This is the code: <!doctype html> <html> <head> <title>Game2</title> <script type="text/javascript" src="js/phaser.min.js"></script> </head> <body> <script type="text/javascript"> window.onload=function() { var game=new Phaser.Game(800,600,Phaser.AUTO,'',{preload:preload,create:create,update:update}); var player; var platforms; var count=0; var t; var style; function preload() { game.load.image('ground','assets/platform.png'); game.load.image('sky','assets/sky.png'); game.load.spritesheet('hero','assets/hero.png',128,128,16); } function create() { game.world.setBounds(0,0,800,600); //game.add.sprite(0,0,'sky'); platforms=game.add.group(); var ground=platforms.create(0,304,'ground'); ground.scale.setTo(2,2); ground.body.immovable=true; //var ledge = platforms.create(400, 400, 'ground'); //ledge.body.immovable = true; //ledge = platforms.create(-150, 250, 'ground'); //ledge.body.immovable = true; player=game.add.sprite(390,32,'hero'); player.body.bounce.y=0.1; player.body.gravity.y=10; player.body.collideWorldBounds=true; player.animations.add('left',[0,1,2,3],10,true); player.animations.add('right',[4,5,6,7],10,true); player.animations.add('stop',[9],10,true); game.camera.follow(player); //var count="0"; style = { font: "65px Arial", fill: "#ff0044", align: "center" }; t = game.add.text(game.world.centerX-350, 0, count, style); //game.time.events.loop(Phaser.Timer.SECOND,distance,this); } function update() { distance(); game.physics.collide(player,platforms); player.body.velocity.x=0; /*if(game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) { player.body.velocity.x=-250; console.log("Left"); player.animations.play('left'); } else if(game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) { player.body.velocity.x=250; console.log("Right"); player.animations.play('right'); }*/ player.animations.play('right',10,true); //this was done since in an infinite runner the character always runs never stops, the //only key needed to be pressed is the up key to jump when the platform ends. if (game.input.keyboard.isDown(Phaser.Keyboard.UP) && player.body.touching.down) { player.body.velocity.y = -350; } } function distance() { count++; //this value will hold the score of every player. I need to pass it to the leader board using php. How? t.content=count; } }; </script> </body> i wish to pass the value of the count variable in the distance() function to the leader board using php. How can i do that? A: Assuming you have a PHP file for keep the scores, you can do it with AJAX: function submitScore(username, count) { var data="username="+username+"&count="+count; var request = new XMLHttpRequest(); request.open('POST', '/setScore.php', true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); request.onload = function() { if (request.status >= 200 && request.status < 400){ // Success! // here you could go to the leaderboard or restart your game . } else { // We reached our target server, but it returned an error } }; request.send(data); }
[ "stackoverflow", "0055703173.txt" ]
Q: How can I append a value replacing multiple elements in a list? I'm trying to make a search system that finds the search keyword containing mutiple ANDs, ORs, and parentheses. What I'm trying to do now is replacing the parenthesis with boolean values. So if I have a list ["A", "or", "(", "B", "and", "C", ")"] , I want to change this list to ["A", "or", True]. First, I've tried the del keyword then append the boolean value like the code below. This works this only example. However I might have parenthesis in the front or middle of the list, and in this case it doesn't work.(because the append keyword always adds elements to the end) Also I've tried the replace keyword but this returned the output ["A", "or", "T", "r", "u", "e"] How can I replace ["(", "B", "and", "C", ")"] to True? sentence = ["B", "C", "D"] search = ["A", "or", "(", "B", "and", "C", ")"] if "(" in search: start = search.index("(") end = search.index(")") bracket = search[start + 1 : end] if "and" in bracket: index_of_and = bracket.index("and") if bracket[index_of_and - 1] and bracket[index_of_and + 1] in sentence: print("both in") bracket = 'True' else: print("only one or nothing in") bracket = 'False' elif "or" in bracket: index_of_or = bracket.index("or") if bracket[index_of_or -1] in sentence or bracket[index_of_or +1] in sentence: bracket = 'True' else: bracket = 'False' else: if bracket[0] in sentence: bracket = 'True' else: bracket = 'False' del search[start:end+1] search = search.append(bool(bracket)) A: your code is a little hard to read but i think its only issue is the append at the end, since you dont know that the closing bracket is the end of the sentence appending can mangle your logic, instead you should insert and the append operation doesnt return anything so this line: search = search.append(bool(bracket)) should be search.insert(start - 1, bool(bracket)) I'm also unsure how you managed to get true to be split letter wise, that should only happen if you do list("true")
[ "stackoverflow", "0006660164.txt" ]
Q: SQL Like search in LIST and LINQ in C# I have a List which contains the list of words that needs to be excluded. My approach is to have a List which contains these words and use Linq to search. List<string> lstExcludeLibs = new List<string>() { "CONFIG", "BOARDSUPPORTPACKAGE", "COMMONINTERFACE", ".H", }; string strSearch = "BoardSupportPackageSamsung"; bool has = lstExcludeLibs.Any(cus => lstExcludeLibs.Contains(strSearch.ToUpper())); I want to find out part of the string strSearch is present in the lstExcludedLibs. It turns out that .any looks only for exact match. Is there any possibilities of using like or wildcard search Is this possible in linq? I could have achieved it using a foreach and contains but I wanted to use LINQ to make it simpler. Edit: I tried List.Contains but it also doesn't seem to work A: You've got it the wrong way round, it should be:- List<string> lstExcludeLibs = new List<string>() { "CONFIG", "BOARDSUPPORTPACKAGE", "COMMONINTERFACE", ".H", }; string strSearch = "BoardSupportPackageSamsung"; bool has = lstExcludeLibs.Any(cus => strSearch.ToUpper().Contains(cus)); Btw - this is just an observation but, IMHO, your variable name prefixes 'lst' and 'str' should be ommitted. This is a mis-interpretation of Hungarian notation and is redundant.
[ "stackoverflow", "0044965588.txt" ]
Q: Find Pattern in arrays I have two sub-sequences of values and the values can be 0, -1 and 1. The values reprensent the slope, 0 for null, -1 for negative one and 1 for positive one. I want to join the two sub-sequences and build the sequence that represent the "union" of the two sub-sequences. Example here : 1 a1 = [0 -1 0 1] and r1 = [0 -1 0] give me p1 = [0 -1 0 1] a2 = [-1 0] and r2 = [0 1] give me p2 = [-1 0 1] But i cannot find an algorithm working well. In fact the problem is that the values are not unique so the union doesn't do well. Thanks in advance for your help. Baptiste. A: Here is an idea how you could solve your problem (assuming a2 is the smaller array, otherwise just swap)(actually, it should be irrelevant which array is larger)
[ "mathematica.stackexchange", "0000027859.txt" ]
Q: WeatherData for the 15th day of each month Suppose we have WeatherData["Helsinki", "MeanTemperature", {{2007, 1, 1}, {2012, 12, 31}, "Day"}] How we can have data just for 15th day of each month? A: After grabbing the data from WeatherData, use Cases to get only those datapoints obtained on the 15th day: data = WeatherData["Helsinki", "MeanTemperature", {{2011, 1, 1}, {2012, 12, 31}, "Day"}]; just15 = Cases[data, x_ /; x[[1, 3]] == 15];
[ "tex.stackexchange", "0000133668.txt" ]
Q: Increasing space between text in tikz I am making a picture in tikz, and I have some labels that don't look nice. Here's the code \documentclass{article} \usepackage{tikz} \usetikzlibrary{snakes} \usepackage{mathrsfs} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usetikzlibrary{arrows} \definecolor{zut}{RGB}{253,200,0} \definecolor{nar}{RGB}{240,95,0} \definecolor{pla}{RGB}{134,206,255} \begin{document} \center \begin{tikzpicture} \draw[zut, fill=pla, thick] (0,0) ellipse (4cm and 2cm); \draw[nar, fill=white, thick] (0,0) circle (2cm); \draw[zut, dashed, thick] (0,0) ellipse (1.4cm and 0.5cm); \draw[nar, dashed, thick] (0,0) ellipse (1cm and 0.5cm); \draw[dotted, thick] (0,0) ellipse (1cm and 0.15cm); \draw[-latex'] (0,0) to (0,3.5); \node at (-0.2,3.5) {$z$}; \draw[-latex'] (0,0) to (5,0); \node at (5.2,0.2) {$y$}; \draw[-latex'] (0,0) to (-2.5,-2.5); \node at (-2.2,-2.7) {$x$}; \draw[dashed] (0,0) to (0,-3); \draw[latex-, thick] (1.8,1) -- (3,1.7) --(6.8,1.7); \node[align=center] at (4.7,2.2) {\textsf{Vanjski horizont događaja}\\ $r=r_+=M+\sqrt{M^2-a^2}$}; \draw[->] (-0.4,3) to [bend right=80] (0.4,3.1); \node at (-0.6,3) {$\phi$}; \node at (0.6,2.4) {$\theta=0$}; \node at (0.8,-2.4) {$\theta=\pi$}; \draw[->, red, dashed] (-5,2) to [bend left=10] (-3.8,1); \node at (-5,2.3) {ergosfera}; \draw[->, red, dashed] (-4.2,-2.2) to [bend right=30] (-1.8,-1); \node[align=center] at (-5,-2.4) {horizont \\ događaja}; \draw[->, red, dashed] (5.5,0.5) to [bend left=10] (4,-0.35); \node[align=center] at (6,0.85) {$r=M+\sqrt{M^2-a^2\cos^2\theta}$}; \draw[->, red, dashed] (5,-1.5) to [bend left=20] (3,-0.35); \node[align=center] at (6,-1.5) {ergoregija}; \end{tikzpicture} \end{document} And here's the picture The 'Vanjski horizont događaja' is a bit too close to the formula beneath it. I tried adding \vspace but that didn't do a thing. The longer solution is just dividing those two and manually setting the nodes, but I'm sure there's a way to fix this without separating anything, I'm just not that good at tikz :D A: No need for any TikZ tricks: \node[align=center] at (4.7,2.3) {\textsf{Vanjski horizont događaja}\\[10pt] $r=r_+=M+\sqrt{M^2-a^2}$}; The syntax \\[<length] is defined by LaTeX. It starts a new line and adds <length> of vertical space before the next line.
[ "stackoverflow", "0024456624.txt" ]
Q: control structure, repetition exercise: How to get the sum of the digits of a number? Guys can you please help me answer this exercise using for loop without using string methods. Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. For example, the program should output the individual digits of 3456 as 3 4 5 6 and the sum as 18,and output the individual digits of -2345 as 2 3 4 5 and the sum as 14. This is the code: package MyPackage; import java.util.*; public class Integer { public static void main(String args[]) { Scanner console = new Scanner (System.in); int input; int sum = 0; int num1 = 0; int counter = 1; String num = ""; System.out.print("enter a number: "); input = console.nextInt(); if (input == (-input)) { input = input * (-1); num = String.valueOf(input); num1 = num.length(); System.out.print("the digits of " + input + " are: "); for (int i = 0; i < num1; i++ ) { String var = num.substring(i,counter); int var1 = Character.getNumericValue(var.charAt(0)); System.out.print(var + " "); sum = sum + var1; counter++; } System.out.println(); System.out.println("the sum is: " + sum); } else { num = String.valueOf(input); num1 = num.length(); System.out.print("the digits of " + input + " are: "); for (int i = 0; i < num1; i++ ) { String var = num.substring(i,counter); int var1 = Character.getNumericValue(var.charAt(0)); System.out.print(var + " "); sum = sum + var1; counter++; } System.err.println(); System.out.println("the sum is: " + sum); } } } A: Iterating all the digits from right to left is easy enough - you just keep dividing by 10 and keeping the remainder. Since you need to print them from left to right, but there don't seem to be any constraint on the memory usage, you could just keep them in a list, and print it backwards: int num = ...; // inputed from user List<Integer> digits = new LinkedList<>(); int sum = 0; // Extract the digits and the sum while (num != 0) { int digit = num % 10; digits.add (digit); sum += digit; num /= 10; } // Print backwards: System.out.print ("The digits are: "); for (int i = digits.size() - 1; i >= 0; --i) { System.out.print (digits.get(i) + " "); } System.out.println(); System.out.println("Their sum is: " + sum);
[ "mathoverflow", "0000110103.txt" ]
Q: Geometry Realization of Homology Class Hello! My question is about the realization of homology class. The definition of the realizaion of homology class is: for manifold M and a homology class $z\in H_k(M)$, k is an integer. If we find a k-dimensional manifold N and a map $f:N \rightarrow M$ such that $f_* [N]=z$, $[N]$ is the fundamental class, then we call the homology class $z$ can be realized. For this problem, Thom has the following theorem: Thom[1954] For every manifold M, consider a interger coefficient homology class $z\in H_*(M)$, that there exist a interger $l$ and $lz$ can be realized. My Question is Simple: Why we should add this interger $l$? Thom's original paper is written by French and I cann't understand it. Recently, I am reading a paper by A.Gaifullin:Combinatorial Realisation of Cycles and Small Covers and the result is related to Thom's paper. A: Duplicate of this question, which has a very good answer by Eric Wofsey.
[ "stackoverflow", "0048612591.txt" ]
Q: Right REST method for logic execution I know this is debatable but what is the right HTTP method which just takes an input and executes the logic and returns the response. For ex: If I have to expose a REST endpoint which takes an integer and returns some number series ? A: As of described in RFC for HTTP protocol (https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html) HTTP methods can be idempotent ot not: Methods can also have the property of "idempotence" in that (aside from error or expiration issues) the side-effects of N > 0 identical requests is the same as for a single request. The methods GET, HEAD, PUT and DELETE share this property. Also, the methods OPTIONS and TRACE SHOULD NOT have side effects, and so are inherently idempotent. So if your logic changes state of the system noticeably - you better use non-idempotent method - POST. If all changes in the system by calling service method is only record to log file - use safe HTTP method, for instance GET.
[ "physics.stackexchange", "0000367666.txt" ]
Q: Which would be a realistic model of a lying rope? The (badly translated) original text of the problem states: An homogeneous rope of length $l$ and mass $m$ lies partially on a flat, horizontal surface (e.g. a table), with a fraction of its length $l_1$ falling out of it, therefore hanging. Let $\mu_s$ be the coefficient of static friction. Which is the maximum value of $l_1$ before the rope starts sliding? Now, the problem itself, given all the approximations, is very simple. Which ones would then be the aspects to consider if the aim is to obtain the most realistic model of this situation? How much are far the results of the approximation (of each approximation) from the "real" ones? What kind of advanced mathematical tools would be used for models like this? Note: I'm not asking for answers on how to solve this problem (otherwise it would be intelligent to show my efforts and see where my fallacies lie). Instead, I'm interested in the broader, physical modeling, that is beyond the aims of the course I'm taking. A: It all depends on what you want to achieve with this model. The most complete model would propably be modeling the individual atoms of the rope with the standard model. This of course is far away from any practicality and it is an unnecessary complication for the system at hand. For more realistic models it mainly depends on your experiment. If your goal is to measure surface effects, then you need to model the surfaces of the rope and the table with an appropriate model. If your rope has a metal core, maybe electromagnetic effects can be important, so you need to include these. So all in all there is no complete answer, what an appropriate model would be, because it completely depends your experimental conditions and goals. That does not mean though, that this question unnecessary! One of the most important skills to learn in physics is being able to correctly model the system you are interested in, so it is necessary to practice that from the very beginning.
[ "stackoverflow", "0009045774.txt" ]
Q: Change view by swipe, using storyboard I wanna create an app that will have three view controllers. To navigate between them I wanna use swipes and page control (UIPageControl). Also i wanna do this using Stroryboards as much as possible. What's the best way to implement this? Thanks A: This could also be achieved using the storyboard and segues. The basic idea is you would create the segues between the 3 UIViewControllers, then capture the swipe gestures, and then call the perform segue to move between views. On each view, you will have one or two segues: [ View 1 ] -> gotoView2 gotoView1 <- [ View 2 ] -> gotoView3 gotoView2 <- [ View 3 ] Here is a video of how to do it. http://www.youtube.com/watch?v=5u1-DGiUhXU
[ "travel.stackexchange", "0000000116.txt" ]
Q: How much Russian do I need to know for travelling within Russia? Or alternatively - how well-spoken (and widely-spoken) is English? I intend to visit St. Petersburg, Moscow, Irkutsk and Vladivostok. I feel like I might have the most troubles in the latter two cities. Should I be able to read the Cyrillic alphabet? A: You need a bit more information. Are you going with a tour or solo? I went solo and I don't really know any Russian aside form what I picked up while there. I stayed on the Europe side of the Urals, and bounced between hostels. It is definitely more difficult to go solo, but with some pedimiming and patience, it is easy enough. Contrary to a lot of stereotypes Russians are generally nice, helpful people. I can't tell you how many pairs of nit socks I bought from the babushkas on the streets. If you smile and point, you should be fine. It really depends on how experienced you are at traveling. I do, of course, always recommend studying up on the culture and language A BIT before you go. Know some words and carry a dictionary. The 'Where is...(bathroom/police/embassy)' and 'I want...(food/water/beer)' set of words is pretty much required where ever you go. A: I'm in Russia now - just got off the train in Volgograd. I know only a few words and am travelling on my own. Fair warning - Russia (my second visit) is the hardest country I've travelled in. I struggle with the Cyrillic - but it's definitely worth learning. It gets faster to read quite quickly. One of the best suggestions is to write requests down. For example - trains, I write the destination (in Cyrillic), the time (numbers are mostly universal) and the class, and draw a set of bunks to indicate the top bunk. Almost no words are required, but it's clear what I'm after. It's hard, but I arrived with fewer than 10 words, and I've certainly managed - entering from Finland, I went to Murmansk, down to St Petersburg, across to Moscow and back, and now down to Volgograd. It's a fantastic country, well worth it, but it IS hard :) A: You don't have to be able to read the alphabet to travel but learning it will save you from a lot of confusion when you're trying to synchronize the map, the signs and what you heard from the other people. Cyrillic ain't that hard—the hardest part may be to realize that some letters don't match (Cyrillic “В”, “Р”, “С” and “У” are actually “V”, “R”, “S” and “U”). Russians are very willing to help you with the directions, and the younger generation speaks English well. Older people rarely know English but would still try to help you as long as you're able to communicate your destination with gestures and the map. Russians absolutely love explaining their language to the foreigners so don't hesitate to ask them to teach you a few words during a cup of tea. There are a lot of fun things about Russian language. Because the syntax is slightly less strict than English, you may want to ask about the difference between “Я тебя люблю”, “Люблю я тебя” and “Тебя люблю я” (all variations on “I love you”). They will also teach you some Russian mat (sometimes even without you knowing, so never trust what they just taught you is appropriate). Note that smiling out of politeness is not common in Russia and you should be aware of the fact. Russians smile when there is real emotion involved and rarely do so to strangers. People may look dead serious when talking to you but they don't mean to be rude at all.
[ "travel.stackexchange", "0000099636.txt" ]
Q: Which national parks in Nepal do not legally require you to have a guide? I am having difficulty finding out which national parks in Nepal do not legally require you to have a guide, using my phone and local data. There doesn't seem to be a single website, even a Nepali governmental one, to summarise that information. It's easy enough to find out how much entry fees are, but for guide requirements, it seems to be different in every website. A: National parks in Nepal do not legally require you to have a guide. Guidelines, Rules, Acts, Policy, Regulation Collection 2073Language: Nepali Government of Nepal Department of National Parks and Wildlife Conservation, doesn't state anything that make guide compulsory for a tourist. Two things that I have found concerning this question is: (National parks and Wildlife Reserves only) 1. My translation: Without entry card provided by authenticated person of the Government of Nepal no person can enter the National park or Hunting Reserves. (other part is exception for Government person) 2. My translation: Entering in National park or Wildlife Reserves will be your sole responsibility. If some accidents happen inside National Park or Wildlife Reserves Government of Nepal is not responsible for compensation. SO, legally you are not required to have guide for National Parks or even wildlife reserve in Nepal but if you want one that guide must have license provided by Government.
[ "ell.stackexchange", "0000028933.txt" ]
Q: 'order number 1 and 2', 'orders number 1 and 2', or 'order numbers 1 and 2'? From this question by jess: Is there a difference between using "number" and "numbers" when referring to multiple numbers? For example, when calling a merchant to inquire about multiple orders, should I say: I need RMAs for order numbers 1 and 2. or I need RMAs for order number 1 and 2. This question might sound stupid, but I'm not sure what the main subject is. Is "number" the subject and therefore should I use "numbers"? Or are the order numbers (1 and 2) the subject, so should I keep "number" singular? FumbleFingers answered : Personally, I'd say "for orders number 1 and 2". while TecBrat answered : I usually hear that as "order numbers 1 and 2", with the "s". Fumble's comment gives a good way to get around it anyway. Which one is correct? Which one is wrong and why? A: In the first example, "number X" is modifying the subject "order" as part of a series. The "1" and "2" represent the place in the series: I need RMAs for orders number 1 and number 2 (out of 5). I need RMAs for orders 1 and 2. I need RMAs for orders number 1 (ID# 56789) and number 2 (ID#56790). Making "numbers" plural instead indicates that "order numbers" is the complete, more descriptive subject, similar to "tracking numbers" or "inventory numbers." That ties it directly to that item, no matter how many orders there are or in what sequence. This makes more sense if for example you provide a complete tracking number: I need RMAs for order numbers 1234-XYZ-0987 and 1234-ABC-7890. Of course this could also be shortened to just use "orders," which in that case is the complete subject & needs to be plural. I need RMAs for orders 1234-XYZ-0987 and 1234-ABC-7890.
[ "stackoverflow", "0009220707.txt" ]
Q: Trying to make a vector using templates I'm trying to self-teach myself C++, and once again I got stuck on something and can't seem to fix it. Please excuse the horrible mess of a code that you're about to see. This is also my first post on this site, so the post's format will probably be off too, sorry. There are two files: main.cpp and vect1.h (no vect1.cpp because it seems templates like to only hang out in header files) main.cpp: #include <iostream> #include "vect1.H" using namespace std; int main(){ vect1<int> inst1(10); inst1[9]=4; cout<<inst1[9]<<endl; //----- vect1<double> inst2(10); inst2[5]=5.112; cout<<inst2[5]<<endl; //----- //====PART 2=====// cout<<"--------"<<endl; inst2[9]=999; cout<<inst2[9]<<endl; //inst2.pop(); inst2.push(2); cout<<inst2[9]<<endl; cout<<inst2[10]<<endl;//New block system("PAUSE"); return 0;} vect1.h: #ifndef VECT1_H #define VECT1_H #include <iostream> //DEBUG template <class T> class vect1{ private: T *ptr; T total; //work on this int units; int counter; public: //vect1(); vect1(T); vect1(); T &operator[](const int &); void pop(); void push(T); }; //--------------------- /* template <class T> vect1<T>::vect1(){ ptr = new int [0]; } */ template <class T> vect1<T>::vect1(T number){ ptr = new T [number]; total=0; units=(int)number; for(counter=0;counter<number;counter++){ ptr[counter]=0; } } /* now the destruct is giving me errors... template <class T> vect1<T>::~vect1(){ total=0; delete[] ptr; }*/ //<<this line tosses a C2039 error template <class T> T &vect1<T>::operator[](const int & ref){ if(ref>0 && ref<(units)){ return ptr[ref]; }else{ throw "Error! Out of range!"; //<<make catch } } //-------- template <class T> void vect1<T>::pop(){ units = (units-1); T *tempPtr; tempPtr = new T[units]; for(counter=0;counter<units;counter++){ tempPtr[counter]=ptr[counter]; } delete[] ptr; ptr = new T[units]; for(counter=0;counter<units;counter++){ ptr[counter]=tempPtr[counter]; } delete[] tempPtr; } //-- template <class T> void vect1<T>::push(T pushnum){ units++; const int newsize=(int)units; //<<<<< T *tempPtr; tempPtr = new T[units]; for(counter=0;counter<(units-1);counter++){ tempPtr[counter]=ptr[counter]; } //tempPtr[(int)units]=pushnum; delete[] ptr; std::cout<<units<<std::endl;//<<DEBUG ptr = new T[units]; for(counter=0;counter<(units-1);counter++){ ptr[counter]=tempPtr[counter]; //ptr[9]=101; } ptr[newsize]=pushnum; /* <<bleh */ //ptr[newsize]=12321; //DEBUG //<<Even this isn't working... delete[] tempPtr; } //--------------------- #endif output(in the console): 4 5.112 -------- 999 11 999 -6.27744e+066 Press any key to continue . . . The plan is to make it so when you pop() it will create a new temp array of T and copy everything but the last block from the original to the temp array, delete the original array, and then create a new array one size smaller than before and send everything back, deleting the temp array. Same idea for the push(number), only the opposite. Push would copy itself to temp, push would delete itself and then re-create itself as 1 size bigger, then send everything from temp to push and delete temp. Then send the number sent with push into the new block. So this program should print out '2' after the second "999" line. But instead I get "-6.27744e+066". Pop() seems to work. Sorta. Having real issues with push(num) though. I also seem to suddenly get a C2039 error from my destructor. It wasn't doing that before, and I've yet to change anything in it. I would really appreciate it if someone could look over this mess and give me some tips on what to fix. Thanks! I use Visual Studio 2010 as my compiler. This is my build log(with some nice errors/warnings to go with it!): 1>------ Rebuild All started: Project: chapter 16-5, Configuration: Debug Win32 ------ 1>Build started 2/9/2012 5:34:01 PM. 1>_PrepareForClean: 1> Deleting file "Debug\chapter 16-5.lastbuildstate". 1>InitializeBuildStatus: 1> Creating "Debug\chapter 16-5.unsuccessfulbuild" because "AlwaysCreate" was specified. 1>ClCompile: 1> main.cpp 1>e:\programming(cpp)\chapter 16-5\chapter 16-5\vect1.h(31): warning C4244: 'initializing' : conversion from 'double' to 'unsigned int', possible loss of data 1> e:\programming(cpp)\chapter 16-5\chapter 16-5\vect1.h(30) : while compiling class template member function 'vect1<T>::vect1(T)' 1> with 1> [ 1> T=double 1> ] 1> e:\programming(cpp)\chapter 16-5\chapter 16-5\main.cpp(11) : see reference to class template instantiation 'vect1<T>' being compiled 1> with 1> [ 1> T=double 1> ] 1>Manifest: 1> Deleting file "Debug\chapter 16-5.exe.embed.manifest". 1>LinkEmbedManifest: 1> chapter 16-5.vcxproj -> E:\Programming(CPP)\chapter 16-5\Debug\chapter 16-5.exe 1>FinalizeBuildStatus: 1> Deleting file "Debug\chapter 16-5.unsuccessfulbuild". 1> Touching "Debug\chapter 16-5.lastbuildstate". 1> 1>Build succeeded. 1> 1>Time Elapsed 00:00:10.62 ========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ========== A: template <class T> vect1<T>::vect1(T number){ ptr = new T [number]; total=0; units=(int)number; for(counter=0; counter<number; counter++) { ptr[counter]=0; } } This constructor allocates space for number objects, but number has general type T and you cast it to int. If you want to have a vector of strings or objects, conversion to int fails. number should have type int. Casting is generally not needed and it could be a symptom of bad design (except inheritance - dynamic_cast). Because T could be anything you can't initialize it in constructor and you must leave it to the user of your vector. T &vect1<T>::operator[](const int & ref){ You use const reference because you were probably told that it is faster than passing by value. Well this is true for larger objects, not for int. Reference is basically just another pointer (with different syntax). The function is passed an address to the target variable. Pointer and int are usually equally large so there is no improvement here and accessing through pointer is definitely slower than directly accessing the value. template <class T> void vect1<T>::pop(){ units = units-1; T *tempPtr = new T[units]; for(counter=0;counter<units;counter++){ tempPtr[counter]=ptr[counter]; } delete[] ptr; ptr = tempPtr; } There is no need to copy data back to ptr it is enough to copy the pointer. template <class T> void vect1<T>::push(T pushnum){ units++; T *tempPtr = new T[units]; for(counter=0;counter<(units-1);counter++){ tempPtr[counter]=ptr[counter]; } tempPtr[units-1]=pushnum; // New item is at units-1 position! delete[] ptr; ptr=tempPtr; // Again, just assign the pointer. } And add the destructor releasing allocated memory. I hope this helped and I am sorry for my bad English.
[ "stackoverflow", "0016998366.txt" ]
Q: How to Fix Weird C++ Codes that Assume the Relative Ordering of Class Members I need to modify the ordering of my C++ class members. For example: class B { public: int i; int j; int k; ... }; becomes class B { public: int j; int k; int i; ... }; The problem is there are weird codes in my large code bases that depend on relative location of the class members. For example some functions would assume address of member j is smaller than that of member k. Is there any CASE tool that can help me to identify any code that read the address of a class member? A: I am not aware of any tool that solve your problem, but I would define a class which supports all operators for int type and which overloads ampersand operator so that the result of the operator cannot be casted to a pointer. Then I'd use this class instead of int in your class member definitions and look at places where compiler gives errors. Something like class IntWrapper { public: IntWrapper() { } IntWrapper(const int x) { } // don't care about implementation as we operator int() const { return 0; } // want compile-time errors only IntWrapper& operator ++() { return *this; } IntWrapper& operator ++(int) { return *this; } ... void operator &() const { } // make it void so it would cause compiler error }; And then: class B { public: IntWrapper i; IntWrapper j; IntWrapper k; ... }; This will not help against using boost::addressof function or some dirty reinterpret_cast of a reference, but addressof is probably never used at all in your project, as well as the reinterpret_cast<char&> trick (who would use it for plain integers?). You should also care about taking an address of the whole object of B class.
[ "magento.stackexchange", "0000135736.txt" ]
Q: Magento 2.1 product urls end with .html.html - why? I cannot figure out what settings would prevent this from happening. Also cannot figure out how to fix the urls that have been set this way already. Thanks Sam A: We fixed the URL's like this: Remove all product related rewrites from url_rewrite table Mass update all products in admin (select all, update, set website as default) If problem still exists, run this MySQL command: UPDATE url_rewrite SET request_path = REPLACE(request_path, '.html.html', '.html') WHERE url_rewrite.request_path like '%html.html'; Then clear the caches.
[ "stackoverflow", "0025430774.txt" ]
Q: BX slider, transition from first to last slide flickers(goes right then come back to original) Following is my code for simple implementation for BX slider: var slider = $('#bxslider').bxSlider(); <ul id="bxslider"> <li> <img class="carouselimage" src="images/01e_image.jpg" /> </li> <li > <img class="carouselimage" src="images/01c_image.jpg" /> </li> <li > <img class="carouselimage" src="images/01a_image.jpg" /> </li> </ul> I've used everything correctly, no extra CSS and JS. While I make the transition by clicking left arrow from first to last (reverse), the last slide goes towards the right out of the container for a sec and comes back to original, looks like a flickering. Anybody got any clue? Thanks in advance. A: I fix it that way: $('.bxslider').bxSlider({ auto: true, useCSS: false }); (thanks to stevenwanderski on https://github.com/stevenwanderski/bxslider-4/issues/127) A: My co-worker had this issue, she used this on bxslider -webkit-perspective: 1000; -webkit-backface-visibility: hidden; See here iPhone WebKit CSS animations cause flicker A: i got this fixed.. if anyone else needs.. i've added "if (0===value) value=-40;// fix for flickering issue 2208141730" in following function, you can find this function in BxSlider v4.1.2(jquery.bxslider.js) at line no. 535 and above fix is added at line no. 539 var setPositionProperty = function(value, type, duration, params){ // use CSS transform if(slider.usingCSS){ // determine the translate3d value if (0===value) value=-40;// fix for flickering issue 2208141730
[ "gaming.stackexchange", "0000064514.txt" ]
Q: Where can I find the collectibles for the last page of the Collectopaedia? I'm about 30 hours into Xenoblade Chronicles, and one thing I've made a point of doing in every region is filling up the Collectopaedia with all of the various shiny blue dots of fun that are scattered around the world map. Normally, with each subsequent area I enter, a new page is added to the Collectopaedia, starting with Colony 9, then with Tephra Cave, and on to the Bionis Leg, and so on and so forth. However, since I've started playing, there has been a page marked 'Other', with far fewer 'open slots' than any other page. I am yet to find any items that belong on this page. Where are they? What are my rewards for finding them? A: To quote Split Infinity's Xenoblade Chronicles: Achievement/Collectopaedia List: The items in Other category can only be obtained by trading! Minute Mantis from Sonia in Colony 9 (4* affinity) Love Beetle from Lupa in Frontier Village (3* affinity) Golden Cog from Oleksiy in Colony 6 (5* affinity) Angel Engine Y from Rakzet in Machina Village (5* affinity) Thunder Compass from Jarack in Ether Plant, Eryth Sea (5* affinity) Coin of Fortune from Mac'rish in Colony 6 (5* affinity) Love Source from Jer'ell in Colony 6 (5* affinity)
[ "stackoverflow", "0025922574.txt" ]
Q: AS3 - Read contents from .ini file I have an AIR application that I am wanting to open and read contents from a .ini file that has some properties in it. I've looked around online and can't find anything - seems most of what Adobe had has been expired (LoadVars, PropertyLoader, etc.) Any suggestions? thanks A: You can use either URLLoader or a combination of File and FileStream
[ "stackoverflow", "0000938978.txt" ]
Q: Attacking websites without leaving an audit trail Recently Aetna suffered a breach where it lost 65,000 SSNs. They never were able to find an audit trail of what happened which probably hints that the attack leveraged XSS or similar technique. Are there specific known attacks that the bad guys are repeatedly leveraging for this type of attack? A: There are common mistakes that people make and there are common platforms that people use. Each, if left unpatched would allow somebody to break in using a simple script. But if somebody was going after something specifically, in this case social security numbers, that have high value in organised crime rings, I would have expected somebody to spend a little more time figuring out how the site worked and applying a custom exploit to grab the data. I don't see why it has to be XSS either. If their systems weren't sending access logs off-server, or even logging every entry point, there are a variety of methods somebody could exploit an exploitable server and clean up afterwards.
[ "stackoverflow", "0007808650.txt" ]
Q: Overwrite getter to act differently depending on where it was called in template o not. Django Is it posible object to know if it getter called in template or not? Check for same global variables or any ideas? I wanna Moddel to give field attributes wrapped in div when it is called in template. A: No. It is not possible. You could write a custom template tag like {% divwrapper model.attr %} or you could write a model method like "html_dump_all_attrs" that returned something. But no, your solution won't work.
[ "arduino.stackexchange", "0000033114.txt" ]
Q: Digital read on voltages between 1 and 31 volts? Hello Arduino comunity! I am working on a circuit that uses an Arduino Mini to read values from certain points of a boost/buck converter circuit to determine things like input state, output state, overheat and so on. The circuit is working all right, and the only part left to do is to connect the digital pins of the Arduino to the different points in the boost/buck regulator. The problem is however that I need to read from a range of voltages between 1 and 31 volts with the Arduino, which isn't possible, because not only will it damage the controller if the voltage exceeds 5V, but values below 3V will be regarded as false. I thought of putting some potential dividers, which would obviously not do the trick, and I also thought of using a WS78L05 voltage regulator per input pin (because each pin might have a different voltage from the rest) but that isn't dealing with voltages <=5V and 31V exceeds its rating as well. Lastly I thought of using transistors, which seemed like a good idea, but I would require 2 transistors per input wired as follows: simulate this circuit – Schematic created using CircuitLab But it is impractical to do for 4 inputs and there is limited space available on the PCB too :( Is there any IC that encapsulates the circuit above, or is there any other way to achieve what I want to do? Thanks very much :) A: Using a simple voltage divider (51K / 10K as you have worked out already) fed directly into an ADC input will give you a reading of 32 on the ADC at 1V input. That should be enough to give a reliable threshold detection. If you want to have higher sensitivity at lower voltages you can increase the output of your voltage divider to more than 5V and then clip it with a zenner diode. For instance if you reduce the 51K to 33K you get 7.2V out of the voltage divider. A 5V zenner diode can then clip it to 5V. Your 1V input (which would be 0.233V on the output of the divider) would now read 47 on the ADC. Anything over 21V would then read 1023. simulate this circuit – Schematic created using CircuitLab Theoretically you could get away with not having the voltage divider at all and just using the zenner and one resistor to clip the incoming voltage to 5.1V. That would give you the greatest sensitivity, but also the greatest current flow through the zenner. simulate this circuit Size R1 to limit the current at your maximum voltage to within the rating of the zenner.
[ "ru.stackoverflow", "0000618006.txt" ]
Q: Java. Что происходит, когда возвращаемое значение не помещается ни в какую переменную? Вопрос слегка глупый, просто интересно, понятно, что так никто не делает, но все же - это будет жрать ресурсы и т.д? Например, есть вот такой метод public String getName(){ return name; } И я где-нибудь его вызываю вот так, без сохранения в переменную getName(); Надо так. String s = getName(); :D Да, очень глупо получилось, но все же. Что происходит со значением, если оно никуда не делось? A: В данном случае в области памяти под названием "куча" (там, где создаются вообще все объекты) просто будет создаваться объект типа String. Но к нему не ведет никакой ссылки, соответственно, использовать данный объект мы уже никогда не сможем. Поэтому сборщик мусора при первой же необходимости попросту удалит этот объект из памяти.
[ "stackoverflow", "0027497238.txt" ]
Q: node.js require function not finding module I have a server.js file that I downloaded from someone's website. The first line is: var express=require('express'); When I try to run this server with "node server.js" I get the following error: "Cannot find module 'express'." The express module is installed in the default node install location: C:\Users\myname\node_modules\express\ I'm able to successfully run express by executing "node express.js" from the express install location in node_modules. I also tried copying over the express folder and file into my c:\node-testing\ directory where my server.js file is located but I still get the error. Any idea what the problem might be and how to fix? A: You can set the NODE_PATH environment variable to tell nodejs to search other paths for globally installed modules that are not in the project directory. See http://nodejs.org/api/modules.html#modules_loading_from_the_global_folders for details. On Unix installations there are some built-in default locations, but on Windows, it appears you have to set this environment variable manually to support a global location. FYI, if you want require to load a module from the project directory, then you have to use require("./filename"); with the ./ in front of it. That's why it didn't work when you copied it to the project directory. node makes a distinction between loading from the project directory vs. loading from the node_modules directory below and thus requires a different syntax to specify which one you want. Express.js is also not a stand-alone module because it depends on a bunch of other modules so you could not copy only it. I'd recommend using the NODE_PATH option or install express into your project directory (it will end up in a node_modules sub-directory).
[ "stackoverflow", "0056494526.txt" ]
Q: Can I use Guzzle for GraphQL API consumption? There isn't a lot of information in the google-verse about consuming GraphQL API's in PHP. There are several packages that from my perspective, are mostly about creating your own GraphQL API, but nothing specific to consuming. It's possible that I'm over complicating things or that the solution to my question is obvious. I've solved my problem and will post the answer. A: I didn't want to pull these packages in when I barely understood what they provided and I just wanted to use the same tools I was used to in the REST world for a lightweight transition. The answer is Yes, you can use Guzzle for consuming a GraphQL API. There are probably ways to make this prettier, but for now, this is what's working. You pass authorization through the Authorization header and Content-Type must be set to application/json. When constructing your query be wary of quotes, spacing, and line breaks. I haven't yet figured out a way to make the code prettier and still maintain a valid query. The first portion {"query": "query { is a requirement for every query. The object name must be wrapped in double quotes and the query body "query { }" must be wrapped in double quotes as well. $graphQLquery = '{"query": "query { viewer { repositories(last: 100) { nodes { name id isPrivate nameWithOwner } } } } "}'; use GuzzleHttp\Client; $response = (new Client)->request('post', '{graphql-endpoint}', [ 'headers' => [ 'Authorization' => 'bearer ' . $token, 'Content-Type' => 'application/json' ], 'body' => $graphQLquery ]); A: Just make normal post request from guzzle. Add form params as query and variables. Put your query in query form param and and variables as array of key value. $response = $this->client->post('https://grapqlEndPoint', [ 'form_params' => [ 'query' => ' query($username: String!) { users(username: $username) { username } }', 'variables' => [ 'username' => $username ] ] ]); echo $response->getBody()->getContents();
[ "stackoverflow", "0036481871.txt" ]
Q: Combine array into one string I want to be able to combine a variable length array into a single string, for example: var1 = ['Hello',' ','World','!'] becomes: var2 = 'Hello World!' and the first array may be bigger than 4. Thanks for any help! A: str.join() Return a string which is the concatenation of the strings in the iterable iterable. The separator between elements is the string providing this method. List items will be joined (concatenated) with the supplied string. Using '' will join all items with no character between them. Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> var1 = ['hello', ' ', 'world', '!'] >>> ''.join(var1) 'hello world!' >>> ' '.join(var1) 'hello world !' >>> '*%*%*'.join(var1) 'hello*%*%* *%*%*world*%*%*!' >>>
[ "stackoverflow", "0010802278.txt" ]
Q: c# image resizing Just working on a image uploader/resizer in my asp.net 4 web forms project. Does anyone know of a technique in C# for resizing uploaded images that could help with ones that are smaller than the minimum size required? Obviously the quality will be suspect if resizing up the way, so has anyone found a way of possibly creating a new image that is the right size that is maybe plain white and then placing the original image on top of that white background? Thanks Edit - now ImageResizer.net is working well, but having a job resizing when the image is smaller. See comment below IrishChieftains answer for full details: FINAL EDIT ################ Ok, I swear I tried this last night and it didn't work, so maybe just needed a clean browser or VS2010 restart but for anyone who's interested, here was my final solution. The key was scale=upscalecanvas : int maxWidth = 400; int maxHeight = 200; ImageBuilder.Current.Build(saveLocation, saveLocation, new ResizeSettings("width=" + maxWidth + "&height=" + maxHeight + "&mode=pad&bgcolor=DDDDDD&anchor=middlecenter&scale=upscalecanvas")); Can't rate ImageResizer.net highly enough - great program A: The best library out there is ImageResizer. If that doesn't help, then you'll end up trying it by hand... Standardizing jpeg size in asp.net
[ "stackoverflow", "0004676458.txt" ]
Q: Super Simple Boolean Function— what am I doing wrong? I'm not sure why I can't get this to work: A super simple function that just needs to return true or false: <?php function check_for_header_images() { if ( file_exists('path/to/file') && file_exists('path/to/file')) return true; } ?> It will not return true: <?php if(check_for_header_images()) { // do stuff } ?> …doesn't do stuff: <?php if(!check_for_header_images()) { // do stuff } ?> …does do stuff. The conditions I've set for the function SHOULD return true. If I take that same exact if statement and just do this: <?php if ( file_exists('path/to/file') && file_exists('path/to/file')) { //do stuff } ?> It works. Do I just not understand how to write a function? A: <?php function check_for_header_images() { if ( file_exists('path/to/file') && file_exists('path/to/file')) return true; return false; // missing the default return when it's false } ?> or you could do: <?php function check_for_header_images() { return ( file_exists('path/to/file') && file_exists('path/to/file')); } ?> also, the ! in your if statement means opposite. that means if (!false) is true, and if (!true) is false
[ "stackoverflow", "0009529166.txt" ]
Q: Membership.Islockedout property not available I am using aspnet_Membership in my asp.net MVC 3 application and I am using maxInvalidPasswordAttempts="5" in web.config under membership\providers. I see that user is lockedout after 5 attempts ( that is what I want). Now on login view I want to show user that you are lockedout due to 5 invalid attempts. But I dont see provider.Islockedout property there. Please suggest. A: You can use the below code to check if the user is locked out. MembershipUser usr = Membership.GetUser(userName); if (usr.IsLockedOut) // do whatever action...
[ "superuser", "0001241850.txt" ]
Q: Move-Item -exclude throwing redundant error I'm moving a group of files from a directory and I'm using the -exclude modifier to exclude files with a .gpg extension: Move-Item -path $encrypted_folder\*.* -EXCLUDE *.gpg -destination $final_dir And while this works fine by moving every non-.gpg file, I get the following error every time Move-Item encounters a .gpg file: Move-Item : Cannot move item because the item at 'C:\Users\ThisUser\Documents\PGP Encryption test\UUID\xxxx.gpg' does not exist. At C:\Users\ThisUser\Documents\PGP Encryption test\yyyy.ps1:41 char:1 + Move-Item -path $encrypted_folder\*.* -EXCLUDE *.gpg -destination $final_dir + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Move-Item], PSInvalidOperationException + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.MoveItemCommand Why is it complaining that it can't move a .gpg item because it doesn't exist, when I've set the command to exclude .gpg items? (which definitely exist). The exclusion is occurring, and a subsequent command to -include .gpg files works fine, but I'm not happy with the errors on my -exclude command. A: I would rewrite the expression as follows: gci $encrypted_folder\*.* -exclude *.gpg | move-item -destination $final_dir You may also build more sophisticated filters using where-object and -match/notmatch, for example exclude only those with 4 or more chars before extension: gci |? name -notmatch '^.{4,}\.gpg$' | [rest of processing here] Explanation As noted in comments, this error is reported here: https://github.com/PowerShell/PowerShell/issues/2385. I can replicate it in PS 4 as well: $psversiontable Name Value ---- ----- PSVersion 4.0 WSManStackVersion 3.0 SerializationVersion 1.1.0.1 CLRVersion 4.0.30319.42000 BuildVersion 6.3.9600.18728 PSCompatibleVersions {1.0, 2.0, 3.0, 4.0} PSRemotingProtocolVersion 2.2 New-Item -Name "foo.txt" -ItemType File New-Item -Name "bar.txt" -ItemType File Move-Item -Path ".\*" -Destination "move.txt" -Exclude "bar*" Move-Item : Cannot move item because the item at 'C:\temp\test\bar.txt' does not exist. At line:1 char:1 + Move-Item -Path ".\*" -Destination "move.txt" -Exclude "bar*" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Move-Item], PSInvalidOperationException + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.MoveItemCommand The fix for this is in the not-yet-released version 6 (https://github.com/PowerShell/PowerShell/tree/v6.0.0-beta.5).
[ "stackoverflow", "0006031582.txt" ]
Q: Complications with SQL Server database having different collation than the server default? We are in the process of migrating databases off an old SQL Server 2k EE server with default collation "Latin1_General_CI_AS" onto new SQL Server 2005 & 2008 servers with default collation "SQL_Latin1_General_CP1_CI_AS". There are no international characters that would require Unicode that I know of, so the two codepages are almost the same for practical purposes. The primary SQL Server DBA is adamant that every single database (most of which are built by 3rd-party apps) must be rebuilt with the new collation before he will migrate them. I know that ever since SQL Server 2000 it's been possible to set individual databases to have a different collation than the default. But what are the real consequences of running with mixed collations? One article from Microsoft suggests complications with the shared tempdb, for example (but can it easily be avoided?). And, perhaps more importantly, what might we do to avoid these problems if we do need to support multiple collations on the new servers? A: The problem with different collations between server and db is as is mention before that temp tables will default be created with the server collation. That will make any comparisons on character fields between a temp table and a regular table fail. This can be avoided by the developers of the 3rd-party apps by using COLLATE database_default for character fields of temp tables. create table #Tmp(Col1 nvarchar(50) COLLATE database_default) I come from the "other" side. I'm not a DBA but a 3rd party software developer and I think that it is my responsibility to build my app to work in an environment where the collation is different between database and server. It is also my responsibility that my app will work with case sensitive collation. A: Okay not the best answer, but You asked: "What are the real consequences of running with different collations" It can be a headache. The article you mentioned by Microsoft nails it on the head. In my personal experience I've come across that issue and it wasn't easy to avoid. Mismatched collations will pop up in unplanned places unless you test well. You also asked "what might we do to avoid these problems if we do need to support multiple collations on the new servers?" Nothing comes to mind except to test like crazy. I really wish you luck, it can be a common and hairy problem that I wouldn't wish on anyone.
[ "stackoverflow", "0038617275.txt" ]
Q: Split array into a unspecific number of chuncks I have a string that contains the given answers from a qiuz by a user. This string is saved on the db table and it has this form. ,P1,1,2,3,5,8,9,,P2,1,3,4,5,6,8,9,,P3,1,2,3,4,6,8,9,,P4,1,,P5a,b,,P5b,d,,P5c,a,,P5d,c,,P6,4,,P7,2,,P8a,hc,,P8b,df,,P8c,bg,,P8d,e,,P9,4,,P10,3,,P11,4,,P12,2,,P13,3,,P14,3,,P15a,acejg,,P15b,dfhib,,P16,1,3,,P17,2,,P18,1,,P19,3,,P20,3,5,6 Ater getting the string i explode it, and the form becomes like this. Array ( [0] => P1 [1] => 1 [2] => 2 [3] => 3 [4] => 5 [5] => 8 [6] => 9 [7] => P2 [8] => 1 [9] => 3 [10] => 4 [11] => 5 [12] => 6 [13] => 8 [14] => 9 [15] => P3 [16] => 1 [17] => 2 [18] => 3 [19] => 4 [20] => 6 [21] => 8 [22] => 9 [23] => P4 [24] => 1 [25] => P5a [26] => b [27] => P5b [28] => d [29] => P5c [30] => a [31] => P5d [32] => c [33] => P6 [34] => 4 [35] => P7 [36] => 2 [37] => P8a [38] => hc [39] => P8b [40] => df [41] => P8c [42] => bg [43] => P8d [44] => e [45] => P9 [46] => 4 [47] => P10 [48] => 3 [49] => P11 [50] => 4 [51] => P12 [52] => 2 [53] => P13 [54] => 3 [55] => P14 [56] => 3 [57] => P15a [58] => acejg [59] => P15b [60] => dfhib [61] => P16 [62] => 1 [63] => 3 [64] => P17 [65] => 2 [66] => P18 [67] => 1 [68] => P19 [69] => 3 [70] => P20 [71] => 3 [72] => 5 [73] => 6 ) each question starts with a "P". So question 1 will be "P1" question 2 "P2" and so on. Each given answer is between the "P" until next "P". So the answers given from the user for the question number 1 are " 1 | 2 | 3 | 5 | 8 | 9 ". I was trying to insert the values to another array with a foreach loop but i could not find any way to seperate the answers. My desire output is. Array ( [P1] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 5 [4] => 8 [5] => 9 ) [P2] => Array ( [0] => 3 [1] => 4 [2] => 5 [3] => 6 [4] => 8 [5] => 9 ) ) Please tell me if you have any suggestions.Thank you very much A: assuming we ve everything inside $p $res= array(); foreach($p as $key => $value){ if(strpos($value, "P") !== false){ $currentP = $value; $res[$currentP] = array(); }elseif($value){ $res[$currentP][] = $value; } } WORKING PHP FIDDLE tested with v5 and v7
[ "datascience.stackexchange", "0000029006.txt" ]
Q: Feature selection vs Feature extraction. Which to use when? Feature extraction and feature selection essentially reduce the dimensionality of the data, but feature extraction also makes the data more separable, if I am right. Which technique would be preferred over the other and when? I was thinking, since feature selection does not modify the original data and it's properties, I assume that you will use feature selection when it's important that the features you're training on be unchanged. But I can't imagine why you would want something like this.. A: Adding to The answer given by Toros, These(see below bullets) three are quite similar but with a subtle differences-:(concise and easy to remember) feature extraction and feature engineering: transformation of raw data into features suitable for modeling; feature transformation: transformation of data to improve the accuracy of the algorithm; feature selection: removing unnecessary features. Just to add an Example of the same, Feature Extraction and Engineering(we can extract something from them) Texts(ngrams, word2vec, tf-idf etc) Images(CNN'S, texts, q&a) Geospatial data(lat, long etc) Date and time(day, month, week, year, rolling based) Time series, web, etc Dimensional Reduction Techniques (PCA, SVD, Eigen-Faces etc) Maybe we can use Clustering as well (DBSCAN etc) .....(And Many Others) Feature transformations(transforming them to make sense) Normalization and changing distribution(Scaling) Interactions Filling in the missing values(median filling etc) .....(And Many Others) Feature selection(building your model on these selected features) Statistical approaches Selection by modeling Grid search Cross Validation .....(And Many Others) Hope this helps... Do look at the links shared by others. They are Quite Nice... A: As Aditya said, there are 3 feature-related terms that sometimes are confused with each other. I will try and give summary explanation to each one of them: Feature extraction: Generation of features from data that are in a format that is difficult to analyse directly/are not directly comparable (e.g. images, time-series, etc.) In the example of a time-series, some simple features could be for example: length of time-series, period, mean value, std, etc. Feature transformation: Transformation of existing features in order to create new ones based on the old ones. A very popularly used technique for dimensionality reduction is Principal Component Analysis (pca) that uses some orthogonal transformation in order to produce a set of linearly non-correlated variables based on the initial set of variables. Feature selection: Selection of the features with the highest "importance"/influence on the target variable, from a set of existing features. This can be done with various techniques: e.g. Linear Regression, Decision Trees, calculation of "importance" weights (e.g. Fisher score, ReliefF) If the only thing you want to achieve is dimensionality reduction in an existing dataset, you can use either feature transformation or feature selection methods. But if you need to know the physical interpretation of the features you identify as "important" or you are trying to limit the amount of data that need to be collected for your analysis (you need all the initial set of features for feature transformation), then only feature selection can work. You can find more details on Feature Selection and Dimensionality Reduction in the following links: A summary of Dimension Reduction methods Classification and Feature Selection: A Review Relevant question and answers in Stack Overflow A: I think they are 2 different things, Lets start with Feature Selection: This technique is used for selecting the features which explain the most of the target variable(has a correlation with the target variable).This test is ran just before the model is applied on the data. To explain it better let us go by an example: there are 10 feature and 1 target variable, 9 features explain 90% of the target variable and 10 features together explains 91% of the target variable. So the 1 variable is not making much of a difference so you tend to remove that before modelling(It is subjective to the business as well). I can also be called as Predictor Importance. Now lets talk about Feature Extraction, Which is used in Unsupervised Learning,extraction of contours in images, extraction of Bi-grams from a text, extraction of phonemes from recording of spoken text. When you don't know anything about the data like no data dictionary, too many features which means the data is not in understandable format. Then you try applying this technique to get some features which explains the most of the data. Feature extraction involves a transformation of the features, which often is not reversible because some information is lost in the process of dimensionality reduction. You can apply Feature Extraction on the given data to extract features and then apply Feature Selection with respect to the Target Variable to select the subset which can help in making a good model with good results. you can go through these Link-1,Link-2 for better understanding. we can implement them in R, Python, SPSS. let me know if need any more clarification.
[ "stackoverflow", "0041022726.txt" ]
Q: Algolia add footer to javascript autocomplete search results dropdown I am using Rails to create my app, but javascript to implement the search. This is what I have for my Algolia autocomplete. I am on the free ('Hacker') plan with Algolia, and I want to add a footer. Is there an easy way to do this? What I have below (which I found at: https://github.com/algolia/autocomplete.js/blob/master/README.md) is not working. var client = algoliasearch("<%= ENV['ALGOLIA_API'] %>", "<%= ENV['ALGOLIA_SECRET'] %>"); var index = client.initIndex('User'); //initialize autocomplete on search input (ID selector must match) autocomplete('#aa-search-input', { hint: false }, [{ source: autocomplete.sources.hits(index, {hitsPerPage: 5}), //value to be displayed in input control after user's suggestion selection displayKey: function(suggestion) { return suggestion.first_name + " " + suggestion.last_name}, //hash of templates used when rendering dataset templates: { //'suggestion' templating function used to render a single suggestion suggestion: function(suggestion) { var link = "<form action='<%= ENV['HOST'] %>users/" + suggestion.id + "/friend_requests' method='post' id='addfriend' style='color: lightgreen'> <input name='authenticity_token' value='<%= form_authenticity_token %>' type='hidden'> <button type='submit' name='user_id' value='" + suggestion.id + "' class='btn-link'>Add</button></form>"; var card = "<span>" + "<img src=<%= ENV['CLOUDINARY_SECOND_URL'] %>" + suggestion.photo.path + " alt='' class='avatar'> " + suggestion._highlightResult.first_name.value + " " + suggestion._highlightResult.last_name.value + "</span><span>" + link +"</span>"; return card } } footer: '<span class="branding">Powered by <img src="https://www.algolia.com/assets/algolia128x40.png" /></span>' }]).on('autocomplete:selected', function(event, suggestion, dataset) { var url = "<%= ENV['HOST'] %>users/"; window.location.assign(url + suggestion.id)}); A: You need to put footer inside of the templates object. Like that: templates: { //'suggestion' templating function used to render a single suggestion suggestion: function(suggestion) { var link = "<form action='<%= ENV['HOST'] %>users/" + suggestion.id + "/friend_requests' method='post' id='addfriend' style='color: lightgreen'> <input name='authenticity_token' value='<%= form_authenticity_token %>' type='hidden'> <button type='submit' name='user_id' value='" + suggestion.id + "' class='btn-link'>Add</button></form>"; var card = "<span>" + "<img src=<%= ENV['CLOUDINARY_SECOND_URL'] %>" + suggestion.photo.path + " alt='' class='avatar'> " + suggestion._highlightResult.first_name.value + " " + suggestion._highlightResult.last_name.value + "</span><span>" + link +"</span>"; return card }, footer: '<span class="branding">Powered by <img src="https://www.algolia.com/assets/algolia128x40.png" /></span>' } Right now you have it outside, so it does not take footer template into account.
[ "stackoverflow", "0020222580.txt" ]
Q: C++ - How to inform that a data field is not used or set? I have an std::vector<T> where T is a type composed of small numeric fields such as ints or floats; let's say that I have a total of 4 fields for my T, so for example in T I have an int, a uint32_t, a double and a float. Sometimes I need all 4, sometimes I only need 1 and all the others are not needed or I can easily discard them since they are at their "default value" ( 0 or 0.0 ) when I read them. There is a way to design my type T such as when I'll insert a new set of values I can flag the unused field as unused ? Obviously my problem is that I can't use a different T for each combination ( also it would be a crazy thing to do for each combination ) and I would like to combine a compact structure ( without spending even time on the insertion of a value that I'm not using ) with a common type for every scenario so the user just checks if that record is used or not. Is this possible in standard C++ 11 or C++ 03 ? A: What you hint at is an optional type. You might want to redesign your architecture, so that you don't need to store the unnecessary values. However, if you still wish to do so, there are: Boost.Optional Poco::Optional a c++11 implementation of std::optional If you don't want to use something like std::vector< optional<T> > from a library, you could use std::pair from the standard library std::vector< std::pair<T,bool> > and std::optional should be available in the head development version of Clang.
[ "stackoverflow", "0013642854.txt" ]
Q: Not clear why error happened, is due to incorrect usage of AsyncTask? Not clear why error happened, is due to incorrect usage of AsyncTask? I'm now developing an android calendar app. I want to have synchronize function which allow user can synchronize their data to server or vice verse. When user open the app, it fetch data from server and update the new data to sqlite database on android device. And whenever user create new data, it send this data to server to update to database on server. I implemented my ideal like this. 1. MainActivity class to do sync action public class MainActivity extends Activity { DataSyncTask syncTask; public void onCreate(Bundle savedInstanceState){ Button insertBt = (Button) findViewById(R.id.bt_insert); // get data1 Data1 data1; syncTask = new DataSyncTask(this); syncTask.syncOnStart(data1); insertBt.setOnClickListener(new OnClickListener(){ public void onClick(View v){ Data2 data2; // get data2 syncTask.syncOnInsert(data2); } }); } } 2. DataSyncTask to collect asyncTask public class DataSyncTask { Context mContext; public DataSyncTask(Context context){ mContext = context; } private class SyncWhenStartTask extends AsyncTask<Data1, Integer, String>{ protected String doInBackground(Data1... data1s){ Object obj1 = ServerUtilities.sendDataForStep1(data1s[0]); Data2 data2; // Process Object Object obj2 = ServerUtilities.sendDataToInsert(data2); return "Success"; } } private class SyncWhenInsertTask extends AsyncTask<Data2, Integer, String>{ protected String doInBackground(Data2... datas){ Object obj2 = ServerUtilities.sendDataToInsert(datas[0]); return "Success"; } } public void syncOnStart(Data1 data1){ new SyncWhenStartTask().execute(data1); } public void syncOnInsert(Data2 data2){ new SyncWhenInsertTask().execute(data2); } } 3. ServerUtilities class public final class ServerUtilities { static final String SERVER_URL = "http://172.2.100.99:8080"; public static String sendDataForStep1(Data1 data1) { String url = SERVER_URL + "/sendDataForStep1"; ServerUtil<Data1, String> server = ServerUtil<Data1, String>(); return server.post(url, data1, String.class); } public static String sendDataToInsert(Data2 data2) { String url = SERVER_URL + "/sendDataToInsert"; ServerUtil<Data2, String> server = ServerUtil<Data2, String>(); return server.post(url, data2, String.class); } private static class ServerUtil<T1, T2> { public T2 post(String url, T1 obj, Class<T2> returnType) { HttpHeaders requestHeaders = new HttpHeaders(); // Sending a JSON or XML object i.e. "application/json" or // "application/xml" requestHeaders.setContentType(MediaType.APPLICATION_JSON); // Populate the Message object to serialize and headers in an // HttpEntity object to use for the request try { HttpEntity<T1> requestEntity = new HttpEntity<T1>( object, requestHeaders); // Create a new RestTemplate instance RestTemplate restTemplate = new RestTemplate(true); // Make the network request, posting the message, expecting // a list of SyncData in response from the server ResponseEntity<T2> response = restTemplate .exchange(url, HttpMethod.POST, requestEntity, returnType); if(response != null) { return response.getBody(); } } catch (Exception e) { Log.e(TAG + "-Exception", e.getMessage()); // Line 345 in logcat } return null; } } } When i start MainActivity, it connect to server, fetch data, update to sqlite database and send new data from device to server to update sucess, everything is ok. But when i create a new data, when execute syncTask.syncOnInsert(), it get Exception: 11-30 14:38:25.849: W/dalvikvm(14140): threadid=12: thread exiting with uncaught exception (group=0x40a13300) 11-30 14:38:25.869: E/AndroidRuntime(14140): FATAL EXCEPTION: AsyncTask #2 11-30 14:38:25.869: E/AndroidRuntime(14140): java.lang.RuntimeException: An error occured while executing doInBackground() 11-30 14:38:25.869: E/AndroidRuntime(14140): at android.os.AsyncTask$3.done(AsyncTask.java:299) 11-30 14:38:25.869: E/AndroidRuntime(14140): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 11-30 14:38:25.869: E/AndroidRuntime(14140): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 11-30 14:38:25.869: E/AndroidRuntime(14140): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 11-30 14:38:25.869: E/AndroidRuntime(14140): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 11-30 14:38:25.869: E/AndroidRuntime(14140): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 11-30 14:38:25.869: E/AndroidRuntime(14140): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 11-30 14:38:25.869: E/AndroidRuntime(14140): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 11-30 14:38:25.869: E/AndroidRuntime(14140): at java.lang.Thread.run(Thread.java:856) 11-30 14:38:25.869: E/AndroidRuntime(14140): Caused by: java.lang.NullPointerException: println needs a message 11-30 14:38:25.869: E/AndroidRuntime(14140): at android.util.Log.println_native(Native Method) 11-30 14:38:25.869: E/AndroidRuntime(14140): at android.util.Log.e(Log.java:231) 11-30 14:38:25.869: E/AndroidRuntime(14140): at vn.com.bip.office.smart.form.ServerUtilities$ServerUtil.post(ServerUtilities.java:345) 11-30 14:38:25.869: E/AndroidRuntime(14140): at vn.com.bip.office.smart.form.ServerUtilities.sendSyncData(ServerUtilities.java:283) 11-30 14:38:25.869: E/AndroidRuntime(14140): at vn.com.bip.office.smart.util.DataSyncTask$SyncWhenChangeOnScheduleTask.doInBackground(DataSyncTask.java:158) 11-30 14:38:25.869: E/AndroidRuntime(14140): at vn.com.bip.office.smart.util.DataSyncTask$SyncWhenChangeOnScheduleTask.doInBackground(DataSyncTask.java:1) 11-30 14:38:25.869: E/AndroidRuntime(14140): at android.os.AsyncTask$2.call(AsyncTask.java:287) 11-30 14:38:25.869: E/AndroidRuntime(14140): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 11-30 14:38:25.869: E/AndroidRuntime(14140): ... 5 more Can anyone explain me why this happen and teach me how to resolve this error. Thanks in advance! A: Log.e(TAG + "-Exception", e.getMessage()); e.getMessage() not always returns a valid string. Sometimes it returns null. That's why your app is crashing
[ "stackoverflow", "0006088708.txt" ]
Q: Get information on a website with php I 've been reading some of the topic about this. However, I dont quite understand how to do it. Need some help. I want to get information from a website. For example, I want to get information such as Market, Open, High, Low, Last, Change, Pct from http://quotes.ino.com/exchanges/futboard/ Thank you for ur help. A: This is called "screen scraping". It usually involves obtaining the HTML from the page (such as with curl), then parsing the HTML. Before doing this, you should first obtain permission from the owner of the web site. Also, if they have an API, it would be the preferred method.
[ "gis.stackexchange", "0000086656.txt" ]
Q: How to force network analyst to use metero station? I'm new to use multimodal network analyst .I use esri tutorial for multimodal network analyst.It was very interesting for me .What i need is that i want to force network analyst to use metero station for network analyst .for example in esri tutorial multimodal network i don't want to route from street to street like the below image and i'd like to use metero station.How can i force network analyst to use metero station ? thanks for advance A: Based on what you said, let's consider that you want to minimize the walking distance from point A to point B. Stated like this, you need to solve your model based on the minimum walking distance, which means that the "cost" of the metro is "zero". This will force network analyst to use metro more often, though you will avoid using metro in trivial cases like if points A and B are 20 m apart and the closest metro station is 40 meters away.
[ "math.stackexchange", "0002795148.txt" ]
Q: Distinctness in constructive math I am beginning to learn about constructive math on my own and am casually reading the paper Algebraic Numbers, a Constructive Development by W. Julian, R. Mines, and F. Richman (Pacific Journal of Mathematics, Vol. 74, No. 1, 1978). I am confused by some of their preliminary remarks they give. First, before they provide the field axioms they say the following Inequality is to be thought of as a positive notion of distinctness rather than the denial of equality. I take this to mean $a=b\iff\neg(a\neq b)$. After providing the field axioms, which look like the standard axioms with the exception of this one: For each integer $n$, $a^{n}=0$ implies $a=0$, they mention something called Heyting's axiom apart from their given list of field axioms and which says If $x\neq y$ is impossible, then $x=y$, and they mention that the funny axiom (6) is what is used to replace Heyting's axiom (whose invocation they recommend abstaining from). This confuses me, since Heyting's axiom seems to follow from the provided definition of distinctness. What am I misunderstanding? A: You've taken the exact opposite meaning of what they intended with respect to inequality. What they are saying is that there is a binary relation $a\#b$, often called apartness, for which it is not necessarily the case that $a = b \iff \neg(a\#b)$. They are using $\neq$ for what I called $\#$, but what they are saying is exactly that $x\neq y$ does not necessarily mean $\neg(x=y)$. Instead $\neq$ should be treated as its own binary relation unrelated to equality. (Well, not completely unrelated. You will have things like $x\neq y\implies \neg(x=y)$ and $x=y\implies \neg(x\neq y)$, but these aren't equivalences in general.) There are multiple distinct ways of formalizing the notion of a field in constructive mathematics. As mentioned by the paper, it is a weakening of the notion of a Heyting field. I don't believe it corresponds exactly to any of the definitions given on the nLab page, but I haven't thought about it too hard.
[ "tex.stackexchange", "0000330787.txt" ]
Q: Impact of option "everypage" from scrlayer-scrpage package Can somebody confirm that the option everypage is having an impact on how often a layer is been printed during page creation? My understanding was that it's not. However, in the example below my PDF viewer (Okular Version 0.24.2) the text a little bit bold. I had this effects before with text that was printed multiple times at the same place. However, in the paper printed version everything is fine... \documentclass[]{scrartcl} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage[]{scrlayer-scrpage} \DeclareNewLayer[% foreground,% Avoid multiple code execution. addvoffset=5em,% Adapt position for better comparisim. addhoffset=1in + \oddsidemargin,% ... mode=text,% everypage,% <--- Impact? contents={% Text in 'ExtraLayer'. }% ]{ExtraLayer} \AddLayersToPageStyle{headings}{ExtraLayer} \begin{document} \noindent Text in 'headings'. \end{document} Option activated: Upper text different than lower one. Option deactivated: Upper and lower text look the same. I am using pdfTeX 3.14159265-2.6-1.40.17 (TeX Live 2016). Can someone help? Thanks. Best regards, Thomas A: It seems that there is a little bug in scrlayer-scrpage. There is no need to use everypage for a new new declared layer, because it will be printed on every page if you do not set one of the options evenpage, oddpage, floatpage or nonfloatpage. But everypage could be helpful if you modify or clone an existing layer. Then everypage should reset the changes done by evenpage, oddpage, floatpage and nonfloatpage. But unfortunaly it resets the changes done by foreground and background too. So the layer in your code is printed twice: in foreground and background. Workarounds if everypage is needed: replace everypage by oddorevenpage, floatornonfloatpage change the order of everypage and foreground to everypage, foreground.
[ "stackoverflow", "0003688025.txt" ]
Q: Should view logic go in a UIView or (when applicable) its UIViewController? I recently discovered that UIViews should only have UIViewControllers when they fill the entire window (or are managed by another UIViewController such as a UINavigationController or UISplitViewController). This quotation is from the documentation for UIViewController: You should not use view controllers to manage views that fill only a part of their window—that is, only part of the area defined by the application content rectangle. If you want to have an interface composed of several smaller views, embed them all in a single root view and manage that view with your view controller. I usually put my view logic in the UIView even when it is managed by a UIViewController, yet I often find myself needing to access properties of the UIViewController such as its navigationController property. However, UIViews are not supposed to be aware of their UIViewController. My conclusion is that view logic should go in a UIView's UIViewController when one exists, and in the UIView itself otherwise. Alternatively, is it better practice to create a controller class for a view which is not a subclass of UIViewController? UIPopoverController (an NSObject subclass) appears to follow this pattern, although in most cases (UIButton, etc.) views do not seem to have dedicated controller classes. A: Application logic should never go in a UIView. Period. The purpose of a UIViewController is to manage a view and its subviews and, under most circumstances, is the appropriate place for the logic. UIKit adheres to the Model-View-Controller paradigm. Models hold the data, views display it and accept input, and controllers manage the interaction between the other two layers. That's why the controller is the logical place for application logic. In iOS, UIViewController and its subclasses are the usual controller classes. I'd suggest reading up on Apple's guidance to better understand this pattern and how it's used in iOS. The quote from Apple's documentation is telling you that you don't create a UIViewController for each label or button. You create one for each "page" or "screen" of your application and you use it to manage the controls in that view. Notice that UIKit has classes to manage table views, tab views and navigation views. That's the level of object that you would use UIViewController to manage. I'd recommend browsing through the iOS examples included with the SDK. They should give you a good idea of how the framework expects applications to be structured. A: I came from the Win32 + .NET + Java Swing GUI world and I used to do the same thing. But then I fixed my evil ways. Now the only time I put code in UIView is if I wish to customize the VIEW ITSELF (OpenGL drawing, for example). Controllers set the state of the view. The view renders its state.
[ "stackoverflow", "0018255757.txt" ]
Q: Is it possible to pass samples of unequal size to function boot in R I'm currently writing a tutorial about bootstrapping in R. I settled on the function boot in the boot package. I got the book "An introduction to the Bootstrap" by Efron/Tibshirani (1993) and just replicate a few of their examples. Quite often in those examples, they compute statistics based on different samples. For instance, they have this one example where they have a sample of 16 mice. 7 of those mice received a treatment that was meant to prolong survival time after a test surgery. The remaining 9 mice did not receive the treatment. For each mouse, the number of days it survived was collected (values are given below). Now, I want to use the bootstrapping approach to find out if the difference of mean is significant or not. However, if I understand the help page of boot correctly, I can't just pass two different samples with unequal sample size to the function. My workaround is as follows: #Load package boot library(boot) #Read in the survival time in days for each mouse treatment <- c(94, 197, 16, 38, 99, 141, 23) control <- c(52, 104, 146, 10, 51, 30, 40, 27, 46) #Call boot twice(!) b1 <- boot(data = treatment, statistic = function(x, i) {mean(x[i])}, R = 10000) b2 <- boot(data = control, statistic = function(x, i) {mean(x[i])}, R = 10000) #Compute difference of mean manually mean_diff <- b1$t -b2$t In my opinion, this solution is a bit of a hack. The statistic I'm interested in is now saved in a vector mean_diff, but I don't get all the great functionality of the boot package anymore. I can't call boot.ci on mean_diff, etc. So my question basically is if my hack is the only way to do a bootstrap with the boot package in R and statistics that compare two different samples. Or is there another way? I thought about passing one data.frame in with 16 rows and an additional column "Group": df <- data.frame(survival=c(treatment, control), group=c(rep(1, length(treatment)), rep(2, length(control)))) head(df) survival group 1 94 1 2 197 1 3 16 1 4 38 1 5 99 1 6 141 1 However, now I would have to tell boot that it has to sample always 7 observations from the first 7 rows and 9 observations from the last 9 rows and treat these as separate samples. I would not know how to do that. A: Giving it another thought, I realized that I could actually combine Thomas' answer with boot. Here is a solution: b <- boot(data=df, statistic = function(x, i) { booty <- tapply(x$survival,x$group,FUN=function(x) sample(x,length(x),TRUE)) diff(sapply(booty,mean))*-1 }, R=10000) The trick is that the function you provide to the argument statistic has to accept a parameter i for the index, but that you completely ignore this parameter within your function. Instead, you do the sampling yourself. Of course, this is not the most efficient (because boot has to do the sampling as well), but I guess that in most cases this shouldn't be a big issue.
[ "stackoverflow", "0035469050.txt" ]
Q: Why does it say attempt to index 'pac' global (a nil value) My friend sent me this script, and the error I get is [ERROR] gamemodes/santosrp/gamemode/sh_pacmodels.lua:137: attempt to index global 'pac' (a nil value) 1. PlayerSwitchWeapon - gamemodes/santosrp/gamemode/sh_pacmodels.lua:137 2. UpdatePlayers - gamemodes/santosrp/gamemode/sh_pacmodels.lua:169 3. unknown - gamemodes/santosrp/gamemode/cl_init.lua:105 sh_pacmodels 137 is this function GM.PacModels:PlayerSwitchWeapon( pPlayer, entOldWep, entNewWep ) if not pPlayer.AttachPACPart then pac.SetupENT( pPlayer ) --line 137 pPlayer:SetPACDrawDistance( GetConVarNumber("srp_pac_drawrange") ) end local invalid for slotName, _ in pairs( GAMEMODE.Inv.m_tblEquipmentSlots ) do item = GAMEMODE.Inv:GetItem( GAMEMODE.Player:GetSharedGameVar(pPlayer, "eq_slot_".. slotName, "") ) if not item or not item.PacOutfit then continue end if not IsValid( entOldWep ) or not IsValid( entNewWep ) then continue end if item.EquipGiveClass == entOldWep:GetClass() or item.EquipGiveClass == entNewWep:GetClass() then invalid = true break end end sh_pacmodels 169 is this function GM.PacModels:UpdatePlayers() if not self.m_intLastThink then self.m_intLastThink = CurTime() +0.1 end if self.m_intLastThink > CurTime() then return end self.m_intLastThink = CurTime() +0.1 local ragdoll, item for k, v in pairs( player.GetAll() ) do --Track active weapon if not v.m_entLastActiveWeapon then v.m_entLastActiveWeapon = v:GetActiveWeapon() else if v:GetActiveWeapon() ~= v.m_entLastActiveWeapon then self:PlayerSwitchWeapon( v, v.m_entLastActiveWeapon, v:GetActiveWeapon() ) -- line 169 v.m_entLastActiveWeapon = v:GetActiveWeapon() end end A: pac is not defined. Yes it's that simple.
[ "stackoverflow", "0025710066.txt" ]
Q: How to identify whether List is a list of Ts that implement a specific interface Okay so I have a class containing multiple properties of type List. Some of the lists are just simple types like string, int etc. But some are lists of custom types like Feature, Trailer, Artwork etc. public class Movie : IMedia { public List<Feature> Features; public List<Artwork> Artwork; public List<string> Genres; } All the custom types (and the Movie class itself) implement the interface IMedia. Using reflection I want to traverse the Movie properties and do something with those that is of type List<IMedia> - but here lies the problem; Because apparently I can't just use is List<IMedia> when also wanting to specify the property to be of a specific type like List<Feature>. How would you guys suggest I go about identifying these types? Extend List<T> itself or something completely different? A: To get the type of the first generic argument: var lst = new List<MyClass>(); var t1 = lst.GetType().GenericTypeArguments[0]; To check if you can cast it to an interface: bool b = typeof(IInterface).IsAssignableFrom(t1); Another approach could be: var castedLst = lst.OfType<IInterface>().ToList(); bool b = castedLst.Count == lst.Count; // all items were casted successfully A: Assuming you're actually working with properties (which is what's mentioned in the question) and not private fields (which is what the class in your question is using), you could do something like this: var movie = new Movie() { ... }; foreach (var prop in typeof(Movie).GetProperties()) { if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof (List<>)) { /* Get the generic type parameter of the List<> we're working with: */ Type genericArg = prop.PropertyType.GetGenericArguments()[0]; /* If this is a List of something derived from IMedia: */ if (typeof(IMedia).IsAssignableFrom(genericArg)) { var enumerable = (IEnumerable)prop.GetValue(movie); List<IMedia> media = enumerable != null ? enumerable.Cast<IMedia>().ToList() : null; // where DoSomething takes a List<IMedia> DoSomething(media); } } }
[ "stackoverflow", "0018113667.txt" ]
Q: java.io.EOFException between sendRedirect() and ObjectOutputStream the problem is that it launch a java.io.EOFException in the server side when i try to do ois = new ObjectInputStream(request.getInputStream()); private void writeObjectStream(HttpServletRequest request, HttpServletResponse response) { ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(response.getOutputStream()); oos.writeChars("x"); } catch (IOException e) { e.printStackTrace(); } finally { IOUtil.closeQuietly(oos, ois); } } the call of writeObjectStream : .... response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); response.setHeader("Location", "www.sample.com"); response.setHeader("Content-Length", "" + 500); writeObjectStream(request, response); return true; A: Object streams have a particular format and if you are reading something which was not in the format you can easily confuse it. Each type of data you write/read with this type of stream has a tag and if the tag doesn't match the expected one the exception thrown is an EOFException. This is confusing in my opinion give it can throw a StreamCorruptedException in a different context and that would be more appropriate. In short, you are trying to read something which is not an ObjectInputStream, or the data you are reading not the right type, or it is corrupted.
[ "stackoverflow", "0013103230.txt" ]
Q: Custom jQuery plugin but can't figure out custom methods I'm rewriting a plugin so that each main section is turned into a method as per this question and the jQuery documentation, and so far the whole thing is still working. The plugin is initialized with: $('#mySelector').myPlugin({ // want to keep initial options option1: true, option2: 'right' // etc. }); Then later, I want to use a refresh method: $('#mySelector').myPlugin('refresh'); Basically, I need "refresh" to do everything in this plugin, except re-applying the HTML DOM modifications (while keeping all of the original initialized options). I can't seem to figure it out. I cannot just use methods.binders(var1, var2); because I need to get the variables too. However, the init() needs the methods.html() when it's first initialized. How can I skip that one part when I do my refresh? Maybe it's simple, but I have a headache now. (function ($) { var methods = { defaults : { option1: false, option2: 'left' // etc. }, settings : {}, init : function(options) { methods.settings = $.extend({}, methods.defaults, options); $(this).each(function() { if ($(this).is('[type=radio]')) { var var1 = $(this); var var2 = $('.somethingelse'); // etc. methods.html(var1, var2); methods.binders(var1, var2); }; }); }, refresh : function () { // no idea?? }, html : function(var1, var2) { // various HTML DOM manipulations }, binders : function(var1, var2) { // binding various events, hover, click, etc. // assigns classes } }; $.fn.myPlugin = function(method) { if ( methods[method] ) { return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.myPlugin' ); } }; })(jQuery); A: Following moves most of the code from methods.init to a function doInit() that can be called in both methods.init and methods.refresh with argument for initType and a conditional inside to call some code for init but not refresh (function($) { var methods = { /* see answer edit about moving this out of here*/ defaults: { option1: false, option2: 'left' // etc. }, settings: {}, init: function(options) { /* see answer edit about moving this out of here*/ methods.settings = $.extend({}, methods.defaults, options); doInit(this, 'init', methods); }, refresh: function() { doInit(this, 'refresh', methods); }, html: function(var1, var2) { // various HTML DOM manipulations }, binders: function(var1, var2) { // binding various events, hover, click, etc. // assigns classes } }; function doInit(el, initType, methods) { $(el).each(function() { if ($(this).is('[type=radio]')) { var var1 = $(this); var var2 = $('.somethingelse'); // etc. methods.html(var1, var2); if (initType == 'init') { methods.binders(var1, var2); } }; }); } $.fn.myPlugin = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.myPlugin'); } }; })(jQuery); May not be bug free but idea should get you going EDIT: Realized I forgot to make the settings more global. One way is to remove defaults from methods and create var defaults={ /* ..... */}; $.fn.myPlugin.defaults=$.extend({},defaults, options); Now you have access to the user defined settings when you do the refresh. Another really helpful addition is to store the settings in jQuery DOM data like: $(this).data('myPlugin.settings', {/* extended settings object*/});
[ "math.stackexchange", "0000394796.txt" ]
Q: Sum of square root of primes I was playing around with prime numbers and a question came into my mind: Let $S(n)$ denote the sum of square roots of primes from $2$ to the $n$th prime number. Are there infinitely many numbers $n$ so that $\left\lfloor S(n) \right\rfloor$ is prime itself? (Where $\left\lfloor X \right\rfloor$ denotes the floor function.) Please tell me if you had any ideas about it. I actually could do nothing. xD A: If this problem is solvable, it would require advanced tools from analytic number theory. As for a heuristic: $S(n)$ is asymptotically $\sum_{k=1}^n \sqrt{k\log k} \sim \frac23n^{3/2}\sqrt{\log n}$; and I don't see any reason why $\lfloor S(n)\rfloor$ is more or less likely to be even, a multiple of $3$, or more generally divisible by any fixed prime. (This independence is borne out by numerical experiments.) Thus the prediction would be that $\lfloor S(n)\rfloor$ is just as likely to be prime as a random integer of the same size, which is about $1/\log S(n) \sim 2/(3\log n)$. In other words, I would predict that the number of $n\le x$ for which $\lfloor S(n)\rfloor$ is prime should be asymptotically $\frac23x/\log x$. (Numerical experiments also make this appear more likely than a constant times $x/\log^2x$.)
[ "stackoverflow", "0005169194.txt" ]
Q: Silverlight 4 Nested Navigation Frame Communication Hey everyone, this one is really stumping us and we can't find anyone else having the same issue. We have a Silverlight business application, with nested Navigation Frames. Within the nested frame we have some User Controls which we want to use to make the outer Navigation Frame navigate to a new page. How do get access up to the outermost Navigation Frame, from the lowest level user controls? Thanks for any help you can give. Martyn. A: We eventually came across the Prism framework and have utilised the DelegateCommand functionaltiy to achieve our goal.
[ "stackoverflow", "0030073294.txt" ]
Q: How to properly deal with Silverlight deprecation? Recently, Chrome deprecated NPAPI support, so that means no Silverlight. Now, I've learned to be a good web developer and prefer feature detection over browser detection to deliver a good user experience. Unfortunately, it seems impossible to do NPAPI support feature detection properly. I've built a JavaScript replacement for our Silverlight tool. I initially check if the user is on IE9 or older using conditional comments, which is a reliable approach (correct me if I'm wrong). In that case, I'd serve them Silverlight tool. Other browsers are assumed to support all the necessary features (we only target Desktop browsers in this case), so they are served the new JS tool. After testing, it turns out that IE10 and IE11 are too slow to handle our application well. Specifically some I/O operations (MD5 hashing and DICOM parsing) are approx. 10-15x slower. I thought I'd then just serve ALL versions of IE the Silverlight tool, but conditional comments are no longer supported in IE10+. I'm torn. It seems like I have to resort to unreliable browser detection after all. My only alternative appears to be testing if the JS engine is slow but that doesn't seem reliable either. So I turn to the good people of StackOverflow; what to do? A: It's a shame no one had a better suggestion. In the end I was able to write a pure JavaScript replacement for our Silverlight control. Since IE10 and IE11 still had poor performance for the I/O operations, I decided to detect them to fall back to the Silverlight control. <!--[if IE]> <script type="text/javascript"> window.is_ie = true; </script> <![endif]--> <script type="text/javascript"> function isIE(ua) { if (ua.indexOf('MSIE ') > -1) return true; if (ua.indexOf('Trident/') > -1) return true; return false; } if(!window.is_ie) { window.is_ie = isIE(window.navigator.userAgent); } </script>
[ "askubuntu", "0000985629.txt" ]
Q: Syncing Ubuntu Devices I run several Ubuntu virtual machines. I would like to keep them synced up, the installed software at least. I found this article but it doesn't seem to pertain to 17.10 as the software center doesn't have a file menu, and doesn't offer a way to sign in or up for ubuntu software center account. Is there a new way to do this or is it gone? https://www.howtogeek.com/111989/how-to-sync-quickly-reinstall-applications-on-ubuntu/ A: To keep your software synced you could use apt-clone. it will backup or restore your installed packages, software sources, signing keys and state. sudo apt install apt-clone man apt-clone
[ "stackoverflow", "0040644428.txt" ]
Q: Angular $http requests not fulfilling in Promise.all I have a array of http requests that I am using in an Promise.all. The issue is that when Promise.all is fulfilled, console.log(values); shows the original dealers array instead of the resolved http requests response object. Why am I not getting the resolved http requests in the Promise.all? function getDealer(regionMarketDealer) { var params = { url: API_BASE_URI + 'service/ppv/' + regionMarketDealer, method: 'GET' }; return $http(params); } function getAllMarketDealers(dealers) { var dealerHttpRequests = dealers.filter(function(dealer) { if (dealer.name !== 'All') { var promise = getDealer(dealer.name); return promise; } else { return false; } }); Promise.all([dealerHttpRequests]) .then(function(values) { console.log(values); }); } A: .filter is used to filter your array by returning true or false in a function and that then creates a new array with the filtered result. If you then want to create promises of the filtered array you should then use .map and return a promise function getDealer(regionMarketDealer) { var params = { url: API_BASE_URI + 'service/ppv/' + regionMarketDealer, method: 'GET' }; return $http(params); } function getAllMarketDealers(dealers) { var dealerHttpRequests = dealers.filter(function(dealer) { return dealer.name !== 'All'; }) .map(function(dealer) { return getDealer(dealer.name); }); Promise.all(dealerHttpRequests) .then(function(values) { console.log(values); }); }
[ "stackoverflow", "0033267434.txt" ]
Q: PYQT directory dialog opens twice I have a function which gets the directory by a button. Whenever I want to use the directory thats retrieved with other functions, it makes the open dialog appear again. Any way to work around this. I created another function to call that will hopefully avoid it but still isnt working. Here is what im trying.. def selectFilecsvtoxml(self): directory = QtGui.QFileDialog.getExistingDirectory(self, caption="Pick a folder", directory=QtCore.QDir.currentPath()) print directory + " this si dirrrrectory" self.listDirPath.setText(directory) for file_name in os.listdir(directory): if not file_name.startswith("."): print (file_name) + " this is selectFilcestoxml" return directory def showDirectory(self): showDir = self.selectFilecsvtoxml dir = str(showDir) print showDir + " this is the files from this class which makes dumbpop" print dir + " this might fix it" return dir A: You created a function which shows a dialog and returns the directory chosen by the user. The purpose of the function is to ask the user something you don't know, here a path to a folder. Once you know the directory, there is no need to ask the user again: you shouldn't call this function more than once. Instead, you should store the value that the user gave you. Here's a simple example: class myWidget(QtGui.QWidget): def __init__(self,parent=None): ... self.directory=None self.button=QtGui.QPushButton("choose a folder") self.button.clicked.connect(self.select) def select(self): self.directory=QtGui.QFileDialog... def do_stuff_with_directory(self): print(self.directory) At the beginning, self.directory is None because you don't know what it should be. When the user click the "chose a folder" button, self.directory is set to their choice. Since it's an attribute of MyWidget, you can use it in any of it's method. You should just check that it is not None before using it. I saw that you wrote self.listDirPath.setText(directory). So another way to get the chosen directory in any function would be: directory=self.listDirPath.text()
[ "stackoverflow", "0048241222.txt" ]
Q: Trigger cronjobs on Fibase Firestore update I'm trying to build a scheduling system to run a firebase cloud function after 60 minutes from a specific event in the database. After some lectures I know that firebase has not a built in schedule system. Indeed, what I have to do is to schedule an http request when a specific document in firestore is updated. Someone recommends me https://cron-job.org/en/, anyone knows if with this service I can schedule automatically some http requests when a document in firestore is updated? A: If you want to have a http request when a document in firestore updated you may need firestore trigger function initialized instead cron-job. something like ; exports.makeHttpRequest = functions.firestore .document('myCollection/myDocument').onUpdate((event) => { setTimeout( ()=> { var cronJobUrl = "https//:www..."; // Set the url you want to make a http request windows.open(cronJobUrl); },60000*60) // to fire this function after 60 min. });
[ "math.stackexchange", "0001542750.txt" ]
Q: Does the graph of $\ln(-2 - |x|)$ exist? I tried to figure out if this graph exists, but I don't know if I am thinking this right. The absolute value of $x$ is always positive and the minus in front of the absolute value of $x$ makes it always negative. So my final conclusion is that it does not exist but I am not sure of this. A: If it's only real numbers you're working with, then no. If you're familiar with complex logarithms then $\log(z)=\log|z|+\mathrm{i}\theta$ might help, where $\theta$ is the argument of $z$.
[ "stackoverflow", "0035120360.txt" ]
Q: Convert array and object with HTML entities I am trying to write a piece of code, that will recursively convert every string in an array or object to be safe with the quotes for displaying in input boxes. This is an array I wrote, with parts I have seen from other peoples. And it works for objects but not arrays, it seems to get to the second array, and outputs a string "null" function fixQuotes($item) { if (is_object($item)) { foreach (get_object_vars($item) as $property => $value) { //If item is an object, then run recursively if (is_array($value) || is_object($value)) { fixQuotes($value); } else { $item->$property = htmlentities($value, ENT_QUOTES); } } return $item; } elseif (is_array($item)) { foreach ($item as $property => $value) { //If item is an array, then run recursively if (is_array($value) || is_object($value)) { fixQuotes($value); } else { $item[$property] = htmlentities((string)$value, ENT_QUOTES); } } } } A: It was not saving the array if it was two arrays deep, it is now working, also it was missing the return on the array. Thanks for reading it. Here is a copy of the fixed code if someone in future needs a script that does this. function fixQuotes($item) { if (is_object($item)) { foreach (get_object_vars($item) as $property => $value) { //If item is an object, then run recursively if (is_array($value) || is_object($value)) { $item->$property = fixQuotes($value); } else { $item->$property = htmlentities($value, ENT_QUOTES); } } return $item; } elseif (is_array($item)) { foreach ($item as $property => $value) { //If item is an array, then run recursively if (is_array($value) || is_object($value)) { $item[$property] = fixQuotes($value); } else { $item[$property] = htmlentities((string)$value, ENT_QUOTES); } } return $item; } }
[ "stackoverflow", "0020441609.txt" ]
Q: Referencing the user's home directory in a Gradle script Is there a cleaner way to reference a file in the user's home directory than doing the following in a gradle script? (referencing an Android keystore in this example) homeDir = System.getenv('HOMEDRIVE') + System.getenv('HOMEPATH'); ... signingConfigs { release { storeFile file(homeDir + "\\.android\\releaseKeystore.jks") } } ... A: more generic (read: "groovy" & not using "ant") def homePath = System.properties['user.home'] A: Untested code, but how about something like this (might need parentheses around the "X as File" bit): signingConfigs { release { storeFile "${System.properties['user.home']}${File.separator}.android${File.separator}releaseKeystore.jks" as File } }
[ "stackoverflow", "0025862888.txt" ]
Q: how to replace string with different replacement in java Now I have a String like this it is #1, or #2, or #3 I want to transfer it to this: it is < a href="/1">#1< /a>, or #< a href="/2">#2< /a>, or < a href="/3">#3< /a> So I want to replace the word "#{num}" to "< a href="/{num}">#{num}< /a>" What shall I do? A: This Java code should work: String repl = input.replaceAll("(?<!>)#(\\d+)(?!<)", "<a href=\"/$1\">#$1</a>"); RegEx Demo PS: I have added lookaheads to make sure we don't replace a string with hyperlinks like: it is <a href="/1">#1</a> (check demo link for an example).
[ "stackoverflow", "0020662644.txt" ]
Q: How to get the MaxLength from a Fluent API mapping specification in runtime? I need to retrieve the maxlength value specified for a field using Fluent API and Entity Framework 5 Code First. I have seen a couple of examples using MetadataWorkspace but it doesn't work when you use Fluent API. For instance, I tried this code but the value for MaxLenght is always null: ObjectContext.MetadataWorkspace.GetItem<GlobalItem>(typeof(TEntity).FullName, DataSpace.OSpace).MetadataProperties[field].TypeUsage.Facets["MaxLength"].Value Inside the Fluent API configuration file I have the following code for the necessary properties: Property(t => t.Name).HasMaxLength(50); I know the mapping is working because if I try to save the object with more than 50 characters in that field it fails. I just need guidance for getting the maxlenght value but to give some perspective the goal is: Create new Foo object Get the maxlength value defined for Bar property using Fluent API. Apply certain rules based on the maxlength to the string to be assigned to Bar. Save. Thanks in advance. A: You should use the storage model. Check docu on the Enum DataSpace Use The EntityType items. [TestMethod] public void EFToolsTest() { var context = new BosMasterDbContext("MYDBCONTEXT"); ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext; MetadataWorkspace workspace = objContext.MetadataWorkspace; var xyz = workspace.GetItems<EntityType>(DataSpace.SSpace); foreach (var ET in xyz) { foreach (var sp in ET.Properties) { Debug.WriteLine(sp.Name + ":" + sp.MaxLength); } } }
[ "math.stackexchange", "0002833072.txt" ]
Q: Isotopy classes of essential simple closed curves in a 4-punctured sphere This textbook says that it is well known that the Isotopy classes of essential simple closed curves in a 4-punctured sphere can be identified to $\mathbb{Q}\cup\{\infty \}$. I tried to find some textbooks/pdf on google that I can find explanations to that, but I couldn't. Can anyone explain that to me? From here, I understand the case of the Torus but the case of the 4-punctured sphere looks mysterious to me. A: (You likely mean curves that separate the four points into two sets of two points, which is the case I'll answer here.) Fix a sphere $S$ with four distinct points $x_1,x_2,x_3,x_4\in S$. Also, choose two non-intersecting oriented simple arcs $x_1$ to $x_2$ and $x_3$ to $x_4$. If you slice along these two arcs you get a cylinder whose boundaries can be labeled with the four points and two copies each of the two arcs. Take two copies of this cylinder and glue them together in a way that respects the orientations of the arcs, the orientations of the surfaces, and the point labels. This defines a cover of the four-times punctured sphere by the 4-times punctured torus. In fact, it's a double branched cover with the four points being the branch loci. The blue arcs lift to meridians, and if we consider the arcs as being on an equator of the sphere, the lifts of the parts of the equator in the complement of the arcs form longitudes (both by fiat). When oriented in some way, these give the homological coordinate system for the torus, which we need to actually pin down curves as elements of $\mathbb{Q}\cup\{\infty\}$. Given a simple closed curve in the complement of the four points in the sphere, lift the curve up to the torus, and choose one of the two lifts. Isotopies of the curve in the sphere lift to isotopies of the curve in the torus. This means that the slope of the lift is an invariant (so if two curves in the four-times punctured sphere lift to curves of different slopes, they are not isotopic). Every slope is possible, since for a given slope, shift a standard parameterization of a curve with that slope a little so it doesn't intersect the four points, and then the image down on the sphere is a simple closed curve. What remains is why if two curves lift to curves with the same slopes then they are isotopic on the sphere. Let's make sure we start out with a curve in a nice form. Assume it intersects the blue arcs transversely first of all. What we can do is make sure that the curve never intersects the same blue arc twice in a row; that is, it intersects one, then the other, then the first, etc. This is because if it intersects the same one twice and forms a digon, the innermost such digon can be used to isotope the curve across the arc. And, if it intersects the arc twice from the same side, by winding number considerations it'll have to backtrack and thus form a digon. These two cases are illustrated in the following picture. So, in the cylinder point of view (from when we slice open the blue arcs), we get either a single essential loop, or we get a collection of parallel green arcs that connect the two boundary components. In the lift, the corresponding simple closed curve is isotopic to a standard slope without having to cross any of the four points. That's it for completeness of the invariant. By the way, the green curve is the boundary of the compression disk that book you link to mentions. If you give the torus a Euclidean metric, it is natural to think of the sphere as being a flat pillowcase. The corners add up to 180 degrees, which is what you would expect from a double branched cover. There are also more algebraic approaches involving rational tangles, for instance https://arxiv.org/abs/math/0311511 Another approach is to think of a four-times punctured sphere as a three-times punctured disk. The mapping class group of the the 3-times punctured disk, holding the boundary fixed, is the braid group on three strands. This is realized by isotoping the three punctures around each other, where the points through time trace out a braid. In the following picture, $a$ and $b$ are the generating swaps. The group also acts on simple closed curves by letting them follow along for the ride. Notice that the case when a simple closed curve contains one or three of the points is uninteresting. One of the sides is a disk with one point, and it follows that there are four such possible simple closed curves. So, we proceed with the case that the curve contains exactly two points. That curve bounds a disk, and since every disk is isotopic to every other disk, there is some ambient isotopy that carries this particular curve to the standard green curve as pictured in the image above. Furthermore, we can isotope the three points to where they are supposed to be, and so there is an element of the mapping class group realizing this transformation. In particular, there is some braid element that gives this particular simple closed curve (in the picture, the third curve is given by $b^{-1}a$). (One way to proceed is to go back to the torus and realize $a$ and $b$ on the torus as Dehn twists.) Let $c_0,\dots,c_{2k}\in\mathbb{Z}$ be such that $a^{c_0}b^{-c_1}a^{c_2}\cdots a^{c_{2k}}$ is a braid element that gets the simple closed curve. There are no $b$'s at the end because they act trivially on the standard green curve. It turns out that the continued fraction $$[c_0;c_1,c_2,\dots,c_{2k}]=c_0+\frac{1}{c_1+\frac{1}{c_2+\cdots+\frac{1}{c_{2k}}}}$$ (as an element of $\mathbb{Q}\cup\{\infty\}$) is a complete invariant for the simple closed curve. (I won't prove this here, but it comes down to using the Euclidean algorithm to get a standard form for a continued fraction.)
[ "photo.stackexchange", "0000102587.txt" ]
Q: Error:"Press Shutter Release Button Again" on Nikon D5300 My D5300 with 18-140mm lens is having problem "Press Shutter Release Button Again"...as error message pops ups in AF mode....but in manual focus mode...the error is not there, but images are over-exposed most of the time. The strange thing is that, with the same body and nikon 200-500mm lens there's no problem..it's perfeclty fine in both mode...what can be the issue?? It works fine with nikon 200-500mm lens, and why not on 18-140mm lens? Check my images with nikon 200-500mm lens on the same body here https://instagram.com/sayan275/ A: If it works fine with the 200-500mm, then the problem is either: with the 18-140mm lens. Or, with the combination of the interaction between your particular camera and your 18-140mm lens. The way to absolutely diagnose it is to try your 18-140mm on multiple different camera bodies, and to try multiple other lenses on your D5300 body. If the problem occurs when you lens is mounted to different bodies, then the problem is with your lens. And conversely, if the problem occurs with other lenses mounted on your camera, then the camera body is the likely suspect. Unfortunately, most of us don't have several camera bodies and lenses we can interchange to do this diagnosis. So you'll probably have to have them serviced. In your description, you said that even if the error doesn't appear, with your 18-140mm lens the images appear overexposed. This sounds like your lens has a sticky, bent, or otherwise suffers from high friction somewhere in the aperture or aperture linkage system, as though the aperture does return to its spring-loaded stopped-down position (or at least, its setting less than fully open). That's why images are still overexposed. Unless you're familiar and comfortable with lens repair, there's not much you do, other than have the lens serviced or repaired.
[ "stackoverflow", "0008218872.txt" ]
Q: Is there a way to export code from a corrupt database? Last week I was modifying portions of two modules in an access 2010 db when the program crashed, and would crash every time I tried opening up the db thereafter. I was able to create a new database and import the tables and queries from the corrupted one, but when I tried to import the forms/macros/modules the new database would start crashing also. I keep daily backups, but ended up losing several hours worth of work. This happened twice last week, each time MS Access would crash without warning and the VBA was unrecoverable. The functionality works as intended until the db crashes seemingly at some unknown point. There must be some sort of issue with my VBA code, since this only started happening when I started modifying the module last week, but I can't pinpoint it since the crashes actually occurred when nothing was being executed. Ie during save. Does anyone know if it's possible to export the VBA out of access without exporting it to another database? Ie export it without having to use MS Access to do so. On a related note, has anyone created a library that exports query definitions, table schema, and all VBA to text files that I could drop them into source control? Thanks. A: In addition to the method suggested by @Remou, you could try the SaveAsText method to save a code module to a text file. Application.SaveAsText acModule, "Module1", "D:\Access\Module1.txt" However, that doesn't satisfy your desire to do it without using Access. Try a decompile operation on the chance your project includes saved compiled code which has been corrupted. You can find detailed instructions for decompile in the 2 answers to this Stack Overflow question: ms-access: HOW TO decompile and recompile After decompile, make sure all your modules include Option Explicit in their Declarations sections. Check the project's references, and fix any that are broken (missing). Then run Debug->Compile from the VB editor's main menu to verify your code compiles without error. Those steps are the best I can offer to reduce potential for continued corruption problems. For integrating source control with Access, start with this selection of related Stack Overflow threads: site:stackoverflow.com ms-access version control
[ "stackoverflow", "0049110745.txt" ]
Q: How to retain slf4j MDC logging context in CompletableFuture? When executing async CompletableFuture, the parent threadcontext and moreover the org.slf4j.MDC context is lost. This is bad as I'm using some kind of "fish tagging" to track logs from one request among multiple logfiles. MDC.put("fishid", randomId()) Question: how can I retain that id during the tasks of CompletableFutures in general? List<CompletableFuture<UpdateHotelAllotmentsRsp>> futures = tasks.stream() .map(task -> CompletableFuture.supplyAsync( () -> businesslogic(task)) .collect(Collectors.toList()); List results = futures.stream() .map(CompletableFuture::join) .collect(Collectors.toList()); public void businesslogic(Task task) { LOGGER.info("mdc fishtag context is lost here"); } A: The most readable way I solved this problem was as below - ---------------Thread utils class-------------------- public static Runnable withMdc(Runnable runnable) { Map<String, String> mdc = MDC.getCopyOfContextMap(); return () -> { MDC.setContextMap(mdc); runnable.run(); }; } public static <U> Supplier<U> withMdc(Supplier<U> supplier) { Map<String, String> mdc = MDC.getCopyOfContextMap(); return (Supplier) () -> { MDC.setContextMap(mdc); return supplier.get(); }; } ---------------Usage-------------- CompletableFuture.supplyAsync(withMdc(() -> someSupplier())) .thenRunAsync(withMdc(() -> someRunnable()) .... WithMdc in ThreadUtils would have to be overloaded to include other functional interfaces which are accepted by CompletableFuture Please note that the withMdc() method is statically imported to improve readability. A: At the end I created a Supplier wrapper retaining the MDC. If anyone has a better idea feel free to comment. public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor) { return CompletableFuture.supplyAsync(new SupplierMDC(supplier), executor); } private static class SupplierMDC<T> implements Supplier<T> { private final Supplier<T> delegate; private final Map<String, String> mdc; public SupplierMDC(Supplier<T> delegate) { this.delegate = delegate; this.mdc = MDC.getCopyOfContextMap(); } @Override public T get() { MDC.setContextMap(mdc); return delegate.get(); } }
[ "stackoverflow", "0011193333.txt" ]
Q: Looking for nice RoR way to correctly validate a state of a record I have a model and a column of this model represents a state . It's numeric value and it could be 1,2,3. I have two concerns: a) Based on the business logic, the state can only go from 1 to 2 and from 2 to 3. It can't go back from higher numbers to lower number and it can't just from 1 to 3 in one step. b) I don't want to expose these numbers to controllers (don't like magical numbers flying around). I did following I created methods like stateX?, stateY?, stateZ? to allow controllers check current state. This helps me with concern b). I created methods setStateX, setStateY, stateZ and raise in them, if a controller does unacceptable switch of state. This helps me with concern a) and b). However, I feel that's more Java/C++ way (which is my background) - 6 methods to do one thing. Is there any better way to accomplish this in RoR? A: Not sure if this is still the best way to do it (my Rails is a little rusty) but there is a gem called acts_as_state_machine which I think will do exactly what you want.
[ "stackoverflow", "0032867874.txt" ]
Q: Why is this panel not working? Have a look at this code here, as you will see I'm just doing a bit of practice with jQuery and trying to build a tab panel. I got stuck on trying to get the sections to move out of the way once i clicked on a new section. I have no idea why this is not working for me like this. <html> <head> <script src="https://code.jquery.com/jquery-2.1.4.js"></script> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <div class="buttons"> <a href="" class="active_button" data-sectionId="section1">Section 1</a> <a href="" data-sectionId="section2">Section 2</a> <a href="" data-sectionId="section3">Section 3</a> <a href="" data-sectionId="section4">Section 4</a> </div> <div class="sections"> <div class="section active_section" id="section1"> Section 1 <br> Section 1 <br> Section 1 <br> Section 1 <br><br> </div> <div class="section" id="section2"> Section 2 <br> Section 2 <br> Section 2 <br> Section 2 <br> <br> </div> <div class="section" id="section3"> Section 3 <br> Section 3 <br> Section 3 <br> Section 3 <br><br> </div> <div class="section" id="section4"> Section 4 <br> Section 4 <br> Section 4 <br> Section 4 <br><br> </div> </div> </body> </html> sass body text-align: center padding-top: 50px a color: white text-decoration: none padding: 10px background-color: grey margin: 0px -1px border-radius: 10px 10px 0px 0px transition: all 0.3s ease-in-out &:hover background-color: lightgrey .active_button background-color: lightgrey .sections position: relative .section display: none padding: 20px background-color: lightgrey position: absolute width: 286px top: 10px left: 50% margin-left: -163px border-radius: 0 0 10px 10px .active_section display: block jquery $(function() { // capture click of section button $("a").click(function(e) { // prevent default link behaviour e.preventDefault(); // hide the current active section $(".section .active_section").slideUp(500, function(){ // then take away their active class $(this).removeClass("active_section"); }); }); // click function closes here // find out what section button is pressed var sectionId = $("a").attr("data-sectionId"); // slide down that section $("#"+sectionId).slideDown(500, function(){ // add the active class $(this).addClass("active_section"); }); }); A: Move all your code to the click function, and it's work ;) https://jsfiddle.net/pgytuq6j/ // capture click of section button $("a").click(function(e) { // prevent default link behaviour e.preventDefault(); // find out what section button is pressed var sectionId = $(this).attr("data-sectionId"); // hide the current active section $(".active_section").slideUp(500, function(){ // then take away their active class $(this).removeClass("active_section"); }); // slide down that section $("#"+sectionId).slideDown(500, function(){ // add the active class $(this).addClass("active_section"); }); }); // click function closes here This is what you want ?
[ "math.stackexchange", "0000604213.txt" ]
Q: Which function would best describe Moore's law Moore's law states that the transistor density on integrated circuits doubles every 2 years. So this is an exponential function. My question is simple; what function of the form $y= a \times e^{bx+c}$ would best describe this growth (with a length of 1 on the x-axis corresponding to 1 month of time)? If there are other functions which are not of the aforementioned form, that would be good too. Please also show the derivation. A: The $c$ doesn't matter-you can do $e^{bx+c}=e^{bx}e^c$ and absorb it into $a$. But $a$ doesn't matter either-that just sets the scale, or the zero of time. We are just looking for $b$. After $24$ months things have doubled, so we need $2=e^{24b}$ Taking logs we get $b=\frac {\log 2}{24}$
[ "stackoverflow", "0010352679.txt" ]
Q: Styling GridViewColumns I was browsing stackoverflow to try to figure out a way to style the GridViewColumns in my ListView. I came across this: WPF Text Formatting in GridViewColumn The top answer shows how to style one (1) GridViewColumn. My question is, is there a way to style these GridViewColumns in the Window.Resources so I don't have to do it for each individual GridViewColumn? A: There are a few possibilities: <!-- if style doesn't change --> <GridViewColumn CellTemplate="{StaticResource yourCellTemplate}"/> <!-- if you need to change it up based on criteria - template selector--> <GridViewColumn CellTemplateSelector="{StaticResource YourTemplateSelector}"/> <!-- same goes for headers --> <GridViewColumn HeaderTemplate="{StaticResource yourheaderTempalte}"/> ..or HeaderContainerStyle, HeaderTemplateSelector if you want to use template selectors: create a class, instanciate it in resource dict, and plug it in you gridview column, here's a little sample public class MyTemplateSelector : DataTemplateSelector { public DataTemplate SimpleTemplate { get; set; } public DataTemplate ComplexTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { //if I have just text return SimpleTemplate; //if I have comments and other fancy stuff return ComplexTemplate; then in your ResourceDictionary <DataTemplate x:Key="ComplexTemplate"> <Views:MyCustomControl DataContext="{Binding}"/> </DataTemplate> <Views:MyTemplateSelector x:Key="TxtVsExpensiveCell_TemplateSelector" SimpleTemplate ="{StaticResource SimpleTemplate}" ComplexTemplate="{StaticResource ComplexTemplate}"/> <!-- then you use it in your view like this --> <GridViewColumn CellTemplateSelector="{StaticResource TxtVsExpensiveCell_TemplateSelector}"/> If you don't want to go through all that trouble, and just what to tweak styles of predefined controls, why not use DataGrid? It has predefined columns, where you can tweak styles per each.. <DataGrid> <DataGrid.Columns> <DataGridTextColumn/> <DataGridCheckBoxColumn/> <DataGridHyperlinkColumn/> <DataGridCheckBoxColumn/> ....there are several more column types! </DataGrid.Columns> </DataGrid>
[ "math.stackexchange", "0001691800.txt" ]
Q: Algorith/Method to determine if a percentage will be greater than fixed amount without knowing the final number. If you are applying a discount to a price and you have two possible choices on the discount to apply, a percentage or a fixed amount, e.g. I could remove a fixed amount of 5 or I can remove a 20% of the final price HOWEVER at this point we are unaware of the final price. As you are unable to determine the final price the discount may be greater in some situations than other, e.g. if the price is 20 and a 20% discount would make your total 18 whereas applying a discount of 5 would make it 15, 5 greater than 20% however if the price is 100 a 20% discount would make your final price 80 whereas a discount of 5 would make it 95 making 20% more valuable. How can I determine which one will yield a greater discount (e.g. the final price will be lower if x is applied over y)? A: The two discount schemes will give the same result for an original price $p$ where $$p - \frac{20}{100}p = p - 5$$ which is not difficult to solve for $p$. As you say, the left hand side will be smaller (larger) than the right hand side when $p$ is larger (smaller) than that solution.
[ "stackoverflow", "0032714569.txt" ]
Q: Using git and xcode, some folders are not commited I'm new to git and just started using bitbucket in xcode. Is it normal that some folders are not commited? Folders like: resources, libs, framework, supporting files, products - are missing when I view the folders in bitbucket site. Thanks... A: Please check your .gitignore file, maybe it has that folders listed there
[ "stackoverflow", "0017875996.txt" ]
Q: How to use ActiveSupport::Inflector with Cyrillic ActiveSupport::Inflector methods like titleize, capitalize, camelize do not work with Cyrillic (Russian, Belarussian, Ukraine, ...) letters. 'xyz'.titleize # => "Xyz" # OK 'абв'.titleize # => "АБВ" # FAIL How can I use ActiveSupport::Inflector methods with Cyrillic letters? A: We can use mb_chars to "save" Cyrillic string then ActiveSupport::Inflector methods should work: 'абв'.mb_chars.capitalize.to_s => "Абв"
[ "stackoverflow", "0038463190.txt" ]
Q: javafx tableview not able to fetch data while initializing I'm trying to populate tableview at the time of loading. Please forgive if there is any mistake. public class users { public String username; public String FullName; public String password; public String phone; public String email; public String doj; public String city; public String state; public String address; public ObservableList <ListEmply> emplylst = FXCollections.observableArrayList(); } public class UserDetail { @FXML private ObservableList <ListEmply> emplylst; @FXML private TableView <ListEmply> tbl_employeeview; @FXML private TableColumn<Object, Object> employeename; users User = new users(); Dbconnection dbcon = new Dbconnection(); Connection con; PreparedStatement pst; ResultSet rs; public void showDetails(users User){ con = dbcon.geConnection(); try{ pst = con.prepareStatement("select room_no from room"); rs = pst.executeQuery(); while (rs.next()){ User.emplylst.add(new ListEmply( rs.getString(1) )); } System.out.println(rs); rs.close(); pst.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } public void usrdetails(){ tbl_employeeview.setItems(emplylst); showDetails(User); employeename.setCellValueFactory(new PropertyValueFactory<>("employeename")); System.out.println(rs); } public void Initializable(URL url, ResourceBundle rb){ usrdetails(); } } ListEmply Class public class ListEmply { public String employeename; public ListEmply(String employeename) { super(); this.employeename = employeename; } public String getEmployeename() { return employeename; } } public void setEmployeename(String employeename) { this.employeename = employeename; } } A: As described in the documentation, the controller method that is called to initialize the controller is called initialize(...), not Initializable(...): public void initialize(URL url, ResourceBundle rb){ usrdetails(); } As noted by @fabian in the comments, since you are not implementing the (legacy) interface Initializable and not using the parameters, you can omit the parameters from the method definition: public void initialize(){ usrdetails(); }