text
stringlengths
8
267k
meta
dict
Q: "Call to undefined function odbc_exec()" error connecting to Access database on Linux PHP server I am getting the folowing error trying to run a test query on an Access Database "Fatal error: Call to undefined function odbc_exec() in /home/ratpackc/public_html/Preview/ADOdb/drivers/adodb-odbc.inc.php on line 536" I downloaded (from http://adodb.sourceforge.net) and unzipped the entire contents of the adodb514.zip into a folder I named ADOdb. I am running the following test code: <?PHP include("ADOdb/adodb.inc.php"); $RecCount = 0; $DBPath = realpath("TheData/TheData.mdb"); echo $DBPath . " <br />" . chr(13); $DBConn =& ADONewConnection('access'); $DSN = "Driver={Microsoft Access Driver (*.mdb)};Dbq=$DBPath;"; $DBConn->Connect($DSN); $SqlStr = "SELECT TheDate FROM SomeTable "; echo $SqlStr . " <br />" . chr(13); $DBConn->debug = true; if ($DBConn->Execute($SqlStr) === false) print ErrorMsg(); $RS = $DBConn->Execute($SqlStr); if (!$RS) echo $DBConn->ErrorMsg(); else while (!$RS->EOF) { $RecCount++; echo $RS->fields("TheDate")." <br />" . chr(13); $RS->MoveNext(); } $RS->Close(); $DBConn->Close(); echo "<hr />" . chr(13); echo $RecCount." <br />" . chr(13); ?> You can see the actual results of this code at http://www.rat-pack.com/Preview/DBTest.php If it helps at all here is my phpinfo http://www.rat-pack.com/Preview/phpinfo.php A: Create a sample file that contains: <?php phpinfo(); If you don't see the odbc extension loaded you'll need to load it in your php.ini or recompile with odbc support. A: Maybe because you don't have odbc installed or setup with php ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7535327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery Tab with tab titles as links I'm using the standard jquery tab functionality and i was wondering if there is any way to make some of the tab headers simply a links that will redirect the user to another pages. I'm actually want that when you hover over the tab you will see: "http://www.mysite.com/mypage" , i.e, the href of the tab header will be a simple link. please let me know if its doable. Thanks A: Yes you can make links to other pages, not sure if that your question. If you want the user to see the URL when they hover make the title attribute of the link the url, and it will show as a tools tip. ie: <a href="http://www.stackoverflow.com" title="http://www.stackoverflow.com">My Tab</a> If you need help with the tabs themselves, thats too broad. Try using jQuery Tools A: Straight from the jQuery UI website: $('#example').tabs({ select: function(event, ui) { var url = $.data(ui.tab, 'load.tabs'); if( url ) { location.href = url; return false; } return true; } }); When you set up your tabs, make the href attribute a hyperlink instead of using the "#tab" format. DEMO: http://jsfiddle.net/v2pKQ/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7535328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How should I store types of coupons in my db? I'm creating a coupon system with many different types of coupons. I'd like to structure it so it can be extended. I'm not sure the best way to store the different types of coupons, for example: * *Fixed amount off entire order *Fixed precentage off entire order *Fixed amount off one item (could be by sku of item or could be most expensive item) *Fixed percent off one item (could be by sku of item or could be most expensive item) *Buy x get y *Free product (by sku of item, by price) *x for $y (3 for $2, 10 for $15, etc.) I'm using mysql, would it best to store as an array? json? Any other ideas or people with similar issues care to share how they did it? A: Off of the top of my head you could have tables designed as follows: Table: Coupon_Summary Columns: Coupon_ID(primary key), Coupon_Name This table will hold 'top-level' data about the Coupon. Table: Coupon_Description Columns: Coupon_ID(foreign key), Coupon_Description This table will hold the description of the coupon. Table: Coupon_Value Columns: Coupon_ID(foreign key), Coupon_Value, Coupon_Currancy This table will hold how much discount the coupon offers. Coupon_Value can be a percentage or a hard value(percentage will be appended with a % sign), if this is zero the coupon offers full discount, or the item is free in other words. This also includes the currency to base the discount amount off of, so that you can do conversions between currencies. Table: Coupon_Target_Order Columns: Coupon_ID(foreign key), Order_IDs This table holds data related to which Order the coupon effects. If the Order_ID is null or zero, the coupon is valid for all orders. Otherwise you can have multiple IDs for multiple orders. I hope this was of some help =). A: With SomeSQL, I'd rather not use JSON for it is nearly impossible to efficiently query it. My Approach would Be, simplistically speaking, to have one Table for Coupon types (columns: id, name, ...) and another one for The actual coupons. In The coupon Table, I would have a column "type_id" Cross-referencing to The "couponTypes" Table (or a Foreign Key, for that matter). This way, you can always add new Coupon types later on without invalidating The Data you had to this Point. Querying "Coupons by Type" is a matter of "SELECT 'id' FROM couponTypes WHERE 'name' = 'fixed sum'"; => $id "SELECT * FROM coupons WHERE 'type_id' = $id"; => All fixed sum Coupons. Welcome to MySQL! A: I assume you have some sort of products table that contains all products you can sell. You can create a coupons table that looks something like: id discount discount_percentage INT PK DECIMAL(10,2) DECIMAL(3,2) 1 5.00 NULL 2 NULL 10.00 Then you could create a link table coupons_products like this: coupon_id required_product_id INT FK INT FK 1 4773 1 993 So in this example, coupon ID 1 gives a $5.00 discount and requires two products to be present on the order: 4773 and 993. Coupon ID 2 gives a 10% discount and requires no products. A: I would create another table - tblCouponType for instance and populate it with a unique numerical and string for notes of the types I have, and add to it as new types become available. Then add another column to your coupon table that references the numerical value of your coupon type. This helps with the whole -"Relational" part of the database:)
{ "language": "en", "url": "https://stackoverflow.com/questions/7535332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Combres.axd returns 404 in WebForms app I have 2 ASP.NET apps, 1 WebForms and 1 MVC. Combres worked beautifully for both while working locally on IIS Express. After deploying both apps to the test server (IIS 7, both apps are in the same web site in IIS) the combres.axd link referenced in the pages of the WebForms app is returning a 404, while the MVC app works fine. I hooked up the the WebForms app to my local IIS as well and it again worked fine. I looked at the modules and handlers between my local IIS, the MVC app and the WebForms app and the routing registrations appear to be the same. If I set defaultDebugEnabled="true" then it generates a script tag for each script in the resource set and works fine. Any ideas how to debug the 404 from combres.axd? A: Tracked it down to the modules config in web.config: <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> </system.webServer> I am working with a legacy WebForms app that was created around .NET 3.0/3.5, so I did not have the runAllManagedModulesForAllRequests attribute set. I see in the latest Visual Studio 2010 ASP.NET WebForms template, this is now the default. I also found a post that suggests a less brute force method to get the UrlRoutingModule to catch the combres.axd route. <system.webServer> <modules> <remove name="UrlRoutingModule-4.0" /> <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" /> </modules> </system.webServer> One of the comments mentioned this update, I haven't tested it yet though: http://support.microsoft.com/kb/980368
{ "language": "en", "url": "https://stackoverflow.com/questions/7535333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: MS Access: Detecting a new item and notifiying user I have an Access DB that stores sales data for a small business. Each sale is recorded as a record in the "Sales" table. For each sale, the item name and customer name are stored, along with some other information. There is also a "Customer" table and an "Item" table, which contain all valid customers and items, respectively. If the user attempts to import a record that contains a customer that is not listed in the "Customer" table, this record is not imported; similar situation with items. I would like to change this so that if the user attempts to import a record that contains a new customer or item, then the user is notified of this (e.g. "A new customer, Adam Smith, appears in one of the records you are trying to import.") and then given the option to add this new customer. I realize that this is probably not good practice, but does anyone know of a quick way to add this functionality? [Information regarding the import feature: The user's sales data is stored in an Excel workbook. To import new sales data, the user uses a form that I built that allows him to select a file to import and then imports the data into the proper table. This is implemented in VBA.] Thanks! A: You could link the Excel table, run a query that shows up new customers in a form. You can then ask the user to either match to an existing customer or create a new customer. The added records could be flagged as incomplete, if necessary, and the user could be asked to add relevant details at a suitable point. Most of this can be accomplished with queries, for example, adding customers to the customer table can either be done with an append query or by writing the relevant data to the customer table by using fields in the review form.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Server safely cast string and fail silently declare @input varchar(255) = 'abc' select * from table where id = CAST(@input as int) Can I do this so that the cast will fail silently, or default to some user-provided (or system default) value? A: From SQL Server 2012 and up you can use try_convert and try_parse functions. Until then you can use DECLARE @input VARCHAR(11) = 'abc' SELECT * FROM table WHERE id = CAST(CASE WHEN @input NOT LIKE '%[^0-9]%' THEN @input END AS INT) You may need to tweak the test a bit (e.g. it disallows negative integers and allows positive ones bigger than the maximum int) but if you find a suitable test (e.g. the one here) and use a CASE statement you should avoid any casting errors as order of evaluation for CASE is mostly guaranteed. A: You can put your select in TRY-CATCH block and re-issue the query in CATCH with default value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: ASP.Net Web Parts, personalization, and javascript Folks, I have some personalized properties on an ASP.Net Web Part that I would like to set via Ajax (for example, the size to which the user has expanded the WebPart using the jQuery Resizable plugin.) I've read this question and answer, but I don't think it will work. Personalized properties are instance properties. (If they were static, they couldn't be user-scoped, could they?) A WebMethod, which must be static, can't access them. You might be thinking that I could just use a hidden field and send my values back that way, but that assumes that a postback is done at least once after the values are set. In this case I can't guarantee that: the page in question displays a lot of data but doesn't take any user input other than for configuration. I seem to recall that some Ajax techniques involve remotely instantiating a page on the server and going through at least part of the page life cycle, but the last time I messed with that was 2006 and I never could get it to work very well. I have the impression that modern Ajax techniques, even for ASP.Net, work in other ways. So, does anybody have an idea of how this could be managed? Thanks very much, Ann L. A: Webmethods only have to be static when they are page-based. Create a webservice in your project and stick non-static webmethods in there. You can even enable session state.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Different User Agents in the browsers I have noticed that some browsers via a build in development feature allow you to choose different user agents. Does this mean that they change their rendering engine? Say for example, if I set Safari's user agent to internet explorer - will that then change the rending engine from webkit to trident? At the moment on my mac I have Safari, Chrome, Firefox and iCab installed. I would imagine they would represent the different engine's better than the user agent function built in. However you are only limited to installing 1 version of each unless you go the virtual machine or dual boot way. So what is your advice? Run multiple virtual machine and of course the extra licenses to do it legal will need to be purchased. or stick with the user agent function built in and that gives a good enough interperatation of the differences?? Cheers Jeff A: Say for example, if I set Safari's user agent to internet explorer - will that then change the rending engine from webkit to trident? No. A user agent is just a string that the browser sends to identify itself. I could set my user agent to cheeseburger if I wanted. It won't use a cheeseburger to try and render the page. Officially, the only correct way to run Internet Explorer is on Windows - which would require a Windows installation - a VM is a perfect valid and common solution. On a Mac you also have the option of Bootcamp. There are other services, like http://browsershots.org/, that allow you to specify a URL and they will send you a screenshot of what the URL likes like in a particular browser. I typically don't like these solutions because they are slow, you don't have any debugging tools, etc. A: the user agent setting in safari (and other browsers) only spoofs the user agent, it doesn't change the rendering engine. you can use that spoofing, to get for example the iPhone version of a webpage in your desktop safari. to check your page in different browsers, you could use some web service like http://browsershots.org/ (thats just the first google result) or setup an array of virtual machines. we do the latter, which ineed costs you 2-3 windows licenses, but you can pack a lot of browsers into one virtual machine, just distribute the different versions among different machines
{ "language": "en", "url": "https://stackoverflow.com/questions/7535348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I change the colors for my source code on GitHub? I tried using GitHub to host a gist of Perl code, but I don't think there is enough contrast in colors. Can I modify them? I've tried searching Google, GitHub, and Stackoverflow. A: I don't think there's any way to do this through Github; however, you could always use something like the Stylish add-on for Firefox to change Github's css locally.\ Since this only changes the css locally, you will see the different style but everyone else who visits your project will still see the standard Github style.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Makefile-based Eclipse CDT with run/debug launch configuration depend on release/debug build configuration I have a Makefile that based on given target (all/debug) generates executable in release/debug directories on the project folder. I have setup the Eclipse-CDT C/C++ build behavior mechanism to generate the right output depending on the active build configuration. For example the "release" build configuration will call "make" with "all" as the behavior, that makes release/output file, "debug" configuration makes a debug version at debug/output So far so good, but when I need to setup the "run configurations" I should enter the path for the binary (search project just does not show anything), Variable ${ConfigName} also does not expand there so I cannot use something like ${ConfigName}/output as binary to run/debug. I also tried adding release and debug to the "Paths and symbols"/"Output location" and that not help either. I can enter the relative/absolute path (for examle ./release/output) there and if I hit run, it runs the binary or if I hit debug it debugs it. However, because of the reliance on the path I have to have two launch configurations one for debug and one for release. The problem is that run and debug configurations are basically the same only one has the option to customize gdb, which makes it very confusing. Regardless of whether it is debug or release active, one can run/debug any of the four combinations! Is there anyway I can run/debug what actually is built? so if the debug build is active one can run/debug the debug build? I am not even constraining the debug build to be non-runnable or the release build to be non-debuggable, I guess that is asking too much. The problem is because of the two launch configurations, and I cannot find anyway to make it just one that depends on the build configuration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Jenkins Master Slave Interaction Does the Server maintain a constant/continuous connection with client throughout the build process? or is the interaction between server and client connectionless? As in does it open a connection distribute builds, close connection, And after the build is over client opens a connection to the master and reports? A: A connection is maintained between the master and slave, if just so the console output can be displayed on the master real time (and perhaps other status reporting as well). Apart from that, builds (i.e., the process executing the build) is self contained and executes independently on the slave machines.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I access a pixel in OpenCV? I have an x,y point coordinate, how would I use this to access a specific point on an IplImage? Thanks A: Use CV_IMAGE_ELEM CV_IMAGE_ELEM( image_header, elemtype, y, x*N+C ) E.g. given an 8-bit 3 channel (such as RGB) IplImage* img, we want (x,y) on the 2nd channel: CV_IMAGE_ELEM(img, uchar, y, (x * 3) + 1)) A: OR, you can do this. for more matrix operation, see here. http://note.sonots.com/OpenCV/MatrixOperations.html int col, row, z; uchar b, g, r; for( y = 0; row < img->height; y++ ) { for ( col = 0; col < img->width; col++ ) { //for( z = 0; z < img->nChannels; z++ ) //{ // c = img->imageData[img->widthStep * row + col * img->nChannels + z]; //} b = img->imageData[img->widthStep * row + col * 3] g = img->imageData[img->widthStep * row + col * 3 + 1]; r = img->imageData[img->widthStep * row + col * 3 + 2]; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is adding maximum character restrictions a good idea on form fields which store data in a database? I already have minimum character limit, but was wondering is also adding a maximum a good idea? For example; I have a post topic form which creates a forum topic (and stores the info in a MySQL database - the data type for the columns which are effected is text) - I have a minimum character limit for both the topic title and topic body, but I've seen on several other sites they have a maximum character limit aswell? Is there any specific reason which in my situation it would be a bad idea?, why do sites commonly have this restriction (other then the obvious - could it effect functionality?) and if so what would be a typical/average maximum character limit for a topic title and a topic body (is there a general rule of thumb to determine this)? Thank You. A: The biggest reason I can think of as to setting a maximum character limit is because if you insert data into a MySQL database and the input is larger than the maximum length the column supports, the data is simply truncated with no error. You can set the limits on the text field in HTML, but a user with the right tools can remove this restriction, so for very important data, you may want to check the length on the server side and make sure it can fit where it is going. For your situation, I guess the other reason would be to prevent a user from creating a thread subject that is extremely long. The title of your post here is good, but it may not be good if you were to add much more to it i.e.: Is adding maximum character restrictions a good idea on form fields which store data in a database because I am not doing it on my site and think I should, but don't know if I should or not. So I think it serves as a limitation in that sense too. Also, since your display may truncate the subject to a certain length in order to prevent breaking a layout or looking bad, it helps the user come up with a concise subject. You may look at some free forum software to see what limits they put on the subjects, a reasonable limit seems like maybe 128 characters. Your subject is 100. As for limiting the body, 65,635 bytes is pretty reasonable. On forums people who make really long posts tend to break them up into multiple posts because of limitations imposed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does Android's Java version relate to a Java SE version? I am constantly wondering how the Java version used for Android development relates to a Java SE version. For example, I was reading today about "Type Inference and Generic Methods" which is a feature added in Java SE 7. I wonder to myself, "Can I use this in Android code?" Of course I could type the code into an Android project and see if it compiles, but I'd be happier to have some kind of mapping in my head. I've tried Googling for this info, checking the Android docs, etc, but can't find an answer. Edit: I'm more interested in language features, e.g. how does the Android Java syntax version relate to Java SE syntax. A: Android's version doesn't directly relate to Java SE, although it uses a subset of Apache Harmony's SE 6 libraries and tools. It will be up to the Android team to decide if & when to support/require the SE 7 version of Harmony. Edit It looks like as of KitKat Android supports Java SE 7 language features. See the comments below. A: There is no direct mapping: * *Some parts of the API (such as JAXB, which has been around since at least Java 6) have never been available on Android. *When features of a new Java version are introduced, this can happen gradually over multiple versions. *Some newer Java features are made available for older, already-released versions as backports. In the past it has taken Google some 2–3 years to start adopting a new Java version. Java 7 features started appearing around API 19 (KitKat). Java 8 features started at API 26 (Nougat), but a mechanism called desugaring is available to make certain Java 8 features available on earlier Android versions, regardless of their API level. So, generally speaking, if you want to know whether a particular Java API feature is available on Android, look it up on the Android developer reference and check the minimum API version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "73" }
Q: mysql dynamic rows everyone i would like to perform a query on MySQL with dynamic rows. Imagine this: table phones_categories +----+------------+ | id | name | +----+------------+ | 1 | Home Phone | | 2 | Cell Phone | | 3 | Fax | +----+------------+ table phones +----+-----------+-------------------+--------------+ | id | entity_id | phone_category_id | phone_number | +----+-----------+-------------------+--------------+ | 1 | 1 | 1 | X19 XXX 2XX | | 2 | 1 | 3 | X19 XXX 2XX | | 3 | 2 | 1 | X18 XXX 4XX | | 4 | 2 | 3 | X18 XXX 4XX | +----+-----------+-------------------+--------------+ i would like to have the following output: +-----------+--------------+--------------+-------------+ | entity_id | Home Phone | Cell Phone | Fax | +-----------+--------------+--------------+-------------+ | 1 | X19 XXX 2XX | | X19 XXX 2XX | | 2 | X18 XXX 4XX | | X18 XXX 4XX | +-----------+--------------+--------------+-------------+ Ok i need some "dynamic" becacuse on the future the table phone_categories can grow. A: This is called a "pivot table" or "crosstab query". MySQL alone cannot do this dynamically. You always need to know the column names ahead of time, so if you are using a programming/scripting language for your output you can use it to dynamically build up the SQL statement with a for loop after you've determined the categories. But the query will look like: SELECT phones.entity_id, CASE WHEN phones.phone_category_id = 1 THEN phones.phone_number ELSE NULL END AS `Home Phone`, CASE WHEN phones.phone_category_id = 2 THEN phones.phone_number ELSE NULL END AS `Cell Phone`, CASE WHEN phones.phone_category_id = 3 THEN phones.phone_number ELSE NULL END AS `Fax` FROM phones You haven't identified any programming language, so here's some pseudocode to generate the query: categories = "SELECT id, name FROM phone_categories;" foreach categories sql_columns = sql_columns + " CASE WHEN phones.phone_category_id = " + categories.id + " THEN phones.phone_number ELSE NULL END AS `categories.name`
{ "language": "en", "url": "https://stackoverflow.com/questions/7535386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Download and execute SQL script - what are the security issues + solutions? I'm tasked with designing a .Net application that will download a sql script file from a specific server and execute that file against a database. I can think of a number of security steps I'll want to include: * *Use a secure connection to the server (SFTP) *Database user only has certain access (insert, update data on specific tables) *I suggested sandboxing the transaction in a separate database instance. Unfortunately, they say the transfer data set is too large for this to be practical. I'm primarily worried not only about allowing someone to purposefully damage information in a very large database, but, ideally, to help prevent accidental damage as well. Questions: * *Did I miss anything? Are there any best practices to keep in mind for this kind of thing? *What would be the best way to authenticate the server cert against a man-in-the-middle attack? A: To point 1) * *Keep an audit log. *To whatever degree possible, help the user create these SQL scripts. Drop downs to choose table names, radio buttons to choose the command, a column selector, etc... This will help prevent accidents. *Ideally, you would be able to roll back to before any specific script is executed (think of how a bank has to be able to replay your transactions to verify your account balance if ever questioned). Depending on the frequency of updates and this data's importance, you're probably fine with just some daily backups instead of an actual transcriptional, re-playable history. To point 2) * *WinVerifyTrust to make sure the certificate is valid and has a valid root. *CryptQueryObject to check for a specific certificate. A: I would implement your point 2 as restrictive as possible, but obviously your script has to be allowed to do some stuff. So you will have to trust the person which provides the script. To make sure that you execute a script which is really from that person you trust, I would sign the script and would validate the signature before executing the script. So you can be sure that it has not been modified by somebody else.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android TextView casting error: android.widget.LinearLayout cannot be cast to android.widget.TextView I have the following textview in a layout file, this is the full contents of the layout file: <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/seasonTitle" android:padding="3dip" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="#FFFFFFFF" android:textSize="14sp" android:textStyle="bold" android:maxHeight="26sp" android:background="#FFCC3333" /> It has been in my app for a year or so with no problems. All of the sudden I'm getting the error: android.widget.LinearLayout cannot be cast to android.widget.TextView I can't figure it out. The layout file is inflated with code like this: TextView seasonTv = (TextView)mInflater.inflate(R.layout.section_title, null); Any insight on why this is happening? Thanks! A: It appears that you are passing in null as the root element of the view group. I would assume that the inflater is defaulting your view group to a linear layout, when you don't actually have a view group at all. I would try to modify your inflate call, as your layout file appears OK. source: http://developer.android.com/reference/android/view/LayoutInflater.html A: try this View season = (View)mInflater.inflate(R.layout.section_title, null); TextView seasonTv = (TextView)findViewById(R.id.seasonTitle); You trying to inflate layout and cast it to TextView widget. You should inflate layout and find widget
{ "language": "en", "url": "https://stackoverflow.com/questions/7535396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to implement a dialog for different activities? I want to show the same dialog in different activities. I tried to make a BaseActivitiy. The Activities extends my BaseActivity. That worked so far, but now I want to update the Activity which shows the dialog when the dialog is closed. Update means in my case to fill a listview with data from a SQLite database. I also tried to retrieve the classname to use the update method of those activities. But it is not possible to change the update method to static, because of the non-static SQL methods... Do you have any idea? Activity: public class MyActivity extends Dialogs { ... @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); int idx = info.position; switch (item.getItemId()) { case CONTEXTMENU_ID: showMyDialog(this,DIALOG_ID); break; } return true; } public void update() { ... } } DialogsClass public class Dialogs extends Activity { @Override protected Dialog onCreateDialog(int id) { ... } ... //Called on Dialog-Butten press private void ReloadActivity(){ if(DialogCalledByClass.contains("MyActivity")) { MyActivity.update();// It doesn't worke because non-static.... } else if(DialogCalledByClass.contains("MyActivity2")) { } } public void showMyDialog(Context ctx,int id) { showDialog(id); DialogCalledByClass =ctx.getClass().toString(); } } That's what I have tried... A: For example... Instead of create a BaseActivity you could create your own Dialog: class myDialog extends AlertDialog { Activity myActivity; public myDialog(Activity myAct){ myActivity=myAct; } @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.my_dialog); ... ... } @Override public void dismiss(){ myActivity.update(); } @Override public void cancel(){ myActivity.update(); } } I don't know if I've understood your question, but it's an idea. I hope it help you. A: I found a Solution. Thanks to you David!! Sry I couldn't vote up because to less reputation... private void ReloadActivity(){ if(DialogCalledByClass.contains("MyActivity")){ try { Method m = DialogActivity.getClass().getMethod("Update"); try { m.invoke(DialogActivity); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } catch (SecurityException e) { error.d(TAG, "SecurityException"+ e); e.printStackTrace(); } catch (NoSuchMethodException e) { Log.d(TAG, "NoSuchMethodException"+ e); } } else if(DialogCalledByClass.contains("MyActivity2")){ } } public void showMyDialog(Activity act,int id){ showDialog(id); DialogCalledByClass = act.getClass().toString(); DialogActivity = act; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to Insert conditional hyperlink in Crystal Reports I have Crystal reports, and I'd like to modify a field to be a hyperlink, depending on another field. But the other field may or may not have data. How do I define the field? Fields: IDNumber, LinkField If LinkField is not NULL, show IDNumber as its own value, with a underline and hyperlink set to LinkField. If LinkField is NULL, then just show IDNumber as itself, with no hyperlink. So, if the report had three IDNumbers, and only the second had a hyperlink, starting with data (3455, NULL; 4933, http://nothing; 4939, NULL) It would look something like the following: 3455 4933 4939 A: I could make a field that had a value and another field with the hyperlink. The hyperlink field was suppressed but on top of the field with the value. That worked from within Crystal Developer, but not when it was moved to our server. Since I was short of space, I tried displaying just part of the link. That worked both in development and on the server, but I was ultimately wishing to print the files to PDF and maintain the links. The links in the PDF only worked if they showed entirely. I eventually had to show the entire link in the report, giving it a separate line (to make room). (I also tried printing it in 1 point font, which did make it look like an underline, but that was hard to click on and also still overwrote fields.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7535400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: How do you fill a bitmap with color by volume? I have a bitmap image that is of irregular shape that I fill with a certain color to simulate a "meter" of sorts. My current method uses a ColorMatrixColorFilter to replace color on the original bimtap, up to a percentage by bitmap height. What I'd really like to do is replace the color by volume. A: You could draw a filled bitmap overtop of the unfilled one, but use a clipping path based on the meter's level. If that can be done with a rectangular clip, it will be quite straightforward with Canvas.clipRect(float,float,float,float). Otherwise, you may have to specify a more general path and use Canvas.clipPath(Path). However, the clipPath is not anti-aliased, so it can look a bit lousy. Another option is to draw the overlay directly with a custom Path, possibly using SVG path primitives for convenience. See this project: http://code.google.com/p/svg-android/ and specifically this method: http://svg-android.googlecode.com/svn/trunk/svgandroid/docs/com/larvalabs/svgandroid/SVGParser.html#parsePath(java.lang.String).
{ "language": "en", "url": "https://stackoverflow.com/questions/7535402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Latex editor for Red Hat Can anyone suggest me a good latex editor (GUI) for RedHat LInux. I have tex installed on my machine which is fine for compiling documents in command line mode, but without a GUI editor (with code completion facility) it is really difficult to draft a new tex document. I have looked at Kile and I am not able to install it on my Redhat machine despite repeated attempts. Also two of the most popular GUI latex editors - Texnic center and Led don't have Linux versions :-( A: Have you tried Texmaker? From what I see here it should be available into the RH repositories. A: How about emacs with YaTeX mode though it's not a GUI for LaTeX? YaTeX provides a completion functionality for TeX commands. Emacs also has the dynamic abbreviation functionality (bound to Meta-/ key sequence by default) for any word in your text file. You can also customize emacs to invoke shell commands. Unless you definitely want to click a button to compile a LaTeX document, I think this may be a good option. YaTeX Web site http://www.yatex.org/
{ "language": "en", "url": "https://stackoverflow.com/questions/7535403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Jumble text on website My website is coming up with some weird jumbled text. Has anyone seen this before? The site is nextlevelwebworks.com. Is this happening for you too? Thank you. A: I tried it in Chrome, Firefox, and IE, and they all turned out the same. What browsers/OS did you try it on?
{ "language": "en", "url": "https://stackoverflow.com/questions/7535404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: calculate area of 2-dimensional confidence ellipse in R So I have log-transformed measurement data arranged in a simple table: x y 1.158362492 1.322219295 1.1430148 1.267171728 1.11058971 1.252853031 1.120573931 1.260071388 1.149219113 1.278753601 1.123851641 1.276461804 1.096910013 1.222716471 I know there are functions for plotting a confidence ellipse for these data, but how to I calculate the area of the generated shape? Thanks A: First calculate the ellipse, then determine the lengths of the major and minor axes, and then calculate the area. Here's a brainless approximation. First, your data. dat <- structure(list(x = c(1.158362492, 1.1430148, 1.11058971, 1.120573931, 1.149219113, 1.123851641, 1.096910013), y = c(1.322219295, 1.267171728, 1.252853031, 1.260071388, 1.278753601, 1.276461804, 1.222716471 )), .Names = c("x", "y"), class = "data.frame", row.names = c(NA, -7L)) Then load the package car; dataEllipse can be used to calculate an ellipse using a bivariate normal approximation to the data. require(car) dataEllipse(dat$x, dat$y, levels=0.5) A call to ellipse can give points along the ellipse that dataEllipse plots. me <- apply(dat, 2, mean) v <- var(dat) rad <- sqrt(2*qf(0.5, 2, nrow(dat)-1)) z <- ellipse(me, v, rad, segments=1001) We can then calculate the distance from each point on the ellipse to the center. dist2center <- sqrt(rowSums((t(t(z)-me))^2)) The minimum and maximum of these distances are the half-lengths of the minor and major axes. So we can get the area as follows. pi*min(dist2center)*max(dist2center) A: You can use package mclust, there is a hidden function called mvn_plot, the input parameters are mean and std. You may try to read its code and modify it to get the length of each axis. A: The area can be directly calculated from the covariance matrix by calculating the eigenvalues first. You need to scale the variances / eigenvalues by the factor of confidence that you want to get. This thread is very helpful cov_dat <- cov(dat) # covariance matrix eig_dat <- eigen(cov(dat))$values #eigenvalues of covariance matrix vec <- sqrt(5.991* eig_dat) # half the length of major and minor axis for the 95% confidence ellipse pi * vec[1] * vec[2] #> [1] 0.005796157 Created on 2020-02-27 by the reprex package (v0.3.0) dat from user Karl's answer
{ "language": "en", "url": "https://stackoverflow.com/questions/7535406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails/Mysql/SQLite - What's the best idea for building 2- or 3-level menu I think about the best way, how to create a 2- 3-level menu. My first idea is everything to store to one database table, with the following structure: - id - item - level If I create the first-level menu item, so level will 0. If I will create the menu item of second level (eg. Contact - phone), so phone is the second menu item and the value of level will be the ID of Contact. But now - I don't know, how to print it from database - in the first loop I will print the first level of menu items (with level=0) and then I should to print the second menu items (with level=ID_of_first_menu_item) - exist any elegant way, how to simultaneously print first and second level items (I will build it in Rails)? And the second way - every level of menu items stored to separate table - but I mean this is not good idea... Thanks for your help! A: take a look at https://github.com/collectiveidea/awesome_nested_set which is basically a tree. suits perfectly for nested navigation
{ "language": "en", "url": "https://stackoverflow.com/questions/7535407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create a numeric vector with names in one statement? I'm trying to set the default value for a function parameter to a named numeric. Is there a way to create one in a single statement? I checked ?numeric and ?vector but it doesn't seem so. Perhaps I can convert/coerce a matrix or data.frame and achieve the same result in one statement? To be clear, I'm trying to do the following in one shot: test = c( 1 , 2 ) names( test ) = c( "A" , "B" ) A: How about: c(A = 1, B = 2) A B 1 2 A: ...as a side note, the structure function allows you to set ALL attributes, not just names: structure(1:10, names=letters[1:10], foo="bar", class="myclass") Which would produce a b c d e f g h i j 1 2 3 4 5 6 7 8 9 10 attr(,"foo") [1] "bar" attr(,"class") [1] "myclass" A: magrittr offers a nice and clean solution. result = c(1,2) %>% set_names(c("A", "B")) print(result) A B 1 2 You can also use it to transform data.frames into vectors. df = data.frame(value=1:10, label=letters[1:10]) vec = extract2(df, 'value') %>% set_names(df$label) vec a b c d e f g h i j 1 2 3 4 5 6 7 8 9 10 df value label 1 1 a 2 2 b 3 3 c 4 4 d 5 5 e 6 6 f 7 7 g 8 8 h 9 9 i 10 10 j A: To expand upon @joran's answer (I couldn't get this to format correctly as a comment): If the named vector is assigned to a variable, the values of A and B are accessed via subsetting using the [ function. Use the names to subset the vector the same way you might use the index number to subset: my_vector = c(A = 1, B = 2) my_vector["A"] # subset by name # A # 1 my_vector[1] # subset by index # A # 1 A: The convention for naming vector elements is the same as with lists: newfunc <- function(A=1, B=2) { body} # the parameters are an 'alist' with two items If instead you wanted this to be a parameter that was a named vector (the sort of function that would handle arguments supplied by apply): newfunc <- function(params =c(A=1, B=2) ) { body} # a vector wtih two elements If instead you wanted this to be a parameter that was a named list: newfunc <- function(params =list(A=1, B=2) ) { body} # a single parameter (with two elements in a list structure A: The setNames() function is made for this purpose. As described in Advanced R and ?setNames: test <- setNames(c(1, 2), c("A", "B"))
{ "language": "en", "url": "https://stackoverflow.com/questions/7535412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "86" }
Q: Drupal 7 Bugtracker module? I need a Bugtracker / Issuetracker module for Drupal 7. All i've found is Support Ticketing System. But its a bit buggy, always tells me "You must select a client" (user rights are configured properly, dont ask ;-). Is there any alternative to it? A: Did you try the project module and project issue module yet? http://drupal.org/project/project http://drupal.org/project/project_issue A: In addition to project modules, you can also try Case Tracker module. https://drupal.org/project/casetracker
{ "language": "en", "url": "https://stackoverflow.com/questions/7535415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Bast way to move file from server to server in PHP I have sites where stored some xml files, and I want to download to our server, we don't have ftp connection, so we can download through http. I always used file(url) is there any better way to download files through php A: If you can access them via http, file() (which reads the file into an array) and file_get_contents() (which reads content into a string) are perfectly fine provided that the wrappers are enabled. A: Using CURL could also be a nice option: // create a new CURL resource $ch = curl_init(); // set URL and other appropriate options curl_setopt($ch, CURLOPT_URL, "http://www.server.com/file.zip"); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); set_time_limit(300); # 5 minutes for PHP curl_setopt($ch, CURLOPT_TIMEOUT, 300); # and also for CURL $outfile = fopen('/mysite/file.zip', 'wb'); curl_setopt($ch, CURLOPT_FILE, $outfile); // grab file from URL curl_exec($ch); fclose($outfile); // close CURL resource, and free up system resources curl_close($ch);
{ "language": "en", "url": "https://stackoverflow.com/questions/7535419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I highlight many code blocks [code][/code] with PHP? Hello I have a dynamic text and I want to add code like all the forums like this: [code]My code here...[/code] Is there an easy way to have a function in PHP to do this stuff?? For example if I write on my text: Hello world example with PHP [code]echo "hello "world";[/code] and an addition example with PHP [code] echo 5+5; //The result will be 10[/code] etc... Will apear: Hello world example with PHP <?php echo "hello "world"; ?> and an addition example with PHP <?php echo 5+5; //The result will be 10 ?> etc.... A: In addition, you can use this PHP syntax-highlighting library. Geshi A: Simple case scenario (no nesting, other weird formatting): $text = preg_replace('#\[code\](.*?)\[\/code\]#s', '<div class="whatever">$1</div>', $text);
{ "language": "en", "url": "https://stackoverflow.com/questions/7535422", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Making TextView scrollable without knowing max lines I want to make my TextView vertically scrollable. I have read "Making TextView Scrollable in Android" but since I don't know the size of the screen of the final device, I can't know which value should be set for maximum lines. Is there any other way, so it gets the scrolling for any screen size? My XML looks like this: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content" android:fillViewport="true" android:layout_weight="1.0"> <TextView android:id="@+id/consola" android:layout_width="fill_parent" android:layout_height="match_parent"/> </ScrollView> <EditText android:id="@+id/comando" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0.0"/> <LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="0.0"> <Button android:text="Conectar" android:id="@+id/boton_conectar" android:layout_width="wrap_content" android:layout_weight="0.5" android:layout_height="wrap_content"> </Button> <Button android:text="Enviar" android:id="@+id/boton_enviar" android:layout_width="wrap_content" android:layout_weight="0.5" android:layout_height="wrap_content"> </Button> </LinearLayout> </LinearLayout> A: Look, here the structure of my XML layout with scroll: <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scrollbars="vertical" android:visibility="visible"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> ..... //your sub-widgets ..... </LinearLayout> </ScrollView> As for me, works fine. A: If you do not know number of lines (moreover, it could vary if soft input method are shown or not), you should use RelativeLayout to place you widget like TextView. And then connect both (it's critical, not one but both) top and bottom edges of it to parent withandroid:layout_alignParentTop and android:layout_alignParentBottom attibutes, or neighbors with android:layout_above and android:layout_below attributes. After both sides are connected to other widgets, android will recalculate size of TextView and scroller properly, even if you change orientation or show/hide soft keyboard. A: Put the TextView inside ScrollView with height = MATCH_PARENT try: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ScrollView android:layout_width="0dp" android:layout_height="wrap_content" android:fillViewport="true" android:layout_weight="1.0"> <TextView android:id="@+id/consola" android:layout_width="fill_parent" android:layout_height="match_parent"/> </ScrollView> <EditText android:id="@+id/comando" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" /> <LinearLayout android:orientation="horizontal" android:layout_width="wrap_parent" android:layout_height="wrap_content" android:layout_weight="1"> <Button android:text="Conectar" android:id="@+id/boton_conectar" android:layout_width="wrap_content" android:layout_weight="0.5" android:layout_height="wrap_content"> </Button> <Button android:text="Enviar" android:id="@+id/boton_enviar" android:layout_width="wrap_content" android:layout_weight="0.5" android:layout_height="wrap_content"> </Button> </LinearLayout> </LinearLayout> A: ScrollView is only allowed to have one sub widget. You should put the linearlayout inside of the scroll view. and set the textview inside of the linear layout.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to test a stale link click (or link I can't get to) using capybara/rspec Artists cannot rate their own artworks it "should display error if voting on own artwork", :js => true do sign_in visit "/upcoming" click_link "like_post_1" page.should have_content("Can't vote on your own artwork") end This was passing just fine. However, I can't click on like_post_1 anymore because I added a feature to prevent voting links from appearing next to your own artworks. Does this mean I no longer need test coverage for this scenario because it's extremely rare that someone can click on a voting link for their own artwork? Or should still have coverage to test the ajax response, because it's not tested anywhere else and it's possible for some stale page of links to somehow exist in a tabbed browser window. If so... how do I test it if I cannot call click_link? I could try to create a POST request to create the vote, but capybara doesn't support posts, and I can't test the ajax response that way... Or is there a way to simulate tabbed browsing in capybara? Suggestions? A: You can use CSS display:none or visibility:hidden for the own artwork instead of eliminating the link from the DOM. You might have to set Capybara.ignore_hidden_elements = false Another way is giving up Capybara and putting them into the controller/model spec. Controller/model spec might be a better place for the extremely rare case or safeguarding your app case. A: Please try this: Use sleep function. sleep 10 use to wait process upto 10 seconds.. it "should display error if voting on own artwork", :js => true do sign_in visit "/upcoming" click_link "like_post_1" sleep 10 page.should have_content("Can't vote on your own artwork") end
{ "language": "en", "url": "https://stackoverflow.com/questions/7535426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Adding a class to fb:comment-count I'd like to add a class to fb:comment-count (without using a div). I noticed when using web inspector there appears to be a blank class assignment by default. I was wondering if anyone knew how to add a class into this field? A: You don't have control over what classes Facebook renders when using their FBML tags. You should be able to apply styling to the fb_comments_count class though in your css file or wrap the tag in a div and style that div.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby and a Math Problem Let's say I have to have a cart with a subtotal of 1836.36. I must achieve this exact amount by adding up several products from a list with a range of prices. Say, I have a few products at 9.99, 29.99, 59.99 and I can add several of each to meet the desired subtotal. How would one approach this problem using Ruby? I've thought of feeding the list of prices into a script and somehow getting the script to add until it reaches the subtotal and then spit out the prices required to reach the subtotal... just not sure how to approach it. Any suggestions are welcome and thanks in advance. Looking forward to ideas. A: 9.99*x + 29.99*y + 59.99*z = 1836.36 brute force iterate through all the permutations of x,y,z within a range of integers For example: (0..9).each do |x| (0..9).each do |y| (0..9).each do |z| puts "x #{x} y #{y} z #{z}" if (x * 9.99 + y * 29.99 + z * 59.99 == 1836.36) end end end discard any answer whose sum is not 1835.36. Something like that... haven't tested it. You could probably tweak and optimize it to ignore cases that would certainly fail to pass.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP: Bolding of overlapping keywords in string This is a problem that I have figured out how to solve, but I want to solve it in a simpler way... I'm trying to improve as a programmer. Have done my research and have failed to find an elegant solution to the following problem: I have a hypothetical array of keywords to search for: $keyword_array = array('he','heather'); and a hypothetical string: $text = "What did he say to heather?"; And, finally, a hypothetical function: function bold_keywords($text, $keyword_array) { $pattern = array(); $replace = array(); foreach($keyword_array as $keyword) { $pattern[] = "/($keyword)/is"; $replace[] = "<b>$1</b>"; } $text = preg_replace($pattern, $replace, $text); return $text; } The function (not too surprisingly) is returning something like this: "What did <b>he</b> say to <b>he</b>ather?" Because it is not recognizing "heather" when there is a bold tag in the middle of it. What I want the final solution to do is, as simply as possible, return one of the two following strings: "What did <b>he</b> say to <b>heather</b>?" "What did <b>he</b> say to <b><b>he</b>ather</b>?" Some final conditions: --I would like the final solution to deal with a very large number of possible keywords --I would like it to deal with the following two situations (lines represent overlapping strings): One string engulfs the other, like the following two examples: -- he, heather -- sanding, and Or one string does not engulf the other: -- entrain, training Possible way to solve: -A regex that ignores tags in keywords -Long way (that I am trying to avoid): *Search string for all occurrences of each keyword, store an array of positions (start and end) of keywords to be bolded *Process this array recursively to combine overlapping keywords, so there is no redundancy *Add the bold tags (starting from the end of the string, to avoid the positions of information shifting from the additional characters) Many thanks in advance! A: Example $keyword_array = array('he','heather'); $text = "What did he say to heather?"; $pattern = array(); $replace = array(); sort($keyword_array, SORT_NUMERIC); foreach($keyword_array as $keyword) { $pattern[] = "/ ($keyword)/is"; $replace[] = " <b>$1</b>"; } $text = preg_replace($pattern, $replace, $text); echo $text; // What did <b>he</b> say to <b>heather</b>? A: Simplistic and lazy-ish Approach off The Top of My head: Sort your initial Array by Item length, descending! No more "Not recognized because there's already a Tag in The Middle" issues! Edit: The nested tags issue is then easily fixed by extending your regex in a Way that >foo and foo< isn't being matched anymore. A: need to change your regex pattern to recognize that each "term" you are searching for is followed by whitespace or punctuation, so that it does not apply the pattern match to items followed by an alpha-numeric.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add button to bottom of linear layout programmatically I have a bunch of buttons displayed using the default gravity. The last button I add to the LinearLayout view is what I'd like to appear at the bottom of the view. How do I add it programmtically to appear at the bottom of the screen? I've tried setting the gravity, but everything falls to the bottom. I just want the one button to fall to the bottom of the screen. Ideally, I won't have to make another view. A: Try this: Button button = new Button(this); youLinearLayout.addView(button, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.BOTTOM)); edit sorry, the code above dont work. You cant do this using an single LinearLayout if orientation==vertical. You'll need create another layout(RelativeLayout) and add TextView to it. RelativeLayout relative = new RelativeLayout(this); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ); params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); relativeLayout.addView(textView, params); linearLayout.addView(relativeLayout, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); A: If the rest of the screen is not empty, you can give android:layout_weight=0.0 to the Button, and 1.0 to the widget on the top. In that way, widget with 1.0 weight will expand to fill empty areas, and Button with 0.0 will take only the default space, and being the last item addes to a vertical LinearLayout, it will be sticked to the bottom.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I get the same result of the "tr///" operator from perl in java What is the fastest way to implement the perl operator tr///? For instance, if I were to have a String "ATGCATGC" and I use perl tr/GTCA/CAGT/ then I would get "TACGTACG". Is there a single java function that does this? A: There's no way to do it using standard java. There is however the apache commons-lang library method StringUtils.replaceChars(String str, String searchChars, String replaceChars) Use in like this: import org.apache.commons.lang.StringUtils; StringUtils.replaceChars("ATGCATGC", "GTCA", "CAGT"); // "TACGTACG" Good luck with your genetics research :) A: As others have commented, Apache Commons StringUtils will do it for you. So will this method, though: public static String replaceChars(final String str, final String sourceChars, final String replaceChars) { int ix; final StringBuilder sb = new StringBuilder(str); for (int i = 0 ; i < sb.length() ; i++) { if ((ix = sourceChars.indexOf(sb.charAt(i))) != -1) { sb.replace(i, i + 1, replaceChars.substring(ix, ix + 1)); } } return sb.toString(); } A: You start with perldoc -f tr which says: The transliteration operator... Now that you know a good search term, enter: java transliteration into the little box at google.com. This first hit looks interesting: jtr, a transliteration library for Java jtr.sourceforge.net jtr is a small Java library that emulates the Perl 5 "transliterate" operation on a given string. Most Perl 5 features are supported, including all the standard ... A: There is no built-in function to do this in Java. A really basic function to just replace every occurence of one char with another would be: public static String transliterate(String str, String source, String target) { StringBuilder builder = new StringBuilder(); for(int i = 0; i < str.length(); i++) { char ch = str.charAt(i); int j = -1; for(int k = 0; k < source.length(); k++) { if(source.charAt(k) == ch) { j = k; break; } } if(j > -1 && j < target.length()) { builder.append(target.charAt(j)); } else { builder.append(ch); } } return builder.toString(); } public static void main(String[] args) { System.out.println(transliterate("ABCDDCBDA", "ABCD", "1234")); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Eclipse color theme plugin issue I just installed the Eclipse color theme plugin and when I go to "Preferences-General-Appearance-Color Theme" and choose a new theme it does not change my colors. I am testing this in both the "Web" and "JavaScript" perspectives. Currently my background color is black (which it was not before, and I in fact have no idea how it got switched). I just want to switch it back to a typical white theme. A: Ok, I figured this out. I also have Aptana Studio installed in my Eclipse. Under the settings for Aptana Studio is a category called "Themes". When I changed the theme here my colors finally changed. This also explains why my screen switched to a black background. It must have been the default color theme for Aptana when I installed it. I guess the Aptana Studio themes override the default Eclipse color settings and also the "Color Theme" plugin I installed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Making margins smaller - Java Printing I am using this code to print on paper: //Overriden from printable interface public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException { if (pageIndex != 0) { return Printable.NO_SUCH_PAGE; } Paper a4 = new Paper(); a4.setImageableArea(0, 0, a4.getWidth(), a4.getHeight()); pageFormat.setPaper(a4); pageFormat.setOrientation(PageFormat.PORTRAIT); Graphics2D g2d = (Graphics2D)g; //g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); this.setDoubleBuffered(false); panel.print(g2d); JOptionPane.showMessageDialog(null, new ImageIcon(image)); this.setDoubleBuffered(true); return Printable.PAGE_EXISTS; } I am trying to reduce the size of the margins programmatically. Whatever I do, there always seems to be a large missing chunk from the image's sides (Unless I remove the margins from the print dialog - but as I said, I want to remove them programatically to automate the whole process). A: US Letter sized paper, for example, measures 8½ x 11 inches. At 72 dots per inch, that's 612 x 792. On a typical printer having paper of that size selected, the PageFormat object reports the following area. System.out.println(pf.getImageableX() + " " + pf.getImageableY() + " " + pf.getImageableWidth() + " " + pf.getImageableHeight()); 18.0 18.0 576.0 734.0 18.0 18.0 576.0 734.0 Few consumer printers are full-bleed, so the pritable area is smaller than the paper's physical dimensions would suggest. In effect, the printer can't put ink where it can't print.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Making an HTML table of specific width colummns I'm trying to made a table in HTML. One column is 85% wide, and the text in it is in the middle. I believe it is because I have a form bigger than the text in another column. My question is, how do I get the text in the middle to go to the top? A: for the TD : vertical-align:top
{ "language": "en", "url": "https://stackoverflow.com/questions/7535446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: hadoop : supporting multiple outputs for Map Reduce jobs Seems like it is supported in Hadoop(reference), but I dont know how to use this. I want to : a.) Map - Read a huge XML file and load the relevant data and pass on to reduce b.) Reduce - write two .sql files for different tables Why I am choosing map/reduce is because I have to do this for over 100k(may be many more) xml files residing ondisk. any better suggestions are welcome Any resources/tutorials explaining how to use this is appreciated. I am using Python and would want to learn how to achieve this using streaming Thank you A: Might not be an elegant solution, but you could create two templates to convert the output of the reduce tasks into the required format once the job is complete. Much could be automated by writing a shell script which would look for the reduce outputs and apply the templates on them. With the shell script the transformation happens in sequence and doesn't take care of the n machines in the cluster. Or else in the reduce tasks you could create the two output formats into a single file with some delimiter and split them later using the delimiter. In this approach since the transformation happens in the reduce, the transformation is spread across all the nodes in the cluster.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why doesn't gravity scale work in box2d I am trying to turn off gravity on one of my bodies. I have used the bodyDef.gravityScale = 0.0f but I am having no luck. Here u can look at my code below. Please help. b2BodyDef monkey1BodyDef; monkey1BodyDef.position.Set(0, 200/PTM_RATIO); monkey1BodyDef.type = b2_dynamicBody; monkey1BodyDef.userData = monkey1; monkey1BodyDef.bullet = true; monkey1BodyDef.gravityScale = 0.0f; //Why doesn't this work I get an error that says no member named 'gravityScale' in 'b2BodyDef' b2Body *monkey1Body = world->CreateBody(&monkey1BodyDef); A: I've hit this problem too. After a little digging I've found that the stable Cocos2D builds don't include recent versions of Box2D, so gravityScale is missing from b2BodyDef. That explains the discrepancy with the Box2D documentation. There are workarounds, but I've opted to update my Box2D to 2.2.1 (currently the latest). In doing that I encountered the following issues (with solutions): * *The b2PolygonShape.SetAsEdge method no longer exists. If you're using that to define screen boundaries you'll need to use something like "myPolygonShape.Set(lowerLeftCorner, lowerRightCorner);" for each screen edge. There's an excellent discussion of this at Programmers' Goodies. *b2DebugDraw has been superseded by b2Draw. Just replace any calls to b2DebugDraw with b2Draw and you should be set. For example, if, like me, you're using the Cocos2D Box2D template, you'll need to replace this: // Debug Draw functions m_debugDraw = new GLESDebugDraw( PTM_RATIO ); _world->SetDebugDraw(m_debugDraw); uint32 flags = 0; flags += b2DebugDraw::e_shapeBit; flags += b2DebugDraw::e_centerOfMassBit; m_debugDraw->SetFlags(flags); with this: // Debug Draw functions m_debugDraw = new GLESDebugDraw( PTM_RATIO ); _world->SetDebugDraw(m_debugDraw); uint32 flags = 0; flags += b2Draw::e_shapeBit; flags += b2Draw::e_centerOfMassBit; m_debugDraw->SetFlags(flags); * *b2Transform has different attribute names for position and rotation. For example, myTransform.position is now myTransform.p (but is still a b2Vec2). myTransform.R, which was defined as b2Mat22, has been replaced with myTransform.q, defined as b2Rot. Again, if you're using the Cocos2D Box2D template, replace the following in GLES-Render.mm: void GLESDebugDraw::DrawTransform(const b2Transform& xf) { b2Vec2 p1 = xf.position, p2; const float32 k_axisScale = 0.4f; p2 = p1 + k_axisScale * xf.R.col1; DrawSegment(p1,p2,b2Color(1,0,0)); p2 = p1 + k_axisScale * xf.R.col2; DrawSegment(p1,p2,b2Color(0,1,0)); } …with: void GLESDebugDraw::DrawTransform(const b2Transform& xf) { b2Vec2 p1 = xf.p, p2; const float32 k_axisScale = 0.4f; p2 = p1 + k_axisScale * xf.q.GetXAxis(); DrawSegment(p1,p2,b2Color(1,0,0)); p2 = p1 + k_axisScale * xf.q.GetXAxis(); DrawSegment(p1,p2,b2Color(0,1,0)); } I hope this helps! A: Because no member named 'gravityScale' exists in 'b2BodyDef' :( documentation is outdated compared with the code A: Change gravity definition of world, coz it's world, that have gravity, As: b2Vec2 gravity = b2Vec2(0.0f, -10.0f); bool doSleep = false; world = new b2World(gravity, doSleep); World is b2World A: If body.setGravityScale(0); doesn't work, you can use it with body.setAwake(false); at second line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ggplot2 - draw logistic distribution with small part of the area colored I have following code to draw my logistic distribution: x=seq(-2000,2000,length=1000) dat <- data.frame(x=x) dat$value <- dlogis(x,location=200,scale=400/log(10)) dat$type <- "Expected score" p <- ggplot(data=dat, aes(x=x, y=value)) + geom_line(col="blue", size=1) + coord_cartesian(xlim = c(-500, 900), ylim = c(0, 0.0016)) + scale_x_continuous(breaks=c(seq(-500, 800, 100))) pp <- p + geom_line(aes(x = c(0,0), y = c(0,0.0011)), size=0.9, colour="green", linetype=2, alpha=0.7) Now what I would like to do is to highlight the area to the left of x = 0. I tried to do it like this: x = seq(-500, 0, length=10) y = dlogis(x,location=200,scale=400/log(10)) pol <- data.frame(x = x, y = y) pp + geom_polygon(aes(data=pol,x=x, y=y), fill="light blue", alpha=0.6) But this does not work. Not sure what I am doing wrong. Any help? A: I haven't diagnosed the problem with your polygon (although I think you would need to give the full path around the outside, i.e. attach rep(0,length(x)) to the end of y and rev(x) to the end of x), but geom_ribbon (as in Shading a kernel density plot between two points. ) seems to do the trick: pp + geom_ribbon(data=data.frame(x=x,y=y),aes(ymax=y,x=x,y=NULL), ymin=0,fill="light blue",alpha=0.5)
{ "language": "en", "url": "https://stackoverflow.com/questions/7535454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can you access PCI cards(32 bits) in "real mode"? Can you access PCI cards(32 bits) in "real mode" ? Isn't "real mode" 16 bits? I have a developer claiming he can only access hardware in Real mode. But PCI is 32bits... A: Yes, you can. IO ports 0xCF8 and 0xCF9 act as index and data registers for accessing PCI Config space. The address to be written to index register (i.e. 0xCF8) has a fixed predefined format (refer PCI spec). To access pci config data, one writes to index register and then reads from data register. The Index register is a DWORD (32-bit) register and the format is: Byte-3 = 0x80 Byte-2 = Bus No Byte-1 = Upper 5 bits as DEVICE no, and lower 3 bits as FUNCTION no. Byte-0 = Register no. to read from config space So to read from Bus:0 Device:0 Func:0 register:0 in real mode, you would say: IoPortWrite32(0xCF8, 0x80000000); ValueRead = IoPortRead32(0xCFC); Hope this helps! Thanks, Rohit
{ "language": "en", "url": "https://stackoverflow.com/questions/7535457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is the static keyword needed in this template code? Working on a simple example for template functions. The code compiles and works as expected. But my question is why "static" is required in both "Cmp" and "Lit"? Otherwise, it will not compile? Thanks a lot! template<class T> class Cmp{ public: static int work(T a, T b) { std::cout << "Cmp\n"; return 0; } }; template<class T> class Lit{ public: static int work(T a, T b){ std::cout << "Lit\n" ; return 0; } }; template<class T, class C> int compare(const T &a, const T &b){ return C::work(a, b); } void test9(){ compare<double, Cmp<double> >( 10.1, 20.2); compare<char, Lit<char> >('a','b'); } A: C::work(a, b) names a static member function work() of class C. A: The reason that static is required here is that in the compare template function, you have this line: return C::work(a, b); The syntax C::work(a, b) here means "call the function work nested inside the class C. Normally, this would try to call a member function without providing a receiver object. That is, typically the way you'd call a function work would be by writing C myCObject; myCObject.work(a, b); In this case, though, we don't want to be calling a member function. Instead, we want the function work to be similar to a regular function in that we can call it at any time without having it act relative to some other object. Consequently, we mark those functions static so that they can be called like regular functions. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7535462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tomcat 404 error in Eclipse - For any page except Welcome page I am trying to run a website in Eclipse using Tomcat, but I just can view the welcome page. Any link or URL to other pages bring error 404. What I've done so far: * *I use a Dynamic Web Project, with some jsp pages. There are no errors in the files. *I've tried Tomcat 6 & 7 servers, and I can see the tomcat default page (http://localhost:8080). *Everything seem fine in Tomcat server configurations, including HTTP port, Arguments, etc. *When I run the server, I'm able to see the Welcome page using http://localhost:8080/. *When I click on a link to another page in directory (ref to http://localhost:8080//), or I redirect to http://localhost:8080// I receive the 404 error. *I tried cleaning server, running new servers, renaming web file names, etc; but the problem remains. *The files also seem OK in the Tomcat wtpwebapps folder. The website Web.xml is as follows: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>ERF_Prototype</display-name> <welcome-file-list> <welcome-file>/WEB-INF/Prototype.jsp</welcome-file> </welcome-file-list> </web-app> Any Idea how to solve the problem? Thanks Update---------------------------------------------------------------- Problem not solved; I am just trying to avoid it by exporting website to .War, and then import it using tomcat manager.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Passing text from UITextView to string in different ViewController I need to pass the text of a UITextView in viewController1 to viewController2 and set the text to a string in viewController2. I thought I had the code figured out, but it turns out that nothing is being passed. In viewController2.h I added viewController1*v1 and assigned a property to it. in the viewController2.m -(void)method{ v1=[[viewController1 alloc] initWithNibName:@"viewController1" bundle:nil]; NSString *text=[[NSString alloc]init]; [v1.tweetText setText:text]; } This is probably the wrong way to go about it, so does anyone have other solutions to this problem? A: Thats the correct way to send data to another vc, but you are not setting the variable text to anything. Try setting it to hello and see if you get hello as the tweetText in the other vc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Form Post to ASP.NET ASPX Page? I have three PHP web sites that collect a small amount of form data. I want to set the action of these PHP pages to post to the ASP.NET (another instance) web site. On the ASPX side, on page load, I'm looking for the form collection, and doing some stuff in SQL with it. I thought that an ASPX page could just receive a form post from another web site? Am I way off base? Ideas? The snippet of PHP code that does the post (I think) $host = "www.myaspnetwebsite.com"; $port = 80; $path = "/leads.aspx"; //send the server request fputs($fp, "POST $path HTTP/1.1\r\n"); fputs($fp, "Host: $host\r\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($fp, "Content-length: ".strlen($poststring)."\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $poststring . "\r\n\r\n"); //loop through the response from the server while(!feof($fp)) { $response .= fgets($fp, 4096); } //close fp - we are done with it fclose($fp); The form is on an HTML page with action of the PHP (snip) above. There's more in the file, but that looks like what's doing the post. <form action="process-final.php" method="post" id="in-quote-form"> A: I'm doing something along these lines ATM. I'm testing my code with a HTML file containing a simple <form method="post" action="targetpage.aspx">, at first it didn't work because I was using the id attribute because I thought the name attribute was deprecated. It turns out though that it only works with Request.Form("X") where <input type="text" name="X" />. Hope this helps. A: Have you tried this and you are having a problem? Or just asking if it's possible? In the Page_Load event you can use Request.Form("somefieldname") A: I've written asp.net applications that receive POST data from my customer's applications, so I can assure you that what you are trying to do is possible. Are you sure the asp.net application is working correctly? What happens if you attempt a GET request to the resource you are trying to POST to? Can you post the opening form tag of your php application? Is the action a fully qualified domain name (i.e. http://www.example.com/customers)? I don't believe a relative url will work unless the applications share a directory structure. We need a bit more information to really help you nail this down.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Comment box not appearing in XFBML Like button linked to Facebook page On my website I have an XFBML Like button linked to a Facebook page. I set up the app with the website's domain as the App Domain and included the Javascript SDK with the app id. The Like button itself works, but the comment section does not appear. Inspecting the page in Chrome shows that an iframe appears beneath the like button, but it contains only a script tag with some code. What am I doing wrong here? A: You are loading the javascript sdk with this code: (function(d){ var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/en_US/all.js"; d.getElementsByTagName('head')[0].appendChild(js); }(document)); It is looking for a div with an id of facebook-jssdk, but this div doesn't exist. Try adding this somewhere in your page: <div id="facebook-jssdk"></div> A: Take a look at this known Facebook bug: http://developers.facebook.com/bugs/293075054049400 Basically, one gets this behavior if secure browsing is enabled on the Facebook user's account.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Transform any date (from anywhere) to DD-MM-YYYY I'm trying to create a function that could get a date in different formats and (languages) and transform it to DD-MM-YYYY. For example, this function could get 22 Fev 2011 (Portuguese) and also 22 Feb 2011 (English). For both it should return 22-02-2011. Let's assume that I have a limited amount of languages, so I can have some kind of data structure that carries the months and shortens of those. My question is: "Assuming that strtotime works for English strings, what is my best choice for creating a function that given a string of a date in a language X, returns a date with the format DD-MM-YYY?" A: Other than using (i.e. paying for) translation API services, you could create database tables for languages, weekdays, abbreviated weekdays, months, abbreviated months. The four weekday/month tables will have a language_id foreign key. You can store the english equivalents in the rows or, better, normalize those out. Then have the function grab the alpha tokens from the date string (preg_match) and query the tables for rows that match the token and language. Then, if the appropriate rows are returned, substitute the english tokens into the date string and pass to the date function. A: Date/time manipulation sure is a pain. :) Proposed solution 1. Locale data I just paid a visit to Yii's svn repository and shamelessly copied these: $locales = array( 'pt' => array( 'monthNames' => array( 'wide' => array ( 1 => 'janeiro', 2 => 'fevereiro', 3 => 'marco', 4 => 'abril', 5 => 'maio', 6 => 'junho', 7 => 'julho', 8 => 'agosto', 9 => 'setembro', 10 => 'outubro', 11 => 'novembro', 12 => 'dezembro', ), 'abbreviated' => array( 1 => 'jan', 2 => 'fev', 3 => 'mar', 4 => 'abr', 5 => 'mai', 6 => 'jun', 7 => 'jul', 8 => 'ago', 9 => 'set', 10 => 'out', 11 => 'nov', 12 => 'dez', ), ), 'weekDayNames' => array( 'wide' => array ( 0 => 'domingo', 1 => 'segunda-feira', 2 => 'terca-feira', 3 => 'quarta-feira', 4 => 'quinta-feira', 5 => 'sexta-feira', 6 => 'sabado', ), 'abbreviated' => array( 0 => 'dom', 1 => 'seg', 2 => 'ter', 3 => 'qua', 4 => 'qui', 5 => 'sex', 6 => 'sab', ), ), ), 'en' => array( 'monthNames' => array( 'wide' => array ( 1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April', 5 => 'May', 6 => 'June', 7 => 'July', 8 => 'August', 9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December', ), 'abbreviated' => array( 1 => 'Jan', 2 => 'Feb', 3 => 'Mar', 4 => 'Apr', 5 => 'May', 6 => 'Jun', 7 => 'Jul', 8 => 'Aug', 9 => 'Sep', 10 => 'Oct', 11 => 'Nov', 12 => 'Dec', ), ), 'weekDayNames' => array( 'wide' => array ( 0 => 'Sunday', 1 => 'Monday', 2 => 'Tuesday', 3 => 'Wednesday', 4 => 'Thursday', 5 => 'Friday', 6 => 'Saturday', ), 'abbreviated' => array( 0 => 'Sun', 1 => 'Mon', 2 => 'Tue', 3 => 'Wed', 4 => 'Thu', 5 => 'Fri', 6 => 'Sat', ), ), ), ); 2. Brute forcing the problem Assuming that your app isn't spending all its time converting human-readable dates, speed shouldn't really matter. Therefore I went for a shortish solution with good extensibility, at the cost of not trying to optimize and being slightly cryptic. function strtotimeIntl($timeString, $locales, $normalizeCallback = 'strtolower') { // STEP 1 -- TRY ENGLISH $ts = strtotime($timeString); if ($ts !== false) { return $ts; } // STEP 2 -- BRUTE FORCE $english = $locales['en']; foreach($locales as $code => $localeInfo) { if($code == 'en') { continue; // don't try english again } $subject = $normalizeCallback($timeString); // reset // These reflect the structure of $localeInfo $replacementKeys = array( array('monthNames', 'wide'), array('monthNames', 'abbreviated'), array('weekDayNames', 'wide'), array('weekDayNames', 'abbreviated'), ); // Replace everything present in the string with english equivalents foreach($replacementKeys as $keys) { $map = array_map($normalizeCallback, $localeInfo[$keys[0]][$keys[1]]); $flipped = array_flip($map); $subject = preg_replace('/\b('.implode('|', $map).')\b/e', '$english[$keys[0]][$keys[1]][$flipped[\'$1\']]', $subject); } // Does this look right? $ts = strtotime($subject); if ($ts !== false) { return $ts; } } // Give up, it's not like we didn't try return false; } That inner foreach does look smelly, but I think it's acceptable. What it does is try to replace any substring that looks like one of the items inside the sub-array of $localeInfo (current locale being tested) identified by the indexes $keys[0] and $keys[1]. To make the replacement as tersely as possible it uses an auxiliary array $flipped and preg_replace in evaluation mode; if you don't like this kind of code, it can certainly be replaced with a more familiar loop-based approach. 3. How to use it $timeString = '22 Feb 2011'; echo strtotimeIntl($timeString, $locales); $timeString = '22 Fev 2011'; echo strtotimeIntl($timeString, $locales); 4. What's with the third argument? Well, it would be nice if the replacement worked in a case-insensitive manner. The problem with this is that you can't blindly use strtolower and the /i regex modifier, because at least the former will not work unless you change the LC_TEXT locale which is a painful requirement and not reliable to boot (locale names are OS-dependent). And the shotgun argument is that even if everything goes well that far, you still need to have your locale data saved in an ANSI encoding (which means you can't save them all in the same file). Therefore the caller has the option of supplying their own normalization function if needed; mb_strtolower would be an excellent choice here if your data is saved in UTF-8. 5. Does that even work? Sure it does. 6. And there are no caveats? Well, apart from the normalization function there is one more I can think of: strtotime internally uses the local timezone to convert the parsed date to a timestamp. This means that a date in e.g. French will be parsed correctly given the appropriate locale data, but the timestamp will be produced for the local time zone, not CET/CEST (the timezone France uses). Depending on your requirements, you might also want to account for the timezone difference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why after creating a JFrame object and setting it as visible, the program will not end executing? My program looks like this: import java.awt.*; import javax.swing.*; public class Main { public static void main(String[] args) { JFrame jf = new JFrame(); jf.setSize(new Dimension(200, 200)); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } } I'm just confused why after JVM's quitting from main(), my program does not end instantly? I noticed that if I remove the line "jf.setVisible(true);", it will end. Is it implemented though techniques like garbage collecting or class destructors? I'm interested that if I want to write something similar, how could I do it. A: The reason is that when you call setVisible(true) on the JFrame, behind the scenes a non-daemon thread is started, and the JVM will not exit until all non-daemon threads terminate. Please have a look here for more on AWT/Swing Threading issues. It states: "There is at least one alive non-daemon thread while there is at least one displayable AWT or Swing component within the application (see Component.isDisplayable)." While this is for Java 1.5, I think that it is still valid information. Also, I believe that the Event Dispatch Thread or EDT is not a daemon thread, and so it is another thread associated with Swing that drives this. Edit 1 This suggests that the EDT is in fact a non-Daemon thread: import javax.swing.JFrame; import javax.swing.SwingUtilities; public class IsEdtDaemon { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); System.out.printf("Is the current thread the EDT thread: %b%n", SwingUtilities.isEventDispatchThread()); System.out.printf("Is our EDT Thread a daemon thread: %b%n", Thread.currentThread().isDaemon()); } }); } } The output from the code is: Is the current thread the EDT thread: true Is our EDT Thread a daemon thread: false A: When you create the JFrame and make it visible you've created an implicit event listener that is now waiting for an action. If you hadn't set the default close action you would've needed to provide some other way for the application to "know" it can exit. A: If you do not call jf.setVisible(true) then your program does construct the JFrame, sets it's dimensions and defines the default close operation, but never draws the JFrame on screen and so it exits. It wouldn't make any sense to create a JFrame if you do not want to ever make it visible. The behavior one expects from a top-level container like JFrame, would be after setting it to visible to stay up and be used, until someone clicks on the close button which happens because of the jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setting. Just think about what goes on with any application, i.e. your browser. It starts and stays up until you press the close button or exit the application in another way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535480", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How does an Objective-C method have access to the callee's ivars? I was reading Apple's documentation, The Objective-C Programming Language (PDF link). On pg. 18, under The Receiver’s Instance Variables, I saw this. A method has automatic access to the receiving object’s instance variables. You don’t need to pass them to the method as parameters. For example, the primaryColor method illustrated above takes no parameters, yet it can find the primary color for otherRect and return it. Every method assumes the receiver and its instance variables, without having to declare them as parameters. This convention simplifies Objective-C source code. It also supports the way object-oriented programmers think about objects and messages. Messages are sent to receivers much as letters are delivered to your home. Message parameters bring information from the outside to the receiver; they don’t need to bring the receiver to itself. I am trying to better understand what they are describing; is this like Python's self parameter, or style? A: Objective-C is a strict superset of C. So Objective-C methods are "just" function pointers, and instances are "just" C structs. A method has two hidden parameters. The first one is self(the current instance), the second _cmd (the method's selector). But what the documentation is describing in page 18 is the access to the class instance variables from a method. It just says a method of a class can access the instance variables of that class. It's pretty basic from an object-oriented perspective, but not from a C perspective. It also say that you can't access instance variables from another class instance, unless they are public. A: While I would not say that it is a "slam" against Python, it is most certainly referring to the Python style of Object Orientation (which, in honesty, is derived from the "pseudo-object orientation" available in C (whether it is truly OO or not is a debate for another forum)). It is good to remember that Python has a very different concept of scope from the rest of the world — each method more or less exists in its own little reality. This is contrasted with more "self-aware" languages which either have a "this" variable or an implicit instance construct of some form.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When i append html element it override click functions this.div=$j("<div class='test' id='test"+this._x+"'>"+this.getHtml(inner)+"<a id='testa"+this._x+"''>Close</a></div>"); this.div.hide().appendTo($j("body")).fadeIn(100); this.div.children("#testa"+this._x).bind('click', function(){ alert(this._x); }); in constructor this._x = x; x++; when i click testa he gives me this._x last x number is there an override? A: Yes, JS events are tied to the element itself. If you delete and recreate an element the handlers go with it. You can either re-connect them, or look into using jQuery's .live() functionality. A: this._x in your event listener points to non existant property of (A._x). this.div=$j("<div class='test' id='test"+this._x+"'>"+this.getHtml(inner)+"<a id='testa"+this._x+"''>Close</a></div>"); this.div.hide().appendTo($j("body")).fadeIn(100); var newX = this._x; this.div.children("#testa"+this._x).bind('click', function(){ alert(newX); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7535486", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how do i tell nginx to handle the file after fastcgi rewrites it? I have a asp.net app and i am using nginx with fastcgi&mono. When i visit static.mysite.com/type/258/nicename.png i need nginx to grab the file from apppath/public/uploads/00/00/01/02 which is hex of 258. ATM i have asp.net rewriting the file however i am positive asp.net is still handling the file instead of nginx. I'm sure nginx would be faster and since i have the static subdomain i can skip asp.net if i have a way to tell nginx how to map the url to file How do i get nginx to handle the file transfers? A: Check XSendFile.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Declaring In-Line Secret Keys in Ruby On Rails I'm learning Ruby On Rails. I'm trying to use the aws-s3 gem to access Amazon S3. One line of my controller code reads: AWS::S3::Base.establish_connection!( :access_key_id => 'myrealaccesskeyishere', :secret_access_key => 'myrealsecretkeyishere' ) I've noticed that if I make an error, sometimes rails will come back and show a few lines of code where it thinks the error might be. Should I not be writing these out in the .rb controller files like this? Am I potentially risking my secret key? If so, how should I be doing this instead? A: You should put this in an initializer. Place it in config/intializers/amazon_s3.rb Is there a reason you are putting this code directly in the controller?
{ "language": "en", "url": "https://stackoverflow.com/questions/7535496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UIButton custom font vertical alignment I've got a UIButton which uses a custom font, which is set when my view loads: - (void)viewDidLoad { [super viewDidLoad]; self.searchButton.titleLabel.font = [UIFont fontWithName: @"FONTNAME" size: 15.0 ]; } The problem I've got is that the font is appearing to float up of the center line. If I comment out this line, the default font appears vertically centered fine. But changing to the custom font breaks the vertical alignment. I'm getting the same issue on a Table Cell with a custom font too. Do I need to tell the view somewhere that the custom font is not as tall as other fonts? EDIT: I've just realized that the font I'm using is a Windows TrueType Font. I can use it fine in TextEdit on the Mac, only a problem with the alignment in my App A: Not sure if this will help as it may depend on your font, but it could be that your baseline is misaligned. self.searchButton.titleLabel.baselineAdjustment = UIBaselineAdjustmentAlignCenters; A: I think this is the best answer. no playing with ascender, numberOfHMetrics etc... just import-export by Glyphs application and Job done. Thanks to this answer: https://stackoverflow.com/a/16798036/1207684 A: I solved the problem adjusting the top content (not the title!) inset. For example: button.contentEdgeInsets = UIEdgeInsetsMake(10.0, 0.0, 0.0, 0.0); Good luck! A: A similar problem was discussed at Custom installed font not displayed correctly in UILabel. There was no solution given. Here's the solution that worked for my custom font which had the same issue in UILabel, UIButton and such. The problem with the font turned out to be the fact that its ascender property was too small compared to the value of system fonts. Ascender is a vertical whitespace above font's characters. To fix your font you will have to download Apple Font Tool Suite command line utilities. Then take your font and do the following: ~$ ftxdumperfuser -t hhea -A d Bold.ttf This will create Bold.hhea.xml. Open it with a text editor and increase the value of ascender attribute. You will have to experiment a little to find out the exact value that works best for you. In my case I changed it from 750 to 1200. Then run the utility again with the following command line to merge your changes back into the ttf file: ~$ ftxdumperfuser -t hhea -A f Bold.ttf Then just use the resulting ttf font in your app. OS X El Capitan The Apple Font Tool Suite Installer doesn't work anymore on OSX El Capitan because of SIP because it tries to install the binary files into a protected directory. You have to manually extract ftxdumperfuser. First copy the pkg from the dmg to a local directory afterwards unpack the OS X Font Tools.pkg with ~$ xar -xf OS\ X\ Font\ Tools.pkg Now navigate into the folder fontTools.pkg with ~$ cd fontTools.pkg/ Extract payload with ~$ cat Payload | gunzip -dc | cpio -i Now the ftxdumperfuser binary is in your current folder. You could move it to /usr/local/bin/ so that you can use it in every folder inside of the terminal application with the following. ~$ mv ftxdumperfuser /usr/local/bin/ A: Late to the party, but as this issue hit me for the Nth time, I thought I'd post the simplest solution I've found: using Python FontTools. * *Install Python 3 if it's not available on your system. *Install FontTools pip3 install fonttools FontTools include a TTX tool which enables conversion to and from XML. *Convert your font to .ttx in the same folder ttx myFontFile.otf *Make the necessary edits to .ttx and delete the .otf file as this will be replaced in the next step. *Convert the file back to .otf ttx myFontFile.ttx Motivation: The solution by kolyuchi is incomplete, and even with this extended installation flow, running ftxdumperfuser resulted in an error on 10.15.2 Catalina. A: You can try this out in Interface Builder. Here is a snapshot of how to do it - As you can see trying to do this in IB has its own benefits.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "122" }
Q: How to decrypt data with Openssl tool encrypted with AES128 in iOS I have many snippets of code, which encrypt the data with AES128 (If you provide your working implementation I will be very thankfull) For example this one: - (NSData*)AES128EncryptWithKey:(NSString*)key { // 'key' should be 16 bytes for AES128, will be null-padded otherwise char keyPtr[kCCKeySizeAES128 + 1]; // room for terminator (unused) bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding) // fetch key data [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; NSUInteger dataLength = [self length]; //See the doc: For block ciphers, the output size will always be less than or //equal to the input size plus the size of one block. //That's why we need to add the size of one block here size_t bufferSize = dataLength + kCCBlockSizeAES128; void* buffer = malloc(bufferSize); size_t numBytesEncrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode + kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES128, NULL /* initialization vector (optional) */, [self bytes], dataLength, /* input */ buffer, bufferSize, /* output */ &numBytesEncrypted); if (cryptStatus == kCCSuccess) { //the returned NSData takes ownership of the buffer and will free it on deallocation return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]; } free(buffer); //free the buffer; return nil; } After it the data is base64 encoded, with online tool I save it to data.bin The thing I want to do is to decrypt this data with OpenSSl. But, when I call openssl enc -aes-128-ecb -in data.bin -out out.bin -d -pass pass:0123456789123456 It tolds me bad magic number In case I use openssl enc -aes-128-ecb -in data.bin -out out.bin -d -pass pass:0123456789123456 -nosalt It tolds me bad decrypt Please help. A: There are several problems here. First, you're encrypting with CBC mode (which is the default for CCCrypt) but decrypting in ECB mode. There is very seldom reason to use ECB mode. You're encrypting with a string (I assume "0123456789123456") as the key, not the password. These are different things. I'm not certain how openssl translates a password into a key. I don't see an explanation of that on the enc(1) page. I assume it uses PBKDF2, but it's not clear (and the number of iterations isn't given). You should be passing the actual key with the -K option. In that case, you also need to pass the IV explicitly. You're not correctly generating an IV, or a salt. You should be, and you then should be passing them to openssl. To understand how to encrypt this correctly, see Properly encrypting with AES with CommonCrypto. Once you have something properly encrypted, you should then have a proper key, a salt, and an IV. Hand all of these to enc, using aes-128-cbc (assuming 128-bit AES), and it should work. EDIT It's worth stating the obvious here: Encryption/decryption is much easier if you use the same toolkit on both sides. To do what you're trying to do, you really do have to understand the nuts and bolts of both CCCrypt() and OpenSSL, which is why I'm discussing them. Even if you find something that "seems to work," the security can easily be very poor without you realizing it. AES128EncryptWithKey: is an example of this; it looks fine and it "works," but it has several security problems. If possible, I'd either use OpenSSL on both sides, or CCCrypt on both sides.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Mono for Android exit code 255 on BitmapFactory.DecodeStream I'm using Mono for Android (latest version as of this post) with the Visual Studio plugin to build an Android application. It targets API Level 8, Android 2.2 framework. The app runs fine on a Motorola Droid running Android version 2.2.2 It crashes with almost no output from the debugger on Motorola Droid X2 running Android 2.3.3 The only output is: The program 'Mono' has exited with code 255 (0xff). The crash happens in this method on the line that starts with using (Bitmap... public static Drawable GetDrawable(string url) { try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeStream(response.GetResponseStream())) { Drawable image = (Drawable)(new BitmapDrawable(bitmap)); return image; } } catch { return null; } } If I set a breakpoint on that line it breaks correctly but I can't find anything wrong. If I set a breakpoint after that line the debugger simply detaches and the app force quits. I have a similar method that returns an object from JSON and it works fine. So, I'm fairly sure it's related to the dynamic bitmap creation but at this point I've tried everything I can think of. UPDATE: I just reproduced this problem in a small, self-contained project available here: DrawableTest.zip Here's the full code: using System; using System.Net; using System.Threading; using Android.App; using Android.Widget; using Android.OS; using Android.Graphics; using Android.Graphics.Drawables; namespace DrawableTest { [Activity(Label = "DrawableTest", MainLauncher = true, Icon = "@drawable/icon")] public class Activity1 : Activity { ImageView mImage; Button mButton; public const string mImageUrl = "http://i.stpost.com/erez4/erez?src=ProductImages/3576U_02.tif&tmp=MediumLargeG4&redirect=0&headers=proxy"; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); mImage = FindViewById<ImageView>(Resource.Id.MyImage); mButton = FindViewById<Button>(Resource.Id.MyButton); mButton.Click += new EventHandler(mButton_Click); } void mButton_Click(object sender, EventArgs e) { ThreadPool.QueueUserWorkItem(o => AsyncImageLoad()); } private Drawable GetDrawable(string url) { try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeStream(response.GetResponseStream())) { Drawable image = new BitmapDrawable(bitmap); return image; } } catch (Exception e) { return null; } } private void AsyncImageLoad() { Drawable image = GetDrawable(mImageUrl); RunOnUiThread(() => { mImage.SetImageDrawable(image); }); } } } A: This is probably a bug in our Stream mapping code, similar to: http://bugzilla.xamarin.com/show_bug.cgi?id=1054 This should be fixed in the next release (1.9.x, probably). As a workaround, try copying response.GetResponseStream() into a System.IO.MemoryStream, and then pass the MemoryStream to BitmapFactory.DecodeStream(). Update I had the right idea, but the wrong approach. Instead of using BitmapFactory.DecodeStream(), use BitmapFactory.DecodeByteArray(). The following code works for me in your DrawableTest.zip app: private Drawable GetDrawable(string url) { try { HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(url); using (HttpWebResponse response = (HttpWebResponse) request.GetResponse()) using (Stream responseStream = response.GetResponseStream()) { MemoryStream workaround = new MemoryStream(); responseStream.CopyTo(workaround); Bitmap bitmap = Android.Graphics.BitmapFactory.DecodeByteArray ( workaround.GetBuffer (), 0, (int) workaround.Length); Drawable image = new BitmapDrawable(bitmap); return image; } } catch (Exception e) { Log.Error("DrawableTest", "Exception: " + e.Message); return null; } } Note the using blocks to ensure that the resources are disposed. A: Try running without the debugger (Ctrl-F5), and then checking the Android Debug Log for the exception: http://android.xamarin.com/Documentation/Guides/Android_Debug_Log
{ "language": "en", "url": "https://stackoverflow.com/questions/7535503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is this class using connection pool feature right now ? - MSSQL 2008 R2 - ASP.net 4.0 I looked over the web but i could not understand exactly connection pool thing. This is my query executing class. Every query is getting executed by this class. Thank you. using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Web; using System.Data.Sql; using System.Data.SqlClient; using System.Data; using System.IO; public class DbConnection { public static string srConnectionString = "server=localhost;database=mydb;uid=sa;pwd=mypw;"; public DbConnection() { } public static DataSet db_Select_Query(string strQuery) { DataSet dSet = new DataSet(); try { using (SqlConnection connection = new SqlConnection(srConnectionString)) { connection.Open(); SqlDataAdapter DA = new SqlDataAdapter(strQuery, connection); DA.Fill(dSet); } return dSet; } catch (Exception) { using (SqlConnection connection = new SqlConnection(srConnectionString)) { if (srConnectionString.IndexOf("select Id from tblAspErrors") != -1) { connection.Open(); strQuery = strQuery.Replace("'", "''"); SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection); command.ExecuteNonQuery(); } } return dSet; } } public static void db_Update_Delete_Query(string strQuery) { try { using (SqlConnection connection = new SqlConnection(srConnectionString)) { connection.Open(); SqlCommand command = new SqlCommand(strQuery, connection); command.ExecuteNonQuery(); } } catch (Exception) { strQuery = strQuery.Replace("'", "''"); using (SqlConnection connection = new SqlConnection(srConnectionString)) { connection.Open(); SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection); command.ExecuteNonQuery(); } } } } A: Yes, connection pools are created per connection string. To prevent memory leaks, you should also have a using statement around your SqlCommand and SqlDataAdapter objects as well. SQL Server Connection Pooling (ADO.NET) A connection pool is created for each unique connection string. When a pool is created, multiple connection objects are created and added to the pool so that the minimum pool size requirement is satisfied. Connections are added to the pool as needed, up to the maximum pool size specified (100 is the default). Connections are released back into the pool when they are closed or disposed. Example using statements: using (SqlConnection connection = new SqlConnection(srConnectionString)) { connection.Open(); using(SqlDataAdapter DA = new SqlDataAdapter(strQuery, connection)) { DA.Fill(dSet); } } using (SqlConnection connection = new SqlConnection(srConnectionString)) { if (srConnectionString.IndexOf("select Id from tblAspErrors") != -1) { connection.Open(); strQuery = strQuery.Replace("'", "''"); using(SqlCommand command = new SqlCommand("insert into tblSqlErrors values ('" + strQuery + "')", connection)) { command.ExecuteNonQuery(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MVC 3 Session.Abandon() called before setting a TempData["myvalue"] = "foo" causes the next controller to have TempData as null I have a controller will logic that looks for a: Session value //checks value null etc.. for existing record in session memory. Session["certnum"] Then in the controller I had decided to have a condition where: //is called to initiate a New Record that will be created. Session.Abandon(); However In the procedural coding is that Session.Abandon(); comes before the creation of TempData["myobject"] = "foo" , and upon stepping through the code the TempData in immediate window shows my value and all seems good. Then upon redirect to another controller: return RedirectToAction("ChildInfo", "NewRecord"); This ChildInfo method no longer has the TempData value ... Now it is null. The Session Abandon Method was called way before the TempData value was set, not sure if this is a bug with MVC Sessions, but that make zero sense to me. If I am creating a new lighweight session TempData, then it should persist to the next controller. If I remove the Session.Abandon() method then the TempData value persist working as it did previously. A: The Session.Abandon() method clears the current session at the end of the request, that it what it is designed to do. See http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.abandon.aspx If you want to redirect to a different action, you do need to call the redirect like you have done. If you use Abandon() the request will get a new session id. If you want to remove something from a session you need to use the Session.Remove or Session.RemoveAll methods (Also Clear can be used to do the same as RemoveAll. This would be done by: Session.Remove(itemToRemove); or Session.RemoveAll() By using either of these two options you can remove some or all previously stored data from the session without actually causing the session id to be regenerated on the next request. A: The Session.Abandon method doesn't clear the session object, it only flags that it should not be kept. The session object is still intact during the current request. When the response is complete, the session object is abandoned, so that the next time the browser makes a request, the server has to set up a new session object. Anything that you put in the session object during that entire request goes away when the session object is abandoned. When you make a redirect, a redirection page is sent as response to the browser, which then requests the new page. If you mark the session object to be abandoned and then do a redirect, the new page will get the new session object. A: This is how it's supposed to work. Session.Abandon does not kill the session immediately. It last until the end of the page. Then, upon the next page load, a new session is created.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to fix problems regarding connection between Android program and MySQL I am very new to Android and php. I was following a turtorial from a website and made a program that sends and year and receives the info of people in my database who are born after it. However, I am getting these logcat errors: 09-23 18:30:04.146: ERROR/log_tag(16030): Error in http connection java.net.UnknownHostException: www.enjoyen.in 09-23 18:30:04.146: ERROR/log_tag(16030): Error converting result java.lang.NullPointerException 09-23 18:30:04.154: ERROR/log_tag(16030): Error parsing data org.json.JSONException: End of input at character 0 of I'm not sure how I should fix that This is my java file: public class PS extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Create a crude view - this should really be set via the layout resources String result = null; InputStream is = null; StringBuilder sb=null; //the year data to send ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("year","1980")); //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://mywebsite/sampleDB/HAconnect.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //parse json data try{ JSONArray jArray = new JSONArray(result); for(int i=0;i<jArray.length();i++){ JSONObject json_data = jArray.getJSONObject(i); Log.i("log_tag","id: "+json_data.getInt("id")+ ", name: "+json_data.getString("name")+ ", sex: "+json_data.getInt("sex")+ ", birthyear: "+json_data.getInt("birthyear") ); } } catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString()); } } } And this is my php file: <html> <body> <?php mysql_connect("localhost","user","password"); mysql_select_db("database"); $q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'"); while($e=mysql_fetch_assoc($q)) $output[]=$e; print(json_encode($output)); mysql_close(); ?> </body> </html> What should I do?? A: try to search by "android UnknownHostException". This is emulator problem. To solve it try to restart emulator or recreate avd
{ "language": "en", "url": "https://stackoverflow.com/questions/7535513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Download Latest Version of a CodePlex Project I'm writing an update program for another piece of software. This update program downloads/installs updates to this program's extensions (my update program is, in fact, just another extension). Some of these extensions are CodePlex projects. Other's are just on people's personal websites or on their company's website, etc... Point is, there's no central extension repository. I'm having trouble downloading the updates that are hosted on CodePlex because I cannot seem to just find URL that returns/downloads the latest version. E.g. on this page there is the big, green "Download" button. All I want is, for any given CodePlex project, a URL I can hit that will download the latest version (like that Download button does after the stupid prompt). I created a CodePlex feature request for this, but it hasn't been updated and neither have the other hundreds of requests people have had for that site. In summary, I want something like this: http://coolestProjectEver.codeplex.com/download This link would return/download the latest version of that project without any questions/prompts. Any ideas what I can do? A: One thing that might help is that there is a permanent link to the latest source: http://[project].codeplex.com/releases. This might also help: Read Latest Version From Source You could just have that read a file that you know is already there containing the version number. Visual Studio keeps this in the project or solution files. For your references with Mercurial you can just go to https://hg.codeplex.com/[project]/raw-file/tip/ and start building the path to the file you want. Just hope it isn't a .vb file as that doesn't seem to work. UDPATE: Based on the comments found here http://codeplex.codeplex.com/workitem/25464 I was able to retrieve the latest version of a specific file. Which ever file in your target project contains the version number you can see it here. Add in a little regex and you should be good to go. The format is: http://[project].codeplex.com/SourceControl/BrowseLatest#[PathToFile] A: Like discussed above, only if CodePlex changes its implementation, it will be too hard to achieve what you want. Don't hack, as they may upgrade their site just another day and break your hack. Consider hosting the binaries in a separate site (maybe create a backup site on Google Code, where the Download page (http://code.google.com/p/lextudio/downloads/list) does not prompt.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do I update the quantity column from two other tables in mySQL? I have three tables so I can display separate tables and keep track of different things. How do I make 'pull_qty" in CARTONS_PULLED and 'add_qty' in CARTONS_ADDED update 'qty' in CARTONS _CURRENT? When I create a new Part Number with a quantity it inserts into CARTONS_CURRENT. Now I need to update the 'qty" in CARTONS_CURRENT with adds and pulls from the two other tables? the 'part_no' is the primary key and is always the reference to update. Here are my tables: DATABASE NAME: _hero  TABLE NAME:  CARTONS_CURRENT +--------------+--------------+--------+--------+-------------------+------------+ | Column     |  Type        |  Null  |  Key   |  Default          |  Extra     | +--------------+--------------+--------+--------+-------------------+------------+ | orig_time  | timestamp    |  No    |        | CURRENT_TIMESTAMP |            | | type   | text    |  No    |        | |            | | part_no     | varchar(20)  |  No    |  Prim  |                   |            | | description | varchar(75)  |  No    |    |                   |            | | count | varchar(2)   |  No    |    |                   |            | | size | varchar(30)  |  No    |    |                   |            | | min | int(7)   |  No    |    |                   |            | | max | int(7)   |  No    |    |                   |            | | qty         | int(8)       |  No    |        |                   |            | +--------------+--------------+--------+--------+-------------------+------------+ TABLE NAME:  CARTONS_ADDED +--------------+--------------+--------+--------+-------------------+------------+ | Column     |  Type        |  Null  |  Key   |  Default          |  Extra     | +--------------+--------------+--------+--------+-------------------+------------+ | add_time  | timestamp    |  No    |  Prim  | CURRENT_TIMESTAMP |            | | type     | text  |  No    |    |                   |            | | part_no     | varchar(20)  |  No    |  Prim  |                   |            | | add_type | varchar(25)  |  No    |    |                   |            | | add_qty | int(8)   |  No    |    |                   |            | | add_ref | varchar(35)  |  No    |    |                   |            | | add_by | text   |  No    |    |                   |            | | add_notes | varchar(300) |  No    |    |                   |            | +--------------+--------------+--------+--------+-------------------+------------+ TABLE NAME:  CARTONS_PULLED +--------------+--------------+--------+--------+-------------------+------------+ | Column     |  Type        |  Null  |  Key   |  Default          |  Extra     | +--------------+--------------+--------+--------+-------------------+------------+ | pull_time  | timestamp    |  No    |  Prim  | CURRENT_TIMESTAMP |            | | type     | text  |  No    |    |                   |            | | part_no     | varchar(20)  |  No    |  Prim  |                   |            | | pull_type | varchar(25)  |  No    |    |                   |            | | pull_qty | int(8)   |  No    |    |                   |            | | pull_ref | varchar(35)  |  No    |    |                   |            | | pull_by | text   |  No    |    |                   |            | | pull_notes | varchar(300) |  No    |    |                   |            | +--------------+--------------+--------+--------+-------------------+------------+ A: You'd write triggers for the CARTONS_PULLED and CARTONS_ADDED tables which do the appropriate updates in CARTONS_CURRENT table. Ie something like CREATE TRIGGER Upd_Cartons_qty AFTER INSERT ON CARTONS_ADDED FOR EACH ROW BEGIN UPDATE CARTONS_CURRENT SET qty = qty + NEW.add_qty WHERE part_no = NEW.part_no; END; if you want to add the value of add_qty to the CARTONS_CURRENT.qty when new record is inserted into CARTONS_ADDED.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pros/cons of MongoDB or MySQL for this purpose I'm looking for a bit of help or guidance on which database to use for a project. If you can raise any points, or note flaws, answer any questions or promote either database type for the purpose I'm about to spell out, I would really appreciate it. Anyways: * *We have some software that tracks forms. *We have users that can have MANY different properties, literally hundreds of settings, and I'm not a fan of MySQL tables that wide. I really like Mongo for this. *We have different types of forms, each can have completely different fields. Right now, we have a list of forms with generic data, then join the relevant table for additional data. I would have all of these fields in one distinct document with Mongo, and I could easily add fields without worrying. *We have fees, notes, history on each form. I like how in MySQL they are in a different table, and I can get history by form or by user - same as notes. *Our policy is pretty much keep ALL data, even deleted or pre-edited data... forever. Should I be worried about hitting a size limit? We're probably talking 100gb by the end of 2013 *How many Mongo queries per page will bog things down? 20? 100? Would that change if I had a SSD in the server? (Right now, we have about 60 MySQL queries a page. This can be improved on.) *Is it a bad idea for my first Mongo project to be a somewhat major bit of software? Is it something I can learn as I go? *I like the case insensitivity of MySQL column names for quick and dirty things. *In MySQL, I break things out to different tables. Is it fine, in Mongo, to put data together that CAN be separated? Example: username, email, phone, license1 => [num,isValid], license2 => [num, isValid], notifications => [notification1...notification50000], password hash, salt, setting1, setting2...setting1000, permission1, permission2...permission1000 Of course, I'd make use of the nested style to organize, but is it best to store all this under "user" or break it out to settings, licenses, permissions? Second example: formName, address, notes => [note1 => [user,note,date], note2 => [user,note,date]] *Is there any problems with doing a HYBRID setup, where user data is is Mongo, and form data is in MySQL? *We have to run a lot of reports, are there limitations on this in Mongo? For example, would I run into problems looking for every form from the past 40 days with a fee over $10, with the fees in each row totaled up, sorted by the age of the user who filled it out? *Data redundancy - On the Amazon cloud, MySQL has MASSIVE amounts of redundancy. Is there any service to match that with Mongo? Is it complex to get into setting that up on my own? *Is MongoDB supported by any "cloud" providers? AWS does a lot for MySQL, but it looks like I'd be on my own for Mongo Just a few things off the top of my head - I really do appreciate anything anyone has to say. A: We have users that can have MANY different properties, literally hundreds of settings, and I'm not a fan of MySQL tables that wide. I really like Mongo for this. We have different types of forms, each can have completely different fields. Right now, we have a list of forms with generic data, then join the relevant table for additional data. I would have all of these fields in one distinct document with Mongo, and I could easily add fields without worrying. From your post i understand that your ultimate aim is to handle the users & forms that contains varying schema(aka schemaless). I believe mongodb is a right choice for this purpose. We have fees, notes, history on each form. I like how in MySQL they are in a different table, and I can get history by form or by user - same as notes. No problem, You can use different documents (or embedded documents based on the size of it - 16 mb is the max size of the doc) to handle this without any problems. so you can have the schema like Form - form field1 - form field1 - id of the fees doc - id of the notes doc - id of the history doc or (for embedded docs) Form - form field1 - form field2 - embedded fees doc - fees field1 - fees field2 - embedded notes doc - notes field1 - notes field2 Our policy is pretty much keep ALL data, even deleted or pre-edited data... forever. >Should I be worried about hitting a size limit? We're probably talking 100gb by the end of >2013 You will store as much as data you would do, already there are production deployments storing data over Terabytes. Is it a bad idea for my first Mongo project to be a somewhat major bit of software? Is it something I can learn as I go? Yes if you are going to use mongodb without prototyping your application model. i would recommend to implement (prototype) a minimal set of your app (like features that sucks in mysql) and learn basics and see how comfortable you are. I like the case insensitivity of MySQL column names for quick and dirty things. Mongo enforces the case sensitivity, because thats a nature of BSON (as well JSON) key value pairs. In MySQL, I break things out to different tables. Is it fine, in Mongo, to put data together that CAN be separated? Example: username, email, phone, license1 => [num,isValid], Main advantage of mongo over other sql data store is, you can store as much of relevant info within the same document (within the 16 mb size) . If you are unsure about the size or certain parts of data are growing, then you can split the part into another. Since you are concern about the no of queries, it will drastically reduce the number of requests. Is there any problems with doing a HYBRID setup, where user data is is Mongo, and form data is in MySQL? No absolutely not, in fact i am currently running mongodb along with mysql(for transactions alone). But if you are not handling any transactions, you can stick with mongodb. We have to run a lot of reports, are there limitations on this in Mongo? For example, would I run into problems looking for every form from the past 40 days with a fee over $10, with the fees in each row totaled up, sorted by the age of the user who filled it out? No i don't see any limitation in this. In fact its very fast handling queries with the proper indexes. But there are certain things you can't do with mongo like normal joins, instead you can use map/reduce to handle the data for reports. Is MongoDB supported by any "cloud" providers? AWS does a lot for MySQL, but it looks like I'd be on my own for Mongo Mongohq,Mongolab are some of the dedicated managed mongo hosting services available. Also redhat openshift & vmware cloundfoundry provides the hosting platforms for mongo, you can check out the mongo hosting center for more info Hope this helps A: You could use either MongoDB or MySQL for what you are wanting. The main thing to be aware of is scaling. In MySQL you scale vertically. You get a bigger machine, a better machine. And hope it makes a difference. In MongoDB you scale horizontally. You have multiple machines and shard. Scaling vertically has a limit. But scaling horizontally does not. In terms of cost scaling vertically is easy to understand. Scaling horizontally usually results in buying a cluster of machines, and then when you want to scale further it becomes exponential. So it's something you have to consider. Doing statistical queries is a downside of MongoDB. For a few reasons. First of all there will be features of MySQL you just won't have in MongoDB. Secondly, for anyone who is more of a DB person and is super-familiar with SQL statements they may have a really hard time adjusting to the syntax of MongoDB. It's something new to learn. And people often like (and work well with) what they know. Like most other 'NoSQL' platforms MongoDB does not employ ACID, which gives it a bit of a performance boost. But that does mean that it may be riskier. There are some cloud-based solutions. Take a look at MongoHQ and MongoLab. I may be wrong, but I don't believe they have SSD. It's all spindles. But ping their support. They usually reply fast. In my experience MongoDB does go fast. Very fast. MySQL is slow when you have large tables, joins, etc. And you can index in MongoDB, as you would expect. I've seen that if you index too many things, or things like arrays where it must index each element, then it can be more taxing per transaction. I would not push you in either direction. It's something that takes some research. I wouldn't say using MongoDB is a bad idea for such a large project, but it would take time to figure out if it works for your situation. As with all things. There are some alternatives, specifically proprietary extensions to MySQL that can give you a big performance boost (depending on your setup, average type of transactions, etc). One that comes to mind is InfoBright, but these are often costly. A: Here's some information on MongoDB in the cloud: http://www.mongodb.org/display/DOCS/Hosting+Center
{ "language": "en", "url": "https://stackoverflow.com/questions/7535522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: get certain data from pages using crawler I am looking to use a crawler to fetch data from a site, I found How do I make a simple crawler in PHP? and it was helpfull but I am looking to use the code on http://findpeopleonplus.com/ to get all the google plus links from the pages. I will paste the code here for reference : $seen[$url] = true; $dom = new DOMDocument('1.0'); @$dom->loadHTMLFile($url); $anchors = $dom->getElementsByTagName('a'); foreach ($anchors as $element) { $href = $element->getAttribute('href'); if (0 !== strpos($href, 'http')) { $path = '/' . ltrim($href, '/'); if (extension_loaded('http')) { $href = http_build_url($url, array('path' => $path)); } else { $parts = parse_url($url); $href = $parts['scheme'] . '://'; if (isset($parts['user']) && isset($parts['pass'])) { $href .= $parts['user'] . ':' . $parts['pass'] . '@'; } $href .= $parts['host']; if (isset($parts['port'])) { $href .= ':' . $parts['port']; } $href .= $path; } } crawl_page($href, $depth - 1); } echo "URL:",$url,PHP_EOL,"CONTENT:",PHP_EOL,$dom->saveHTML(),PHP_EOL,PHP_EOL; } crawl_page("http://hobodave.com", 2);
{ "language": "en", "url": "https://stackoverflow.com/questions/7535523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Limiting query_posts in Wordpress, but still having pagination I really hope someone can help me. Basically I have a Wordpress site I am using as an affiliate site. I have about 1/2 million posts, which are essentially the products. The site is running fine, except for on the category pages where there are more than 5,000 posts. If someone was searching for a product they probaby wouldn't go past page 10 in the search results, so What I'd like to do is limit the query_posts results returned to 500 posts. But still have 25 posts per page. Does anyone know if this possible? A: you mean this code <?php $args = array( 'numberposts' => 10, 'order'=> 'ASC', 'orderby' => 'title' ); $postslist = get_posts( $args ); foreach ($postslist as $post) : setup_postdata($post); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7535526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with removing element I don't know why this working: $('.deleteQuestion').live('click', function(){ $.ajax({ type: 'GET', url: '/delete_question/' + $(this).attr('name') + '/', success: $('[what="question"][name="' + $(this).attr('name') + '"]').remove() }); }); but this not working: $('.deleteQuestion').live('click', function(){ $.ajax({ type: 'GET', url: '/delete_question/' + $(this).attr('name') + '/', success: function(){$('[what="question"][name="' + $(this).attr('name') + '"]').remove();} } }); }); Does someone know? A: The success callback doesn't operate on the same this that the click handler does. Save it in a variable: $('.deleteQuestion').live('click', function(){ var element = $(this); $.ajax({ type: 'GET', url: '/delete_question/' + $(this).attr('name') + '/', success: function(){ //this has to be a function, not a jQuery chain. $('[what="question"][name="' + element.attr('name') + '"]').remove();} } }); }); A: In the first version $(this).attr('name') is evaluated right away. In the second version this is not pointing to the current element since it only gets evaluated when the callback function executes, which is in a different context - so it won't work correctly. A: I think in this instance neither are working as you intend. In the first version, you have the following: success: $('[what="question"][name="' + $(this).attr('name') + '"]').remove() This is executed as soon as the line is reached and not on the success callback. In the 2nd version, you lose the context of this in your callback: success: function(){$('[what="question"][name="' + $(this).attr('name') + '"]').remove();} Also, it looks like you have an additional end brace. remove();} } Try the following: $('.deleteQuestion').live('click', function(){ var self = this; $.ajax({ type: 'GET', url: '/delete_question/' + $(this).attr('name') + '/', success: function(){$('[what="question"][name="' + $(self).attr('name') + '"]').remove();} }); }); A: this is not pointing to what you what in the success function. Try this instead: $('.deleteQuestion').live('click', function() { var that = this; $.ajax({ type: 'GET', url: '/delete_question/' + $(this).attr('name') + '/', success: function() { $('[what="question"][name="' + $(that).attr('name') + '"]').remove(); } }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7535529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: can browsers select scripts based on user's viewing resolution? I want to implement a JQuery script that requires the browser's width at 100% which depends solely on the user's viewing resolution. Can i prepare multiple scripts for the different resolutions for the browser to automatically detect and choose or does there need to be a single script with if/then clauses? A: Apparently the can via Javascript using screen.width and screen.height. A: While I don't know what exactly you are trying to implement, you might want to look into CSS media queries as an interesting approach to adaptive Layouts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535530", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems with BinaryFormatter on class with DataContract? I have a class [DataContract] public class Car { public bool pbIsHatchBack; string prSt = "royi"; } And i want to serialize it with BinaryFormatter: BinaryFormatter binFormat = new BinaryFormatter(); Stream fStream = new FileStream("c:\\CarData.dat", FileMode.Create, FileAccess.Write, FileShare.None); binFormat.Serialize(fStream, carObj); fStream.Close(); But u get this error Type 'SerializationTypes+Car' in Assembly 'ConsoleApplication2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable. If i remove the [DataContract] and replace it with [Serializable] its ok. but why ? how WCF does it behind the scene (when tcpBinding ?)? Why can't i use the DataContract ??? A: WCF does not use the BinaryFormatter to serialize its objects, it uses either the DataContractSerializer (by default) or some of its other serializers (XmlSerializer, DataContractJsonSerializer, etc). BinaryFormatter was released before WCF (in .NET Framework 1.0, IIRC) so is not aware of the [DataContract]/[DataMember] attributes (which were released in .NET Framework 3.0, along with WCF. On netTcpBinding WCF still uses the DataContractSerializer, but instead of using a "normal" XML reader/writer, it uses a binary-aware XML reader/writer, which is how we have the binary encoding in WCF. The WCF serializers understand the [Serializable] attribute, so you can use it with WCF as well. Or you can also use both attributes, if you want your type to be serializable by the BinaryFormatter but use the more fine-grained control that the [DC]/[DM] attributes give you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL time difference within single table I have a single MySQL table with login data of users. user | date | type -----+---------------------+------ 1 | 2011-01-05 08:00:00 | login 1 | 2011-01-06 09:00:00 | login 1 | 2011-01-06 10:00:00 | logout 1 | 2011-01-06 09:50:00 | login Given the above table I would like to calculate the time difference between the logout date and the previous login date by adding a new cell called duration. E.g. the logout date was '2011-01-06 10:00:00; and the previous login date would be '2011-01-06 09:50:00'. The result should look somehow like this. Rows with type=login should not have a duration value. user | date | type | duration -----+---------------------+--------+---------- 1 | 2011-01-05 08:00:00 | login | - 1 | 2011-01-06 09:00:00 | login | - 1 | 2011-01-06 10:00:00 | logout | 10min 1 | 2011-01-06 09:50:00 | login | - Thanks in advance, mawo A: SELECT x.*, TIMEDIFF(x.logout_date, x.login_date) as duration FROM ( SELECT a.user_id, a.`date` as logout_date, (SELECT MAX(b.`date`) FROM table1 b WHERE b.`date` <a.`date` and b.user=a.user and b.type = 'login') as login_date FROM table1 a WHERE a.type ='logout' )x
{ "language": "en", "url": "https://stackoverflow.com/questions/7535533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mysql keeps entering blank fields, can anyone help me fix this? I'm trying to learn php and mysql and its been going good but I'm trying to use the $_POST method to insert something to a database from another page, and when I check the database to see if it worked it creates another row but with no information. First page <html> <body> <form action="InsertExternal.php" method=post> First Name: <input type="text" name="firstname" /> Last Name: <input type="text" name="lastname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> Second page <?php $con = mysql_connect("localhost","root","root"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("Learning", $con); $sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?> Thanks for any help. I imagine its something simple I'm missing. A: Make sure you are not contacting this page directly. In this case before doing the actual insert check if there are values in the fields: if(isset($_POST['firstname']) && isset($_POST['lastname']) && .. Second thing, You must sanitize your input before inserting into the database: use: $firstname = mysql_real_esacpe_string($_POST['firstname']); You can also use or with in the statement: mysql_query($q) or die(mysql_error()); A: You are never checking if the form was submitted on the second page, nothing "huge" but it could just be that a refresh is occuring and empty data is going in. Second, you will should really change the insert portion up so you do not get a ton of "Undefined Constant notices" from not surrounding the associative indexed $_POST array with single quotes. <?php if (empty($_POST['age'])) { echo "Sorry, you appear to have omitted a few items. Try again!"; exit; } $con = mysql_connect("localhost","root","root"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("Learning", $con); $sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('{$_POST['firstname']}','{$_POST['lastname']}','{$_POST['age']}')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?> There is also the obvious worry of SQL Injection, if you plan on really wanting to use MySQL that is a topic you should read up on and learn the proper methods to prevent it. A: <?php $con = mysql_connect("localhost","root","root"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("Learning", $con); $sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('" . $_POST["firstname"] . "','" . $_POST["lastname"] . "','" . $_POST["age"] . "')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?> Didnt quote the globals properly
{ "language": "en", "url": "https://stackoverflow.com/questions/7535535", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to fold left a list of BigDecimal? ("overloaded method + cannot be applied") I want to write a short functional sum-function for a List of BigDecimal and tried with: def sum(xs: List[BigDecimal]): BigDecimal = (0 /: xs) (_ + _) But I got this error message: <console>:7: error: overloaded method value + with alternatives: (x: Int)Int <and> (x: Char)Int <and> (x: Short)Int <and> (x: Byte)Int cannot be applied to (BigDecimal) def sum(xs: List[BigDecimal]): BigDecimal = (0 /: xs) (_ + _) ^ If I use Int instead, that function works. I guess this is because BigDecimal's operator overloading of +. What is a good workaround for BigDecimal? A: foldLeft requires an initialization value. def foldLeft[B](z: B)(f: (B, A) ⇒ B): B This initialization value (named z) has to be of the same type as the type to fold over: (BigDecimal(0) /: xs) { (sum: BigDecimal, x: BigDecimal) => sum+x } // with syntax sugar (BigDecimal(0) /: xs) { _+_ } If you add an Int as initialization value the foldLeft will look like: (0 /: xs) { (sum: Int, x: BigDecimal) => sum+x } // error: not possible to add a BigDecimal to Int A: In a situation like this (where the accumulator has the same type as the items in the list) you can start the fold by adding the first and second items in the list—i.e., you don't necessarily need a starting value. Scala's reduce provides this kind of fold: def sum(xs: List[BigDecimal]) = xs.reduce(_ + _) There are also reduceLeft and reduceRight versions if your operation isn't associative. A: The problem is in inital value. The solution is here and is quite simple: sum(xs: List[BigDecimal]): BigDecimal = (BigDecimal(0) /: xs) (_ + _) A: As others have already said, you got an error because of initial value, so correct way is to wrap it in BigDecimal. In addition, if you have number of such functions and don't want to write BigDecimal(value) everywhere, you can create implicit convert function like this: implicit def intToBigDecimal(value: Int) = BigDecimal(value) and next time Scala will silently convert all your Ints (including constants) to BigDecimal. In fact, most programming languages use silent conversions from integers to decimal or even from decimals to fractions (e.g. Lisps), so it seems to be very logical move.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535536", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What version of Visual studio 11 is bundled with Windows 8 Developer Preview? is the version of Visual studio 11 bundled with Windows 8 Developer preview the same as the version available as standalone download from Microsoft site ? cause i have noticed the one bundled with windows 8 only have metro-style/Grid Projects.. A: The version included with the Windows 8 Developer Preview is the Express Edition. The version available for download is different - I am guessing from the file names and description that it is the VS Ultimate edition. Here's an MSDN blog post announcing the VS 11 Developer Preview, with additional information links.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: The container "…" must contain only one certificate and its private key I am unable to install a mobile provisioning certificate on iOS 5 because I get this error: The container "…" must contain only one certificate and its private key. I used the same process that worked in the past but on iOS 5 it doesn't work and I have no idea how to export my certificate in a "desirable" state. A: I was able to fix this by exporting the private key from the "Certificates" Category of Keychain, rather than exporting the Key directly. So export the NAME of the cert, not the private key itself, and you should be good to go. A: I think a more specific answer is that you... * *open up Keychain app *(I am assuming you already have the key pair of your Identity in a keychain ) *Like @Brent Shaffer says, choosing from "Certificates" is more straight forward (The reason being is that the Keychain App logically groups the Certificate and private key for identities when using the "Certificates" view) *SHIFT-select both your SMIME certificate and its corresponding private key *right-click the selection and choose 'Export 2 Items' *Save as a (.p12) file with a very strong password *email the .p12 file to your email account *And from your iphone Mail app you can tap the .p12 file *and Mail will suggest to import this as a Profile. You will need the password from earlier.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Check for Event Daily, and Send Notification Messages What is the best way to set up a system that checks for events daily and sends messages via email, Twitter, SMS, and possibly Facebook? Keep in mind, that I do not have access to a web server with root access (Using Rackspace Cloud). Would PHP have a solution for this? Would there be any drawbacks to using Google App Engine and Python? A: If you are using Google App Engine with Python you could use "Cron" to schedule a task to automatically run each day. GAE also allows you to send emails, just a little tip: make sure that you 'invite' the email address used to send mail to the application as an administrator so that you can programatically send emails etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Template type constructor parameters Given a template class: template<class T> class Foo { public: void FunctionThatCreatesT() { _object = new T; } private: shared_ptr<T> _object; } Is it possible to somehow pass a set of constructor parameters for T to Foo (perhaps when Foo is constructed) such that Foo can use them when it creates T? A C++11 only solution is fine (so, variadics are on the table for example). A: Exactly that, variadic templates and perfect forwarding via std::forward. #include <memory> #include <utility> template<class T> class Foo { public: template<class... Args> void FunctionThatCreatesT(Args&&... args) { _object = new T(std::forward<Args>(args)...); } private: std::shared_ptr<T> _object; } For a listing of how this works, see this excellent answer. You can emulate a limited version of this in C++03 with many overloaded functions, but.. it's a PITA. Also, this is only from memory, so no testing done. Might contain an off-by-one error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Shared DataSource between combobox and textbox I have this three controls: ComboBox: list of myobject TextBox: view a description DataSource: list(of MyObject) MyObject: * *property id as int *property combodesctription as string *property description as string I want to select an element on the combobox and see the selected object description into the TextBox. How can I do that ? A: //On Combobox Selected Index Change textbox1.text = Combobox1.Items(1).ToString() A: You can handle ComboBox1's SelectedIndexChanged event. If Not IsNothing(ComboBox1.SelectedItem) Then Dim obj As MyObject = CType(ComboBox1.SelectedItem, MyObject) TextBox1.Text = obj.Description End If
{ "language": "en", "url": "https://stackoverflow.com/questions/7535547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: development with git and php (web development) I'm struggling with the best approach to test php development code which is dependent on certain framework files to be present. I think there are three possible scenario's with git: * *Create a copy of the live production directory and clone this 'dev' directory to the local workstation. The next step would be to edit code on the local workstation and commit/push every change. You can check your work via the 'dev' url on the production server. If everything is alright you can push the changes to the 'live' directory. This approach may result in a lot of commits as you are editing/fixing your code (syntax errors or other obvious mistakes) and it adds an extra step (commit/push) to see your result. *Create a 'dev' server which mirrors the production server. This server will contain all the framework files and you'll be able to edit a copy of the 'live' directory directly and immediately see your changes. If you prefer you can mount the remote 'dev' directory to your local workstation. This requires an extra server which needs to be maintained and you would need the resources to set it up. *Create a local 'dev' workstation environment and clone the repository on the 'live' or 'dev' server. This way you'll be able to test all the code on your local machine and only push out the commits which have been tested and approved. This reduces the number of commits as opposed to method one. To recreate the 'dev' environment locally you might have to install a lot framework/dependent files to your local workstation and even then it might not be 100% reliable when the code is ported to the actual live server. Basically I want to find the best method for the 'write-test-revise-test-revise-test-commit' cycle if you are dependent on framework files (whatever framework that may be). Would you create a 'dev' server or would you recreate the exact production environment on your local workstation? Ideally you would only commit the code when you have done some initial testing (obvious syntax errors etc.). A 'dev' server with local git repo would require that you commit every little change to test your work which may be tedious.... I hope I have made myself clear. I'm looking for the best way to integrate git and the 'write-test-commit' cycle. Normally you would test on the local machine but with web development you may need a webserver + framework to be able to test your code. Editing directly on the 'live' server is what I want to avoid. Thanks for your input! A: Call me opinionated, but every developer should have a local development AMP stack which they can develop against. If you don't know how to set up an exact mirror of your production server, solve that problem first. Once you're there, it should be trivial to have each developer set up a virtual machine with a clean OS install, configure web/php/db servers and libraries/framewroks to match the production environment, check out your project, and get to work. Developers commit against personal branches in their own local repos as they go, and after local testing, ship their code (via either a push, or a pull request, or whatever). The exact rules about how to merge changes into master depend on your team an preferences. But developers should almost always have a complete local dev environment. If it seems like it's hard to set one up, that's a big problem. Figure out how to make it easy and then document it. A: There are definitely many ways to do this, but here is my 2 cents from how I have been working lately. First off, I would probably avoid a dev server per se, because if you have more than 1 developer, each developer may try to update the dev server with conflicting code, or if they are working on similar areas, overwrite some of your test code since you both probably are working from the same branch but have both modified the code and not yet pushed the changes. That said, you may want a dev server that closely resembles your live server so that after you and some of your other developers have made a number of changes, you can test them on the dev server before updating the code on the live server. In my environment, I develop on Linux and have Apache/PHP running the same versions and configs as the live server. This way, I clone my git repo, have my environment set up so that my document root is the "public" directory of my git repo (e.g. htdocs). In this case, we have a dev MySQL server which is usually shared, and not on the local machine, but you can do whatever is easiest there. Our system depends on constantly updated data from the field so this is why the shared database, we have a system which adds a lot of this necessary "test" data automatically to the database. This way, I can pull the latest code from git, work on it all I want, work-break-fix-work-work-work etc etc and when I have completed my task, I can push the changes back to git for other developers. When you are ready for a release, you can do all of your testing and stuff on the dev server, verify it is good to go and then push to the live. In my case for updating the "live" server, one person is responsible for that, and I use rsync to sync my local working directory to the live server. So when I am absolutely sure we are ready to deploy, I pull the most recent code from git, and run my script which rsyncs my git directory to the server. I'd avoid your methods 1 & 2, and go with something like 3. That will probably be the sanest thing for you to do and easiest to manage. Depending on what your team is like, you could create a dev VM that is pre-built with all the dependencies, correct software, and development tools you are all using, or leave it up to the developer to set themselves up. So far this method has worked pretty well for me and the others on my team.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Printing control with C when i execute the below code, the compiler returns the message "(.text+0x31): undefined reference to 'sqrt'". but if i take away the q* the compiler correctly gives me 8.000000 i'm trying to get the program to multiply the INCREMENT by 1 (and eventually 2 and 3 when i write the loop in). how come the below doesn't work? #include <stdio.h> #include <math.h> #define INCREMENT 64 int main () { int q = 1; printf("%f", sqrt(q*INCREMENT)); return 0; } A: You probably need to link to the math library. (though I thought visual C++ does this automatically...) The reason why it works without the q is because the compiler is optimizing out the sqrt since it's a constant. A: The code is correct c code. I tested it under vs 2010 and it returned the value 8. However it is not correct c++ code. sqrt becomes ambigueous when the argument is an integer. Is it possible that your source file has a .cpp extension, instead of a .c extension?
{ "language": "en", "url": "https://stackoverflow.com/questions/7535550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I use git to track SRPM customizations? Our team frequently performs customization to various packages distributed with RHEL/CentOS. Our workflow involves installing the SRPM, executing rpmbuild -bp to unpack and patch the source, making our changes and creating a .patch to be included in the specfile, and building the new customized SRPM for later use with mock: $ rpm -i grub-0.97-13.5.1.src.rpm $ rpmbuild -bp rpmbuild/SPECS/grub.spec $ cp -a rpmbuild/BUILD/grub-0.97 grub-0.97.orig $ cd rpmbuild/BUILD/grub-0.97 # Make modifications, generate .patch against ".orig" copy $ vim rpmbuild/SPECS/grub.spec # Add custom .patch to specfile, update version, etc $ rpmbuild -bs rpmbuild/SPECS/grub.spec $ mock -r default-x86_64.cfg rpmbuild/SRPMS/grub-0.97-13.5.1.custom-1.src.rpm This process works well but we are not currently using any form of source control to keep track of our modifications and specfile changes. Based on my (admittedly basic) understanding of git, I think it should be possible to inject it into this workflow and leverage some of its power to optimize a few of the steps (in addition to the normal benefits of SCM). For example, rather than creating a copy of the source to diff against later we could create an initial commit of the upstream patched source and then make our modifications. When ready, use git format-patch to create our feature patch and add it to the specfile. I would also like to version control the specfiles as well, though I'm not sure how best to achieve that. So my question is threefold: * *Does anyone out there use SCM when customizing upstream packages? *What is the most effective way to integrate git into our workflow? *Is there a better workflow that is more conducive to version-controlled custom RPM authoring? Extra credit: Assuming a git-based workflow, how would I structure a central repository to accept pushes? One repo with submodules? One repo per package? A: Does anyone out there use SCM when customizing upstream packages? Sure. This is pretty common. What is the most effective way to integrate git into our workflow? Is there a better workflow that is more conducive to version-controlled custom RPM authoring? I don't know about most effective, but here's what I do. I start with the following ~/.rpmmacros file: %_topdir %(echo ${RPM_TOPDIR:-$HOME/redhat}) %_specdir %{_topdir}/PACKAGES/%{name}/%{version} %_sourcedir %{_topdir}/PACKAGES/%{name}/%{version}/sources %_rpmdir %{_topdir}/PACKAGES/%{name}/%{version}/rpms If I install a package (say, foo-1.0-1.src.rpm), the spec file ends up in ~/redhat/PACKAGES/foo/1.0/foo.spec, and the source tarball (and any patches) end up in ~/redhat/PACKAGES/foo/1.0/sources. Now I initialize the package directory as a git repository: cd ~/redhat/PACKAGES/foo/1.0 git init git add foo.spec sources/*.patch git ci -m 'initial commit' There's nothing special about recording changes to the spec file: git ci -m 'made some really spiffy changes' foo.spec If I need to make changes to package source files, I do this: rpmbuild -bp foo.spec And now I create a temporary git repository: cd ~/redhat/BUILD/foo-1.0 git init git add . git ci -m 'initial commit' git tag upstream From this point on, if I make any changes I can generate patches against the upstream package like this: git diff upstream Or if I've made a series of commits, I can use git's format-patch command to create a series of patches: $ git format-patch upstream 0001-added-text.patch 0002-very-important-fix.patch And these can be copied into the appropriate sources directory and added to the spec file. Note that the temporary git repository I've created for tracking changes in the build directory will be obliterated next time I run rpmbuild.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: What is the IP address of the Facebook server that sends me app deauthorization callbacks? I would like to whitelist the IP addresses of the Facebook servers that sends me a callback whenever a user deauthorizes my App. Which IP addresses should I whitelist? A: You can check Facebook's IPs with: whois -h whois.radb.net "!gAS32934" Documented at https://developers.facebook.com/docs/ApplicationSecurity/ A: Many people have asked, but Facebook does not publish their IP addresses, and they change over time from what I've seen. A: I think you'll find it easier to use domain rather than ip. A: From what I know, Facebook, Inc. owns the following subnets: 31.13.24.0/21 31.13.64.0/19 31.13.69.0/24 31.13.72.0/24 31.13.73.0/24 31.13.75.0/24 31.13.76.0/24 31.13.77.0/24 66.220.144.0/21 66.220.152.0/21 69.63.176.0/21 69.63.176.0/24 69.63.184.0/21 69.171.224.0/20 69.171.239.0/24 69.171.240.0/20 69.171.255.0/24 74.119.76.0/22 103.4.96.0/22 173.252.64.0/19 173.252.70.0/24 204.15.20.0/22 A: You really should use DNS when ever possible. The correct "host name" will generally get you where you expect to be regardless of what IP is being used today. A: To find the current list of IPs use: whois -h whois.radb.net -- '-i origin AS32934' | grep ^route
{ "language": "en", "url": "https://stackoverflow.com/questions/7535553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any IDE capable of Rename refactoring namespaces in PHP? Do you know any PHP IDE capable of rename classes and namespaces, and refactor the code (all files) properly? A: Same as the suggestion made by @BetaRide. I use PHPStorm: http://www.jetbrains.com/phpstorm/ and its probably one of the best IDE's I have used. Check it out A: Have you tried Zend Studio? It's not free, but it will refactor/rename across files in a project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to find a index from a two dimensional array What I'm trying to do is print the largest number within a two dimensional array and it's index location. I'm able to find the largest number, but I can't seem to figure out how to print it's index location. Anyway, here's what I have so far: public static void main(String[] args) { int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}}; double max = arr[0][0]; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { if (arr[i][j] > max) { max = arr[i][j]; } } } System.out.println(max); System.out.println(i + j); //No idea what I should be doing here, just trying out everything I can think of A: Right now, you should consistently get 2 * arr.length as the final value. That isn't what you are probably looking for. It looks like you want to know the coordinates for the max value. To do this, you'll need to cache the values of the indexes and then use them later: public static void main(String[] args) { int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}}; int tmpI = 0; int tmpJ = 0; double max = arr[0][0]; // there are some changes here. in addition to the caching for (int i = 0; i < arr.length; i++) { int[] inner = arr[i]; // caches inner variable so that it does not have to be looked up // as often, and it also tests based on the inner loop's length in // case the inner loop has a different length from the outer loop. for (int j = 0; j < inner.length; j++) { if (inner[j] > max) { max = inner[j]; // store the coordinates of max tmpI = i; tmpJ = j; } } } System.out.println(max); // convert to string before outputting: System.out.println("The (x,y) is: ("+tmpI+","+tmpJ+")"); A: Be careful with your array dimensions! The second for-statement most of you have is wrong. It should go to up to arr[i].length: for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { if (arr[i][j] > max) { max = arr[i][j]; tmpI = i; tmpJ = j; } } } A: Store i, j whenever you update max. A: You've got a two-dimensional array, therefore you need to know both indexes. Adding them together won't do because you lose which-is-which. How about this: System.out.println("[" + i + "][" + j + "]"); A: This would be if you wanted a single index into a flatten array: public static void main (String[] args) throws java.lang.Exception { int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}}; int[] flattened = new int[6*3]; // based off above int maxIndex = 0; double max = arr[0][0]; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { flattened[i + j] = arr[i][j]; if (arr[i][j] > max) { max = arr[i][j]; maxIndex = i+j; } } } System.out.println(max); System.out.println(flattened [maxIndex]); } A: int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}}; int max = arr[0][0]; int maxI = 0, maxJ = 0; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { if (arr[i][j] > max) { max = arr[i][j]; maxI = i; maxJ = j; } } } System.out.println(max); System.out.println(maxI + "," + maxJ); A: //C++ code #include<iostream> #include<vector> #include<algorithm> using namespace std; vector<int> b; vector<int> c; int Func(int a[][10],int n) { int max; max=a[0][0]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(a[i][j]>max) { max=a[i][j]; b.push_back(i); c.push_back(j); } } } b.push_back(0); c.push_back(0); return max; } void display(int a[][10],int n) { for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cout<<a[i][j]<<"\t"; } cout<<endl; } } int main() { int a[10][10],n; cin>>n; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cin>>a[i][j]; } } cout<<endl; display(a,n); cout<<endl; cout<<Func(a,n)<<" is the greatest "<<endl; if(b.size()==1&&c.size()==1) { cout<<"Location is (1,1)"<<endl; } else { b.erase(b.end() - 1); c.erase(c.end() - 1); cout<<"Location is "<<"("<<b.back()+1<<","<<c.back()+1<<")"<<endl; } return 0; } A: You're just adding the indices i and j together and then printing it to the screen. Since you're running throug the entire loop it's just going to be equal to 2*arr.length-2. What you need to do is store the values of i and j when you encounter a new max value. For example: int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}}; int max = arr[0][0]; //dunno why you made it double when you're dealing with integers int max_row=0; int max_column=0; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length; j++) { if (arr[i][j] > max) { max = arr[i][j]; max_row=i; max_column=j; } } System.out.println("The max is: "+max+" at index ["+max_row+"]["+max_column+"]"); A: Don't sure that you implement effective algorithm, but why you just don't save indices i,j in another variables when you set max. This is very simple. if (arr[i][j] > max) { max = arr[i][j]; maxX = i; maxY = j; } FYI If you want look at "insertion sorting" algorithms if you want better implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Web deployment stops at first dll I am trying to deploy a webapp to a win2003/iis6 server using msbuild and msdeploy, but the process halts at the end of transferring the first dll, returning this message: Web deployment task failed. (Unable to write data to the transport connection: ... This message is followed with the message that the remote server closed the connection (in Dutch). The folder structure is created, config and aspx files as well. I am using these MSBuild options: /p:DeployOnBuild=True /p:DeployTarget=MsDeployPublish /p:CreatePackageOnPublish=True /p:MSDeployPublishMethod=RemoteAgent /p:MSDeployServiceUrl=remote-server /p:DeployIisAppPath="Site/app" /p:UserName=user /p:Password=myPassword Where do I start digging? Regards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535557", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to display different iframe app for fans and non-fans? How can U display different iframe app for fans and non-fans of a page without asking user about permissions like Static Iframe Tab app (http://www.facebook.com/iframehost) is doing? A: Take a look at the data you get from facebook in the so called "signed request". There is a flag included that fits your needs (true if the user has liked the page, otherwise false). A: here's the code for that signed request check: $signed_request = $_REQUEST['signed_request']; function parsePageSignedRequest(){ if (isset($_REQUEST['signed_request'])){ $encoded_sig = null;$payload = null; list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2); $sig = base64_decode(strtr($encoded_sig, '-_', '+/')); $data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true)); return $data; } return false; } if($signed_request = parsePageSignedRequest()){ if($signed_request->page->liked) { // put your "Liked Page Content Here" } else { // put your "Alternate" Page Content Here. } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you GoTo a line label in a different object? E.g. Given Sheet 1 contains: Ref: Do things How can I direct a code in Module 1 to GoTo Ref? If I were in the Sheet1 code moduke then I could simply use a Goto Ref But this doesn't work across different modules A: Your question is not clear and you didn't provide any code, so this is a guess. GoTo is used to jump to different locations within the same sub/function. You cannot use it to jump to parts of other sub routines or functions, which it sounds like you might be trying to do. Also, "NapDone:" is not called a reference, it's formally called a line label. :) A: To help expand on the other answers.. Like they said you shouldn't use GoTo for anything in VBA except error handling. What you should be doing is calling a public sub/function from another module. For example in Module 1 you would have the following Sub TestMod1() Dim MyNumber As Integer MyNumber = GetSquare(6) 'MyNumber returns from the function with a value of 36 End Sub and on Module 2 you have Public Function GetSquare(ByVal MyNumber As Integer) GetSquare = MyNumber * MyNumber End Function So now you know how to avoid it. GoTo is not very good programming practice as you'll have things flying all over the place. Try to break down code you're repeating into multiple Subs and just call them when needed, or functions whatever be the case. Then you'll get into classes, which are just wrapped up to represent an object and it'll do all the work for that object. This should get you on the right track.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: To check declaration of a variable before compilation I code in C/C++ and use vim for editing. I have found that most of times after completing my code when I compile, I get undeclared variables error. These are variables which I forgot to declare before using them. I want to know is there any utility with vim which I can use for testing if all variables in new code are declared before use. It will save my considerable compile time. Thanks, A: The clang-complete plugin can do this. Have a look at its clang_complete-copen and clang_complete-periodic_quickfix configuration variables to enable the checks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RewriteRule to accept 2 parameters mydomain.com/MyFolder/parameter-1 I have this htaccess RewriteRule - RewriteRule ^([a-z0-9\-]+)/?$ index.php?c=$1 [NC,L] The .htaccess file is inside MyFolder and this only accept a single parameter. How can do a RewriteRule to accept 2 parameters mydomain.com/MyFolder/parameter-1/parameter-2 Thanks A: use this: RewriteEngine On # mydomain.com/MyFolder/parameter-1 RewriteRule ^([a-z0-9\-]+)/?$ index.php?c=$1 [NC,L] # mydomain.com/MyFolder/parameter-1/parameter-2 RewriteRule ^([a-z0-9\-]+)/([a-z0-9\-]+)/?$ index.php?c=$1&d=$2 [NC,L]
{ "language": "en", "url": "https://stackoverflow.com/questions/7535563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What is an appropriate directory in which to install Android SDK? I don't use java much so what are the common (best practice) locations to install components like this. I want to put them in a system directory so multiple users have access. A: Common locations are /opt, /srv, and /usr/local. I tend to lean toward /usr/local. Note that the Android SDK doesn't really require you to install much, it's mostly self-contained. All you need to do is tell Eclipse where it is. You may also want to add the tools and/or platform-tools directories to the system-wide PATH so that your users can use adb and other tools. See http://developer.android.com/sdk/installing.html. A: On Linux, I typically use /usr/local/android-sdk, but anywhere that makes sense and that won't get clobbered by your system works. Just be aware that it may actually make sense to put the SDK in a per-user location, since it requires write access to create a VM image and to download SDK updates. A: To be more concise and allow user writing for things like sdk installations and etc, you could put it somewhere inside the ~/.local directory as per the XDG file system hierarchy like ~/.local/lib/arch-id/android-sdk Also remember to set the ANDROID_SDK_ROOT env variable to that directory as the ANDROID_HOME variable was deprecated. A: It doesnt matter where you put the sdk. Just put it in any folder where all user's can access it...
{ "language": "en", "url": "https://stackoverflow.com/questions/7535569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: JavaConfig problem in web application (Vaadin + Spring) UPDATED I found an suspicious log entry: org.springframework.beans.factory.wiring.BeanConfigurerSupport: BeanFactory has not been set on BeanConfigurerSupport: Make sure this configurer runs in a Spring container. Unable to configure bean of type [com.mycompany.projectname.App]. Proceeding without injection. /UPDATED I'm working on an Vaadin + Spring application and I wish to use JavaConfig. According to some tutorial I built them up separately, but when I merge them I got the following (see the first codesnipet App.java - logger.info(">>mainWindow is null");) app postconstruct --------- mainWindow is null I tried several variation of configs for example in applicationContext and so forth. So my question is: how can I find out real problem ? Thanks for your time and effort in advance. Csaba App.java @Configurable public class App extends Application { public MainWindow mainWindow; public MainWindow getMainWindow(... public void setMainWindow(Main.... @PostConstruct public void init() { logger.info(">>app postconstruct --------- "); if(mainWindow==null) logger.info(">>mainWindow is null"); else logger.info(">>mainWindow is not null"); } AppConfig.java @Configuration public class AppConfig { ... @Bean public MainWindow mainWindow(){ return new MainWindow(); } .... } web.xml based on this !tutorial link! ... <context-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>com.mycompany.projectname.config.AppConfig</param-value> </context-param> ... <servlet> <servlet-name>Vaadin Application Servlet</servlet-name> <servlet-class>com.vaadin.terminal.gwt.server.ApplicationServlet</servlet-class> <init-param> <description>Vaadin application class to start</description> <param-name>application</param-name> <param-value>com.mycompany.projectname.App</param-value> </init-param> <init-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </init-param> <init-param> <param-name>contextConfigLocation</param-name> <param-value>com.mycompany.projectname.config.AppConfig</param-value> </init-param> </servlet> A: Why are you using @Configurable? Do you mean to be using @Component instead? @Configurable is typically used on domain objects (aka entities) that are not otherwise Spring-managed objects to allow them to receive dependency injection from the Spring container. This does not appear to be your goal. You should probably simply be wiring up your "App" class as another @Bean method, or otherwise marking it with @Component and picking it up via component-scanning (e.g. with @ComponentScan). Check out the related Javadoc and reference documentation for these annotations for more info. A: Your annotations will not work if you didn't enabled them. Do you have the following in your project spring context xml ? <!-- Activate Spring annotation support --> <context:spring-configured/> <!-- Turn on @Autowired, @PostConstruct etc support --> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" /> <!-- Scans the classpath of this application for @Components to deploy as beans --> <context:component-scan base-package="com.tc.poc.vaddinspring" /> Update: Look at this skeleton.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: (#3) User must be on whitelist, music.listens - Open Graph Music i'v set up my Music Application using this. i'm trying to pubish new user action but it wont work i'm getting (#3) User must be on whitelist. this is the code. FB.api('/me/music.listens&song=track-page-url, 'post', function(response) { if(!response || response.error) { console.log(response.error); } else { console.log('success'); } }); i googled the error and found this question but it appears that there is no answer. A: To apply to be whitelisted, follow the instructions in the Open Graph Builtin Actions docs. Hope that helps! A: I'm getting "An unknown error has occurred.". It seems that music.listens only works for a certain set of applications such as MOG, Rdio, Spotify, Slacker Radio, etc. A: Facebook only allows whitelisted partners to take advantage of the Open Graph Music, on Facebook Open Graph Music, the first line: Facebook Open Graph Music is only available to whitelisted partners at this time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rules/guidelines for documenting C# code? I am a relatively new developer and have been assigned the task of documenting code written by an advanced C# developer. My boss told me to look through it, and to document it so that it would be easier to modify and update as needed. My question is: Is there a standard type of Documentation/Comment structure I should follow? My boss made it sound like everyone knew exactly how to document the code to a certain standard so that anyone could understand it. I am also curious if anyone has a good method for figuring out unfamiliar code or function uncertainty. Any help would be greatly appreciated. A: Sounds like you really did end up getting the short straw. Unfortunately I think you've stumbled on one of the more controversial subjects of software development in general. Comments can be seen as extremely helpful where necessary, and unnecessary cruft when used wrongly. You'll have to be careful and decide quite carefully what goes where. As far as commenting practice, it's usually down to the corporation or the developer. A few common rules I like to use are: * *Comment logic that isn't clear (and consider a refactor) *Only Xml-Doc methods / properties that could be questioned (or, if you need to give a more detailed overview) *If your comments exceed the length of the containing method / class, you might want to think about comment verbosity, or even consider a refactor. *Try and imagine a new developer coming across this code. What questions would they ask? It sounds like your boss is referring to commenting logic (most probably so that you can start understanding it) and using xml-doc comments. If you haven't used xml-doc comments before, check out this link which should give you a little guidance on use and where appropriate. If your workloadi s looking a little heavy (ie, lots of code to comment), I have some good news for you - there's an excellent plugin for Visual Studio that may help you out for xml-doc comments. GhostDoc can make xml-doc commenting methods / classes etc much easier (but remember to change the default placeholder text it inserts in there!) Remember, you may want to check with your boss on just what parts of the code he wants documented before you go on a ghostdoc spree. A: It's a bit of a worry that the original programmer didn't bother to do one of the most important parts of his job. However, there are lots of terrible "good" programmers out there, so this isn't really all that unusual. However, getting you to document the code is also a pretty good training mechanism - you have to read and understand the code before you can write down what it does, and as well as gaining knowledge of the systems, you will undoubtedly pick up a few tips and tricks from the good (and bad!) things the other programmer has done. To help get your documentation done quickly and consistently, you might like to try my add-in for Visual Studio, AtomineerUtils Pro Documentation. This will help with the boring grunt work of creating and updating the comments, make sure the comments are fully formed and in sync with the code, and let you concentrate on the code itself. As to working out how the code works... Hopefully the class, method, parameter and variable names will be descriptive. This should give you a pretty good starting point. You can then take one method or class at a time and determine if you believe that the code within it delivers what you think the naming implies. If there are unit tests then these will give a good indication of what the programmer expected the code to do (or handle). Regardless, try to write some (more) unit tests for the code, because thinking of special cases that might break the code, and working out why the code fails some of your tests, will give you a good understanding of what it does and how it does it. Then you can augment the basic documentation you've written with the more useful details (can this parameter be null? what range of values is legal? What will the return value be if you pass in a blank string? etc) This can be daunting, but if you start with the little classes and methods first (e.g. that Name property that just returns a name string) you will gain familiarity with the surrounding code and be able to gradually work your way up to the more complex classes and methods. Once you have basic code documentation written for the classes, you should then be in a position to write external overview documentation that describes how the system as a whole functions. And then you'll be ready to work on that part of the codebase because you'll understand how it all fits together. I'd recommend using XML documentation (see the other answers) as this is immediately picked up by Visual Studio and used for intellisense help. Then anyone writing code that calls your classes will get help in tooltips as they type the code. This is such a major bonus when working with a team or a large codebase, but many companies/programmers just don't realise what they've been missing, banging their (undocumented) rocks together in the dark ages :-) A: The standard seems to be XML Doc (MSDN Technet article here). You can use /// at the beginning of each line of documentation comments. There are standard XML style elements for documenting your code; each should follow the standard <element>Content</element> usage. Here are some of the elements: <c> Used to differentiate code font from normal text <c>class Foo</c> <code> <example> <exception> <para> Used to control formatting of documentation output. <para>The <c>Foo</c> class...</para> <param> <paramref> Used to refer to a previously described <param> If <paramref name="myFoo" /> is <c>null</c> the method will... <remarks> <returns> <see> Creates a cross-ref to another topic. The <see cref="System.String" /><paramref name="someString"/> represents... <summary> A description (summary) of the code you're documenting. A: I suspect your boss is referring to the following XML Documentation Comments. XML Documentation Comments (C# Programming Guide) A: It might be worth asking your boss if he has any examples of code that is already documented so you can see first-hand what he is after. Mark Needham has written a few blog posts about reading/documenting code (see Archive for the ‘Reading Code’ Category. I remember reading Reading Code: Rhino Mocks some time ago that talks about diagramming the code to help keep track of where you are and to 'map out' what's going on. Hope that helps - good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7535584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Dot product between row vectors by MMULT not working in Excel I am using Excel to do some dot product between two row vectors: =MMULT(B1049:M1049, TRANSPOSE(B1050:M1050)) But it does not work, as the cell for the formula shows "#VALUE!". I wonder why? Thanks! Note that all the cells in "B1049:M1049" and "B1050:M1050" are numbers. PS: Is this question more suitable here or Superuser? A: you need to enter MMULT as an array formula, not as a standard formula rather then hit enter when you type the formula in pres ctrl-shift-enter and excel will enter it as an array it will end up looking like {=MMULT(B1049:M1049, TRANSPOSE(B1050:M1050))} (please note you can't enter the {} manually) You may want to look at Excel help which covers this well A: probably simpler, you can just use =SUMPRODUCT(vec1,vec2). This is exactly the Euclidean inner product, without resorting to array formulas.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: replace two newlines to one in shell command line There are lot of questions about replacing multi-newlines to one newline but no one is working for me. I have a file: first line second line MARKER third line MARKER other lines many other lines I need to replace two newlines (if they exist) after MARKER to one newline. A result file should be: first line second line MARKER third line MARKER other lines many other lines I tried sed ':a;N;$!ba;s/MARKER\n\n/MARKER\n/g' Fail. sed is useful for single line replacements but has problems with newlines. It can't find \n\n I tried perl -i -p -e 's/MARKER\n\n/MARKER\n/g' Fail. This solution looks closer, but it seems that regexp didn't reacts to \n\n. Is it possible to replace \n\n only after MARKER and not to replace other \n\n in the file? I am interested in one-line-solution, not scripts. A: Your Perl solution doesn't work because you are search for lines that contain two newlines. There is no such thing. Here's one solution: perl -ne'print if !$m || !/^$/; $m = /MARKER$/;' infile > outfile Or in-place: perl -i~ -ne'print if !$m || !/^$/; $m = /MARKER$/;' file If you're ok with loading the entire file into memory, you can use perl -0777pe's/MARKER\n\n/MARKER\n/g;' infile > outfile or perl -0777pe's/MARKER\n\K\n//g;' infile > outfile As above, you can use -i~ do edit in-place. Remove the ~ if you don't want to make a backup. A: I think you were on the right track. In a multi-line program, you would load the entire file into a single scalar and run this substitution on it: s/MARKER\n\n/MARKER\n/g The trick to getting a one-liner to load a file into a multi-line string is to set $/ in a BEGIN block. This code will get executed once, before the input is read. perl -i -pe 'BEGIN{$/=undef} s/MARKER\n\n/MARKER\n/g' input A: awk: kent$ cat a first line second line MARKER third line MARKER other lines many other lines kent$ awk 'BEGIN{RS="\x034"} {gsub(/MARKER\n\n/,"MARKER\n");printf $0}' a first line second line MARKER third line MARKER other lines many other lines A: See sed one liners. A: awk ' marker { marker = 0; if (/^$/) next } /MARKER/ { marker = 1 } { print } ' A: This can be done in very simple sed. sed '/MARKER$/{n;/./!d}' A: This might work for you: sed '/MARKER/,//{//!d}' Explanation: Deletes all lines between MARKER's preserving the MARKER lines. Or: sed '/MARKER/{n;N;//D}' Explanation: Read the next line after MARKER, then append the line after that. Delete the previous line if the current line is a MARKER line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ActiveRecord OR clause in scoped query statuses = %w(sick healthy hungry) query = User.scoped(:joins => 'left outer join pets on pets.user_id = users.id', :conditions => { 'pets.id' => nil, 'users.job_status' => stati }) Given the code above, is it possible to add an OR clause to the :conditions to say something like where (pets.id is NULL AND users.status IN ('sick', 'healthy', 'hungry')) OR (users.gender = 'male') A: You can do the following using the MetaWhere gem statuses = %w(sick healthy hungry) query = User.include(:pets).where( ('pets.id' => nil, 'users.job_status' => statuses) | ('users.gender' => 'male') ) The | symbol is used for OR condition. PS : The include directive uses LEFT OUTER JOIN so there is no need to hand code the JOIN. A: You could use an SQL condition instead of a Hash condition: query = User.scoped( :joins => 'left outer join pets on pets.user_id = users.id', :conditions => [ '(pets.id is null AND users.status IN (?)) OR (users.gender = ?)', statuses, 'male' ] ) Or: query = User.scoped( :joins => 'left outer join pets on pets.user_id = users.id', :conditions => [ '(pets.id is null AND users.status IN (:statuses)) OR (users.gender = :gender)', { :status => statuses, :gender => 'male' } ] ) The downside is that you have to avoid trying pets.is = NULL by hand.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I enable/disable cells using Vaadin table component? I have a table with 2 columns: a checkbox and a textfield. I want to disable the textfield depending of the respective (same row) checkbox status. If the checkbox is checked then the textfield will be cleared and be read only. Is this possible ? Here is my code: @SuppressWarnings("serial") private Table filtersTable() { final Table table = new Table(); table.setPageLength(10); table.setSelectable(false); table.setImmediate(true); table.setSizeFull(); // table.setMultiSelectMode(MultiSelectMode.SIMPLE) ; table.addContainerProperty("Tipo filtro", CheckBox.class, null); table.addContainerProperty("Valor", String.class, null); table.setEditable(true); for (int i = 0; i < 15; i++) { TextField t = new TextField(); t.setData(i); t.setMaxLength(50); t.setValue("valor " + i); t.setImmediate(true); t.setWidth(30, UNITS_PERCENTAGE); CheckBox c = new CheckBox(" filtro " + i); c.setWidth(30, UNITS_PERCENTAGE); c.setData(i); c.setImmediate(true); c.addListener(new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { // within this, could I access the respective row ID // (i) then enable/disable TextField t on second column ? System.out.println("event.getProperty().getValue()=" + event.getProperty().getValue()); } }); table.addItem(new Object[] { c, t }, i); } return table; } Thanks A: Few changes to your code made it possible. Not the finiest way, but te simpliest. First,you have to set your second column (Valor) to TextField.class not String.class. Here the change : table.addContainerProperty("Valor", TextField.class, null); Instead of keepin the variable i in the CheckBox.setData(), I suggest you to link your checkBox to the TextField of the same row, like this : c.setData(t); Finally I made little change to your listener : c.addListener(new Property.ValueChangeListener() { public void valueChange(ValueChangeEvent event) { CheckBox checkBox = (CheckBox)event.getProperty(); if((Boolean) checkBox.getValue()) { TextField associatedTextField = (TextField)checkBox.getData(); //Do all your stuff with the TextField associatedTextField.setReadOnly(true); } } }); Hope it's work for you! Regards, Éric A: public class MyCheckBox extends CheckBox { private TextBox t; public MyCheckBox(TextBox t) { this.t = t; attachLsnr(); } private void attachLsnr() { addListener(new Property.ValueChangeListener() { public void valueChange(ValueChangeEvent event) { CheckBox checkBox = (CheckBox)event.getProperty(); if((Boolean) checkBox.getValue()) { t.setReadOnly(true); } } }); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Webmatrix 2 Beta and Visual Studio 10 Issue I just downloaded the Webmatrix 2 Prerelease Beta- http://www.microsoft.com/web/gallery/install.aspx?appid=webmatrix&prerelease=true I played around and made a database with some tables. Then I went to open up Visual Studio 2010 and I was prompted to install some missing components. That all went well except when the plaform installer tried to install ASP Razor 2 Syntax for Visual Studio. I get the following error- "The product you are trying to install is not supported on your operating system. Click here for more information." I click, nothing useful comes up. Has anyone seen this and know a solution? Or am I just a little too early and have to wait? Thanks for your time. A: This sounds like a bug in pre-release software. Could you report it here? https://connect.microsoft.com/webmatrix/Feedback
{ "language": "en", "url": "https://stackoverflow.com/questions/7535604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where is your Application Delegate set and who initializes its window and viewController properties? I have a very newbie question about IOS apps... If I create a new View Based Application called TestForStackOverflow, Xcode automatically creates code like this for the TestForStackOverflowAppDelegate.h: @class TestForStackOverflowViewController; @interface TestForStackOverflowAppDelegate : NSObject <UIApplicationDelegate> @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain) IBOutlet TestForStackOverflowViewController *viewController; @end and the following in TestForStackOverflowAppDelegate.m: #import "TestForStackOverflowAppDelegate.h" #import "TestForStackOverflowViewController.h" @implementation TestForStackOverflowAppDelegate @synthesize window = _window; @synthesize viewController = _viewController; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES; } [...] Here come my questions: 1) where is the TestForStackOverflowAppDelegate class set as delegate for the current application? Is it done "automagically"? I've seen that the main.m source file contains only the following code: int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; } Shouldn't it set the application delegate class in the fourth parameter of the UIApplicationMain function invocation? 2) where are the window and viewController properties of TestForStackOverflowAppDelegate class being set? 3) this may be trivial, but why do we have synthesize window = _window, without having an instance variable called _window in TestForStackOverflowAppDelegate interface? I've seen that you can declare @properties without having the corresponding iVars in the class interfaces (maybe they are automatically created by the compiler), but is it a good practice or should you always create the corresponding iVars in your classes? Excuse me for the very long message, I just hope I've not written a too obvious question since here in Italy is late night and I'm very tired.. but when these questions come into my head, I can't wait for the solution :) A: 1) To be simple, when UIApplicationMain() is called, * *you application .plist is found, *the key "Main nib file base name" is looked up, *this XIB is opened, *The object that supports the UIApplicationDelegate protocol is instantiated and used as the application delegate 2) They are set in the XIB, you can view them if you * *open the main XIB, *select the AppDelegate object, *open the Connections inspector for this object, *look into the Outlets section 3) You are right, they are created automatically by the compiler. It makes the code more readable by having less line, and more easy to refactor having only one place the property is declared. Hope it helps! A: How is the app delegate class loaded? In your -info.plist file there is a key named "Main nib file base name" and has a view something like MainWindow.xib. In that xib file, there's a file's owner proxy object and it has a delegate set to the app delegate class. Open that XIB in the designer. Notice the File's Owner object at the top, context click on it and look at the delegate object. Now look at the objects in the design below the (XCode 4) line - you should see the app delegate object there. Where is the window and viewController for the appDelegate set? Look in the designer and context click on the app delegate object below the (XCode 4) line. The window and viewController target is tied there. _window iVar It's automatically provided for you. Not clear to me whether it's inherited or generated by the compiler. Here's more on _ iVars: Why rename synthesized properties in iOS with leading underscores? If you chose to do the equivalent in code: remove plist xib reference main.m: pass name of delegate int main(int argc, char *argv[]) { int retVal = UIApplicationMain(argc, argv, nil, @"HelloViewAppDelegate"); In app delegate: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. CGRect screenBounds = [[UIScreen mainScreen] applicationFrame]; CGRect windowBounds = screenBounds; windowBounds.origin.y = 0.0; // init window [self setWindow: [[UIWindow alloc] initWithFrame:screenBounds]]; // init view controller _mainViewController = [[MainViewController alloc] init]; [[self window] addSubview:[_mainViewController view]]; [self.window makeKeyAndVisible]; return YES; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Do DLL functions run in a new thread automatically? I did some research and I learned that if I run a program my system will automatically start it in a new thread. What does it look like with a DLL? Some pseudo-code from a DLL, extern_func() is exported from the DLL: func1() { while(true) ...do something; } extern_func() { ...do something func1(); ...do something else } Now if call extern_func() in my program, will it run the function in a new thread or do I have to do this explicitly? A: When a program starts, a thread is created. This is usually called the "main" thread. If you don't explicitly create other threads, or use functions that create other threads, all your code will run in that main thread, even if you call functions that come from a DLL/library. A: No, calling a method in another dll will not automatically start up a new thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7535607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: problem with swipe (fling) gesture recognition on ImageView in Android I am trying to work a simple swipe/fling gesture recognizer on an ImageView in my app. However, I dont see anything. Can any one kindly have a look at the code and let me know what am I missing here ? Thanks. Note1: from my debugging, I can see that execution does go inside the GestureListener. However, it gets a return false from there. code: public class ViewSuccess extends Activity { private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private GestureDetector gestureDetector; View.OnTouchListener gestureListener; ImageView movieFrame; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.test); imageLoader=new ImageLoader(getApplicationContext()); movieFrame = (ImageView) findViewById(R.id.widget32); movieFrame.setImageResource(R.drawable.sample); // Gesture detection gestureDetector = new GestureDetector(new MyGestureDetector()); gestureListener = new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (gestureDetector.onTouchEvent(event)) { return true; } return false; } }; movieFrame.setOnTouchListener(gestureListener); class MyGestureDetector extends SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { System.out.println("in gesture recognizer !!!"); try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false; // right to left swipe if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(ViewSuccess.this, "Left Swipe", Toast.LENGTH_SHORT).show(); } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { Toast.makeText(ViewSuccess.this, "Right Swipe", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { // nothing } return false; } } } A: got it working.... we need to add the following method to the class SimpleOnGestureListener @Override public boolean onDown(MotionEvent e) { return true; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7535612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Crystal Reports for VS 2010 or 2008 - ActiveX Control - How to Use? I am trying to use Crystal Reports ActiveX Viewer 13 from within Winforms. While SAP/BO has said they are not going to support this but I see the ActiveX control available on the machine. Any idea on how to use this control? The Problem i'm facing with the the .Net Viewer is that it crashes on Windows7 if the OLEDB provider has any UI like parameters dialog. I posted the issue separately. One of the friend solved this issue by using Cr11R2 ActiveX Viewer. I am trying to find if it is possible to solve the issue by using the ActiveX Viewer that Comes wit CR for VS2010. Any pointers in this direction is appreciated. Found the Answer - The ActiveX control is still available for use with Webprojects. None of the supporting files to run on a Winforms application are avaialble so .. I guess one cannot use this option anymore A: The ActiveX control is still available for use with Webprojects. None of the supporting files to run on a Winforms application are avaialble so .. I guess one cannot use this option anymore
{ "language": "en", "url": "https://stackoverflow.com/questions/7535614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Single vs Multiple Classes Curious what strategy would be considered better: One large class per element that contains everything. vs Multiple smaller classes all containing pieces. A: in general : multiple smaller like " bold red underline dim" cause if tomorrow you want to change the style of red to more red then you do it in one place - the red class but it depends...
{ "language": "en", "url": "https://stackoverflow.com/questions/7535626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }