text
stringlengths
8
267k
meta
dict
Q: Can Datepicker be used as a month Calendar picker? I wonder if it is possible to user Jquery ui datepicker to only show the month/year part and not the days. I know I can get the month and year with changeMonth and changeYear options, but how can I prevent the days from showing at all? A: Try using CSS: .ui-datepicker-calendar { display: none; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: RCP SaveAndRestore does not reopen views I have a RCP application. Its default perspective opens two views on thew left and the bottom, in relation to the editor area. The option SaveAndRestore is set to true. Upon the next startup of the app, both views are closed. Why? What am i doing wrong? A: Well it seems, that i had something wrong with my ids. Recreated some of them and checked them. Now everything is doing fine. A: I assume you closed the views manually. Use the command org.eclipse.ui.window.resetPerspective to reset the perspective to its initial state or use the "Clear" flag for the Workspace in your launch configuration. A: Do you have a saveState(memento) and init(IViewSite site, IMemento memento) implemented for your view?
{ "language": "en", "url": "https://stackoverflow.com/questions/7567788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Change the index number of a dataframe After I'm done with some manipulation in Dataframe, I got a result dataframe. But the index are not listed properly as below. MsgType/Cxr NoOfMsgs AvgElpsdTime(ms) 161 AM 86 30.13 171 CM 1 104 18 CO 27 1244.81 19 US 23 1369.61 20 VK 2 245 21 VS 11 1273.82 112 fqa 78 1752.22 24 SN 78 1752.22 I would like to get the result as like below. MsgType/Cxr NoOfMsgs AvgElpsdTime(ms) 1 AM 86 30.13 2 CM 1 104 3 CO 27 1244.81 4 US 23 1369.61 5 VK 2 245 6 VS 11 1273.82 7 fqa 78 1752.22 8 SN 78 1752.22 Please guide how I can get this ? A: These are the rownames of your dataframe, which by default are 1:nrow(dfr). When you reordered the dataframe, the original rownames are also reordered. To have the rows of the new order listed sequentially, just use: rownames(dfr) <- 1:nrow(dfr) A: Or, simply rownames(df) <- NULL gives what you want. > d <- data.frame(x = LETTERS[1:5], y = letters[1:5])[sample(5, 5), ] > d x y 5 E e 4 D d 3 C c 2 B b 1 A a > rownames(d) <- NULL > d x y 1 E e 2 D d 3 C c 4 B b 5 A a A: The index is actually the data frame row names. To change them, you can do something like: rownames(dd) = 1:dim(dd)[1] or rownames(dd) = 1:nrow(dd) Personally, I never use rownames. In your example, I suspect that you don't need to worry about them either, since you are just renaming them 1 to n. In particular, when you subset your data frame the rownames will again be incorrect. For example, ##Simple data frame R> dd = data.frame(a = rnorm(6)) R> dd$type = c("A", "B") R> rownames(dd) = 1:nrow(dd) R> dd a type 1 2.1434 A 2 -1.1067 B 3 0.7451 A 4 -0.1711 B 5 1.4348 A 6 -1.3777 B ##Basic subsetting R> dd_sub = dd[dd$type=="A",] ##Rownames are "wrong" R> dd_sub a type 1 2.1434 A 3 0.7451 A 5 1.4348 A
{ "language": "en", "url": "https://stackoverflow.com/questions/7567790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: Search for a Wikipedia page based on its NRHP refnum I have an application which maintains a table of places registered in the National Registry of Historic places. I'd like to reliably search for one of these places in Wikipedia, given its NRHP refnum. The search I am currently using now looks like this: http://en.wikipedia.org/w/index.php?title=Special:Search&search=refnum+66000539 (I use Python as my language, but I don't think this is especially relevant here. I construct the url, do a urlfetch, and see what comes back.) But this example, and many others, turn up no results. However, when I go to the Wikipedia page for New York City Hall: http://en.wikipedia.org/wiki/New_York_City_Hall It clearly gives this exact refnum on the page. How can I construct a search, using the refnum, which I already know, so that I can reliably find this page? A: You can use Wikidata for this. The property for NRHP is P649. Since queries are not implemented yet, use a tool on wmflabs. To get what you want, this works: http://wdq.wmflabs.org/api?q=STRING[649:"66000539"] Which returns: {"status":{"error":"OK","items":1,"querytime":"6.354ms","parsed_query":"STRING[649:'66000539']"},"items":[1065206]} The essential part here is "items" which is the ID of the object in Wikidata. Use that to get the link to Wikipedia. If you want the English language version, this works: http://wikidata.org/w/api.php?action=wbgetentities&format=json&ids=Q1065206&props=sitelinks%2Furls&sitefilter=enwiki Which returns: {"entities":{"Q1065206":{"id":"Q1065206","type":"item","sitelinks":{"enwiki":{"site":"enwiki","title":"New York City Hall","url":"//en.wikipedia.org/wiki/New_York_City_Hall","badges":[]}}}},"success":1} .. A: There doesn't seem to be a way to find an article based on the refnum. What you can do is to use the API to get all articles in Category:National Register of Historic Places and for each of them parse the first section to get the renum. Or you could try asking at Wikipedia:WikiProject National Register of Historic Places.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL INSERT with multiple nested SELECTs Is a query like this possible? MySQL gives me an Syntax error. Multiple insert-values with nested selects... INSERT INTO pv_indices_fields (index_id, veld_id) VALUES ('1', SELECT id FROM pv_fields WHERE col1='76' AND col2='val1'), ('1', SELECT id FROM pv_fields WHERE col1='76' AND col2='val2') A: I've just tested the following (which works): insert into test (id1, id2) values (1, (select max(id) from test2)), (2, (select max(id) from test2)); I imagine the problem is that you haven't got ()s around your selects as this query would not work without it. A: When you have a subquery like that, it has to return one column and one row only. If your subqueries do return one row only, then you need parenthesis around them, as @Thor84no noticed. If they return (or could return) more than row, try this instead: INSERT INTO pv_indices_fields (index_id, veld_id) SELECT '1', id FROM pv_fields WHERE col1='76' AND col2 IN ('val1', 'val2') or if your conditions are very different: INSERT INTO pv_indices_fields (index_id, veld_id) ( SELECT '1', id FROM pv_fields WHERE col1='76' AND col2='val1' ) UNION ALL ( SELECT '1', id FROM pv_fields WHERE col1='76' AND col2='val2' )
{ "language": "en", "url": "https://stackoverflow.com/questions/7567802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: SQL IsNumeric not working The reserve column is a varchar, to perform sums on it I want to cast it to a deciaml. But the SQL below gives me an error select cast(Reserve as decimal) from MyReserves Error converting data type varchar to numeric. I added the isnumeric and not null to try and avoid this error but it still persists, any ideas why? select cast(Reserve as decimal) from MyReserves where isnumeric(Reserve ) = 1 and MyReserves is not null A: Gosh, nobody seems to have explained this correctly. SQL is a descriptive language. It does not specify the order of operations. The problem that you are (well, were) having is that the where does not do the filtering before the conversion takes place. Order of operations, though, is guaranteed for a case statement. So, the following will work: select cast(case when isnumeric(Reserve) = 1 then Reserve end as decimal) from MyReserves where isnumeric(Reserve ) = 1 and MyReserves is not null The issue has nothing to do with the particular numeric format you are converting to or with the isnumeric() function. It is simply that the ordering of operations is not guaranteed. A: It seems that isnumeric has some Problems: http://www.sqlhacks.com/Retrieve/Isnumeric-problems (via internet archive) According to that Link you can solve it like that: select cast(Reserve as decimal) from MyReserves where MyReserves is not null and MyReserves * 1 = MyReserves A: Use try_cast (sql 2012) select try_cast(Reserve as decimal) from MyReserves A: IsNumeric is a problem child -- SQL 2012 and later has TRY_CAST and TRY_CONVERT If you're on an earlier version then you can write a function that'll convert to a decimal (or NULL if it won't convert). This uses the XML conversion functions that don't throw errors when the number won't fit ;) -- Create function to convert a varchar to a decimal (returns null if it fails) IF EXISTS( SELECT * FROM sys.objects WHERE object_id = OBJECT_ID( N'[dbo].[ToDecimal]' ) AND type IN( N'FN',N'IF',N'TF',N'FS',N'FT' )) DROP FUNCTION [dbo].[ToDecimal]; GO CREATE FUNCTION ToDecimal ( @Value VARCHAR(MAX) ) RETURNS DECIMAL(18,8) AS BEGIN -- Uses XML/XPath to convert @Value to Decimal because it returns NULL it doesn't cast correctly DECLARE @ValueAsXml XML SELECT @ValueAsXml = Col FROM (SELECT (SELECT @Value as Value FOR XMl RAW, ELEMENTS) AS Col) AS test DECLARE @Result DECIMAL(38,10) -- XML/XPath will return NULL if the VARCHAR can't be converted to a DECIMAL(38,10) SET @Result = @ValueAsXml.value('(/row/Value)[1] cast as xs:decimal?', 'DECIMAL(38,10)') RETURN CASE -- Check if the number is within the range for a DECIMAL(18,8) WHEN @Result >= -999999999999999999.99999999 AND @Result <= 999999999999999999.99999999 THEN CONVERT(DECIMAL(18,8),@Result) ELSE NULL END END Then just change your query to: select dbo.ToDecimal(Reserve) from MyReserves A: See here: CAST and IsNumeric Try this: WHERE IsNumeric(Reserve + '.0e0') = 1 AND reserve IS NOT NULL UPDATE Default of decimal is (18,0), so declare @i nvarchar(100)='12121212121211212122121'--length is>18 SELECT ISNUMERIC(@i) --gives 1 SELECT CAST(@i as decimal)--throws an error A: isnumeric is not 100% reliable in SQL - see this question Why does ISNUMERIC('.') return 1? I would guess that you have value in the reserve column that passes the isnumeric test but will not cast to decimal. A: Just a heads up on isnumeric; if the string contains some numbers and an 'E' followed by some numbers, this is viewed as an exponent. Example, select isnumeric('123E0') returns 1. A: I had this same problem and it turned out to be scientific notation such as '1.72918E-13' To find this just do where Reserve LIKE '%E%'. Try bypassing these and see if it works. You'll have to write code to convert these to something usable or reformat your source file so it doesn't store any numbers using scientific notation. A: IsNumeric is possibly not ideal in your scenario as from the highlighted Note on this MSDN page it says "ISNUMERIC returns 1 for some characters that are not numbers, such as plus (+), minus (-), and valid currency symbols such as the dollar sign ($)." Also there is a nice article here which further discusses ISNUMERIC. A: Try (for example): select cast(Reserve as decimal(10,2)) from MyReserves Numeric/Decimal generally want a precision an scale. A: I am also facing this issue and I solved by below method. I am sharing this because it may helpful to some one. declare @g varchar (50) set @g=char(10) select isnumeric(@g),@g, isnumeric(replace(replace(@g,char(13),char(10)),char(10),'')) A: Please try this: declare @Value varchar (50)='Test01'; IF @Value LIKE '%[0-9]%' BEGIN PRINT 'Its numeric'; END ELSE BEGIN PRINT 'Its not numeric'; END
{ "language": "en", "url": "https://stackoverflow.com/questions/7567804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Run a script using DBX I have a script like this script = GF1_dd_Daemon_Sh PROCESS_NAME=RG INSTANCE=RG PART_ID=1 Inside this there is an executable which is called. When I run this script(#!/bin/ksh ) it creates a core dump and using dbx when i analyse the stack trace I cannot get any much info. Is there any way to run the script using DBX and can trace the point where the executable is creating the core dump. I am using SOLARIS. Thanks. Stack Trace (dbx) where current thread: t@1 [1] xercesc_2_6::SAXParser::SAXParser(0xffffffff70b833b8, 0xffffffff70b83480, 0x0, 0x0, 0xffffffff70b833f8, 0xffffffff7d12ccd8), at 0xffffffff7ce22fc0 =>[2] __SLIP.INIT_D() (optimized), at 0xffffffff70a447b8 (line ~35) in "Parser.h" [3] __STATIC_CONSTRUCTOR() (optimized), at 0xffffffff70a46f04 (line ~35) in "Parser.h" [4] 0xffffffff70a74718(0xffffffff7f7361b8, 0xffffffff7f738d60, 0x11a340, 0x0, 0xffffffff7f736c60, 0x821), at 0xffffffff70a74718 [5] call_init(0xffffffff7f736530, 0x1, 0xffffffff70a74618, 0xffdfffff, 0xffffffff7f736c60, 0xffffffffffffffff), at 0xffffffff7f618674 [6] dlmopen_intn(0xffffffff7ffe6b0c, 0x8, 0x4a, 0x52, 0xffffffff7ffe6b0c, 0xffffffff77800a60), at 0xffffffff7f61df7c [7] dlmopen_check(0xffffffff7f7361b8, 0xffffffff7ffe6c18, 0x1, 0xffffffff7f400ef0, 0xffffffff7ffe6b0c, 0x118cc8), at 0xffffffff7f61e0f0 [8] _dlopen(0xffffffff7ffe6c18, 0x1, 0x1, 0xffffffff7ea56d30, 0x11, 0xffffffff7fffc226), at 0xffffffff7f61e130 [9] GMF_sfg_ACTIVITY(i_pgmName = ???, i_instance = ???, i_coreReplaceRegister_func_p = ???) (optimized), at 0xffffffff7e926ff0 (line ~200) in "GMF_sfg_ACTIVITY.c" [10] GMF_mdg_EXECinit(i_pcProcessName = ???, i_argc = ???, i_argv = ???) (optimized), at 0xffffffff7eb33394 (line ~556) in "GMF_mdg_EXECinit.c" [11] GMF_mdg_EXECmain(argc = ???, argv = ???) (optimized), at 0xffffffff7eb25ae8 (line ~163) in "GMF_mdg_EXECfunc.c" [12] main(argc = ???, argv = ???) (optimized), at 0x100001eb8 (line ~52) in "GMF_mdg_EXECproc.c" (dbx) down 0xffffffff7ce22fc0: SAXParser+0x0110: ldx [%i2], %o3 A: * *Inside the script check what are the arguments that are being passed to the executable (binary). *start the dbx with that executable *after it start set the arguments which you have discovered in step 1 *stop in GMF_mdg_EXECmain *then start checking the code flow A: One common approach is to add a variable to the script called something like $DEBUGGER #!/bin/sh echo "this is the script" $DEBUGGER the_executable arg1 arg2 If you set the DEBUGGER environment variable to "dbx", then when you run the script, dbx will be started and it will give you a dbx prompt. If you're using the Solaris Studio IDE, you can use "ss_attach" instead of "dbx" and it will attach the debugging session to an IDE that is already running. Check the man page for ss_attach.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding a substring from a database in MySQL I have a Database like this" NAME - AGE alex - 20 mathew - 14 alexandra-31 human-10 now in a text box elsewhere when i type say "al",I should get the result as alex and alexandra. how do i do this in MySQL? please help. A: select * from tableName where name like 'al%' A: Select name, age From yourtable Where name like 'al%' Or, if you want to type any part of the name: Select name, age From yourtable Where name like '%le%' A: create table your_table (NAME varchar(50),AGE int); insert into your_table (NAME,AGE) values ('alex',20); insert into your_table (NAME,AGE) values ('mathew',14); insert into your_table (NAME,AGE) values ('alexandra',31); insert into your_table (NAME,AGE) values ('human',10); select NAME from your_table where name like 'al%'; Should do the trick...
{ "language": "en", "url": "https://stackoverflow.com/questions/7567806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calculating rank on an aggregate column in a Hibernate SQLProjection I am trying to write a query to calculate a rank column based upon an aggregate column. The query is an SQLProjection as part of a Hibernate Criteria query. Here is what I have tried: String sqlProjection = "(select count(*) from IPTStatistic stat2 where max(s.powerRestarts) > max({alias}.powerRestarts)) as rank)"; ProjectionList list = Projections.projectionList(); list.add(Projections.sqlProjection(sqlRankQuery, new String[]{"rank"}, new Type[]{new IntegerType()}))); list.add(Property.forName("managedObjectName").group()); list.add(Projections.max("powerRestarts").as("maxRestarts")); Criteria crit = hibernateSessionHelper.getSessionFactory().getCurrentSession().createCriteria(IPTStatistic.class); crit.setProjection(projection); crit.list(); When I use a non-aggregate column in the SQL projection, the subselect works and I get the expected results, it is only once I introduce the max() that the error occurs. This throws a fairly non-specific org.hibernate.exception.GenericJDBCException with message "Could not execute query". The log shows: WARN logExceptions, SQL Error: -458, SQLState: S1000 ERROR logExceptions, java.lang.NullPointerException java.lang.NullPointerException I can't pinpoint the problem in the query myself from the above error messages, can anyone give me some pointers on how to correct my query? UPDATE: I am now using the following sqlProjection as per axtavt's answer below: String sqlProjection = "(select count(*) from " + "(select name from IPTStatistic s group by s.name " + " having max(s.powerRestarts) > max({alias}.powerRestarts)) " + "as r) as rank" The SQL generated by Hibernate is: select (select count(*) from (select iptManagedObjectName from IPTStatistic s group by s.iptManagedObjectName having max(s.powerRestarts) > max(this_.powerRestarts)) as r) as rank, this_.iptManagedObjectName as y1_, from IPTStatistic this_ I am now getting the error: WARN logExceptions, SQL Error: -5581, SQLState: 42581 ERROR logExceptions, unexpected token: SELECT If I remove max({alias}.powerRestarts) and replace it with either a constant or max(s.powerRestarts), then the query works (but obviously does not calculate the rank correctly). There seems to be a problem using the {alias} in this sqlProjection query - possibly something to do with the nested subqueries - can anyone help? Thankyou. A: HQL doesn't support subqueries in select list, thus you have two options: * *Write this query in SQL and execute it as a native query *Write something like select max(stat.powerRestarts), stat.managedObjectName from IPTStatistic stat group by stat.managedObjectName order by max(stat.powerRestarts) desc then rank can be deduced programmatically from a row number UPDATE: An important point here is that you need to perform two aggregations (max and count) in order to calculate a rank, so that you need two queries to do it: String sqlProjection = "(select count(*) from " + "(select name from IPTStatistic s group by s.name " + " having max(s.powerRestarts) > max({alias}.powerRestarts)) " + "as r) as rank"; Also note the use of having instead of where, since condition should be applied after the first aggregation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to access a CSS class that is loaded via a iframe on a page I have just added a 'Like' button from Facebook. The site is in Arabic, and I have added the necessary Arabic language locals to the FB code. Now the problem is the Icons are displaying slightly different, and I can see that can be controlled by CSS. The FB Code loads an iframe and within that there is a SPAN that has a class that controls the position of the Facebook (blue 'f' icon) which is overlapping over the text. When I try using FireBug and re-position it it words fine. My question is how can I write a CSS code that I can change the value on that iframe loaded CSS from my local CSS file ? The code is as follows: === Code on the iFrame that is loading === <div class="connect_button_slider"> <div class="connect_button_container"> <a class="connect_widget_like_button clearfix like_button_no_like"> <div class="tombstone_cross"></div> <span class="liketext">أعجبني</span> </a> </div> === The CSS that is loaded by FireBug .button_count .like_button_dark .like_button_no_like .liketext, .button_count .connect_widget_like_button .liketext { background-position: -1px -47px; } ==== I need to change the "class"="liketext". I want to change the value of "background-position: -1px -47px;" from that to the following: background-position: 38px -47px; ==== Now I have my local CSS file, how will I be able to access that element "liketext" and change the value from "-1" to "38" ... The page, if you want to check, is on the following link ... URL: http://www.majalla.com/arb/2011/09/article55227042 On top of the article you will find the facebook icon/like overlapping just next to the print icon. A: I really don't like telling you that your work here was pretty much wasted. You can't influence an external iframe with css - that's why Facebook does it that way, to have full control over their icons. Anyway it's a shame that the like button doesn't get displayed properly, but all you can (and should) do is submitting a bug report to facebook! By the way, try taking care of your spelling: It's that, not tath and THAT spelling makes it really hard to read your question ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7567809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to clickRight in selenium dont use javascript and fireevent? I have one contextmenu and i want to clickRight in selenium test. i try to use fireEvent but i m failed. and i dont know java script. So how to do clikright in selenium. thanks A: Use selenium.contextMenu(locator) A: Have you tried the recording feature of the ide? What code does it produce? Search the forum and you find: Selenium IDE - record right click
{ "language": "en", "url": "https://stackoverflow.com/questions/7567810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Validating date format with Zend_validator How can I validate the date format (dd-mm-yyyy) using zend_validate? A: You simply use the Date validator (Zend_Validate_Date). Eg $validator = new Zend_Validate_Date(array( 'format' => 'dd-mm-yyyy', 'locale' => $yourLocale ); A: It is not possible at the moment to validate against an exact date format in zendframework2 (see ZF2 Issue #4763) but you can add an extra regex validator (see example here) or write a custom validator to handle this (see zf2 Issue). use Zend\Validator\Date; use Zend\Validator\Regex; $validator = new Date(array( 'format' => 'd-m-Y', )); $validator2 = new Regex(array( 'pattern' => '%[0-9]{2}-[0-9]{2}-[0-9]{4}%', )); A: This is how i did this, $DateFormat = new \Zend\Validator\Date(array('format' => 'Y-m-d')); if(!($DateFormat->isValid($somedate))){ //if not valid do something }else{ //do something else } i forgot to mention that this is for Zend 2.0
{ "language": "en", "url": "https://stackoverflow.com/questions/7567817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Dynamically set properties of contorls in gridview I have a gridview which has a textbox in an itemtemplate. I want to set the maxlength property of this textbox dynamically. The code I have now is - <asp:GridView ID="grd" runat="server" EnableViewState="true" AutoGenerateColumns="false" OnRowDataBound="grd_RowDataBound" > <Columns> <asp:TemplateField HeaderText="Textbox"> <ItemTemplate> <asp:TextBox ID="txtValue" Text="" runat="server" TextMode="MultiLine" Columns="8" Rows="3"></asp:TextBox> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> My code in the RowDataBound event handler - protected void grd_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { TextBox txtText = (TextBox)e.Row.FindControl("txtValue"); txtText.Text = "test"; //this works fine txtText.MaxLength = 10; //this does not work. } } Does anyone know why I am not able to set the MaxLength property dynamically? And, how can I set the value of a property of the control in gridview dynamically? A: A multiline textbox can't have a MaxLength. Although you wont get any error but it won't work. You can try changing the TextMode of textbox to SingleLine to see if it would work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can use a X.509 certificate created on another computer? I need to encrypt an XML file with a x509 certificate on one computer and be able to decrypt it with the same certificate on another computer. It doesn't seem to work for me like Microsoft suggests: http://msdn.microsoft.com/en-us/library/ms229744.aspx The decryption process always fails on another computer! I create a certificate by using the following command: makecert -r -pe -n "CN=DEEP_201X" -b 01/01/2011 -e 01/01/2014 -sky exchange -ss my deep.cer Then I install it by using: certmgr /add deep.cer /s root And try to get its private key with the FindPrivateKey.exe utility: FindPrivateKey My CurrentUser -n "CN=DEEP_201X" Works great. However, when I perform all the same actions to install the certificate on another computer FindPrivateKey will fail with No certificates with key 'CN=DEEP_201X' found in the store. when I use certmgr /add deep.cer /s my the error message will be like this: Unable to obtain private key file name Could someone please give me a piece of advice on how to make it work? A: I suspect that you only need the private key on the decrypting computer. However... If you really need the private key on both computers, be aware that The .cer file does not include the private key. (I think) makecert adds it to the local machine when it generates the cert. You can write it out using the -sv option. Then build a pfx container for the certificate that contains it. makecert -r -pe -sv myprivatekey.pvk -n "CN=DEEP_201X" -b 01/01/2011 -e 01/01/2014 -sky exchange -ss my deep.cer pvk2pfx -pvk myprivatekey.pvk -spc deep.cr -pfx deep_private.pfx I haven't been able to convince certmgr to import private keys from the commandline. Use it in gui mode or use the certmgr.msc snap-in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Last In-First Out Stack with GCD? I have a UITableView that displays images associated with contacts in each row. In some cases these images are read on first display from the address book contact image, and where there isn't one they are an avatar rendered based on stored data. I presently have these images being updated on a background thread using GCD. However, this loads the images in the order they were requested, which means during rapid scrolling the queue becomes lengthy and when the user stops scrolling the current cells are the last to get updated. On the iPhone 4, the problem isn't really noticeable, but I am keen to support older hardware and am testing on an iPhone 3G. The delay is tolerable but quite noticeable. It strikes me that a Last In-First Out stack would seem likely to largely resolve this issue, as whenever the user stopped scrolling those cells would be the next to be updated and then the others that are currently off-screen would be updated. Is such a thing possible with Grand Central Dispatch? Or not too onerous to implement some other way? Note, by the way, that I am using Core Data with a SQLite store and I am not using an NSFetchedResultsController because of a many-to-many relationship that has to be traversed in order to load the data for this view. (As far as I am aware, that precludes using an NSFetchedResultsController.) [I've discovered an NSFetchedResultsController can be used with many-to-many relationships, despite what the official documentation appears to say. But I'm not using one in this context, yet.] Addition: Just to note that while the topic is "How do I create a Last In-First Out Stack with GCD", in reality I just want to solve the issue outlined above and there may be a better way to do it. I am more than open to suggestions like timthetoolman's one that solves the problem outlined in another way; if such a suggestion is finally what I use I'll recognize both the best answer to the original question as well as the best solution I ended up implementing... :) A: Ok, I've tested this and it works. The object just pulls the next block off the stack and executes it asynchronously. It currently only works with void return blocks, but you could do something fancy like add an object that will has a block and a delegate to pass the block's return type back to. NOTE: I used ARC in this so you'll need the XCode 4.2 or greater, for those of you on later versions, just change the strong to retain and you should be fine, but it will memory leak everything if you don't add in releases. EDIT: To get more specific to your use case, if your TableViewCell has an image I would use my stack class in the following way to get the performance you want, please let me know if it work well for you. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } // Configure the cell... UIImage *avatar = [self getAvatarIfItExists]; // I you have a method to check for the avatar if (!avatar) { [self.blockStack addBlock:^{ // do the heavy lifting with your creation logic UIImage *avatarImage = [self createAvatar]; dispatch_async(dispatch_get_main_queue(), ^{ //return the created image to the main thread. cell.avatarImageView.image = avatarImage; }); }]; } else { cell.avatarImageView.image = avatar; } return cell; } Here's the testing code that show's that it works as a stack: WaschyBlockStack *stack = [[WaschyBlockStack alloc] init]; for (int i = 0; i < 100; i ++) { [stack addBlock:^{ NSLog(@"Block operation %i", i); sleep(1); }]; } Here's the .h: #import <Foundation/Foundation.h> @interface WaschyBlockStack : NSObject { NSMutableArray *_blockStackArray; id _currentBlock; } - (id)init; - (void)addBlock:(void (^)())block; @end And the .m: #import "WaschyBlockStack.h" @interface WaschyBlockStack() @property (atomic, strong) NSMutableArray *blockStackArray; - (void)startNextBlock; + (void)performBlock:(void (^)())block; @end @implementation WaschyBlockStack @synthesize blockStackArray = _blockStackArray; - (id)init { self = [super init]; if (self) { self.blockStackArray = [NSMutableArray array]; } return self; } - (void)addBlock:(void (^)())block { @synchronized(self.blockStackArray) { [self.blockStackArray addObject:block]; } if (self.blockStackArray.count == 1) { [self startNextBlock]; } } - (void)startNextBlock { if (self.blockStackArray.count > 0) { @synchronized(self.blockStackArray) { id blockToPerform = [self.blockStackArray lastObject]; [WaschyBlockStack performSelectorInBackground:@selector(performBlock:) withObject:[blockToPerform copy]]; [self.blockStackArray removeObject:blockToPerform]; } [self startNextBlock]; } } + (void)performBlock:(void (^)())block { block(); } @end A: A simple method that may be Good Enough for your task: use NSOperations' dependencies feature. When you need to submit an operation, get the queue's operations and search for the most recently submitted one (ie. search back from the end of the array) that hasn't been started yet. If such a one exists, set it to depend on your new operation with addDependency:. Then add your new operation. This builds a reverse dependency chain through the non-started operations that will force them to run serially, last-in-first-out, as available. If you want to allow n (> 1) operations to run simultaneously: find the n th most recently added unstarted operation and add the dependency to it. (and of course set the queue's maxConcurrentOperationCount to n.) There are edge cases where this won't be 100% LIFO but it should be good enough for jazz. (This doesn't cover re-prioritizing operations if (e.g.) a user scrolls down the list and then back up a bit, all faster than the queue can fill in the images. If you want to tackle this case, and have given yourself a way to locate the corresponding already-enqueued-but-not-started operation, you can clear the dependencies on that operation. This effectively bumps it back to the "head of the line". But since pure first-in-first-out is almost good enough already, you may not need to get this fancy.) [edited to add:] I've implemented something very like this - a table of users, their avatars lazy-fetched from gravatar.com in the background - and this trick worked great. The former code was: [avatarQueue addOperationWithBlock:^{ // slow code }]; // avatarQueue is limited to 1 concurrent op which became: NSBlockOperation *fetch = [NSBlockOperation blockOperationWithBlock:^{ // same slow code }]; NSArray *pendingOps = [avatarQueue operations]; for (int i = pendingOps.count - 1; i >= 0; i--) { NSOperation *op = [pendingOps objectAtIndex:i]; if (![op isExecuting]) { [op addDependency:fetch]; break; } } [avatarQueue addOperation:fetch]; The icons visibly populate from the top down in the former case. In the second, the top one loads, then the rest load from the bottom up; and scrolling rapidly down causes occasional loading, then immediate loading (from the bottom) of icons of the screenful you stop at. Very slick, much "snappier" feel to the app. A: I haven't tried this - just throwing ideas out there. You could maintain your own stack. Add to the stack and queue to GCD on the foreground thread. The block of code you queue to GCD simply pulls the next block off your stack (the stack itself would need internal synchronization for push & pop) and runs it. Another option may be to simply skip the work if there's more than n items in the queue. That would mean that if you quickly got the queue backed up, it would quickly press through the queue and only process < n. If you scroll back up, the cell reuse queue, would get another cell and then you would queue it again to load the image. That would always prioritize the n most recently queued. The thing I'm not sure about is how the queued block would know about the number of items in the queue. Perhaps there's a GCD way to get at that? If not, you could have a threadsafe counter to increment/decrement. Increment when queueing, decrement on processing. If you do that, I would increment and decrement as the first line of code on both sides. Hope that sparked some ideas ... I may play it around with it later in code. A: Because of the memory constraints of the device, you should load the images on demand and on a background GCD queue. In the cellForRowAtIndexPath: method check to see if your contact's image is nil or has been cached. If the image is nil or not in cache, use a nested dispatch_async to load the image from the database and update the tableView cell. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } // If the contact object's image has not been loaded, // Use a place holder image, then use dispatch_async on a background queue to retrieve it. if (contact.image!=nil){ [[cell imageView] setImage: contact.image]; }else{ // Set a temporary placeholder [[cell imageView] setImage: placeHolderImage]; // Retrieve the image from the database on a background queue dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0); dispatch_async(queue, ^{ UIImage *image = // render image; contact.image=image; // use an index path to get at the cell we want to use because // the original may be reused by the OS. UITableViewCell *theCell=[tableView cellForRowAtIndexPath:indexPath]; // check to see if the cell is visible if ([tableView visibleCells] containsObject: theCell]){ // put the image into the cell's imageView on the main queue dispatch_async(dispatch_get_main_queue(), ^{ [[theCell imageView] setImage:contact.image]; [theCell setNeedsLayout]; }); } }); } return cell; } The WWDC2010 conference video "Introducing Blocks and Grand Central Dispatch" shows an example using the nested dispatch_async as well. another potential optimization could be to start downloading the images on a low priority background queue when the app launches. i.e. // in the ApplicationDidFinishLaunchingWithOptions method // dispatch in on the main queue to get it working as soon // as the main queue comes "online". A trick mentioned by // Apple at WWDC dispatch_async(dispatch_get_main_queue(), ^{ // dispatch to background priority queue as soon as we // get onto the main queue so as not to block the main // queue and therefore the UI dispatch_queue_t lowPriorityQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) dispatch_apply(contactsCount,lowPriorityQueue ,^(size_t idx){ // skip the first 25 because they will be called // almost immediately by the tableView if (idx>24){ UIImage *renderedImage =/// render image [[contactsArray objectAtIndex: idx] setImage: renderedImage]; } }); }); With this nested dispatch, we are rendering the images on an extremely low priority queue. Putting the image rendering on the background priority queue will allow the images being rendered from the cellForRowAtIndexPath method above to be rendered at a higher priority. So, because of the difference in priorities of the queues, you will have a "poor mans" LIFO. Good luck. A: The code below creates a flexible last in-first out stack that is processed in the background using Grand Central Dispatch. The SYNStackController class is generic and reusable but this example also provides the code for the use case identified in the question, rendering table cell images asynchronously, and ensuring that when rapid scrolling stops, the currently displayed cells are the next to be updated. Kudos to Ben M. whose answer to this question provided the initial code on which this was based. (His answer also provides code you can use to test the stack.) The implementation provided here does not require ARC, and uses solely Grand Central Dispatch rather than performSelectorInBackground. The code below also stores a reference to the current cell using objc_setAssociatedObject that will enable the rendered image to be associated with the correct cell, when the image is subsequently loaded asynchronously. Without this code, images rendered for previous contacts will incorrectly be inserted into reused cells even though they are now displaying a different contact. I've awarded the bounty to Ben M. but am marking this as the accepted answer as this code is more fully worked through. SYNStackController.h // // SYNStackController.h // Last-in-first-out stack controller class. // @interface SYNStackController : NSObject { NSMutableArray *stack; } - (void) addBlock:(void (^)())block; - (void) startNextBlock; + (void) performBlock:(void (^)())block; @end SYNStackController.m // // SYNStackController.m // Last-in-first-out stack controller class. // #import "SYNStackController.h" @implementation SYNStackController - (id)init { self = [super init]; if (self != nil) { stack = [[NSMutableArray alloc] init]; } return self; } - (void)addBlock:(void (^)())block { @synchronized(stack) { [stack addObject:[[block copy] autorelease]]; } if (stack.count == 1) { // If the stack was empty before this block was added, processing has ceased, so start processing. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); dispatch_async(queue, ^{ [self startNextBlock]; }); } } - (void)startNextBlock { if (stack.count > 0) { @synchronized(stack) { id blockToPerform = [stack lastObject]; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); dispatch_async(queue, ^{ [SYNStackController performBlock:[[blockToPerform copy] autorelease]]; }); [stack removeObject:blockToPerform]; } [self startNextBlock]; } } + (void)performBlock:(void (^)())block { @autoreleasepool { block(); } } - (void)dealloc { [stack release]; [super dealloc]; } @end In the view.h, before @interface: @class SYNStackController; In the view.h @interface section: SYNStackController *stackController; In the view.h, after the @interface section: @property (nonatomic, retain) SYNStackController *stackController; In the view.m, before @implementation: #import "SYNStackController.h" In the view.m viewDidLoad: // Initialise Stack Controller. self.stackController = [[[SYNStackController alloc] init] autorelease]; In the view.m: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Set up the cell. static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } else { // If an existing cell is being reused, reset the image to the default until it is populated. // Without this code, previous images are displayed against the new people during rapid scrolling. [cell setImage:[UIImage imageNamed:@"DefaultPicture.jpg"]]; } // Set up other aspects of the cell content. ... // Store a reference to the current cell that will enable the image to be associated with the correct // cell, when the image subsequently loaded asynchronously. objc_setAssociatedObject(cell, personIndexPathAssociationKey, indexPath, OBJC_ASSOCIATION_RETAIN); // Queue a block that obtains/creates the image and then loads it into the cell. // The code block will be run asynchronously in a last-in-first-out queue, so that when // rapid scrolling finishes, the current cells being displayed will be the next to be updated. [self.stackController addBlock:^{ UIImage *avatarImage = [self createAvatar]; // The code to achieve this is not implemented in this example. // The block will be processed on a background Grand Central Dispatch queue. // Therefore, ensure that this code that updates the UI will run on the main queue. dispatch_async(dispatch_get_main_queue(), ^{ NSIndexPath *cellIndexPath = (NSIndexPath *)objc_getAssociatedObject(cell, personIndexPathAssociationKey); if ([indexPath isEqual:cellIndexPath]) { // Only set cell image if the cell currently being displayed is the one that actually required this image. // Prevents reused cells from receiving images back from rendering that were requested for that cell in a previous life. [cell setImage:avatarImage]; } }); }]; return cell; } A: I do something like this, but iPad-only, and it seemed fast enough. NSOperationQueue (or raw GCD) seems like the simplest approach, in that everything can be self-contained and you don't need to worry about synchronization. Also, you might be able to save the last operation, and use setQueuePriority: to lower it. Then the most recent one will be pulled from the queue first. Or go through all -operations in the queue and lower their priority. (You could probably do this after completing each one, I assume this would still be significantly faster than doing the work itself.) A: create a thread safe stack, using something like this as a starting point: @interface MONStack : NSObject <NSLocking> // << expose object's lock so you // can easily perform many pushes // at once, keeping everything current. { @private NSMutableArray * objects; NSRecursiveLock * lock; } /** @brief pushes @a object onto the stack. if you have to do many pushes at once, consider adding `addObjects:(NSArray *)` */ - (void)addObject:(id)object; /** @brief removes and returns the top object from the stack */ - (id)popTopObject; /** @return YES if the stack contains zero objects. */ - (BOOL)isEmpty; @end @implementation MONStack - (id)init { self = [super init]; if (0 != self) { objects = [NSMutableArray new]; lock = [NSRecursiveLock new]; if (0 == objects || 0 == lock) { [self release]; return 0; } } return self; } - (void)lock { [lock lock]; } - (void)unlock { [lock unlock]; } - (void)dealloc { [lock release], lock = 0; [objects release], objects = 0; [super dealloc]; } - (void)addObject:(id)object { [self lock]; [objects addObject:object]; [self unlock]; } - (id)popTopObject { [self lock]; id last = 0; if ([objects count]) { last = [[[objects lastObject] retain] autorelease]; } [self unlock]; return last; } - (BOOL)isEmpty { [self lock]; BOOL ret = 0 == [objects count]; [self unlock]; return ret; } @end then use an NSOperation subclass (or GCD, if you prefer). you can share the stack between the operation and the clients. so the empty bit and the NSOperation main are the somewhat tricky sections. let's start with the empty bit. this is tricky because it needs to be threadsafe: // adding a request and creating the operation if needed: { MONStack * stack = self.stack; [stack lock]; BOOL wasEmptyBeforePush = [stack isEmpty]; [stack addObject:thing]; if (wasEmptyBeforePush) { [self.operationQueue addOperation:[MONOperation operationWithStack:stack]]; } [stack unlock]; // ... } the NSOperation main should just go through and exhaust the stack, creating an autorelease pool for each task, and checking for cancellation. when the stack is empty or the operation is cancelled, cleanup and exit main. the client will create a new operation when needed. supporting cancellation for slower requests (e.g. network or disk) can make a huge difference. cancellation in the case of the operation which exhausted the queue would require that the requesting view could remove its request when it is dequeued (e.g. for reuse during scrolling). another common pitfall: immediate async loading (e.g. adding the operation to the operation queue) of the image may easily degrade performance. measure. if the task benefits from parallelization, then allow multiple tasks in the operation queue. you should also identify redundant requests (imagine a user scrolling bidirectionally) in your task queue, if your program is capable of producing them. A: I'm a big fan of NSOperationQueue's interface and ease-of-use, but I also needed a LIFO version. I ended up implementing a LIFO version of NSOperationQueue here that has held up quite well for me. It mimics NSOperationQueue's interface, but executes things in a (roughly) LIFO order.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Specifying project Property values from within Visual Studio If I have properties defined in my project file like so <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <foo>bar</foo> </PropertyGroup> </Project> I can easily set these properties on the MSBuild command line using /p:foo=newValue. Is there a way of specifying the property value within the Visual studio (2010) GUI? I have had a look but could not find anything within the project properties pages. A: Are you looking for conditional compilation symbols? In VS2010: * *Go to the project properties *Go to the Build tab *Under General you will see a place to define "Conditional compilation symbols". You can enter "foo=bar" there, and you will get this in your .csproj file: <Project ...> <PropertyGroup ...> <DefineConstants>Foo=bar</DefineConstants> </PropertyGroup> </Project> A: I found this question when looking for an answer to the same thing: I can easily use /p or environment variables to control things when calling MSBuild on the command line, but how do you do similar in the IDE? My solution was to add a “user” properties file. That is <!-- Running from the IDE, you can't simply set properties via /p or environment variables. So, this local file is read if it exists. It is not checked in to version control; but can contain settings to be used for your immediate work. If you make a settings.props.user file, remember DO NOT check it in! --> <ImportGroup> <Import Condition="exists('$(MSBuildThisFileDirectory)settings.props.user')" Project="$(MSBuildThisFileDirectory)settings.props.user" /> </ImportGroup> I can now edit some properties in the file settings.props.user conveniently located in the same directory, and not worry about accidentally checking in funny settings. Even when building in the IDE, it reads the text file anew when building. So, just keep the props.user file open in a text editor and it's handy enough to change on the fly, without an IDE extension.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I avoid passing context object all over the place? Possible Duplicate: Dependecy Hell - how does one pass dependencies to deeply nested objects Lately I've been struggling with this particular problem. For testing and managing reasons I decided it would be a better option to inject an object like $config to those who need it. While at start it was ok, later it started polluting the code. For example: Object A uses object B to do its job, object B uses strategy object C, object C uses object D, which needs $config object. So, I have to keep passing $config down this whole chain In my code I have two objects like that to pass through, which makes constructors big, having duplicated code and generally it smells wrong. I would appreciate any help in refactoring this relationship. A: Instead of (pseudo code as general advice) ... config <-- ... A.constructor (config) { this.foo = config.foo this.bar = config.bar this.objectB = createB (config) } B.constructor (config) { this.frob = config.frob this.objectC = createC (config) } C.constructor (config) { this.frobnicate = config.frobnicate this.objectD = createC (configD) } you should only pass what is really needed: config <-- ... A.constructor (foo, bar, frob, frobnicate) { this.foo = foo this.bar = bar this.objectB = createB (frob, frobnicate) } B.constructor (frob, frobnicate) { this.frob = frob this.objectC = createC (frobnicate) } C.constructor (frobnicate) { this.frobnicate = frobnicate } Have your state as local as possible. Global state is the root of an indefinite amount of debugging horror scenarios (as I smell you've just faced). Alternatively, many classes don't have to know how their objects look like, they are just interested in the public interface. You can apply dependency inversion, then: config <-- ... objectC = createC (config.frobnicate) objectB = createB (config.frob, objectC) objectA = createA (config.foo, config.bar, objectB) Using dependency inversion means freeing your classes from needing to know too much. E.g., a Car does not need to know about Trailer and its composition, it just needs to know about CouplingDevice: trailer = createTrailer (...) couplingDevice = createCouplingDevice (...) car.install (couplingDevice) couplingDevice.attach (trailer) A: Am I right in thinking that $config contains... well, configuration information that is required by a large portion of your application? If so, it sounds like you should consider the (ubiquitious) singleton design pattern. If you're not already familiar with it, it is a technique which allows only one instance of a class throughout the run-time of your application. This is very useful when maintaining application-wide values, since you do not run the risk of instantiating a second object; nor are you passing around 'copies' of objects. As an example, examine the following: <?php class Test { private static $instance; private function __construct() { } // Private constructor static function instance() { if (!isset(self::$instance)) { self::$instance = new self(); } return self::$instance; } } $a = Test::instance(); $b = Test::instance(); $a->property = 'abc'; var_dump($a->property); var_dump($b->property); ?> You will see that both 'instances' contain the 'property' with value 'abc' since they are both actually the same instance. I apologize if you are already familiar with this technique, but it certainly sounds like the thing you are looking for! Edit As pointed out below, this can still be cloned. If you really wanted to prevent this happening, you would have to override the magic method __clone() to stop this happening. The serialization observation is just being pedantic, though. A: It looks like you need to use a singleton or a registry patterns. The singleton consist of a class (with private constructor) that can be created by a static method in order to obtain the same object (forgive me for the simplification) every time you need it. It follow this scheme: class Config { static private instance=null; private function __constructor() { // do your initializzation here } static public function getInstance() { if (self::instance==null) { self::instance== new Config(); } return self::instance; } // other methods and properties as needed } In this way you can obtain the desired object where you need it with something like $config = Config::getInstance(); without passing it down in your call stack without resorting to globals variables. The registry has a similar working scheme but let you create a sort of registry, hence the name, of objects you need to make available.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android SharedPreferences design model I have these two classes. SettingsManager extends another class and stores the data and also gets the context from the Activity as parameter. However this doesn't seem to work and I get empty EditText fields. Could you please suggest anything to fix this? public class SettingsActivity extends Activity { private EditText _userSoftSerialNumberEditText; private EditText _databaseServerEditText; private EditText _databaseNameEditText; private EditText _userApplicationEditText; private EditText _databaseUserNameEditText; private EditText _databasePasswordEditText; private SettingsManager _settingsManager; private Context _context; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settingsview_layout); _context = this; _settingsManager = new SettingsManager(_context); _settingsManager.loadSettings(); // Setting the values in the EditText fields in the settingsview_layout.xml _userSoftSerialNumberEditText = (EditText) findViewById(R.id.userSoftSerialNumberEditText); _userSoftSerialNumberEditText.setText(_settingsManager.getUserSoftSerialNumber()); _databaseServerEditText = (EditText) findViewById(R.id.databaseServerEditText); _databaseServerEditText.setText(_settingsManager.getDatabaseServer()); _databaseNameEditText = (EditText) findViewById(R.id.databaseNameEditText); _databaseNameEditText.setText(_settingsManager.getDatabaseName()); _userApplicationEditText = (EditText) findViewById(R.id.userApplicationEditText); _userApplicationEditText.setText(_settingsManager.getUserApplication()); _databaseUserNameEditText = (EditText) findViewById(R.id.databaseUserNameEditText); _databaseUserNameEditText.setText(_settingsManager.getDatabaseUserName()); _databasePasswordEditText = (EditText) findViewById(R.id.databasePasswordEditText); _databasePasswordEditText.setText(_settingsManager.getDatabasePassword()); // Creating a "Save Settings" button Button _saveSettingsButton = (Button) findViewById(R.id.saveSettingsButton); // Implementing the "Save Settings" button click _saveSettingsButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { _settingsManager.saveSettings(); } }); } } public class SettingsManager extends ConnectionInfo { private SharedPreferences _settings; private Context _context; public SettingsManager (Context context) { _context = context; _settings = PreferenceManager.getDefaultSharedPreferences(context); } public void saveSettings() { SharedPreferences.Editor _editor = _settings.edit(); _editor.putString("userSoftSerialNumber", _userSoftSerialNumber); _editor.putString("databaseUserName", _databaseUserName); _editor.putString("databasePassword", _databasePassword); _editor.putString("databaseServer", _databaseServer); _editor.putString("databaseName", _databaseName); _editor.putString("userApplication", _userApplication); _editor.commit(); // Never forget the commit()!!!! } public void loadSettings() { _userSoftSerialNumber = _settings.getString("userSoftSerialNumber", ""); _databaseUserName = _settings.getString("databaseUserName", ""); _databasePassword = _settings.getString("databasePassword", ""); _databaseServer = _settings.getString("databaseServer", ""); _databaseName = _settings.getString("databaseName", ""); _userApplication = _settings.getString("userApplication", ""); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Attributes reversed in certificate subject and issuer I am trying to generate X509 certificates with bouncycastle 1.46, with the code below. The issue I have is that when a certificate is written in a JKS and then reread, the DNs are reversed. For instance, if I run the code below, I get the following output: CN=test,O=gina CN=test,O=gina CN=test,O=gina O=gina, CN=test Does anybody know the reason for this? how to avoid it? Thanks in advance. Code: public static void main(String[] args) { try { Security.addProvider(new BouncyCastleProvider()); KeyPair pair = generateKeyPair("RSA", 1024); X500Name principal = new X500Name("cn=test,o=gina"); System.out.println(principal); BigInteger sn = BigInteger.valueOf(1234); Date start = today(); Date end = addYears(start, 2); X509Certificate cert = generateCert(principal, pair, sn, start, end, "SHA1withRSA"); cert.verify(pair.getPublic()); System.out.println(cert.getSubjectDN()); // Store the certificate in the JKS KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); ks.setKeyEntry("alias", pair.getPrivate(), KEY_PWD, new X509Certificate[] {cert}); X509Certificate c = (X509Certificate)ks.getCertificateChain("alias")[0]; System.out.println(c.getSubjectDN()); OutputStream out = new FileOutputStream("text.jks"); try { ks.store(out, KEYSTORE_PWD); } finally { out.close(); } // Reread the JKS ks = KeyStore.getInstance("JKS"); InputStream in = new FileInputStream("text.jks"); try { ks.load(in, KEYSTORE_PWD); } finally { in.close(); } c = (X509Certificate)ks.getCertificateChain("alias")[0]; c.verify(pair.getPublic()); System.out.println(c.getSubjectDN()); } catch (Exception e) { e.printStackTrace(); } } private static X509Certificate generateCert(X500Name principal, KeyPair pair, BigInteger sn, Date start, Date end, String sigalg) throws OperatorCreationException, CertificateException { JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(principal, sn, start, end, principal, pair.getPublic()); JcaContentSignerBuilder builder = new JcaContentSignerBuilder(sigalg); builder.setProvider("BC"); ContentSigner signr = builder.build(pair.getPrivate()); X509CertificateHolder certHolder = certGen.build(signr); JcaX509CertificateConverter conv = new JcaX509CertificateConverter(); conv.setProvider("BC"); return conv.getCertificate(certHolder); } private static KeyPair generateKeyPair(String algorithm, int keySize) throws NoSuchAlgorithmException { KeyPairGenerator gen = KeyPairGenerator.getInstance(algorithm); gen.initialize(keySize); return gen.generateKeyPair(); } private static Date today() { Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTime(); } private static Date addYears(Date date, int count) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.YEAR, count); return cal.getTime(); } A: I ran into the same issue and resolved it quickly with the following: //CREATES AN X500 CA SUBJECT FOR ISSUER X500Name issuerName = new JcaX509CertificateHolder((X509Certificate) caCert).getSubject(); I then used it with the following: //CONSTRUCTS THE X509 CERTIFIFATE OBJECT X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder( issuerName, serialNumber, startDate, endDate, DevCsr.getSubject(), DevCsr.getSubjectPublicKeyInfo()); The issuer name in the Java Keystore end entity certificate now shows up in the correct order. Cheers! A: I had the same problem with bouncy 1.47. First you must be careful with the classes X500Name and X500Principal. There are the SUN classes and the bouncy classes. They are totally different !! X500Name (bouncy) should be created using X500NameBuilder. But If you need to create it using a String then your attributes must be in the reverse order of RFC2253, this means your attributes must be in this order : " CN, L, ST, O, OU, C, STREET, DC, UID ". This is not convenient because, for example, in my case, I had to create a X500Name (bouncy) from a X500Principal (SUN) and the only way to do it was to use the X500Principal:getName() method which print the attributes according to RFC2253 order. So I created this method : private org.bouncycastle.asn1.x500.X500Name toBouncyX500Name( javax.security.auth.x500.X500Principal principal) { String name = principal.getName(); String[] RDN = name.split(","); StringBuffer buf = new StringBuffer(name.length()); for(int i = RDN.length - 1; i >= 0; i--){ if(i != RDN.length - 1) buf.append(','); buf.append(RDN[i]); } return new X500Name(buf.toString()); } Hope it'll be useful to someone :) A: This may be a bit simpler. At least in BC 1.48+, you can construct the X500Name thusly, and the OIDs will be ordered in the expected way (or at least, the way you specify them): final X500Name subject = new X500Name(RFC4519Style.INSTANCE, "CN=test,O=gina");
{ "language": "en", "url": "https://stackoverflow.com/questions/7567837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Passing structure as pointer I'm trying to pass structure as pointer in function arguments. Here is my code #include <stdio.h> #include <stdbool.h> #include <string.h> typedef struct { int yearOfManufacture; char model[50]; bool gasoline; } Car; void PrintCarDetails(Car details); int main (int argc, const char * argv[]) { Car ford; ford.yearOfManufacture = 1997; ford.gasoline = true; strcpy(ford.model, "Focus"); PrintCarDetails(&ford); return 0; } void PrintCarDetails(Car *details) { printf("Car model %s", details->model); } I get an error "Passing Car to parameter of incompatible type Car. What I miss ? A: Forward declaration should be : void PrintCarDetails(Car * details); A: void PrintCarDetails(Car *details); * is missing in the forward declaration. A: The function definition differs from the function declaration. In the declaration you state that a a Car struct should be used as an argument, but in the definition you want a pointer to a Car struct. A: You probably misspinted declaration of PrintCarDetails function. Should be: void PrintCarDetails(Car *details); works here A: It is just a little mistake, your function definition and declaration don't match: * *line 12 : void PrintCarDetails(Car details); *line 26 : void PrintCarDetails(Car *details); just fix the line 12 with : void PrintCarDetails(Car *details);
{ "language": "en", "url": "https://stackoverflow.com/questions/7567841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php url encode and htaccess parameters I have encoded my url text (ex: Ice's Bird) and pass it as a parameter to another file via htaccess redirection and the url appears as below. http://test.com/nature-pic-Ice%26%23039%3Bs_bird.php In the above url, I want the word Ice's bird as parameter, but I can get only the word before single quote, ex: Ice My redirection code is RewriteCond %{REQUEST_URI} ^/nature-pic-(.*).php RewriteRule ^nature-pic-(.*)\.php content.php?tpath=$1 [L] How can I get the full word from the url? A: this should be your .htaccess RewriteEngine On RewriteRule ^nature-pic-(.*).php test.php?tpath=$1 [L] fully tested with this address nature-pic-Ice's_bird.php hope it will help
{ "language": "en", "url": "https://stackoverflow.com/questions/7567843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: xpath/xquery sql - Get all values Hi I have a blob of xml.. <string>1</string> <string>2</string> <string>3</string> <string>4</string> <string>11</string> <string>1211</string> <string>12331</string> how would I get all the values using xpath/xquery in SQL Thanks A: The xpath //string will return all the values in the intire xml the xpath /string will return only the values in the root node. And for using it in sql look at this post XPath to fetch SQL XML value A: in oracle database you have XMLType (see this) data type.. by this datatype you can get all the value.. all the examples are there itself, please go through that site.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Phone 7 IE - Get GPS Coordinates From Mobisite I use the following code to get the GPS coordinates on a Android/iOS device from a mobisite but it doesn't work on WP7. How can I get a user's GPS coordinates in IE on a WP7 device? (I am testing on a Samsung Omnia 7). <script language="javascript"> navigator.geolocation.getCurrentPosition(findLocation, noLocation); function findLocation(position) { var lat = position.coords.latitude; var lng = position.coords.longitude; document.getElementById("result").innerHTML = "Lat: " + lat + ", Long: " + lng; } function noLocation() { document.getElementById("result").innerHTML = "Unable to get location"; } </script> A: What happens when you run this on a WP7 device? When are you running this? Be sure to do it after the document has loaded. If you're running this inside a WebBrowser control then be sure to set IsGeolocationEnabled to true. ALso check that location is enabled on the device and in IE. X-Ref http://msdn.microsoft.com/en-gb/library/gg593067.aspx The error callback should contain a positionError parameter which may give you more information about any error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to create a program to list all the USB devices in a Mac? I have a limited exposure to the Mac OS X operating system and now I have started using Xcode and am studying about I/O kit. I need to create a program in Xcode under command line tool in order to list all USB devices connected in a Mac system. Those who have previous experience under this, please help me. If anyone could provide me with sample code then it will be of great use, as I am looking for starting point. A: You just need to access the IOKit Registry. You may well be able to use the ioreg tool to do this (e.g. run it via system() or popen()). If not then you can at least use it to verify your code: Info on ioreg tool: $ man ioreg Get list of USB devices: $ ioreg -Src IOUSBDevice A: If you run system_profiler SPUSBDataType it'll list all the USB devices connected to the system, you can then interact with that data either by dumping it into a text file or reading it from the command into the application and working with it there. A: You can adapt USBPrivateDataSample to your needs, the sample sets up a notifier, lists the currently attached devices, then waits for device attach/detach. If you do, you will want to remove the usbVendor and usbProduct matching dictionaries, so all USB devices are matched. Alternately, you can use IOServiceGetMatchingServices to get an iterator for all current matching services, using a dictionary created by IOServiceMatching(kIOUSBDeviceClassName). Here's a short sample (which I've never run): #include <IOKit/IOKitLib.h> #include <IOKit/usb/IOUSBLib.h> int main(int argc, const char *argv[]) { CFMutableDictionaryRef matchingDict; io_iterator_t iter; kern_return_t kr; io_service_t device; /* set up a matching dictionary for the class */ matchingDict = IOServiceMatching(kIOUSBDeviceClassName); if (matchingDict == NULL) { return -1; // fail } /* Now we have a dictionary, get an iterator.*/ kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &iter); if (kr != KERN_SUCCESS) { return -1; } /* iterate */ while ((device = IOIteratorNext(iter))) { /* do something with device, eg. check properties */ /* ... */ /* And free the reference taken before continuing to the next item */ IOObjectRelease(device); } /* Done, release the iterator */ IOObjectRelease(iter); return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: How to test if PerlIO::fse works on file test operators? #!/usr/local/bin/perl use warnings; use strict; use utf8; use Encode qw(encode); my $dir = '/data/Delibes, Léo'; if ( -d $dir ) { print "OK\n"; } if ( -d encode 'utf8', $dir ) { print "OK\n"; } This prints 2 times OK; I suppose this is because Perl stores $dir internally as utf8. I there a way to check if PerlIO::fse has an effect on the filetest operators as long as perl and the filesystem stores in utf8? Edit: #!/usr/local/bin/perl use warnings; use 5.014; binmode STDOUT, 'utf8'; use utf8; my $dir1 = 'é'; my $dir2 = chr(0xE9); opendir my $dh1, $dir1 or warn '1: ', $!; say "OK1" if -d $dir1; opendir my $dh2, $dir2 or warn '2: ', $!; say "OK2" if -d $dir2; utf8::upgrade( $dir1 ); utf8::upgrade( $dir2 ); opendir my $dh3, $dir1 or warn '3: ', $!; say "OK3" if -d $dir1; opendir my $dh4, $dir2 or warn '4: ', $!; say "OK4" if -d $dir2; # OK1 # 2: Datei oder Verzeichnis nicht gefunden at ./temp1.pl line 12. # OK3 # OK4 Maybe I have not exactly understood how PerlIO::fse works - in this example I can't see any effect from PerlIO::fse: #!/usr/local/bin/perl use warnings; use 5.014; binmode STDOUT, 'utf8'; use utf8; use PerlIO::fse 'utf-8'; my $dir1 = 'é'; my $dir2 = chr(0xE9); opendir my $dh1, $dir1 or warn '1: ', $!; say "OK1" if -d $dir1; opendir my $dh2, $dir2 or warn '2: ', $!; say "OK2" if -d $dir2; # OK1 # 2: Datei oder Verzeichnis nicht gefunden at ./temp1.pl line 13. A: Test with: my $file_name = chr(0xE9); # e acute. utf8::downgrade($file_name); my $file_name = chr(0xE9); utf8::upgrade($file_name); The first will produce junk in a UTF-8 locale if it's not UTF-8 encoded first. The second will produce junk in other locales if it's not encoded first. (They're suppose to be the same, but there's a bug in most/all builtins that take file names, the same bug that's preventing you from testing it properly.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7567876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Submit Page with just Code Behind Using C# I am creating a callback page that receives info from a payment gateway and then updates a database. I then want it to 'submit' itself automatically to a 'thank you' page, passing the order number as a hidden field. I have looked at httpwebrequest, but I can't see with this solution how it will 'post itself' if that's the right way to put it. Any help on ho to achieve this would be greatly appreciated. A: If the callback page is regular ASP.NET you could do a server-side Response.Redirect or Server.Execute. If not you can do a client-side post in javascript: <form action="yourThankYouUrl.aspx"> <input type="hidden" name="callbackValue" value="yourCallbackValue" /> </form> <script type="text/javascript"> document.forms[0].submit(); </script> A: So, why not using that receive page to also show what you need and save the trouble to have one more page? If you still want to have a 2nd page just to show the result, at the end of the processing you can write: Session["job-id"] = "12345679"; Response.Redirect("my2ndpage.aspx"); in that 2nd Page, you simply assign the session text to the control you will have HiddenField1.Value = Session["job-id"].ToString();
{ "language": "en", "url": "https://stackoverflow.com/questions/7567882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Thread-safe initialisation of local statics: MSVC Possible Duplicate: Is static init thread-safe with VC2010? I know that gcc and llvm-clang emit code to initialise local static variables in a threadsafe manner (which allows one to escape the static order initialisation fiasco by wrapping global statics in functions). This msdn blog post, however, is the best documentation I can find of vcc's behaviour in these circumstances, and purports that static initialisation cannot ever be threadsafe, because the initialiser for a local static could recursively call into the same scope. I don't buy this argument - it is clearly a programming error if the initialiser relies on its own result. So, given that this article is from 2004, that gcc and clang can do it, and that the current msvc documentation is ambiguous (stating that 'assigning' to a local static isn't threadsafe, but nothing more): Is the initialisation of local statics now threadsafe in MSVC? If not, why not, since it is clearly possible for gcc to do this, but very difficult for the programmer to add in afterwards. A: I heard it is already implemented in vs2010, but can not find any reference. Anyway in c++0x standard such initializations are explicitly required to be thread-safe, so sooner or later ms would comply I guess. A: The C++0x Standard says: §6.7 Declaration statement [stmt.dcl] 4/ The zero-initialization (8.5) of all block-scope variables with static storage duration (3.7.1) or thread storage duration (3.7.2) is performed before any other initialization takes place. Constant initialization (3.6.2) of a block-scope entity with static storage duration, if applicable, is performed before its block is first entered. An implementation is permitted to perform early initialization of other block-scope variables with static or thread storage duration under the same conditions that an implementation is permitted to statically initialize a variable with static or thread storage duration in namespace scope (3.6.2). Otherwise such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.88 If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined. [ Example: int foo(int i) { static int s = foo(2*i); // recursive call - undefined return i+1; } —end example ] 88) The implementation must not introduce any deadlock around execution of the initializer. As expected, it is quite complete. However the fact is that even older versions of gcc already complied with this, and in fact do even better: in case of recursive initialization, an exception is thrown. Finally, regarding a programmer adding it afterward: you can normally do it if you have something like Compare And Swap available, and use a sufficiently small variable, relying on zero-initialization of the variable to mark its non-computed state. However I do agree it's much easier if it's baked in. I am afraid I stopped followed VC++ progresses though, so I don't know where it stands now. My only advice would be... look it up at assembly level.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to find class name inside a bunch of jars I have a whole lot of jar files in my system , related to my Application . How can i find a particular class in that whole lot of jar files ?? Thank you A: If those jar files are in the build path of your Eclipse project: Ctrl-Shift-T (for "Open Type", "type" as in "class") brings up a search box. You can CamelType (i.e. SB instead of StringBuilder). A: You should be able to right-click on the class name in a source file and select one of the sub-items of the Declarations context menu item - i.e., right click on the class name and select Declarations/Project. This will search the project for any declarations of the class and pop up the standard Eclipse search results view. I am assuming that you have the jar as a library in your Eclipse project. If you want to do this on the file system instead, then use a for loop to iterate over the JAR files and use jar tf FILENAME to get the list of class files and pipe that through grep or findstr (depending on your platform). If you are using bash, something like the following would do the trick: bash-3.2$ for f in *.jar do result=$(jar tf $f | grep '/DBObject.class$') [ -n "$result" ] && echo "$f contains $result" done mongodb-api-2.6.3.jar contains com/mongodb/DBObject.class bash-3.2$ You could concoct something similar in Windows using a FOR loop at a command prompt but I don't recall if FINDSTR sets the result ERRORLEVEL correctly. The following should work not completely sure of the syntax: C:\Directory\Containing\Jars> FOR %I IN (*.jar) DO @( FOR /F %J IN ('jar tf %I') DO ECHO "%J: %I" ) | FINDSTR /R /C:"/DBObject.class$" mongodb-api-2.6.3.jar: com/mongodb/DBObject.class C:\Directory\Containing\Jars> If I remember, I'll edit this after I get to a Windows machine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: All Forms Not Passing Parameters All of the forms in my rails application are not submitting parameters even to the production.log: Started GET "/countries/afghanistan/edit/" for 41.132.43.55 at Tue Sep 27 03:39:06 -0700 2011 Processing by CountriesController#edit as HTML Parameters: {"id"=>"afghanistan"} Rendered countries/_form.html.erb (80.2ms) Rendered application/_nav.html.erb (2.8ms) Rendered countries/edit.html.erb within layouts/application (85.2ms) Completed 200 OK in 87ms (Views: 85.6ms | ActiveRecord: 0.5ms) Started GET "/countries/afghanistan/" for 41.132.43.55 at Tue Sep 27 03:40:20 -0700 2011 Processing by CountriesController#show as HTML Parameters: {"id"=>"afghanistan"} Rendered application/_nav.html.erb (3.9ms) Rendered countries/show.html.erb within layouts/application (16.7ms) Completed 200 OK in 21ms (Views: 15.3ms | ActiveRecord: 2.3ms) That's from the edit action and then submitting the form it goes straight to the show action. In my dev inspector it shows that the POST request has been permanently moved (301) to the GET request: I'm not sure what too look for at this point. Everything works fine in development but not in production. Here's my production.rb App::Application.configure do config.cache_classes = true config.consider_all_requests_local = false config.action_controller.perform_caching = true config.action_dispatch.x_sendfile_header = "X-Sendfile" config.serve_static_assets = false config.i18n.fallbacks = true config.active_support.deprecation = :notify ActionMailer::Base.smtp_settings = { :address => "smtp.gmail.com", :port => 587, :user_name => "***@***.com", :password => "***", :authentication => "plain", :enable_starttls_auto => true } config.middleware.use ExceptionNotifier, :email_prefix => "[Exception] ", :sender_address => %{"Exception Notifier" <***@***.com>}, :exception_recipients => %w{***@***.com} end Any help is greatly appreciated. Thanks! UPDATE 1 Here's the sessions#new <%= form_tag sessions_path do %> <p> <%= label_tag :login, "Email Address" %><br /> <%= text_field_tag :login, params[:login] %> </p> <p> <%= label_tag :password %><br /> <%= password_field_tag :password %> </p> <p><%= submit_tag "Log in" %></p> <% end %> And here's another one of the forms: <%= form_for @satellite do |f| %> <%= f.error_messages %> <p> <%= f.label :name %><br /> <%= f.text_field :name %> </p> <p> <% for country in Country.find(:all) %> <%= check_box_tag "satellite[country_ids][]", country.id, @satellite.countries.include?(country) %> <%= label_tag "satellite[country_ids][]", country.name, :for => "satellite[country_ids][]" %><br /> <% end %> </p> <p><%= f.submit %></p> <% end %> But like I said none of the forms are passing parameters. Update 2 Here's the routes: edit_current_user /user/edit(.:format) {:controller=>"users", :action=>"edit"} signup /signup(.:format) {:controller=>"users", :action=>"new"} logout /logout(.:format) {:controller=>"sessions", :action=>"destroy"} login /login(.:format) {:controller=>"sessions", :action=>"new"} sessions GET /sessions(.:format) {:controller=>"sessions", :action=>"index"} POST /sessions(.:format) {:controller=>"sessions", :action=>"create"} new_session GET /sessions/new(.:format) {:controller=>"sessions", :action=>"new"} edit_session GET /sessions/:id/edit(.:format) {:controller=>"sessions", :action=>"edit"} session GET /sessions/:id(.:format) {:controller=>"sessions", :action=>"show"} PUT /sessions/:id(.:format) {:controller=>"sessions", :action=>"update"} DELETE /sessions/:id(.:format) {:controller=>"sessions", :action=>"destroy"} users GET /users(.:format) {:controller=>"users", :action=>"index"} POST /users(.:format) {:controller=>"users", :action=>"create"} new_user GET /users/new(.:format) {:controller=>"users", :action=>"new"} edit_user GET /users/:id/edit(.:format) {:controller=>"users", :action=>"edit"} user GET /users/:id(.:format) {:controller=>"users", :action=>"show"} PUT /users/:id(.:format) {:controller=>"users", :action=>"update"} DELETE /users/:id(.:format) {:controller=>"users", :action=>"destroy"} maps GET /maps(.:format) {:controller=>"maps", :action=>"index"} POST /maps(.:format) {:controller=>"maps", :action=>"create"} new_map GET /maps/new(.:format) {:controller=>"maps", :action=>"new"} edit_map GET /maps/:id/edit(.:format) {:controller=>"maps", :action=>"edit"} map GET /maps/:id(.:format) {:controller=>"maps", :action=>"show"} PUT /maps/:id(.:format) {:controller=>"maps", :action=>"update"} DELETE /maps/:id(.:format) {:controller=>"maps", :action=>"destroy"} country_channels GET /countries/:country_id/channels(.:format) {:controller=>"channels", :action=>"index"} country_channel GET /countries/:country_id/channels/:id(.:format) {:controller=>"channels", :action=>"show"} country_satellites GET /countries/:country_id/satellites(.:format) {:controller=>"satellites", :action=>"index"} country_satellite GET /countries/:country_id/satellites/:id(.:format) {:controller=>"satellites", :action=>"show"} country_testimonies GET /countries/:country_id/testimonies(.:format) {:controller=>"testimonies", :action=>"index"} country_testimony GET /countries/:country_id/testimonies/:id(.:format) {:controller=>"testimonies", :action=>"show"} country_statistics GET /countries/:country_id/statistics(.:format) {:controller=>"statistics", :action=>"index"} country_statistic GET /countries/:country_id/statistics/:id(.:format) {:controller=>"statistics", :action=>"show"} country_videos GET /countries/:country_id/videos(.:format) {:controller=>"videos", :action=>"index"} country_video GET /countries/:country_id/videos/:id(.:format) {:controller=>"videos", :action=>"show"} country_challenges GET /countries/:country_id/challenges(.:format) {:controller=>"challenges", :action=>"index"} country_challenge GET /countries/:country_id/challenges/:id(.:format) {:controller=>"challenges", :action=>"show"} countries GET /countries(.:format) {:controller=>"countries", :action=>"index"} POST /countries(.:format) {:controller=>"countries", :action=>"create"} new_country GET /countries/new(.:format) {:controller=>"countries", :action=>"new"} edit_country GET /countries/:id/edit(.:format) {:controller=>"countries", :action=>"edit"} country GET /countries/:id(.:format) {:controller=>"countries", :action=>"show"} PUT /countries/:id(.:format) {:controller=>"countries", :action=>"update"} DELETE /countries/:id(.:format) {:controller=>"countries", :action=>"destroy"} channels GET /channels(.:format) {:controller=>"channels", :action=>"index"} POST /channels(.:format) {:controller=>"channels", :action=>"create"} new_channel GET /channels/new(.:format) {:controller=>"channels", :action=>"new"} edit_channel GET /channels/:id/edit(.:format) {:controller=>"channels", :action=>"edit"} channel GET /channels/:id(.:format) {:controller=>"channels", :action=>"show"} PUT /channels/:id(.:format) {:controller=>"channels", :action=>"update"} DELETE /channels/:id(.:format) {:controller=>"channels", :action=>"destroy"} satellites GET /satellites(.:format) {:controller=>"satellites", :action=>"index"} POST /satellites(.:format) {:controller=>"satellites", :action=>"create"} new_satellite GET /satellites/new(.:format) {:controller=>"satellites", :action=>"new"} edit_satellite GET /satellites/:id/edit(.:format) {:controller=>"satellites", :action=>"edit"} satellite GET /satellites/:id(.:format) {:controller=>"satellites", :action=>"show"} PUT /satellites/:id(.:format) {:controller=>"satellites", :action=>"update"} DELETE /satellites/:id(.:format) {:controller=>"satellites", :action=>"destroy"} testimonies GET /testimonies(.:format) {:controller=>"testimonies", :action=>"index"} POST /testimonies(.:format) {:controller=>"testimonies", :action=>"create"} new_testimony GET /testimonies/new(.:format) {:controller=>"testimonies", :action=>"new"} edit_testimony GET /testimonies/:id/edit(.:format) {:controller=>"testimonies", :action=>"edit"} testimony GET /testimonies/:id(.:format) {:controller=>"testimonies", :action=>"show"} PUT /testimonies/:id(.:format) {:controller=>"testimonies", :action=>"update"} DELETE /testimonies/:id(.:format) {:controller=>"testimonies", :action=>"destroy"} statistics GET /statistics(.:format) {:controller=>"statistics", :action=>"index"} POST /statistics(.:format) {:controller=>"statistics", :action=>"create"} new_statistic GET /statistics/new(.:format) {:controller=>"statistics", :action=>"new"} edit_statistic GET /statistics/:id/edit(.:format) {:controller=>"statistics", :action=>"edit"} statistic GET /statistics/:id(.:format) {:controller=>"statistics", :action=>"show"} PUT /statistics/:id(.:format) {:controller=>"statistics", :action=>"update"} DELETE /statistics/:id(.:format) {:controller=>"statistics", :action=>"destroy"} videos GET /videos(.:format) {:controller=>"videos", :action=>"index"} POST /videos(.:format) {:controller=>"videos", :action=>"create"} new_video GET /videos/new(.:format) {:controller=>"videos", :action=>"new"} edit_video GET /videos/:id/edit(.:format) {:controller=>"videos", :action=>"edit"} video GET /videos/:id(.:format) {:controller=>"videos", :action=>"show"} PUT /videos/:id(.:format) {:controller=>"videos", :action=>"update"} DELETE /videos/:id(.:format) {:controller=>"videos", :action=>"destroy"} challenges GET /challenges(.:format) {:controller=>"challenges", :action=>"index"} POST /challenges(.:format) {:controller=>"challenges", :action=>"create"} new_challenge GET /challenges/new(.:format) {:controller=>"challenges", :action=>"new"} edit_challenge GET /challenges/:id/edit(.:format) {:controller=>"challenges", :action=>"edit"} challenge GET /challenges/:id(.:format) {:controller=>"challenges", :action=>"show"} PUT /challenges/:id(.:format) {:controller=>"challenges", :action=>"update"} DELETE /challenges/:id(.:format) {:controller=>"challenges", :action=>"destroy"} all_channels /all/channels(.:format) {:controller=>"channels", :action=>"all"} all_satellites /all/satellites(.:format) {:controller=>"satellites", :action=>"all"} all_testimonies /all/testimonies(.:format) {:controller=>"testimonies", :action=>"all"} all_statistics /all/statistics(.:format) {:controller=>"statistics", :action=>"all"} all_videos /all/videos(.:format) {:controller=>"videos", :action=>"all"} all_challenges /all/challenges(.:format) {:controller=>"challenges", :action=>"all"} root /(.:format) {:controller=>"countries", :action=>"map"} home /home(.:format) {:controller=>"countries", :action=>"map"} A: one thing, i ran into a while ago with non-numerical ids, were default constraints on resources routes. overriding this constraints solved the issue for, but this should be a problem in development mode as well. anyway, you can try resources :countries, :constraints => { :id => /.*/ } plus your nested routes
{ "language": "en", "url": "https://stackoverflow.com/questions/7567889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rocket framework portability to web based applications I am designing a windows form application. I want also to provide a web based front for the same application. I understand that I need to redesign the UI part wholly and I am ready for that. But what I would like to know is that what architecture should I follow during development of the windows form so that the maximum part can be reusable. By maximum part I mean the data access logic, the business logic etc. I am planning to use Rocket Framework http://rocketframework.codeplex.com/ for windows application design. Are any one familiar with it? Please suggest. A: After a lot of R&D and extensive study I finally settled here: https://github.com/geersch/ModelViewPresenter It is an MVP architecture written by Christophe Geers. It supports all I needed- Architecture for winform, web portability support, Entity Framework. Really nice and easy to use. Additional reading: http://www.cerquit.com/blogs/post/MVP-Part-I-e28093-Building-it-from-Scratch.aspx A: MVP or MVVM should enable use to re-use portions of your application. Of Interest?: Implementing MVC with Windows Forms
{ "language": "en", "url": "https://stackoverflow.com/questions/7567897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Are any limitations exist as to using different versions of git software on the same physical repository? For example when working from computers which have different git software versions installed. A: git's repository layout has been very stable over time, so using even very old versions of the software with repositories created by later versions should work fine. Of course, there may be config options set by later versions that aren't understood by earlier versions of the tools, but this should not cause problems except perhaps that the older software doesn't behave as you would expect. Also, it should be fine to use versions of the tools built for different operating systems on the same on-disk repository. There are particular features, such as submodules, that may not be supported by older versions of git - to be able to assess whether that would be a problem you would have to tell us what the oldest version you might be using is. You might also want to look at this question about git's backwards-compatibility: * *Git repository backwards compatibility
{ "language": "en", "url": "https://stackoverflow.com/questions/7567899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Restricting importing groups while importing users from LDAP into Jira I don't want to import the groups from LDAP into Jira, while importing the users from LDAP in Jira. I am not familiar to LDAP, but I want to import only users in Jira. Is there anything that can be done at Jira level to restrict importing groups? A: If you fill out your directory settings with the correct, but set the 'Group Object Filter" to an LDAP filter that will match nothing, you will not import any groups. An example of a globally non-matching LDAP filter would be (1=2) If you are using this technique, the other group LDAP settings become redundant, so you can set them as you please. A: I don't know that there is a way to tell LDAP not to return the groups (in JIRA or otherwise), but you can tell JIRA not to use the groups to create JIRA groups. In my experience, JIRA will not automatically create JIRA groups to match LDAP groups if you use the setting "Read Only, with Local Groups". I can't test that right now, I don't have my test server running. But I think that is the way it works. So if that is what you are trying to accomplish, then that should work for you. A: You can specify what you want out of LDAP with extreme precision, certainly including whether you get users, groups, organizations, etc. Look up the LDAP search filter syntax. You will also need to know which LDAP schema is in use at the server, at least for users.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Launch Image on iPad only in PortraitMode (Only device) I wrote an iPad app and I'm using two different images as launch images. The iOS simulator shows the proper image during startup but the device always uses the portrait image. I have the right file size (Xcode does NOT give me any warnings)! I'm using iOS5 Beta 7 with Xcode 4.2 Here is what I did so far: * *I double checked all the file sizes *I readded the files to the project, *I build the project from scratch (including 'Clean') *I cleaned the workspace's derived data directory. *I deleted the app completely from the device. *I restarted the device. I'm running out of ideas. Any ideas? A: In iOS 3.2 and later, an iPad application can provide both landscape and portrait versions of its launch images. Each orientation-specific launch image must include a special modifier string in its filename. The format for orientation-specific launch image filenames is as follows: basename_usage_specific_modifiers_scale_modifier_device_modifier.png Application Launch Images. A: I solved it. I couldnt find any mistakes. So I removed everything according the launchimage from the project (including entries in info.plist), deleted the derived workspace folder, deleted the app from the device. Inserted the pictures again an set the basename for the image in info.plist. It worked. still don't know why. Btw: It seems like Xcode 4.2 (and iOS5) changes the sizes of the launch images for the iPad. iOS < 5: Portrait 768x1004px Landscape: 1024x748px (Source) iOS = 5: Portrait 768x1024px Landscape: 1024x768px (Source: Image) A: I did this: * *Rename image to Default-Landscape~ipad.png *In Info.plist register it as Blockquote <key>UILaunchImageFile~ipad</key> <string>${PRODUCT_NAME}/Default.png</string> Blockquote and it seems to work...
{ "language": "en", "url": "https://stackoverflow.com/questions/7567905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery how to get innerWidth but without the padding? From the docs, innerWidth does almost what I need: "Gets the inner width (excludes the border and includes the padding) for the first matched element." I need to know the width excluding the padding. I.e. the usable space inside the element. Does jquery provide anything like this - done a bit of googling and can't find any solutions. I thought about getting the padding-left and padding-right values to subtract from inner width- But given these could be percentages, pixels or em I'm not sure if this would be reliable. Any suggestions? A: You're probably just looking for the width() function.. See the docs, it excludes the padding: http://api.jquery.com/width/ (Just as intended in modern browser's representation of the css width property) Edit: It's now 2012 and jQuery 1.8 is just coming out. While this is still relevant, you may also want to read the following article from the jQuery blog regarding box-sizing considerations in version 1.8 A: $('#element').width(); It's as simple as that!
{ "language": "en", "url": "https://stackoverflow.com/questions/7567915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "53" }
Q: capybara's fill_in method not working as expected I have 2 forms in my page. The first form has a field "Username" and the second form has a field "Username:". When fill_in label, :with => value is run (where label = "Username:"), the input box labeled "Username" is getting filled instead. I changed "Username:" to "User name:" but even then "Username" gets filled. What am I doing wrong? A: If I understand correctly, you have 2 identically named text inputs on 2 different forms on your page. I believe fill_in some_field will look for an input with a name or ID matching some_field, rather than reading an attached label. Edit: It does actually look for an attached label - thanks to AlistairH for the correction I would suggest the best way to get the behaviour you want is using a within block: within 'form1' do fill_in 'Username', :with => value end Replace 'form1' with the name of whichever form contains the textbox you'd like to target. I would consider this to be far more reliable, and readable, than relying on the presence of spaces or colons to differentiate between almost identically named elements on the page
{ "language": "en", "url": "https://stackoverflow.com/questions/7567919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Email Validation to accept all special character I've regular expression to validate the email address as below var reg = /^([A-Za-z0-9_\-\+\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; please help me to validate the entered email so that the input box should accept all special characters listed below. .!#$%^&*-=_+{}|/?` thanks in advance A: E-mail addresses are barely worth validating as legitimate e-mail addresses can contain almost anything (why would you want to tell someone their e-mail address is not valid?). The only way to be sure anyway will be to send them an e-mail with a confirmation link in it. The fact of the matter is if you don't want to exclude any possibly valid e-mail addresses you'll end up with something really permissive like this: \w+\@\w+.\w+
{ "language": "en", "url": "https://stackoverflow.com/questions/7567921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What could cause a "richedit line insertion error" in C++Builder when inserting text in a different language? I have a C++Builder application using a TRichText control that has to display a report, running under Windows XP. The application was written in English but has been adapted to use other languages. Creating text on the TRichEdit (using the RichEdit->Lines->Add() function) is no problem as long as I am using Western languages. When I'm trying to add Russian (Cyrillic) text however the application throws an EOutOfResources exception with the "RichEdit line insertion error". Now this exception is usually thrown when the amount of text exceeds the RichEdit internal buffer (64KB) but that is certainly not the case and even adding one character fails. It is not a unicode application so I have to switch codepages to see the application in Cyrillic.And then I can see all other texts (like menus and labels) are displayed correct. So what else could cause this error ? A: RTF expects anything outside of 7-bit ASCII to be escape sequences. See this page for more details on the escape sequences. I think the section that details control page encoding would be most useful for you. A: Research shows it's a problem that only occurs on Windows XP. Also the error does not occur when the Windows XP has the locale settings for the specific language. The problem seems to be in the RichEd32.dll that is supplied with this version of Windows. The VCL (Visual Component Library as used by C++Builder and Delphi) fails when the first character of a line of text that is added to the TRichText control is an escaped character. The solution is to use the following code to add a line: AnsiString TextToAdd; TextToAdd = "пример"; // Russian text 'example' RichEdit1->SelStart = RichEdit1->Text.Length(); RichEdit1->SelText = TextToAdd + "\r\n"; Instead of: RichEdit1->Lines->Add( TextToAdd ); This actually has to be done only once. After text was added to any RichEdit control in the application, all subsequent calls to 'Lines->Add()' will work without throwing the exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567927", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems with inheritance with Symfony2, Doctrine2 I edited some mistakes and details... Well, I have been trying to create a inheritance with Product as parent and Film and Book as childs. Checking online and the official documentation didn't solved my problem because examples are poor and incomplete. (http://www.doctrine-project.org/docs/orm/2.0/en/reference/inheritance-mapping.html#class-table-inheritance). I'm not sure if I did it right and now I just don't know how to generate, manipulate and persist inherited objects. Parent class <?php namespace Paf\MyBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Table() * @ORM\Entity * @ORM\InheritanceType("JOINED") * @ORM\DiscriminatorColumn(name="discr", type="string") * @ORM\DiscriminatorMap({ "film" = "FilmE2" , "book" = "BookE2" }) */ class ProductEjemplo2 { /** * @var integer $id * @ORM\Id * @ORM\Column(name="id", type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; //More fields, Name, Description ... } Child Class <?php //Paf\MyBundle\Entity\FilmE2 namespace Paf\MyBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Table() * @ORM\Entity */ class FilmE2 extends ProductEjemplo2 { /** * @var integer $id * @ORM\Id * @ORM\Column(name="id", type="integer") */ protected $id; } doctrine:schema:update --force generates 2 tables: ProductE...(id primary key, disc dunno how works, rest of fields) FilmE2(id primary key, rest of fields) public function create2Action() { $product1 = new ProductEjemplo2(); $product1->setName('New Film 1'); //and more fields //here $product1 ID is null.(autogenerated but yet without value) $em->persist($product1); //error, non-object.... $em->flush(); $film = new FilmE2(); $film->setName('New Film 1'); //and more fields $film->setDirector('dir1'); $film->setId(1); $em->persist($film); //error, non-object.... $em->flush(); //In both cases happens the same. This doesn't work, it's quite obvious because says error "non-object" cant be persisted... but if I try with a new Filme2() happens the same... I realized that the ID of product is autogenerated when I use flush(). So isn't generated when I use persist... A: You cannot have two primary keys in inherited class, simply because it lets you to persist base object class. You can find an example here it works fine. Except that its more complicated to use queries witch should filter specific instances but everything is possible
{ "language": "en", "url": "https://stackoverflow.com/questions/7567928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: solaris lex error Am deploying a lex/yacc solution trying this grammar. The problem comes when i want to compile .lex file using this command: lex -t "file.lex" I get this error:Error: Parse tree too big Try using %e num Any help please thnks. A: I have a similar lex (same output from lex -V) and this grammar works fine for me unchanged (Solaris 10/SPARC) so I suspect you may need a patch. pkginfo output below. $ pkginfo -l SUNWbtool PKGINST: SUNWbtool NAME: CCS tools bundled with SunOS CATEGORY: system ARCH: sparc VERSION: 11.10.0,REV=2005.01.21.15.53 BASEDIR: / VENDOR: Sun Microsystems, Inc. DESC: software development utilities, including ar, dis, dump, elfdump, lex, lorder, mcs, nm, prof, ranlib, rpcgen, size, strip, tsort, and yacc PSTAMP: on10ptchfeat20090911051613 INSTDATE: Mar 15 2011 15:46 HOTLINE: Please contact your local service provider STATUS: completely installed FILES: 48 installed pathnames 8 shared pathnames 2 linked files 8 directories 24 executables 1874 blocks used (approx) $
{ "language": "en", "url": "https://stackoverflow.com/questions/7567931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: iOS - Change color channels levels programmatically Is it possible to adjust color levels using Core Graphics? I would like to adjust channels using parametrized curves in the Gimp or other graphic editor style. A: You can use this: ios-image-filters (like photoshop) if you want to manipulate levels, here's your method, built straight onto the UIImage class: - (UIImage*) levels:(NSInteger)black mid:(NSInteger)mid white:(NSInteger)white
{ "language": "en", "url": "https://stackoverflow.com/questions/7567934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: zombie.js visit() calling back too early (using browserify) Im using zombie to test a backbone app, when I use zombie.visit, zombie calls the vows callback before all scripts on the page are loaded, so my backbone app isn't loaded. However if I wait for the 'done' event, i.e. browser.on 'done', @callback then my backbone app gets loaded before the callback is called. Anyway to get the visit function to only callback once the 'done' event is received? PS Im using browserify to load quite a large script including backbone/underscore/jquery and other jquery plugins A: I ran in to the same thing but, oddly, I used some of your other suggestions to use 'on done' to figure out a way to wait until the document was completely loaded (including any dynamically injected from JS stuffs!). it('should have the correct title', function() { browser.on('done', function(doc) { console.log("DONE finally finito.."); //console.log(browser.html()); expect(doc.document.title).toMatch('.*Login'); expect(doc.document.title).not.toEqual('XXXXX'); asyncSpecDone(); }); browser.visit(LOGIN, function(err, doc) { }); asyncSpecWait(); }); where LOGIN is a URL to my login page. the browser.html() printed out the full page and I saw the dynamically inserted elements as expected. FWIW, my application is using node .ejs files that express.js is compiling on the fly; but this will likely apply to any dynamically injected page that you want to test with zombie. To my mind this looks like an anti-pattern and I would love if the author either corrects me or posts an alternative. However, this is a workaround.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Default all pages to a HTTP connection except for 4 pages which need to be HTTPS I am completely new to .htaccess and rewrite rules and I am struggling. Bascially I am working on a website with thousands of pages, I need all of the pages to be HTTP except for 4 pages which the customer data collection and payment process is collected over. I know I need something along the lines of: RewriteCond %{HTTPS} on RewriteCond %{QUERY_STRING} ^$ RewriteCond %{REQUEST_URI} ^/(index\.php)?$ [NC] RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI} [R=301, NC] RewriteCond %{HTTPS} on RewriteCond %{QUERY_STRING} ^view=(default|new(&.*)?)$ [NC] RewriteCond %{REQUEST_URI} ^/?index\.php$ [NC] RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI} [R=301, NC] Any help you can provide would be greatly appeciated. A: To ensure that those 4 pages are always served via HTTPS try this rule: RewriteEngine On RewriteCond %{HTTPS} =off RewriteRule ^(cart|Cart|summary|control)\.php$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] This rule will ALWAYS redirect these pages to HTTPS if not there already: example.com/cart.php, example.com/Cart.php, example.com/summary.php, example.com/control.php (all pages are located in website root, as you can see). If they have different URLs, then adjust the rule accordingly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VS Code snippet and SimpleTypeName - different results depending upon order in XML? I'm writing a little snippet to generate C# properties (as have many before me no doubt). I would like to add various attributes in the generated code, and would like to use the "SimpleTypeName" function. However, it seems that it doesn't always work, depending upon the order of the usage in the source XML file. Specifically, given snippet XML like this... <Snippet> <Declarations> <Literal Editable="false"> <ID>DesignerSerializationVisibility</ID> <Function>SimpleTypeName(global::System.ComponentModel.DesignerSerializationVisibility)</Function> </Literal> <Literal Editable="false"> <ID>DebuggerStepThrough</ID> <Function>SimpleTypeName(global::System.Diagnostics.DebuggerStepThrough)</Function> </Literal> </Declarations> <Code Language="CSharp"> <![CDATA[ [$DebuggerStepThrough$(), $DesignerSerializationVisibility$($DesignerSerializationVisibility$.Hidden)] public object x {get;set;} [$DesignerSerializationVisibility$($DesignerSerializationVisibility$.Hidden), $DebuggerStepThrough$()] public object z {get;set;} ]]> </Code> </Snippet> ...and the appropriate "using" statements in my source file, I get code like this... [DebuggerStepThrough(), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public object x { get; set; } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DebuggerStepThrough()] public object z { get; set; } All fine and dandy. If, however, I change my snippet XML to be this (note just the order of the functions has changed)... <Snippet> <Declarations> <Literal Editable="false"> <ID>DesignerSerializationVisibility</ID> <Function>SimpleTypeName(global::System.ComponentModel.DesignerSerializationVisibility)</Function> </Literal> <Literal Editable="false"> <ID>DebuggerStepThrough</ID> <Function>SimpleTypeName(global::System.Diagnostics.DebuggerStepThrough)</Function> </Literal> </Declarations> <Code Language="CSharp"> <![CDATA[ [$DesignerSerializationVisibility$($DesignerSerializationVisibility$.Hidden), $DebuggerStepThrough$()] public object z {get;set;} [$DebuggerStepThrough$(), $DesignerSerializationVisibility$($DesignerSerializationVisibility$.Hidden)] public object x {get;set;} ]]> </Code> </Snippet> ...I get this as the inserted C# code: [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), global::System.Diagnostics.DebuggerStepThrough()] public object z { get; set; } [global::System.Diagnostics.DebuggerStepThrough(), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public object x { get; set; } Why does my call to SimpleTypeName(DebuggerStepThrough) seem not to work when the XML is written using the order in the second example ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7567941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: A facebook link not opening on iphone I want to open a facebook comment page link Like http://www.facebook.com/comments.php?href=http://wombeta.jiffysoftware.com/ViewWOMPrint.aspx?WPID=310 but problem is this link doesnot open in iphone device or simulator but opens fine on desktop.When i try to open this link on simulator it opens the m.facebook site then shows error "Could not find the page" Please tell me a way to open this link in iphone My code is simple: NSURL *url = [NSURL URLWithString:@"http://www.facebook.com/comments.php?href=http://wombeta.jiffysoftware.com/ViewWOMPrint.aspx?WPID=317"]; NSURLRequest *requestObject = [NSURLRequest requestWithURL:url]; [webView loadRequest:requestObject]; A: response of any url from FB server (like many other servers) is based on the "user agent" whenever a web call is made, the device automatically attach user agent with request. In your case the "user agent" is being sent by devices is the one of mobile Safari - Native iphone Safari app so the server is returning with mobile site response with m.facebook...... you need to find a mobile site equivalent link for the same and I'm pretty sure that FB will have it in some way or the other. Best of Luck! A: [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.facebook.com/comments.php?href=http://wombeta.jiffysoftware.com/ViewWOMPrint.aspx?WPID=317"]]; it will open safari browser and redirect to required URL.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Echo data from database in each times get I send three times values 1 & 2 & 3 by jquery.serialize() for $hotel_id in PHP, now i want get in the each times from send, data linked with $hotel_id(like: 1 or 2 or 3) from database. but in the following code i just get data that linked to last $hotel_id(3). I want as: First: get data linked with 1 and echo they in json_encode Second: (next 2) get data linked with 2 and echo they in json_encode Third: (next 3)get data linked with 3 and echo they in json_encode... This is output serialize() from jQuery code: hotel_id=1&hotel_id=2&hotel_id=3 This is my php code: $hotel_id = $this->input->post('hotel_id'); $query_r = $this->db->query("SELECT * FROM hotel_submits WHERE id LIKE '$hotel_id' ORDER BY id desc"); $data = array(); foreach ($query_r->result() as $row) { $data_s = json_decode($row->service, true); $data_rp = json_decode($row->address, true); $data[] = array( 'name' => $row->name, 'star_type' => $row->star . '-' . $row->type, 'site' => $row->site, 'service' => $data_s, 'address' => $row->address ); } echo json_encode($data); How do i do? A: You can't pass in the same argument three times. It will only see the final parameter of hotel_id and so you just get number 3. PHP does allow for passing Arrays by naming the parameter with [] at the end like hotel_id[]=1&hotel_id[]=2, etc and then you can get the array of values in php. That means your value of $hotel_id would be an array of values instead of a single value. Since it is an array you would need to implode the array with a comma to use in your SQL: $hotel_id = implode(',', $this->input->post('hotel_id')); Now $hotel_id will look like '1,2,3'; Now your SQL will need to change to: SELECT * FROM hotel_submits WHERE id IN ($hotel_id) ORDER BY id desc Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Migrating an EJB project running on JBoss to Websphere Applicataion Server 7 I have a Java EJB project running on JBoss properly.However I have to migrate it to WAS. So I created an EAR then deployed it to WAS. After I tried to run this project on WAS i get this error: Error 500: javassist.util.proxy.MethodHandler, [Servlet Error]-[javassist.util.proxy.MethodHandler]: java.lang.NoClassDefFoundError: javassist.util.proxy.MethodHandler How can I fix this error and run this project on WAS? A: It seems you use classes in your application not available on WebSphere, but on JBoss (namely javassist). Get the JAR containing those classes and add it to the EAR. This is a common Java issue and not related to any application server, NoClassDefFoundError. You must get all classes your application requires during runtime. Edit: javassist information is available here. Depending on your JBoss and WAS versions you must choose the right version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to find days difference between the current day and input date $a = "Sat Aug 04 23:59:59 GMT 2012" How to find that is that $a is 100 days older ? I can't use any extra perl modules because i cant install it on all hosts A: First you have to parse that string in a DateTime object, using DateTime::Format::Builder, to build a custom string parser. Then you can get the difference between the two with: $dt->delta_days( $datetime ); Where $dt is the DateTime object from string parse, and $datetime is your reference ( another DateTime object ). A: You should use DateTime if available, but if not, then the below should do. Really, at this stage, you should rolling your own date logic, but it still is pretty easy using core module POSIX. use strict; use warnings; use POSIX (); # get a list of month symbols my @mons = qw/Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec/; # Create a symbol -> number table my %num_for = do { my $mon = 0; map { $_ => $mon++ } @mons; }; # Create the alternation of months # Create line regex my $time_rex = qr/ (${\join( '|', @mons )}) \s+ 0? (\d+) \s+ (\d{2}) : (\d{2}) : (\d{2}) \s+ # I made the tz optional to handle scalar( localtime ) (?: (\p{alpha}+) \s+ )? (\d{4}) /x ; ... # Convienience function sub get_time_value { # parse date string return unless my @fields = ( shift =~ /$time_rex/ ); # get numerical month $fields[0] = $num_for{ $fields[0] }; # perl year kludge $fields[-1] -= 1900; return wantarray ? @fields[ 4, 3, 2, 1, 0, 6, 5 ] : POSIX::mktime( @fields[ 4, 3, 2, 1, 0, 6 ] ) ; } sub days_prior_to_now { return unless defined( my $days_prior = shift ); return time unless $days_prior; $days_prior = - $days_prior if $days_prior < 0; my $date_string = scalar( localtime ); return unless my ( $sec, $min, $hr, $day, $mon, $year, $tz ) = get_time_value( $date_string ) ; return POSIX::mktime( $sec, $min, $hr, $day - $days_prior, $mon, $year ); } sub is_100_days_before_now { my $a_string = shift; croak "Could not parse '$a_string'!" unless my $a_value = get_time_value( $a_string ); return $a_value < days_prior_to_now( 100 ); } if ( is_100_days_before_now( $a )) { ... } A: If you get over your fear of modules, Date::Calc would make short work of this: $ perl -MDate::Calc=Delta_Days,Parse_Date,Today -E 'say Delta_Days(Today, Parse_Date(shift))' "Sat Aug 04 23:59:59 GMT 2012" 312 A: There are a lot of date time modules available in the standard Perl installation which means there's no need to install anything. This module has been available in some form since version Perl 3.x: * *Time::Local Here are others in version 5.8: * *Time::tm *Time::gmtime *Time::localtime Newer versions of Perl include: * *Time::Piece You can use the perldoc command to see which modules you have installed: C:> perldoc -l Time::Piece C:\Perl\lib\Time\Piece.pm Unix stores time in the number of seconds since "The Epoc" which is January 1, 1970, and Perl does the same thing (even on Windows). Thus, once you translate your date into a Perl time, you can simply subtract 8,640,000 which is the number of seconds in a 100 days. (100 days * 24 Hours/day * 60 minutes/hour * 60 seconds/minute), then convert this back into a string. At a very, very basic level, you can do this using the gmtime function in Perl and the timegm in the Local::Time module. Other modules make it very simple to convert time from format to another and even do some math. My favorite is Time::Piece which allows you to use strptime format to quickly convert your time from whatever format it happens to be in. Then you can use the epoc member function to convert the time back into seconds, subtract 8,640,000, and reconvert it back into a string. A: If Time::Piece is core in your version of perl: use strict; use warnings; use Time::Piece; use Time::Seconds qw(ONE_DAY); my $t = "Sat Aug 04 23:59:59 GMT 2012"; my $dt = Time::Piece->strptime($t, "%a %b %d %T %Z %Y"); my $day_str = $dt->strftime("%F"); my $day = Time::Piece->strptime($day_str, "%Y-%m-%d") + 100.5*ONE_DAY(); print $day->strftime("%F"),"\n";
{ "language": "en", "url": "https://stackoverflow.com/questions/7567956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What can be the parameters to char getenv(const char *name);? I looked over various documentation on getenv(), all they describe is how to use it and what it does i.e environment variable whose name is specified as argument. But, I am trying to find the complete list or atleast as many as possible which can be used with getenv() I know few like, MANPATH HOSTNAME PATH INFOPATH PKG_CONFIG_PATH USER Can somebody help me extend this list? A: getenv queries your environment for any variable name. In Unix you can set any variable in the shell so there is no limit to what can be used (In OSX I think it is any Unicode string with no whitespace) Thus there is no complete list. To see what is in your environment type env in a Terminal window. Or as per Unix standard The value of an environment variable is a string of characters. For a C-language program, an array of strings called the environment is made available when a process begins. The array is pointed to by the external variable environ, which is defined as: extern char **environ; A: There is no complete list, because any user or any program can define their own environment variables with their own meanings. You might ask for the complete list of variables that a given program understands -- in that case often the man page for the program will list them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How create object of ScriptableObject in java-scripts.....? when I try to make an object of a class in java-script file which extends ScriptableObject... The following error will arise. js: uncaught JavaScript runtime exception: TypeError: Cannot find default value for object.” class file is package sumit2; import org.mozilla.javascript.ScriptableObject; public class Sumit extends ScriptableObject { public String getClassName(){ return "Sumit"; } public void foo() { System.out.println("Sumit!!!!!!!"); } } Java-Script File is:- importPackage(Packages.sumit2); var vv=new Sumit(); print(vv.foo()); A: First, you have to override getDefaultValue in Sumit. This is needed to convert object to string from javascript. package sumit2; import org.mozilla.javascript.ScriptableObject; public class Sumit extends ScriptableObject { public String getClassName(){ return "Sumit"; } public void foo() { System.out.println("Sumit!!!!!!!"); } @Override public Object getDefaultValue(Class<?> typeHint) { return toString(); } } And then, you will get following error message: js: uncaught JavaScript runtime exception: TypeError: Cannot find function foo in object sumit2.Sumit@1bf6770. **NOTE: The exception "Cannot find default value for object.” was caused when displaying exception above. The string value "sumit2.Sumit@1bf6770" is produced by calling getDefaultValue Second, javascript cannot call java methods of objects extended from ScriptableObject. If you want to call foo from javascript, override get(String, Scriptable) like following: package sumit2; import jp.tonyu.js.BuiltinFunc; import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; public class Sumit extends ScriptableObject { public String getClassName(){ return "Sumit"; } public void foo() { System.out.println("Sumit!!!!!!!"); } @Override public Object getDefaultValue(Class<?> typeHint) { return toString(); } @Override public Object get(String name, Scriptable start) { if ("foo".equals(name)) { return new Function() { @Override public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { foo(); return "Return value of foo"; } /** ...Implement all methods of Function other than call **/ }; } return super.get(name, start); } } And you will get: Sumit!!!!!!! Return value of foo I think the part /** ...Implement all methods of Function other than call **/ is annoying. I recommend to create an adapter class which implements Function and overrides all methods of Function with empty statements. A: I tried to use the code concept posted by @hoge1e3 but unfortunately it did not work for me with the latest Rhino build (1_7R5pre). However, I was able to create a Java class with methods that were invokable in JavaScript by using the annotations provided by the Rhino framework. In the end, it was actually very simple and straightforward. As a reference, please see the examples included in the Rhino source provided by Mozilla: https://github.com/mozilla/rhino/tree/master/examples Example class definition: //this gives you access to the annotations needed to expose your Java methods and properties to JavaScript import org.mozilla.javascript.annotations.JSFunction; public class Sumit extends ScriptableObject { public String getClassName(){ return "Sumit"; } @JSFunction public void foo() { //add in the above annotation and your Java method 'foo' will now be available in JavaScript System.out.println("Sumit!!!!!!!"); } } Example of converting the above class from Java to JavaScript: //Make sure to define your Context and Scope beforehand ScriptableObject.defineClass(scope, Sumit.class); A: There is a logical error in the code: you are attempting to print a void value: the return value of vv.foo(). If you change the code from what you have from print(vv.foo()) to: vv.foo(), or alternatively change the Java to return the String "Sumit!!!!!!!" and print that, I think what you have will work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Remove back entry in windows phone mango how can i remove back stack in wp7.1.I have 3 pages and say A,B,C when i navigate from A to B and in B there is a button to add new contact detail.when i click it page navigate to page C and In page C there is a Done button and when i clicked done button the page navigate to home page that is the page A and when i clicked back button from page A.the page C is visible since it is not finished.How can i clear the back stack.Also let me know is there any method to clear a particular page from the back stack.if the back stack contain page A,B,C,D and i have to clear the last two pages that is C and D.is that possible in the windows phone Mango? A: On the Load Event of the main page, put the following code: while (NavigationService.CanGoBack) { NavigationService.RemoveBackEntry(); } I'm not sure whether it's a good practice, but since in Mango users are supposed to close their apps by clicking the back button, I think it's a good way to avoid backing the whole history.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567966", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: MVC3 One model, One Controller, One (CRUD) View I have what i call "help tables" in my sql server database. These tables all contain the same attributes/fields. They will later be transformed into dropdowns. In my mvc3 application, i created a model, a view, and a controller for each table. I feel this is too much when it has to come to maintainability or extensibility. My Q is: Is it possible to reduce the number of my MVC's by having only one of Each MVC for all my "help tables"? if it is... Can you please provide me with a small description or link or anything of the sort that would help me? A: it depends upon your design you can have one controller for your entire project... are you using any ORM, enitity? NHibernate?, any pattern you are using in your project repository for example, if then you can have a single repository for the help tables and control them with one controller here is a helpful link MVC repository pattern design decision
{ "language": "en", "url": "https://stackoverflow.com/questions/7567968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Magento Database Repair Tool Not Working I'm trying to upgrade my magento 1.3.2.4 database to 1.4.0.1 by using "Magento database repair tool", but it's not working. When I enter the details launch the script it takes ages and still nothing happens (once I waited about and hour) and I have a decent server (dual Xeons, 16 GB RAM, 2xSAS RAID). When I get fed up waiting and refresh the page, or launch the script from the beginning, it gives me this error message: Error #1005: Can't create table 'temp.#sql-b4a_26b' (errno: 150) on SQL: ALTER TABLE `magento_wishlist_item` ADD CONSTRAINT `FK_WISHLIST_ITEM_STORE` FOREIGN KEY (`store_id`) REFERENCES `magento_core_store` (`store_id`) ON DELETE SET NULL ON UPDATE CASCADE Is there a way to solve this? A: You are doing it slightly wrong as repair tool is not meant for upgrading but repairing existing state for a successful upgrade do as follows: * *disable all community and local extensions *disable all core rewrites *revert to default theme *perform upgrade *enable extensions one by one and enjoy debugging
{ "language": "en", "url": "https://stackoverflow.com/questions/7567969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I reuse a UIView for drawing? I'm implementing a horizontal carousel of items - a bit like a UITableView, but with the cells arranged horizontally rather than vertically. I'd like it to support large numbers of items, by reusing one item and setting its properties only when it needs to draw or tap a view. How do I do this? Can I just call the views' drawRect from within the carousel's drawRect, or do I need to do something more complicated? A: DTGridView looks nice, also consider iCarousel for iOS which will also do coverflow style A: Also have a look at PhotoScroller sample code from Apple. Its every efficient. A: I doubt it will be as simple as that since the actual drawing in drawRect might happen at a different time than the setup of the cell. Everything in drawRect should ideally just be responsible to actually draw things in that view, not the layout. Hence UITableView has a whole bunch of methods to setup the sections, rows, etc. You might want to have a look at Daniel Tull's DTGridView which is basically doing exactly what you want to achieve. A: You shouldn't call drawRect: You'll want to call -[UIView setNeedsDisplay] to invoke -[UIView drawRect:]. This will set up the graphics context for you to draw into. As for the layout, your carousel should implement -[UIView layoutSubviews], which you invoke by calling -[UIView setNeedsLayout].
{ "language": "en", "url": "https://stackoverflow.com/questions/7567972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: asp.net link button not firing I have a link button inside the asp.net repeater control. I am trying to call the serverside method on the click event but no luck. I tried html anchor but it is not working so I switched to link button. <ItemTemplate> <li class="showmenu"> <p class="subtext">&nbsp;&nbsp;<asp:LinkButton ID="LinkButton1" runat="server" onclick="frontimagechange_click">Front</asp:LinkButton></p> <a href="#"><img id="Img1" src='<%# this.ResolveUrl("~/testimages/" + Eval("front")) %>' width="350" height="560" alt='<%# Eval("stylenumber") %>' runat="server" align="left" /></a> </li> </ItemTemplate> server-side code: protected void frontimagechange_click(object sender, EventArgs e) { //code to get the id of link button and change the //src of the image control inside the repeater } A: You need to handle ItemCommand event of Repeater control. Data controls such as the Repeater, DataList, GridView, FormView, and DetailsView controls uses Forwarded events. Summary: Rather than each button raising an event individually, events from the nested controls are forwarded to the container control. The container in turn raises a generic ItemCommand event with parameters that allow you to discover which individual control raised the original event. By responding to this single event, you can avoid having to write individual event handlers for child controls. Demo: Markup (.aspx) <asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand"> <ItemTemplate> <asp:LinkButton ID="LinkButton1" runat="server" CommandName="cmd" >Click Me</asp:LinkButton> </ItemTemplate> </asp:Repeater> In code-behind file, protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName == "cmd") { LinkButton button = e.CommandSource as LinkButton; } } A: is autoEventWireUp = true in your page ? did yo u enable viewstate for the repeater or page. it will not work if the viewstate is off
{ "language": "en", "url": "https://stackoverflow.com/questions/7567978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What impact do PHP sessions have on Magento functionality? My Magento store generates a whole lot of PHP sessions. I run a cron job to trim them back after they get to be a few days old. Questions is this: What is the impact on user experience of having their PHP session deleted? Is there any? I haven't discovered it... A: Not really and as Jon Stirlng commented it will only terminate the session between the client and server. If user comes back new session is created. You can configure the session length from Magento admin
{ "language": "en", "url": "https://stackoverflow.com/questions/7567984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Access to the clipboard when copying content from a WebControl with a Silverlight-component in VB6 Little old school :) In VB6, I got a UserControl containing a SHDocVwCtl.WebBrowser. The page I am displaying contains a Silverlight-component, and I want to be able to copy content (text) from the SL to the clipboard. For some reason this doesn't work out-of-the-box. I searched the web and found a method for copying text from a html-page to the clipboard, using this command: WebBrowser.ExecWB OLECMDID_COPY, OLECMDEXECOPT_DODEFAULT I was hoping that this would also work for copying content from SilverLight, but alas. Anyone know how to resolve this issue? A: Most operations that represent security risks (including file access and clipboard access) are restricted in Silverlight. I gather you are trying to copy the web page and include Silverlight content from a SL control on that page? If so, forget it. Silverlight effectively renders as a bitmap into the webpage (just like Flash). There is some limited support for clipboard copy/paste in Silverlight, but needs to be user triggered, so is unlikely to do what you seem to want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Correct index for my MySQL query I have the following Table: CREATE TABLE `sal_forwarding` ( `sid` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, `f_shop` INT(11) NOT NULL, `f_offer` INT(11) DEFAULT NULL, . . . PRIMARY KEY (`sid`), KEY `forwardTime` (`forwardTime`,`f_shop`), KEY `forwardTime_2` (`forwardTime`), KEY `f_shop` (`f_shop`) ) ENGINE=INNODB AUTO_INCREMENT=10457068 DEFAULT CHARSET=latin1 This table has more than 5 million rows. I've set indexes, as you can see above, but in my query no indexes are used and I don't understand why. Does anybody see my problem? Explain: EXPLAIN SELECT f_shop , COUNT(sid) , SUM(IF(toolbarUser=1,1,0)) FROM sal_forwarding WHERE DATE(forwardTime) = "2011-09-01" GROUP BY f_shop Result: +----+-------------+----------------+-------+---------------+--------+---------+--------+--------+-------------+ | ID | SELECT_TYPE | TABLE | TYPE | POSSIBLE_KEYS | KEY | KEY_LEN | REF | ROWS | EXTRA | +----+-------------+----------------+-------+---------------+--------+---------+--------+--------+-------------+ | | | | | | | | | | | | 1 | SIMPLE | sal_forwarding | index | (NULL) | f_shop | 4 | (NULL) | 232449 | Using where | +----+-------------+----------------+-------+---------------+--------+---------+--------+--------+-------------+ A: MySQL cannot use an index on a column inside a function. Remove the function date() from your select and MySQL will use the index. You can do this by changing your column definition of forwardtime to DATE Or you can change the query like so SELECT f_shop , COUNT(*) as RowCount , SUM(toolbarUser=1) as NumberOfToolbarUsers FROM sal_forwarding WHERE forwardTime BETWEEN '2011-09-01 00:00' AND '2011-09-01 23:59' GROUP BY f_shop Remarks * *count(*) is faster than count(namedcolumn); *(a=1) => 1 if true, (a=1) => 0 if false, so the if(a=1,1,0) can be shortened; *It's a good idea to alias your aggregate columns, so you can refer to them by their alias later. *If you add the following index (and remove index forwardtime), you query will run even faster. KEY fasttime (forwardTime,f_shop,toolbarUser) *The previous point is especially true on InnoDB where MySQL will use a covering index if possible, which means that it will never read the table itself to retrieve the data if it can find all it needs in the index.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DecimalUpDown (Extended WPF toolkit) - Source only gets updated on lost focus I am using Extended WPF toolkit's DecimalUpDown control with its Value property binded to a Decimal? as follows: <extToolkit:DecimalUpDown Value="{Binding BlahBlah, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ShowButtonSpinner="False" /> private Decimal? blahblah = 5; public Decimal? BlahBlah { get { return blahblah; } set { blahblah = value; } } I noticed that as I key in the number in the textbox, the Value does not get updated until I click outside the control. Its ValueChanged event is not fired as well until I click outside. I intend for the value to be updated as soon as the user changes the Value (i.e. real-time). Is there anyway to accomplish this? A: Yes, you have to replace the control template, with one that has the UpdateSourceTrigger=PropertyChanged. I did this last year by copying the existing template, making the change, then using it in my control. New Resource: <ControlTemplate x:Key="newDecimalUpDownTemplate" TargetType="{x:Type Control}"> <extToolkit:ButtonSpinner x:Name="Spinner" AllowSpin="{Binding AllowSpin, RelativeSource={RelativeSource TemplatedParent}}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" IsTabStop="False" ShowButtonSpinner="{Binding ShowButtonSpinner, RelativeSource={RelativeSource TemplatedParent}}"> <extToolkit:WatermarkTextBox x:Name="TextBox" AcceptsReturn="False" BorderThickness="0" Background="{TemplateBinding Background}" ContextMenu="{TemplateBinding ContextMenu}" Foreground="{TemplateBinding Foreground}" FontWeight="{TemplateBinding FontWeight}" FontStyle="{TemplateBinding FontStyle}" FontStretch="{TemplateBinding FontStretch}" FontSize="{TemplateBinding FontSize}" FontFamily="{TemplateBinding FontFamily}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" MinWidth="20" SelectAllOnGotFocus="{Binding SelectAllOnGotFocus, RelativeSource={RelativeSource TemplatedParent}}" TextAlignment="{Binding TextAlignment, RelativeSource={RelativeSource TemplatedParent}}" TextWrapping="NoWrap" Text="{Binding Text, RelativeSource={RelativeSource TemplatedParent}, UpdateSourceTrigger=PropertyChanged}" TabIndex="{TemplateBinding TabIndex}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" WatermarkTemplate="{Binding WatermarkTemplate, RelativeSource={RelativeSource TemplatedParent}}" Watermark="{Binding Watermark, RelativeSource={RelativeSource TemplatedParent}}"> <extToolkit:WatermarkTextBox.IsReadOnly> <Binding Path="IsEditable" RelativeSource="{RelativeSource TemplatedParent}"> <Binding.Converter> <Converters:InverseBoolConverter/> </Binding.Converter> </Binding> </extToolkit:WatermarkTextBox.IsReadOnly> </extToolkit:WatermarkTextBox> </extToolkit:ButtonSpinner> </ControlTemplate> In my Control: Template="{StaticResource newDecimalUpDownTemplate}" A: I myself also spent some time on this problem and found a pretty nice solution, I edited the template (Right click the DecimalUpDown and go to edit template Edit Template, thanks Ben you saved me some serious time --> How to overwrite a style) and combined it with the brilliant emorog solution! I wrote all of this in a style: <Style x:Key="DecimalUpDownStyle1" TargetType="{x:Type xctk:DecimalUpDown}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type xctk:DecimalUpDown}"> <xctk:ButtonSpinner x:Name="PART_Spinner" AllowSpin="{Binding AllowSpin, RelativeSource={RelativeSource TemplatedParent}}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" ButtonSpinnerLocation="{Binding ButtonSpinnerLocation, RelativeSource={RelativeSource TemplatedParent}}" Background="{TemplateBinding Background}" HorizontalContentAlignment="Stretch" IsTabStop="False" ShowButtonSpinner="{Binding ShowButtonSpinner, RelativeSource={RelativeSource TemplatedParent}}" VerticalContentAlignment="Stretch"> <xctk:WatermarkTextBox x:Name="PART_TextBox" Text="{Binding Text, RelativeSource={RelativeSource TemplatedParent}, UpdateSourceTrigger=PropertyChanged}" AutoMoveFocus="{Binding AutoMoveFocus, RelativeSource={RelativeSource TemplatedParent}}" AutoSelectBehavior="{Binding AutoSelectBehavior, RelativeSource={RelativeSource TemplatedParent}}" AcceptsReturn="False" BorderThickness="0" Background="Transparent" ContextMenu="{TemplateBinding ContextMenu}" Foreground="{TemplateBinding Foreground}" FontWeight="{TemplateBinding FontWeight}" FontStyle="{TemplateBinding FontStyle}" FontStretch="{TemplateBinding FontStretch}" FontSize="{TemplateBinding FontSize}" FontFamily="{TemplateBinding FontFamily}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" IsTabStop="{TemplateBinding IsTabStop}" IsUndoEnabled="True" MinWidth="20" Padding="{TemplateBinding Padding}" SelectAllOnGotFocus="{Binding SelectAllOnGotFocus, RelativeSource={RelativeSource TemplatedParent}}" TextAlignment="{Binding TextAlignment, RelativeSource={RelativeSource TemplatedParent}}" TextWrapping="NoWrap" TabIndex="{TemplateBinding TabIndex}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" WatermarkTemplate="{Binding WatermarkTemplate, RelativeSource={RelativeSource TemplatedParent}}" Watermark="{Binding Watermark, RelativeSource={RelativeSource TemplatedParent}}"/> </xctk:ButtonSpinner> </ControlTemplate> </Setter.Value> </Setter> </Style> and am able to use it like this: <xctk:DecimalUpDown Style="{StaticResource DecimalUpDownStyle1}" Value="{Binding DisplayValue, UpdateSourceTrigger=PropertyChanged}" /> A: I suspect that your binding parameter "gets lost" in the value transitions. The NumericUpDown controls internally bind a WatermarkTextBox to the Text property via TemplateBinding, to have the control respect your UpdateSourceTrigger it would probably need to be applied at that level. So due to this intermediate binding and the non-immediate synching between Value and Text you cannot control the source-update-behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Create dynamically a XSD for a form In the Form Builder tool from Orbeon it's possible to specify a schema by uploading a XSD file. But if we don't have the schema or we are too lazy to c reate it, is it possible to create dynamically the schema ? The schema is needed for the use of the form datas in other systems like a Business Object universe. Regards A: Orbeon Forms doesn't automatically generate schemas based on the forms you create in Form Builder; instead, as you noted, it is designed to consume a schema that you already have. However, there are tools that do just that. You can find some mentioned on the answer to this question on how to generate an XSD schema from an XML instance document. A: I am working on my own project called XsdFormEditor. Application will be able to show any XSD as a form in WinForms (95% done), Web (using Asp.Net MVC, 0% done), WPF (0% done). Idea is to load any XSD file, show it to user as a form, let user input some data and save data as XML. User will be also able to load default values to form from XML file. You can find it here: https://github.com/janstafa/XsdFormEditor
{ "language": "en", "url": "https://stackoverflow.com/questions/7567999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Relative redirect in Django The url config of my app currently looks like this: from django.conf.urls.defaults import patterns from django.views.generic.simple import redirect_to urlpatterns = patterns("myapp.views", (r"^$", redirect_to, {"url": "main/"}), (r"^(?P<title>.+)/$", "article"), ... ) This works fine when the app’s urls are used without prefix. Now, i want to include my app’s urls into a project’s url config with a prefix; like this: urlpatterns = patterns("", (r"^myapp/", include("myapp.urls")), ) But then http://myserver.org/myapp/ isn’t redirected to http://myserver.org/myapp/main/, but to http://myserver.org/main/. I think I understand how it works: The project’s url patterns get "myapp/". This matches the prefix, which is stripped away, leaving "", which is passed to the app’s patterns. The app is agnostic about the stripping and just redirects to main/, which Django interprets as /main/which doesn’t work for deeper nested urls (see edit below). How to tell Django to redirect to a URL relative to the app’s prefix? Edit: Mistake! Aah! Above code works fine, but my browser cached the permanent redirect to the previous url, which was "/main/". I cleared my cache and my new url "main/" (which is now now temporary to prevent caching) Works just fine. Sorry! But I realized that a answer would be helpful when I want to go to a url relative to the app’s root from a deeper nesting: "relative/" may work for http://myserver.org/myapp/foo/, but not for http://myserver.org/myapp/foo/bar/. A: In django 1.4 you will be able to use the function reverse_lazy(): from django.core.urlresolvers import reverse_lazy urlpatterns = patterns("myapp.views", (r"^$", redirect_to, {"url": reverse_lazy("myapp_title")}), (r"^(?P<title>.+)/$", "article", name="myapp_title"), ... ) reverse_lazy() resolves to the URL which was given the same string as "name" parameter that is provided as an argument to reverse_lazy(). If you are working with an earlier version, that you will have to specify the full path, which, of course, violates the DRY principle: (r"^$", redirect_to, {"url": "myapp/title/"}),
{ "language": "en", "url": "https://stackoverflow.com/questions/7568000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: modify iphone static library (.a file) how can i modify (just only change url) my static library file (.a file)? in fact i can see url string when i open with textmate editor and then change then save. but it gives this error: error which i take; ld: in /Users/ysnky/iPhonePro/MySDKTestApp/../../Desktop/iPhoneMySDK/MySDK.a, file is universal but does not contain a(n) i386 slice url which i would like to change; static NSString* baseUrl = @"http://127.0.0.1:8080/SDKProxyServer/secure/"; thanks. A: You shouldn't do it like that! But if you really want to edit binary files try 0xED Remember to keep the length of the file. This meaning that you can only enter an url with the same length or shorter (padding with zeros).
{ "language": "en", "url": "https://stackoverflow.com/questions/7568005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: XML Generator, Poco classes Is there a XML generator that creates a XML file based on my poco classes? I also want my nested classes in the XML output. Example: public class Person { public string Name { get; set; } public List<Child> Children { get; set; } } public class Child { public string Name { get; set; } } A: System.Xml.Serialization namespace, with emphasis on the XmlSerializer class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Storing "irregular" data in MySQL Apologies in advance if this question has already been asked, but I really don't know how to search for the problem I have. I'm developing a hotel booking and reservation management system with the intention of working with multiple clients, and it is expected that some clients will have different requirements, which include additional fields beyond the standard found in the booking response form (name, address, email, post code et cetera). To accomplish this, I've created an "options" field that stores these additional fields and their attendant values as serialized data. However, the client wants those fields to be searchable. While this is possible, this quite clearly isn't the optimal way of storing data that needs to be searched. Also, the table in question is of InnoDB format in MySQL. About the only thing I can think of is moving these additional fields into a separate table, but that presents a lot challenges to the reading and writing process of bookings. What is an optimal way of storing this kind of irregular data for the purposes of searching? A: One option is to use a key-value table. Store the keys separately, e.g.: CREATE TABLE keys ( id INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, keyName VARCHAR(100) ); CREATE TABLE values ( key_id INT(11) UNSIGNED NOT NULL, customer_id INT(11) UNSIGNED NOT NULL, value VARCHAR(100) ); Definitely still not great, but it's a valid solution to your problem. A: I would probably separate it out in to a table of its own if it's something that you won't always be needing when reading that table, i.e., do you ever query this table without returning this field? If you do choose to keep it in the same table there's no reason you can't place an index on it however which would speed up the searches as much as is possible without splitting up the data into logical chunks (which you can't if it can be "anything"). Do be warned that adding indexes will increase write times while decreasing read times (so don't do it in a system that will write more frequently than read or where the writes are more time sensitive). A: Your problem isn't really a database problem but rather an issue of how to support multiple clients and their requirements in a single program. The first thing you need to decide is whether multiple clients will be supported within a single instance of your program, or whether each client will have their own instance. If each client has their own instance, then you can maintain the common codebase separately and customize each client's instance as required. It may take some planning to produce a system in which changes made to the common codebase are correctly inherited by the customized versions, but in the end each client will get exactly what they want. If you're taking the multi-tenanted approach then you need to decide in advance the exact degree to which each client will be able to customize their system. You then provide for that customization in your database and application structure. At the simplest level, this allows each client to store their identifying information and a logo in a table someplace (possibly their own CSS link to really give the application a customized look). In the case of "extra fields", this can be handled in several ways. One is to simply put 10 extra VARCHAR fields on the table in question, and allow each client to "name" these fields as they see fit (possibly with TYPE specifiers that your application will use to coerce the VARCHAR data if needed). However many of the columns they've named are shown (with the correct prompt) where appropriate in the user interface. This approach has the benefit that, once set up, you won't have any additional work to do per client. Another approach would be to allow each client to have an additional 1 to 1 related table that stores the extra fields. In this case you can correctly name and type the fields in the database. The disadvantage is that to the extent you allow the client to freely choose what these fields are, you'll have to modify your user interface to "know" about each individual client.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does brush have only 3 hexa value? For example, in this page there is code such as: <SolidColorBrush x:Key="DisabledBorderBrush" Color="#AAA" /> Why does the color property only have 3 hex value? Doesn't color normally have 6 or 8 hex value? (like Fill="#FF0000FF") What does the 3 hexes means? mean? A: Brush colors may be specified in hex notation with three, four, six or eight digits as shown in the MSDN page for SolidColorBrush: <object property="#rgb"/> - or - <object property="#argb"/> - or - <object property="#rrggbb"/> - or - <object property="#aarrggbb"/> #rgb expands to #rrggbb (like it does in CSS hex notation), and #argb expands to #aarrggbb. Using three or six digits, the alpha is always maxed out. That is, these are all equivalent: <SolidColorBrush x:Key="DisabledBorderBrush" Color="#AAA" /> <SolidColorBrush x:Key="DisabledBorderBrush" Color="#FAAA" /> <SolidColorBrush x:Key="DisabledBorderBrush" Color="#AAAAAA" /> <SolidColorBrush x:Key="DisabledBorderBrush" Color="#FFAAAAAA" /> A: If you use a 3 digit value, each digit is automatically doubled, so #AAA is equivalent to #AAAAAA and #123 = #112233 A: Your example FF0000FF represents 4 Hex (tuple) values which represent 4 Bytes (RGBA). The term #AAA is a shortvalue term. #AAA equals #AAAAAA equals #FFAAAA
{ "language": "en", "url": "https://stackoverflow.com/questions/7568016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Calling a javascript function everytime a key is pressed in input field I want to call a function whenever a key is pressed. I am using onKeyPress event handler. However i see that it calling the function only the first time the key is pressed. I want to call it everytime a key is pressed. Can someone help me in this? A: Probably a bit too late but... <script> function checkPassword(pwd){ if(pwd.length < 8){ document.getElementById('message').innerHTML = 'Password needs to 8 characters minimum.'; } else{ document.getElementById('message').innerHTML = ''; } } </script> In the HTML body... <input type="password" name="password" size=30 onkeyup="checkPassword(this.value)" /> <span id="message"></span><br/> A: Answer 1. <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type="text/javascript"> var jq=jQuery.noConflict(); jq(document).ready( function(){ jq(document).keydown(function(event){ // -- here comes your code of function -- jq("#keycode").html(event.which); // example code, event.which captures key index }); }); </script> </head> <body> <div id="keycode">Press any Key to see its index</div> </body> Answer 2. You should replace onKeyPress with onchange | http://www.w3schools.com/jsref/event_onchange.asp A: I ran your HTML code and it works as expected. Your checkPassword() function may be set to do something only if the password is of a specified length, as in this code: <input type="password" name="password" size=30 onkeyPress="checkPassword(this)" /> <script type="text/javascript"> function checkPassword(pass) { if (pass.value.length > 7) { alert("Password is greater than 7 characters."); } else { //DO NOTHING } } </script> In this case, if the password isn't greater than 7 characters, the function may seem like it isn't getting called, but it actually is (the function just runs so fast you don't even know that it's getting called). A: <script> function l(ths){ document.getElementById('length').innerHTML=ths.length; } </script> Length: <span id="length"></span><br/> <input type="text" onkeyup="l(this.value);"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/7568019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generics Question ordering In an interview they told me Write the code in the brackets to order the list. They said order but you dont know if the type is going to be int or decimal. They also told me not to use framework methods like .sort So I have no idea how would I do it? I need to be ready for the next time somebody asks me this. Possible Inputs: 7,3,8,6,1 Or: 6.9, 4.5, 2.3, 6.1, 9.9 namespace InterViewPreparation1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnSort_Click(object sender, EventArgs e) { List<int> list= new List<int>(); list.Add(int.Parse(i1.Text)); list.Add(int.Parse(i2.Text)); list.Add(int.Parse(i3.Text)); list.Add(int.Parse(i4.Text)); list.Add(int.Parse(i5.Text)); Sort(list); } private void Sort<T>(List<T> list) { bool madeChanges; int itemCount = list.Count; do { madeChanges = false; itemCount--; for (int i = 0; i < itemCount; i++) { int result = Comparer<T>.Default.Compare(list[i], list[i + 1]); if (result > 0) { Swap(list, i, i + 1); madeChanges = true; } } } while (madeChanges); } public List<T> Swap<T>(this List<T> list, int firstIndex, int secondIndex) { T temp = list[firstIndex]; list[firstIndex] = list[secondIndex]; list[secondIndex] = temp; return list; } } } A: It depends how far down the line of "don't use framework methods" you go. Or should we be using logic probes against raw memory? Frankly, not just using list.Sort() is stupid (it is a bad interview question, IMO; I'd argue "no, I'm using list.Sort() - it exists and does the job nicely"). But! Another approach here would be to obtain: var comparer = System.Collections.Generic.Comparer<T>.Default; now you have a type-safe comparer that will work for any T with sortability. The act of calling .Compare lots of times to place into sequence is left as an exercise, and any text-book sorting strategy will work using comparer.Compare(x, y). A: Well, both Int and Double implement IComparable - this means that you should cast each element to an IComparable when performing your sort. As you can't use any standard .Net sorting method you need to implement one yourself. See Sorting algorithm for some inspiration. It would be easier if the method signature was different: public void sortlist<T>(List<T> list) where T : IComparable { } An example implementation of bubble sort: for (int pass = 1; pass < list.Count; pass++) { for (int i = 0; i < list.Count; i++) { if (list[i].CompareTo(list[i + 1]) > 0) { // Swap T temp = list[i]; list[i] = list[i + 1]; list[i + 1] = temp; } } } Alternatively if T isn't constrained to IComparable then you can tweak this slightly as per Marcs suggestion by using Comparer<T>.Default: Comparer<T>.Default.Compare(list[i], list[i + 1])
{ "language": "en", "url": "https://stackoverflow.com/questions/7568022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to avoid duplicate entries in nested iteration How can I rewrite this to avoid duplicate entries? images.each do |img| thumbs.each do |th| html << link_to(image_tag("#{th.url}"), "#{img.url}") end end I want to wrap thumbnail images th.url into links to original images img.url up: I'm using a fog gem to get images and thumbs from S3. They're files with different prefixes: storage.directories.get(bucket, :prefix => "thumbs").files A: Why not relate your images and thumbnails in some way? So if your image is called image_name.jpg you could have your thumbnail called thumbs/image_name.jpg. If your names are unconnected, then why not just associate them in your application so you use an associative array of images and thumbnail names? my_images = [ "image_1.jpg"=>"aflafffff_thumb.jpg", "image_2.jpg"->"zofofroro_thumb.jpg" ] Either of those ways enable you to just find the corresponding thumbnail for each image. A: You're looping through two collections (images and thumbs) - hence the duplicates. Guessing your image and thumb objects are linked somehow... e.g. thumbs available doing something like image.thumb images.each do |image| html << link_to(image_tag(image.thumb.url), image.url) end By only iterating through the images collection you won't get duplicates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysql deleting rows not in other table I know this is possible, but not when you need to reference the row you want to delete from. For example: select * from `dvd_role` r left join `dvd_actor2role` a on a.`roleId` = r.id where a.roleId is null; This produces the offending rows which are not present in the dvd_actor2role table and I want to delete. But I cannot use the dvd_role table in the subquery or I get an error, yet I need that table to be able to determine which rows to delete. Is there a workaround for this within SQL? Thanks. A: Left join and checking for null at the "right limb" seems a pathology these days. Use NOT EXISTS instead. SELECT * FROM dvd_role r WHERE NOT EXISTS ( SELECT * FROM dvd_actor_role a WHERE a.roleId = r.id ); If all is well replace the first "select *" by a DELETE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PostgreSQL user groups and authorization Postgresql version 9.0 I need an idea for grouping postgresql users. i have 150+ table in database, and i want to settle groups of people. some of them can reach all tables, some of them not. I know it is possible to make it using grant or creating roles. but i want to figure out which is the best way to do that. how will it effect the performance? giving all users to access some of the tables and managing them seems hard to me. so i thought what about creating different tablespaces and set permissions by tablespace. is there any good tutorial , article or approach for creating user groups? what is your advice? A: If you set permissions by tablespace, and requirements change such that the people in accounting need access to another table, then you have to move the table from one tablespace to another. But then again you can't move that table into a different tablespace without screwing up the permissions for all the other users. Don't do that. Instead, create logical groups for your users, assign users to groups, and assign permissions to groups. The PostgreSQL term is "roles". It is frequently convenient to group users together to ease management of privileges: that way, privileges can be granted to, or revoked from, a group as a whole. In PostgreSQL this is done by creating a role that represents the group, and then granting membership in the group role to individual user roles.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Web programming principles Coming from a bit of a conventional (if rusty) programming background, I am busy getting to grips with the "stateless" nature of web sites. It is quite a mindset change! I've created a small web site for the team in which I work to use internally to track some aspects of our daily grind. The site is functional, I'm pretty proud of what I managed to come up with, bla bla bla. However I read something somewhere which suggests that I may have done it in a bad way. In particular, the central page of the team website does most of the work. It checks where you came from and then "switches" to perform some work (make some changes in the database) and then again it renders the page. In many cases the page simply calls itself! What I do is I display a table. In the last column of each row is a set of html forms. Each form have a submit button, at least one hidden field. The "submit" buttons have names/values such as "Delete" "Modify" "Archive" etc. If $_POST['submit'] == "delete" then I perform that function on a row identified by a hidden field. Vis a vis for "Archive". For Modify I open a new page, display a form with default values, and when the user submits the form the main PHP page is once again called to do an SQL update before it displays the table. So essentially a large (and growing) case construct near the start of the main page does most of the work, even including the login button! It seems quite neat and organized this way, but I have two questions: * *Is there a way to eliminate the "Resend form data" prompt when a user press Back? The back button doesn't make much sense on this website, most of the time, but we are dealing with humans here. I notice other people have posted similar questions about logout buttons and the like, but the answers I've found so far makes little or no sense to me. *Is this bad programming practice, particularly the whole PHP-calls-itself-from-a-form-action concept .... ? Thank you for the time! A: To your questions: * *You are looking for something like Post-redirect-get, that means after submitting you 'do the work' with your data and redirect your user right after, so hitting the back button won't re-submit! *In general that's how it works...in the beginning. After a while you should have a look at OOP (Object oriented programming) or for starters just seperate each action into functions, maybe those functions even into seperate files. Check the PHP Manual for functions or if you are really keen to learn more, OOP would be the holy grail, but that's a 'bit' complex ;) A: Post-redirect-get is a pattern that solves this quite cleanly. A: What you developed is not a website but more like a web application. In order to eliminate the "back button problem" you should consider using some JavaScript magic(for example Ajax can help you eliminate the need to open another page or to submit to the same page, jQuery can help with displaying and hiding parts oh the page based on user interaction). For the second question: there is nothing wrong with having all the logic in one php file. Sure, it can hurt if you have something like a bazillion lines of of code but for a small application... why not?! Speaking generally it is recommended to separate the logic and the GUI. You can read about it here. A: It is always a wise idea to redirect the page after the form data has been processed. It avoids resending form on page refresh or back button. For redirecting in php, you may use: header("Location: {url here without brackers}");
{ "language": "en", "url": "https://stackoverflow.com/questions/7568041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Issue with modular pattern approach I just went to http://jsperf.com/prototype-vs-closures/2 prototype vs closures performance test. Actually I use Modular pattern a lot which internally uses clousre AFAIK. Now as per test it says protoype wins over modular pattern. Is that true? should I be using prototypes based approach whenever it is possible? A: Look at the diagram and think whether you reach a couple 100k reads / writes. If not: irrelevant for you, take the approach which feels most natural and maintainable to you. Clean code is far more important than optimization, and premature optimiztion causes much grief later on. Also, it is quite possible that the differences are much smaller a couple of JavaScript Enigne revisions (a couple of months) later... A: The test you've linked to has no relation to the module pattern; Rather, it tests prototype-based methods vs closure-based methods on an object. (Crockford's "privileged" methods.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7568042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get form elements values in javascript and create a url with thoese values For example I have a form: <form name='myform' id='myformid'> <input type='text' name='name' id='name'> <input type='text' name='color' id='color'> <input type='text' name='made' id='made'> <input type='submit' name='submit'> </form> Now I want to call a javascript function on above form submit. This function will get all form elements values and create a URL to redirect. For example: example.com/search.php?name=toyota&color=white&made=abc How can I create this JS function? Thanks A: function getValues(){ var form = document.getElementById('myformid'); var url = 'example.com/search.php?'; for(var i=0; i<form.elements.length; i++) { var element = form.elements[i]; //url += (i>0 ? '&' : '') + element.name + '=' + element.value; //UPDATE url += (i>0 ? '&' : '') + encodeURIComponent(element.name) + '=' + encodeURIComponent(element.value); } return url; } A: With the MochiKit library you could use: http://mochi.github.com/mochikit/doc/html/MochiKit/DOM.html#fn-formcontents Source here: https://github.com/mochi/mochikit/blob/master/MochiKit/DOM.js#L45 This along with the 'querystring' function from the same library: http://mochi.github.com/mochikit/doc/html/MochiKit/Base.html#fn-querystring https://github.com/mochi/mochikit/blob/master/MochiKit/Base.js#L1184 And you can have a simple solution: window.location.href = 'example.com/search.php?' + queryString(formContents(getElement('myformid'))) A: I know you want a javascript function, but this way maybe better if you want to send your request after submit: <form name='myform' action='search.php' method='get'> <input type='text' name='name' /> <input type='text' name='color' /> <input type='text' name='made' /> <input type='submit' /> </form> A: <script> function myFunction() { var name=document.myform.name.value; var color=document.myform.color.value; var made=document.myform.made.value; alert('example.com/search.php?name='+name+'&color='+color+'&made='+made); } </script> <form name='myform' id='myformid' onSubmit='javascript:myFunction()'> <input type='text' name='name' id='name'> <input type='text' name='color' id='color'> <input type='text' name='made' id='made'> <input type='submit' name='submit'> </form>
{ "language": "en", "url": "https://stackoverflow.com/questions/7568043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Insert index/Keys into an array D Could you give a an advice how to insert keys/index to a an array in a specific order as you can se.... I would like to in the result index the values id1 = 3 id2 = 4 id3 = 5. How do I do that? This code public static function getTest($ids){ $input = array(); foreach ($ids as $id) { $input['result'] = $ids; } $result = array('status'=>"success", 'message'=>"blah blah", 'result'=> $ids ); var_dump($result); return $result; } produces this (getTest is called from another file and it gives out array(3,4,5)) array(3) { ["status"]=> string(7) "success" ["message"]=> string(9) "blah blah" ["result"]=> array(3) { [0]=> int(3) [1]=> int(4) [2]=> int(5) } } A: If you create an array the elements are in the order you added them: $a = array(); $a[2] = 2; $a[1] = 1; $a[9] = 9; var_dump($a); // array(3) { [2]=> int(2) [1]=> int(1) [9]=> int(9) } I am not really sure what you want but have a look here the page always helps my lot. Response to comment: Try this foreach ($ids as $key => $id) { $input['result']['ID'.$key] = $id; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7568048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hibernate: map last row of a @OneToMany relation I have a relation between element and its names. All historical names as well as the current one are located in table "element_name" that has field "created". The row last created is the current name of the element. How could I map the current name of the element as the property of the element? class Element implements Serializable { @OneToMany(fetch = FetchType.LAZY) private List<ElementName> historyOfElementNames; // What annotations should be used here? private ElementName currentElementName; ... } Thanks in advance! A: An alternative to your solution would be to map all names in a list, sort that list and then get the current name as elementNames.get(elementNames.size() - 1). To enable this, add the @IndexColumn annotation as well as the actual index column and indices. That way you also get the order of name changes. Edit: as of Hibernate 3.5 @IndexColumn seems to have been renamed to @OrderColumn.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Listview below listview android I want to have a listview containing some content. And below it, when you scroll to the buttom of the listview, a new header would be displayed followed with a new list view. Is is possible? //Edit The two listview need to have differet layout xml. Have tried to put the second listview in a the footview of the first. But then the second listview is to small. Here is my layout <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:id="@+id/header" android:background="@drawable/app_topbar" android:layout_width="fill_parent" android:orientation="horizontal" android:layout_height="wrap_content" android:layout_alignParentTop="true"> <TextView android:text="@string/headline_notused" android:gravity="center" android:textSize="24sp" android:textStyle="bold" android:textColor="@color/txtcolor" android:layout_width="fill_parent" android:layout_height="fill_parent"></TextView> </LinearLayout> <ProgressBar android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_below="@+id/header" android:visibility="gone" style="?android:attr/progressBarStyleHorizontal" android:id="@+id/progressbarHorizontal" /> <ListView android:id="@+id/notUsedList" android:divider="@android:color/transparent" android:dividerHeight="5dip" android:layout_height="wrap_content" android:layout_marginBottom="5dip" android:layout_width="fill_parent" android:layout_weight="1" android:layout_below="@+id/progressbarHorizontal"></ListView> <LinearLayout android:orientation="vertical" android:layout_below="@+id/notUsedList" android:background="@drawable/app_background" android:layout_marginBottom="55dip" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:id="@+id/myUsedHeader" android:background="@drawable/app_topbar" android:layout_marginTop="10dip" android:layout_width="fill_parent" android:orientation="horizontal" android:layout_height="wrap_content" android:layout_alignParentTop="true"> <TextView android:text="@string/headline_used" android:gravity="center" android:textSize="24sp" android:textStyle="bold" android:textColor="@color/txtcolor" android:layout_width="fill_parent" android:layout_height="fill_parent"></TextView> </LinearLayout> <ListView android:id="@+id/usedList" android:divider="@android:color/transparent" android:dividerHeight="5dip" android:layout_height="fill_parent" android:layout_width="fill_parent"></ListView> </LinearLayout> </RelativeLayout> A: You mean listview with different sections and each sections having a header. Try this link Jeff sharkey adapter A: You should detect when you arrive at the listview last item. Then, you can change your adapter, change activity or wathever you find appropriate to display the new ListView: Implement an OnScrollListener, set your ListView's onScrollListener and then you should be able to handle things correctly. For example: // Initialization stuff. yourListView.setOnScrollListener(this); // ... ... ... @Override public void onScroll(AbsListView lw, final int firstVisibleItem, final int visibleItemCount, final int totalItemCount) { switch(lw.getId()) { case android.R.id.list: final int lastItem = firstVisibleItem + visibleItemCount; if(lastItem == totalItemCount) { // Last item is fully visible. You will then need to start a New activity, maybe... Or change the layout.. I don't know! } } } A: yes it is possible. you can define one listview in linearlayout and onether in other linearlayout and put both in parent LinearLayout.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Comments in mustache.js icanhaz don't work? I have the following in my template {{! This is a comment that shouldn't be rendered }} I tried it using the demo here: http://mustache.github.com/#demo And found an example from mustache here: https://github.com/janl/mustache.js/blob/master/examples/comments.html But comments are rendering in my templates. I'm using iCanHaz 0.9. A: Must be some sort of bug with mustache.js - you should report it to them If instead you try {{ ! This is a comment that shouldn't be rendered }} (notice the extra space), the comment will NOT be rendered
{ "language": "en", "url": "https://stackoverflow.com/questions/7568060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: stupid error android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed here is the error: 09-27 12:47:39.155: WARN/System.err(10899): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed 09-27 12:47:39.155: WARN/System.err(10899): at android.database.sqlite.SQLiteStatement.native_execute(Native Method) 09-27 12:47:39.155: WARN/System.err(10899): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61) 09-27 12:47:39.155: WARN/System.err(10899): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1809) 09-27 12:47:39.165: WARN/System.err(10899): at de.enough.appmate.dbase.CMSResource.updateItem(CMSResource.java:1279) 09-27 12:47:39.165: WARN/System.err(10899): at de.enough.appmate.dbase.CMSResourceUpdater.updateItems(CMSResourceUpdater.java:178) 09-27 12:47:39.165: WARN/System.err(10899): at de.enough.appmate.dbase.CMSResourceUpdater.loadUpdates(CMSResourceUpdater.java:102) 09-27 12:47:39.165: WARN/System.err(10899): at de.enough.appmate.dbase.CMSResourceUpdaterRunnable.run(CMSResourceUpdaterRunnable.java:32) 09-27 12:47:39.165: WARN/System.err(10899): at java.lang.Thread.run(Thread.java:1019) Here is the code: this.db.execSQL("UPDATE " + CMSConstants.ITEMS + " SET " + CMSConstants.ID + "= ?, " + CMSConstants.TITLE + " = ?, " + CMSConstants.IS_PAGE + " = ?, " + CMSConstants.IS_HIDDEN + " = ?, " + CMSConstants.ITEM_TYPE + " = ?, " + CMSConstants.ORDER_INDEX + " = ?, " + CMSConstants.SECTION_ID + " = ?, " + CMSConstants.TABLE_SECTION_NAME + " = ?, " + CMSConstants.TABLE_SECTION_ID + " = ?, " + CMSConstants.IMAGE1_FILE + " = ?, " + CMSConstants.IMAGE1_CAPTION + " = ?, " + CMSConstants.IMAGE1_DISPLAY_IN_GALLERY + " = ?, " + CMSConstants.CATEGORY1 + " = ?, " + CMSConstants.CATEGORY2 + " = ?, " + CMSConstants.GEO_LONGITUDE + " = ?, " + CMSConstants.GEO_LATITUDE + " = ?, " + CMSConstants.DESCRIPTION + " = ?, " + CMSConstants.KEYWORDS + " = ?, " + CMSConstants.BLOCKWORDS + " = ?, " + CMSConstants.CLEAN_NAME + " = ?, " + CMSConstants.ADDITIONAL_FIELD1_NAME + " = ?, " + CMSConstants.ADDITIONAL_FIELD1_VALUE + " = ?, " + CMSConstants.ADDITIONAL_FIELD2_NAME + " = ?, " + CMSConstants.ADDITIONAL_FIELD2_VALUE + " = ?, " + CMSConstants.ADDITIONAL_FIELD3_NAME + " = ?, " + CMSConstants.ADDITIONAL_FIELD3_VALUE + " = ?, " + CMSConstants.ADDITIONAL_FIELD4_NAME + " = ?, " + CMSConstants.ADDITIONAL_FIELD4_VALUE + " = ?, " + CMSConstants.ADDRESS_LINE1 + " = ?, " + CMSConstants.ADDRESS_LINE2 + " = ?, " + CMSConstants.ADDRESS_LINE3 + " = ?, " + CMSConstants.ADDRESS_LINE4 + " = ?, " + CMSConstants.ADDRESS_LINE5 + " = ?, " + CMSConstants.ADDRESS_POSTCODE + " = ?, " + CMSConstants.CONTACT_EMAIL + " = ?, " + CMSConstants.CONTACT_EMAIL_DISPLAY + " = ?, " + CMSConstants.CONTACT_EMAIL_SUBJECT + " = ?, " + CMSConstants.CONTACT_TEL + " = ?, " + CMSConstants.CONTACT_TEL_DISPLAY + " = ?, " + CMSConstants.CONTACT_WEB + " = ?, " + CMSConstants.CONTACT_WEB_DISPLAY + " = ?, " + CMSConstants.MODIFICATION_DATE + " = ?, " + CMSConstants.PAGE_HEADER + " = ?" , bindArgs); and the bindArgs: String[] bindArgs = { (String) item.get(CMSConstants.ID), (String) item.get(CMSConstants.TITLE), (String) item.get(CMSConstants.IS_PAGE), (String) item.get(CMSConstants.IS_HIDDEN), (String) item.get(CMSConstants.ITEM_TYPE), (String) item.get(CMSConstants.ORDER_INDEX), (String) item.get(CMSConstants.SECTION_ID), "", "", (String) item.get(CMSConstants.IMAGE1_FILE), (String) item.get(CMSConstants.IMAGE1_CAPTION), (String) item.get(CMSConstants.IMAGE1_DISPLAY_IN_GALLERY), (String) item.get(CMSConstants.CATEGORY1), (String) item.get(CMSConstants.CATEGORY2), (String) item.get(CMSConstants.GEO_LONGITUDE), (String) item.get(CMSConstants.GEO_LATITUDE), (String) item.get(CMSConstants.DESCRIPTION), (String) item.get(CMSConstants.KEYWORDS), (String) item.get(CMSConstants.BLOCKWORDS), (String) item.get(CMSConstants.CLEAN_NAME), (String) item.get(CMSConstants.ADDITIONAL_FIELD1_NAME), (String) item.get(CMSConstants.ADDITIONAL_FIELD1_VALUE), (String) item.get(CMSConstants.ADDITIONAL_FIELD2_NAME), (String) item.get(CMSConstants.ADDITIONAL_FIELD2_VALUE), (String) item.get(CMSConstants.ADDITIONAL_FIELD3_NAME), (String) item.get(CMSConstants.ADDITIONAL_FIELD3_VALUE), (String) item.get(CMSConstants.ADDITIONAL_FIELD4_NAME), (String) item.get(CMSConstants.ADDITIONAL_FIELD4_VALUE), (String) item.get(CMSConstants.ADDRESS_LINE1), (String) item.get(CMSConstants.ADDRESS_LINE2), (String) item.get(CMSConstants.ADDRESS_LINE3), (String) item.get(CMSConstants.ADDRESS_LINE4), (String) item.get(CMSConstants.ADDRESS_LINE5), (String) item.get(CMSConstants.ADDRESS_POSTCODE), (String) item.get(CMSConstants.CONTACT_EMAIL), (String) item.get(CMSConstants.CONTACT_EMAIL_DISPLAY), (String) item.get(CMSConstants.CONTACT_EMAIL_SUBJECT), (String) item.get(CMSConstants.CONTACT_TEL), (String) item.get(CMSConstants.CONTACT_TEL_DISPLAY), (String) item.get(CMSConstants.CONTACT_WEB), (String) item.get(CMSConstants.CONTACT_WEB_DISPLAY), (String) item.get(CMSConstants.MODIFICATION_DATE), (String) item.get(CMSConstants.PAGE_HEADER) }; So has anyone an idea why I get this failure? thanx newone A: you are missing WHERE clause, As when you update anything you must point where you want to update
{ "language": "en", "url": "https://stackoverflow.com/questions/7568062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to bind to resource from codebehind without using DataContext I have a datagrid with messages, which has declared itemsource in codebehind. TO every row I need to add contextmenu from which user can select user to whom he wants forward a message. <!-- COLUMN: DATE SENT --> <data:DataGridTemplateColumn x:Name="DateSentColumn" CanUserSort="True" SortMemberPath="DateSent" Width="80"> <data:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding DateSent, ConverterParameter=False, Converter={StaticResource cnvDate}}" ToolTipService.ToolTip="{Binding DateSent, ConverterParameter=True, Converter={StaticResource cnvDate}}" VerticalAlignment="Center" FontWeight="{Binding IsBold, Converter={StaticResource cnvFontWeight}}" Foreground="{Binding IsOverdueMessage, Converter={StaticResource cnvOverdue}}" Margin="5,0,5,0"> <telerik:RadContextMenu.ContextMenu> <telerik:RadContextMenu x:Name="inboxContextMenu" Opened="inboxContextMenu_Opened" ItemClick="inboxContextMenu_ItemClick"> <telerik:RadMenuItem x:Name="ForwardMessageMenuItem" Header="Forward message"> <telerik:RadMenuItem x:Name="SelectUserMenuItem"/> </telerik:RadMenuItem> </telerik:RadContextMenu> </telerik:RadContextMenu.ContextMenu> </TextBlock> </DataTemplate> </data:DataGridTemplateColumn.CellTemplate> </data:DataGridTemplateColumn> I don't know how can I bind users to SelectUserMenuItem radmenuitem. In code behind I have a property Users.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mysql Query to show exact 7 days expiring clients I am having a bit of difficulty in getting the right value. What I want to query is, the users who expire in 7 days, for example on 4th Oct 2011, the query should display the result of that particular day only. Right now I am querying as below: select * from users where exp_date between now() and adddate(now(), INTERVAL 7 DAY). this query keep display till next 7 days. But i want to show only for on 7th day expiring clients as I move on to tomorrow's date then the today's displayed query should not display on tomorrow's display rather it show the expiring client on 5th Oct 2011 and so on. How do I achieve this? please help A: Try this WHERE exp_date = CURDATE()+7 You may add days or subtract days as you move on calender like this: WHERE exp_date = CURDATE()+7+$daysoffset where $daysoffset is 0 for Today, 1 for Tomorrow. A: TRY This: SELECT * FROM users WHERE exp_date = DATE_ADD(CURDATE(), INTERVAL 7 DAY) Make sure your exp_date field is DATE type
{ "language": "en", "url": "https://stackoverflow.com/questions/7568067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Xcode 4 too many clang processes With references to the following question speeding up xcode builds, the following command still works in Xcode 4: defaults write com.apple.Xcode PBXNumberOfParallelBuildSubtasks 4 However it only limits the number of 'cplus' processes that Xcode initiates while building. In Xcode 4 now I also get a ton (more than the number of cores I have) of the 'clang' processes, which eat up a lot of memory and freeze my system. So is there any way to limit the number of 'clang' processes while building? A: The answer is here: https://devforums.apple.com/message/545348#545348 defaults write com.apple.dt.Xcode IDEBuildOperationMaxNumberOfConcurrentCompileTasks 4 A: what worked for me in Xcode5, having the same issue (freezes on archiving on last file) is to change the Build Settings: Set "optimisation level" for RELEASE (or all) to NONE. worked wonders.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Subtract month and day mysql I need to subtract 1 month and 4 days with mysql, I saw the command DATE_ADD (NOW (), - 1 MONTH) perfect for 1 month but for 1 month and 4 days, using 31 days is not valid for every month that some bring 30, 29, 28. I can not add 31 + 4, 30 + 4, etc. A: SELECT CURRENT_TIMESTAMP + INTERVAL - 1 MONTH + INTERVAL - 4 DAY; or SELECT CURRENT_DATE + INTERVAL - 1 MONTH + INTERVAL - 4 DAY; A: SELECT DATE_ADD(DATE_ADD(NOW(),INTERVAL -1 MONTH), INTERVAL -4 DAY) A: Keep it simple: SELECT CURDATE() - INTERVAL 1 MONTH - INTERVAL 4 DAY; or SELECT '2014-03-27' - INTERVAL 1 MONTH - INTERVAL 4 DAY; or if you like to preserve the current time: SELECT NOW() - INTERVAL 1 MONTH - INTERVAL 4 DAY; (Tested on MySQL 5.1.73 and newer) A: using DATE_SUB [docs] like : DATE_SUB((DATE_SUB(curdate(), INTERVAL 1 MONTH)), INTERVAL 4 DAY)
{ "language": "en", "url": "https://stackoverflow.com/questions/7568072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "58" }
Q: Shared variables between two independent processes I have a daemon process running and doing its job. I want to be able to collect statistics from it while it is running. My environment is Linux and the programming language is C. One option is to make the daemon process writes to some log file and parse/analyse the file later to get the statistics. This option does not provide the flexibility to change the sampling rate without restarting the daemon process. Also, it involves parsing log files. Another option is to use shared memory between the daemon process and the statistics collector process. This requires copying manually all monitored variables whenever modified to the shared region. Using pipes or sockets is not preferable as it requires blocking or creating new threads. I am wondering if there is some technique like shared memory, but I need to be able to associate the process variables with this specific addresses within shared region. Whenever the variable is changed, I don't need to copy the variable myself. Any suggestions are welcome. EDIT: What I want actually is like /proc file system on Linux but for user-space processes. A: Use a memory mapped file: http://en.wikipedia.org/wiki/Memory-mapped_file
{ "language": "en", "url": "https://stackoverflow.com/questions/7568075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ninject.Web.Mvc knows about dynamically loaded Controller but ASP.Mvc doesnt? I have got quite a complex project on the go at the moment, and as part of this I have a MEF layer which purely handles loading of plugins and then the newly loaded plugins expose their routes which are registered with asp.mvc and their controllers which are added to Ninject's bindings. The problem however comes in when the dynamically added routes are hit (and they are hit, I have checked with route debugger) even with correctly added Namespaces for the plugin within the route. When I say I have added the namespaces I mean like below: var namespaces = new [] { "MyPlugin.Controllers" }; routeCollection.MapRoute( PluginRoute, "plugin/{action}", new { controller = "Plugin", action = "Default" }, namespaces); Just to give a little more context to this situation, I am inheriting from NinjectHttpApplication and not doing anything else, no custom controller factories, no custom dependency resolvers, just what Ninject gives me. Then I take the currently active Kernel, give it to the plugins and they register themselves. Now the routes that are hit do not work, I just get a 404 for any external routes, even though they are hit and the controller is (yes tripple checked) registered with the Ninject Kernel. So I am thinking that although Ninject has the type registered, Mvc's DefaultControllerFactory cannot find the type when calling through to: GetControllerTypeWithinNamespaces(string controllerName, HashSet<string> namespaces) One thing that baffles me at the moment though, is that it is not finding it even with the correct namespace... HOWEVER just to prove my hypothisis, if I add the plugin as a reference within the asp mvc project and run it (without changing any code, just the plugin assembly is a reference within the project, so it will end up within the bin directory) it will work. Hits the route and I get the desired output... So at this point I am wondering if although MEF is hosting the external DLLs, it is not sharing it in some way with the current AppDomain or something... which seems odd... This is a blocker for me at the moment, so any advice would be great! A: It seems the DefaultControllerFactory does not know which type is responsible for handling the requests. You have either to find out why the DefaultControllerFactory does not know about these controllers or provide your own implementation that is able to handle these cases. The problem is definitely more MEF related than Ninject related. public class MyControllerFactory : DefaultControllerFactory { public override IController CreateController(RequestContext requestContext, string controllerName) { Type controllerType = this.GetControllerType(requestContext, controllerName) ?? this.GetPluginControllerType(requestContext, controllerName) return this.GetControllerInstance(requestContext, controllerType); } private Type GetPluginControllerType(RequestContext requestContext, string controllerName) { // put your own implementation here } } Another solution is to use Ninject'ss assembly loading mechanism instead of MEF. A: Sounds mef related, what happens when you try to instantiate the classes from the kernel directly yourself? If it works you could just create your own controller factory: public class NinjectControllerFactory : DefaultControllerFactory { private IKernel _kernel; public NinjectControllerFactory(IKernel kernel) { _kernel = kernel; } protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType) { if (controllerType == null) return null; return (IController)_kernel.Get(controllerType); } } Although these days with mvc 3 I don't bother with the controllerfactory and go in at dependency resolver level. public class NinjectDependencyResolver : IDependencyResolver { private IKernel _kernel; public NinjectDependencyResolver(IKernel kernel) { _kernel = kernel; } public object GetService(Type serviceType) { return _kernel.TryGet(serviceType); } public System.Collections.Generic.IEnumerable<object> GetServices(Type serviceType) { return _kernel.GetAll(serviceType); } } n.b. both need to be registed in application_start respectively (although you'd only use one) ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(_kernel)); DependencyResolver.SetResolver(new NinjectDependencyResolver(_kernel));
{ "language": "en", "url": "https://stackoverflow.com/questions/7568078", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to specify current working path in jni I have Java Android application (TestApp). From my TestApp I call function from jni code: JNIEXPORT jint JNICALL Java_com_app_test_testApp_CreateFile( JNIEnv* env, jobject thiz, jobject jclass ) { pFile = fopen ("/NDK_Log.txt", "a+"); // Get's current date time and print it in the log file. dateTime = time(NULL); currentTime = ctime( &dateTime ); fprintf( pFile, "\n\n--------------------------------------------------------------------------\n" ); fprintf( pFile, "\t\t\t\t\t\t %s", currentTime ); fprintf( pFile, "--------------------------------------------------------------------------\n\n" ); fprintf( pFile, ">>> Enter Initialize <<<\n" ); #endif return 0; } I want to create file in "data/data/com.app.test.testApp/" folder but I can't, what I am doing wrong, and how I can specify current working directory or give current path of application ? A: You can't rely on fopen to use "current working directory". In device internal memory, you can access only files in your app's data folder. And you may get your app's private folder this way: String dir = getPackageManager().getPackageInfo("com.example.app", 0).applicationInfo.dataDir; It will be somewhere in /data/data folder. A: Android provides getcwd(), but I don't think that's what you really need. As already mentioned, you'll want to retrieve the base path portion from Java. You can implement a method in Java to get the path and call it from C/C++ via JNI if you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Extra default padding problem CSS for Firefox I have that CSS for one of my elements: background: -moz-linear-gradient(top, #3B3B3B 0%, #FFFFFF 100%); When I inspect it at Firebug it is like: -moz-linear-gradient(center top , #3B3B3B 0%, #FFFFFF 100%) repeat scroll 0 0 transparent When I look at my page it has some paddings from top left down and bottom. How can I solve it? PS: The problem is that. I give that style into a a div as like: <html> ... <body> <div id ="myDiv"> ....//That div is just under the body element so includes everything. </div> </body> </html> At firefox html element is upper than that div element and if I give that style into html element I can not see the result at my div. It works at Chrome, I get this error at Firefox. A: Have you removed the margin and padding from your html, body, div elements? Something like: html, body{ padding:0; margin:0; } #myDiv{ padding:0; margin:0; background: -moz-linear-gradient(top, #3B3B3B 0%, #FFFFFF 100%); //OTHER STYLES }
{ "language": "en", "url": "https://stackoverflow.com/questions/7568083", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android - Notifying observers of changes in an sqlite query/view I'm developing an application where I need to update a DB, and then notify interested observers if the updates have changed what they are observing. It seems to me that an obvious way of doing this would be to define triggers which invoke a callback when the data being observed has changed (e.g. see http://www.mail-archive.com/sqlite-users@sqlite.org/msg32753.html). However, the Android SQLite bindings don't appear to support user defined functions, which kills this idea. Can anyone offer another suggestion of how I might do this? I can probably implement a change notification mechanism without involving the database, but I would rather not, as a good part of the reason for using an off the shelf database is to get this kind of functionality... Cheers, Dunk A: Duncan, can you give us a little background on what it is that you're trying to achieve through doing this? It seems that you're programmatically writing information into the database from within your application and then you may or may not want to also visibly notify the user? If this is the case I'm not sure there would need to be a separate database trigger concept to control notification. If these are disassociated activities or there is some other substantial separation I think you may want to look at writing your own custom intent to be fired during the database write and setting up the "interested observers'" activity to receive it. Without more robust support for the SQLite implementation I think that handling this in your application is the best you can shoot for. Android Intents Documentation: http://developer.android.com/guide/topics/intents/intents-filters.html Custom Intent Example: http://thinkandroid.wordpress.com/2010/02/02/custom-intents-and-broadcasting-with-receivers/
{ "language": "en", "url": "https://stackoverflow.com/questions/7568084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Image Lost on Minimizing Window I have added an image to a Canvas and then display that canvas on Panel. But when I minimize and then maximize the Window, the image disappears from the Panel. How can I solve this? Following is the code: public class CloseCanvas extends Canvas{ private static final long serialVersionUID = 2L; @Override public void paint(Graphics g) { setSize(new Dimension(30,22)); BufferedImage image = null; try { image = ImageIO.read(new File("res/close.png")); } catch (IOException ex) { ex.printStackTrace(); } g.drawImage(image, 0, 0, null); } } A: I'd suggest you move out the image loading from the paint method. It seems quite static and for every repaint of the Canvas the image will be reloaded which happens many, many times and that will happen on the event dispatch thread. A: This incorporates the advice of Fredrik and mKorbel, plus a few other tips unrelated to the immediate problem. public class CloseCanvas extends Canvas{ private static final long serialVersionUID = 2L; BufferedImage image = null; CloseCanvas() { try { image = ImageIO.read(new File("res/close.png")); } catch (IOException ex) { ex.printStackTrace(); } setPreferredSize(new Dimension(30,22)); } @Override public void paint(Graphics g) { if (image!=null) { g.drawImage(image, 0, 0, this); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7568089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: call batch by web service in .net I have a batch script that takes as a parameter the source to an image and outputs the image modified. Can I place the batch on a server and call it by means of a webservice? A: To get you started, here is some information and pointers to different alternatives. Try them and see which one more closely solves your requirements and work for you. The simplest, just invoke Process.Start() passing the full filespec to the batch file Process.Start("c:\bats\test.bat") If you need more control, you might create a Process.StartInfo and pass it to the Process.Start method. I have not tested this code. Process p= new Process(); p.StartInfo.WorkingDirectory = "C:\temp"; p.StartInfo.FileName = "c:\bats\test.bat"; p.StartInfo.Arguments = "arguments"; p.StartInfo.CreateNoWindow = false; p.Start(); p.WaitForExit(); A little bit more convoluted way is running a CMD and sending commands to it. See this article http://codebetter.com/brendantompkins/2004/05/13/run-a-bat-file-from-asp-net/ However, this is a pretty rough and brute force batch execution, that may not work for all BAT files (for example those that have FOR commands with %% variables) and have some side effects.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: foreach loop checking a value has changed before moving on I have a foreach loop that looks like this, <?php $current_question = ""; foreach ($question_and_answers as $qa) : ?> <?php $current_question == $qa['current_question']; ?> <?php if($current_question == $current_question) : ?> <input type="text" name="question[]" value="<?php echo $qa['question']; ?>"/> <?php endif; ?> <?php endforeach; ?> I am wanting to create an input field every time the loop hits a new question (a question gets returned numberous times, as a question can have numerous answers). What I have done does not seem to work. I think seeing the array I working with help, Array ( [0] => Array ( [question_id] => 2 [question] => What is my name? [tests_test_id] => 2 [answer_id] => 5 [answer] => Simon [questions_question_id] => 2 [correct] => true ) [1] => Array ( [question_id] => 2 [question] => What is my name? [tests_test_id] => 2 [answer_id] => 6 [answer] => Dave [questions_question_id] => 2 [correct] => false ) [2] => Array ( [question_id] => 2 [question] => What is my name? [tests_test_id] => 2 [answer_id] => 7 [answer] => Fred [questions_question_id] => 2 [correct] => false ) [3] => Array ( [question_id] => 2 [question] => What is my name? [tests_test_id] => 2 [answer_id] => 8 [answer] => John [questions_question_id] => 2 [correct] => false ) [4] => Array ( [question_id] => 3 [question] => What is my surname? [tests_test_id] => 2 [answer_id] => 9 [answer] => Crawford [questions_question_id] => 3 [correct] => true ) [5] => Array ( [question_id] => 3 [question] => What is my surname? [tests_test_id] => 2 [answer_id] => 10 [answer] => Caine [questions_question_id] => 3 [correct] => false ) [6] => Array ( [question_id] => 3 [question] => What is my surname? [tests_test_id] => 2 [answer_id] => 11 [answer] => Rooney [questions_question_id] => 3 [correct] => false ) [7] => Array ( [question_id] => 3 [question] => What is my surname? [tests_test_id] => 2 [answer_id] => 12 [answer] => Ainley [questions_question_id] => 3 [correct] => false ) [8] => Array ( [question_id] => 4 [question] => What is my favourite colour? [tests_test_id] => 2 [answer_id] => 13 [answer] => Blue [questions_question_id] => 4 [correct] => true ) [9] => Array ( [question_id] => 4 [question] => What is my favourite colour? [tests_test_id] => 2 [answer_id] => 14 [answer] => Yellow [questions_question_id] => 4 [correct] => false ) [10] => Array ( [question_id] => 4 [question] => What is my favourite colour? [tests_test_id] => 2 [answer_id] => 15 [answer] => Green [questions_question_id] => 4 [correct] => false ) [11] => Array ( [question_id] => 4 [question] => What is my favourite colour? [tests_test_id] => 2 [answer_id] => 16 [answer] => Red [questions_question_id] => 4 [correct] => false ) [12] => Array ( [question_id] => 5 [question] => Who do I support? [tests_test_id] => 2 [answer_id] => 17 [answer] => Huddersfield Town [questions_question_id] => 5 [correct] => true ) [13] => Array ( [question_id] => 5 [question] => Who do I support? [tests_test_id] => 2 [answer_id] => 18 [answer] => Leeds United [questions_question_id] => 5 [correct] => false ) [14] => Array ( [question_id] => 5 [question] => Who do I support? [tests_test_id] => 2 [answer_id] => 19 [answer] => Manchester United [questions_question_id] => 5 [correct] => false ) [15] => Array ( [question_id] => 5 [question] => Who do I support? [tests_test_id] => 2 [answer_id] => 20 [answer] => Wolverhampton Wanderes [questions_question_id] => 5 [correct] => false ) ) What I am trying to do, loop through the array, and everytime I meet a new question I want to outout a text input with the value of the question. A: Try this. <?php $current_question = ""; foreach ($question_and_answers as $qa) : ?> <?php if($current_question == $qa['current_question']) : ?> <input type="text" name="question[]" value="<?php echo $qa['question']; ?>"/> <?php $current_question = $qa['current_question']; ?> <?php endif; ?> <?php endforeach; ?> A: Your code is very strange, you probably have your reasons for writing it that way but let me rewrite it so I can take a better look: $current_question = ''; foreach($questions_and_answers as $qa){ $current_question == $qa['current_question']; if($current_question == $current_question){ ?> <input type="text" name="question[]" value="<?php echo $qa['question']; ?>"/> <? } } I see a couple of faults: * *$current_question == $qa['current_question']; does nothing, this is a conditional and will return true or false, but it won't return to anything. I think you've got this mixed up with a definition: $current_question = $qa['current_question']; *$current_question == $current_question; will always return 1 because it's the same variable. I think you are trying to compare it to $qa['current_question'] This should be what you're looking for: $current_question = ''; foreach($questions_and_answers as $qa) if($current_question == $qa['current_question']){ ?> <input type="text" name="question[]" value="<?php echo $qa['question']; ?>"/> <? } Or in your code: <?php $current_question = ""; foreach ($question_and_answers as $qa) : ?> <?php if($current_question == $qa['current_question']) : ?> <input type="text" name="question[]" value="<?php echo $qa['question']; ?>"/> <?php endif; ?> <?php endforeach; ?> This is still strange however, because you define $current_question as an empty string, so the conditional will only run if $qa['current_question'] is empty. However your question is too vague to see what you mean exactly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Sencha Touch: Passing data from the onItemDisclosure to the detail view panel and template I have the usual data passed into my onItemDisclosure as below: onItemDisclosure: function(record, btn, index) { console.log(record.data); }... I can see the data no problems but I would like to pass this data onto my panel so its template can then use it? How would I go about this. I have this so far in the detailed panel, but with in the panel code how do I then grab this? detailPanel.update(record.data); UPDATE Well having a play around it seems that I placed the data variable within the template as normal and the whole thing works <tpl for="."><div>{name}</div></tpl> But my Other question is that I have my json set up with a field as below: "name"," joe bloggs", "contacts": [ { "home":"0844 482 5171", "mobile":"", "work":"0844 482 5100" }],..... Now I can access these if I console.log(contacts[0].mobile) but if I place this in the template <tpl for="."><div>{contacts[0].mobile}</div></tpl> it just simply prints out {contacts[0].mobile} So how can I obtain this data within contacts? A: Update use <tpl for="contacts">{mobile}</tpl> end Add the tpl property to the detailPanel object, like this: tpl:'<h1>{text}</h1>' where text is some property of the record.data object. Here are some good tutorials about sencha's templates: http://www.sencha.com/learn/xtemplates-part-i/ http://www.sencha.com/learn/xtemplates-part-ii/
{ "language": "en", "url": "https://stackoverflow.com/questions/7568106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: remove objects from hibernate session I have hibernate pojo class A { B b ; some other properies} with lazy= true for class B. When i get object A, B is not loaded and hibernate returns its proxy. When i pass this object to another module, that module traverse each and every objects in A and when it encounter B.getXXX it throws LazyInitialization exception. In this particular case, I do not want to load class B as it is not required. Is there any way when i call methods on B it either return null or turn proxy of B into real object B so that module doesn't throw LazyInitialization error. I cannot change class B getter,setter as it common class and use by many other classes. A: If I understand your question, you're retrieving an object A with a lazy association to B. However, this association is not initialized, and you find that other modules are throwing exceptions because B is actually used. So it is required in some way. You want to either * *Return null from calls to B (not possible, as far as I know, unless there's some application-specific behavior on those modules that only you can be aware of) or *Initialize B when such calls happen. I'll try to help you implement this one. The reason why you're getting LazyInitializationExceptions is that the session that fetched B (and didn't initialize it) has already been closed, so at this point, the instance of B is of no use at all. One workaround you could apply here is to use the OSIV pattern so that you have the same Hibernate session open in all the request scope. This is the session that will fetch A with lazy B and will initialize B when there is the need. Another option you could apply would be to initialize B in another session (only valid if those exceptions are occurring in the context of another transaction, that is, with another Hibernate session open, different from the one that fetched A). For instance: session.update(a.getB()); Of course, you could always force initialization of B with fetchMode.EAGER or Hibernate.initialize(a.getB()). But that would be loading the instance unconditionally, even if it won't be used at all. Also, you may find the answers to this question may be useful: hibernate: LazyInitializationException: could not initialize proxy A: Actually, you have a few option. 1) Make A->B relation EAGER. 2) You are getting LazyInitializationExceptions when you try to initiate proxy while you hibernate session is lready closed. so he possible solution would be to keep Session open till all your A,B,C...etc object manipulation are not completed. 3) If you are talling about WEB environment, there are a pattern called Open Session in view. which keeps your Hibernate session open till your HTTP Request is alive. I you can read more about it here. I think it will be useful for you to read it. A: Don't send the entities to other modules when the session is closed. If these other module is executed in the same Application Domain as the session, keep the session open when calling the module and close it when it returns. If these module is not in the same AppDomain, if you need some kind of serialization to send the objects or if it is called asynchronously, I would use a DTO. Exposing the entities outside of the server (I don't know if this is the case here) is a bad practice for several reasons. Ayende Rahien calls it the Stripper Pattern. A: Thanks for all your suggestion. My application have layered architecture. Service->Manager->Dao. Hibernate session closes after manager. Other module interacts only through Service. Opening hibernate session till request complete is not an option for me. I also do not want to hit database as it is not necessary that properties of B are populated. I just want to replace hibernate proxy with real object so that anyone who is using service do not face any problem. I found a utility at http://svn.rhq-project.org/repos/rhq/branches/HEIKO-EXP/modules/enterprise/server/safe-invoker/src/main/java/org/rhq/enterprise/server/util/HibernateDetachUtility.java which exactly does what i want. It inspect object and replace hibernate proxy with real object. I need to customize following things in above utility 1. Change instances of classname from org.rhq to my package structure. 2. They expect name of identity field in pojo is "id". I change it to use those property which has annotation of javax.persistence.Id. Basic testing with above changes is done and it is working fine. I just need to test whole application with various scenario so that it is working in all scenario.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Split large string into substrings I have a huge string like ABCDEFGHIJKLM... and I would like to split it into substrings of length 5 in this way: >1 ABCDE >2 BCDEF >3 CDEFG [...] A: ${string:position:length} Extracts $length characters of substring from $string at $position. stringZ=abcABC123ABCabc # 0123456789..... # 0-based indexing. echo ${stringZ:0} # abcABC123ABCabc echo ${stringZ:1} # bcABC123ABCabc echo ${stringZ:7} # 23ABCabc echo ${stringZ:7:3} # 23A # Three characters of substring. -- from Manipulating Strings in the Advanced Bash-Scripting Guide by Mendel Cooper Then use a loop to go through and add 1 to the position to extract each substring of length 5. end=$(( ${#stringZ} - 5 )) for i in $(seq 0 $end); do echo ${stringZ:$i:5} done A: fold -w5 should do the trick. $ echo "ABCDEFGHIJKLMNOPQRSTUVWXYZ" | fold -w5 ABCDE FGHIJ KLMNO PQRST UVWXY Z Cheers! A: ...or use the split command: $ ls $ echo "abcdefghijklmnopqr" | split -b5 $ ls xaa xab xac xad $ cat xaa abcde split also operates on files... A: In bash: s=ABCDEFGHIJ for (( i=0; i < ${#s}-4; i++ )); do printf ">%d\n%s\n" $((i+1)) ${s:$i:5} done outputs >1 ABCDE >2 BCDEF >3 CDEFG >4 DEFGH >5 EFGHI >6 FGHIJ A: sed can do it in one shot: $ echo "abcdefghijklmnopqr"|sed -r 's/(.{5})/\1 /g' abcde fghij klmno pqr or depends on your needs: $ echo "abcdefghijklmnopqr"|sed -r 's/(.{5})/\1\n/g' abcde fghij klmno pqr update i thought it was just simply split string problem, didn't read the question very carefully. Now it should give what you need: still one shot, but with awk this time: $ echo "abcdefghijklmnopqr"|awk '{while(length($0)>=5){print substr($0,1,5);gsub(/^./,"")}}' abcde bcdef cdefg defgh efghi fghij ghijk hijkl ijklm jklmn klmno lmnop mnopq nopqr A: str=ABCDEFGHIJKLM splitfive(){ echo "${1:$2:5}" ; } for (( i=0 ; i < ${#str} ; i++ )) ; do splitfive "$str" $i ; done Or, perhaps you want to do something more intelligent with the results #!/usr/bin/env bash splitstr(){ printf '%s\n' "${1:$2:$3}" } n=$1 offset=$2 declare -a by_fives while IFS= read -r str ; do for (( i=0 ; i < ${#str} ; i++ )) ; do by_fives=("${by_fives[@]}" "$(splitstr "$str" $i $n)") done done echo ${by_fives[$offset]} And then call it $ split-by 5 2 <<<"ABCDEFGHIJKLM" CDEFG You can adapt it from there. EDIT: trivial version in C, for performance comparison: #include <stdio.h> int main(void){ FILE* f; int n=0; char five[6]; five[5] = '\0'; f = fopen("inputfile", "r"); if(f!=0){ fread(&five, sizeof(char), 5, f); while(!feof(f)){ printf("%s\n", five); fseek(f, ++n, SEEK_SET); fread(&five, sizeof(char), 5, f); } } return 0; } Forgive my bad C, I really don't knw the language. A: Would sed do it?: $ sed 's/\(.....\)/\1\n/g' < filecontaininghugestring A: sed can do it: sed -nr ':a;h;s/(.{5}).*/\1/p;g;s/.//;ta;' <<<"ABCDEFGHIJKLM" | # split string sed '=' | sed '1~2s/^/>/' # add line numbers and insert '>' A: You could use cut and specify characters instead of fields, and then change output delimiter to whatever you need, like new line: echo "ABCDEFGHIJKLMNOP" | cut --output-delimiter=$'\n' -c1-5,6-10,11-15 output ABCDE FGHIJ KLMNO or echo "ABCDEFGHIJKLMNOP" | cut --output-delimiter=$':' -c1-5,6-10,11-15 output ABCDE:FGHIJ:KLMNO A: thanks to you guys I was able to find a way to do this fast! This is my solution combining a few ideas from here: str="ABCDEFGHIJKLMNOP" splitfive(){ echo $1 | cut -c $2- | sed -r 's/(.{5})/\1\n/g' } for (( i=0; i <= 5; i++ )); do splitfive "$str" $i done | grep -v "^$" [The above answer was initially added to the question itself. Here are the relevant comments.] Your splitfive could be more efficient. There's no need to pipe to cut, in bash you could say cut -c "$2"- <<<"$1" | sed etc and it will be slightly better. -- sorpigal Sep 28 '11 at 11:48 Your sed expression could also be improved to sed 's/...../&\n/g' which executes about twice as fast. -- sorpigal Sep 28 '11 at 11:56
{ "language": "en", "url": "https://stackoverflow.com/questions/7568112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: invokeMethod from Groovy with parameters I want to invoke groovy method from the given below class package infa9 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import com.ABC.csm.context.AppCtxProperties; import com.ABC.csm.context.AppContext; public class LicenseInfo { private StringBuffer licenseInformation; public LicenseInfo() { licenseInformation = new StringBuffer(); } public StringBuffer getLicenseInformation(){ return licenseInformation; } public void fetchLicenseInformation(HashMap<String,String> params,Map env) { ArrayList<String> licenseList = fetchLicenses(params); . . . } private ArrayList<String> fetchLicenses(HashMap<String,String> params,Map env) { ArrayList<String>licenseList = new ArrayList<String>(); . . . return licenseList; } } So this is what I am trying to do //getting user parameters HashMap<String,String> params = IntermediateResults.get("userparams") //getting environment variables Map env=AppContext.get(AppCtxProperties.environmentVariables) Object[] arguments=new Object[2] arguments.putAt("userparams", params) arguments.putAt("env", env) GroovyShell shell = new GroovyShell() Script infa9LicenseScript = shell.parse("plugins.infa9.LicenseInfo") infa9LicenseScript.invokeMethod(fetchLicenseInformation, arguments) String lic=(String)infa9LicenseScript.invokeMethod(getLicenseInformation,null) Am I passing the parameters to fetchLicenseInformation correctly?? I need to pass HashMap<String,String> ,Map Please help me invoke a groovy method with parameters Error: Exception in thread "main" groovy.lang.MissingPropertyException: No such property: userparams for class: [Ljava.lang.Object; Update public List<String> fetchLicenses( Map<String,String> params, Map env ) { //[ 'a', 'b', 'c' ] ArrayList<String>licenseList = new ArrayList<String>(); String infacmdListLicensesCommand = null; if (System.getProperty("os.name").contains("Win")) { infacmdListLicensesCommand = env.get("INFA_HOME") + "/isp/bin/infacmd.bat ListLicenses -dn " + params.get("dn") + " -un " + params.get("un") + " -pd " + params.get("pd") + " -sdn " + params.get("sdn") + " -hp " + params.get("dh") + ":" + params.get("dp");} else { infacmdListLicensesCommand = env.get("INFA_HOME") + "/isp/bin/infacmd.sh ListLicenses -dn " //this is line no 71, where exception is thrown + params.get("dn") + " -un " + params.get("un") + " -pd " + params.get("pd") + " -sdn " + params.get("sdn") + " -hp " + params.get("dh") + ":" + params.get("dp");} try { Process proc = Runtime.getRuntime().exec(infacmdListLicensesCommand); InputStream stdin = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(stdin); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); licenseList.add(line); } int exitVal = proc.waitFor(); System.out.println("Process exit value is: " + exitVal); }catch (IOException io) { io.printStackTrace(); }catch (InterruptedException ie) { ie.printStackTrace(); } /* end catch */ return licenseList; } Exception Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: java.lang.String.positive() is applicable for argument types: () values: [] Possible solutions: notify(), tokenize(), size() at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55) at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unaryPlus(ScriptBytecodeAdapter.java:764) at infa9.LicenseInfo.fetchLicenses(Infa9LicensesUtil.groovy:71) A: Right...I created this groovy script LicenseInfo.groovy inside a folder ./test/: package test public class LicenseInfo { StringBuffer licenseInformation public LicenseInfo() { licenseInformation = new StringBuffer() } public void fetchLicenseInformation( Map<String,String> params, Map env ) { List<String> licenseList = fetchLicenses( params, env ) println "List is $licenseList" } public List<String> fetchLicenses( Map<String,String> params, Map env ) { [ 'a', 'b', 'c' ] } } inside the current folder ./, I created this groovy script Test.groovy: // Make some params... def params = [ name:'tim', value:'text' ] // Fake an env Map def env = [ something:'whatever' ] // Load the class from the script def liClass = new GroovyClassLoader().parseClass( new File( 'test/LicenseInfo.groovy' ) ) // Run the method liClass.newInstance().fetchLicenseInformation( params, env ) When I execute the command groovy Test.groovy it prints out: List is [a, b, c] Edit after update The positive errors you are getting are due to the way the Groovy parser works... You cannot put the + on the start of the next line when joining Strings, the + has to be trailing on the previous line (as semi-colons are optional for the end of lines in groovy, there is no way for the parser to know you are adding on to the previous line) This will work: if (System.getProperty("os.name").contains("Win")) { infacmdListLicensesCommand = env.get("INFA_HOME") + "/isp/bin/infacmd.bat ListLicenses -dn " + params.get("dn") + " -un " + params.get("un") + " -pd " + params.get("pd") + " -sdn " + params.get("sdn") + " -hp " + params.get("dh") + ":" + params.get("dp") } else { infacmdListLicensesCommand = env.get("INFA_HOME") + "/isp/bin/infacmd.sh ListLicenses -dn " + params.get("dn") + " -un " + params.get("un") + " -pd " + params.get("pd") + " -sdn " + params.get("sdn") + " -hp " + params.get("dh") + ":" + params.get("dp") } And this would be a more Groovy way of doing the same thing: boolean isWindows = System.getProperty("os.name").contains("Win") // Do it as a list of 3 items for formatting purposes infacmdListLicensesCommand = [ "$env.INFA_HOME/isp/bin/infacmd.${isWindows?'bat':'sh'} ListLicenses" "-dn $params.dn -un $params.un -pd $params.pd -sdn $params.sdn" "-hp $params.dh:$params.dp" ].join( ' ' ) // then join them back together println infacmdListLicensesCommand // print it out to see it's the same as before
{ "language": "en", "url": "https://stackoverflow.com/questions/7568120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Change Hypersonic DS to MySql DS I try to switch an existing (and well deploying) application to MySql instead of Hypersonic. After I follow all steps from JBoss tutorial my application fails in deploy saying: org.hibernate.MappingException: An association from the table OLOLO refers to an unmapped class: com.trololo.pack.Class. MySql DB for JBoss has become filled with the data. But my app's DB is empty. I guess it is something wrong with hibernate, right? I have JBoss 4.2.3. In the /default/deploy dir I have 2 *-ds.xml files. One for the JBoss and another for my app. Please share your ideas what is wrong there? Any help is welcome. A: I got the solution. For the unknown reason Hibernate didn't allow to mention com.trololo.pack.Class in cfg.xml for OLOLO class. After I set annotations it worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Easy mySQL Group By question If in a mysql table RESERVATIONS there are DATE_ARRIVAL, DATE_DEPARTED and TOTAL_EARN columns How do I Group By month, all earnings in 2010? A: select monthname(DATE_ARRIVAL),sum(TOTAL_EARN) from RESERVATIONS where DATE_ARRIVAL between '2010-01-01' and '2010-12-31 23:59:59' group by monthname(DATE_ARRIVAL); Though it kind of depends on which column you want to base your predicate (DATE_ARRIVAL or DATE_DEPARTED?) A: select year(DATE_ARRIVAL) year, month(DATE_ARRIVAL) month, sum(TOTAL_EARN) from RESERVATIONS group by year, month order by year, month
{ "language": "en", "url": "https://stackoverflow.com/questions/7568124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Select( ) always block on /dev/ttyUSB0 i m using Select() sys cal on XBee rf module which is on /dev/ttyUSB0.but this syscal just doesnt return(returns only on timeout),but if i use read() in a WHILE loop on this port i can see the data comming /*code to open the port*/ system("stty -F /dev/ttyUSB0 5:0:8bd:0:3:1c:7f:15:1:64:0:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0"); fd = open("/dev/ttyUSB0", O_RDWR ); printf("fd is %d",fd); if(fd == -1) return ERR_PORT; select returns only when TIMEOUT not when port is ready for reading FD_ZERO (&set); FD_SET (fd, &set);//fd is an opened file des. for /dev/ttyUSB0 struct timeval timeout; timeout.tv_sec = 50; timeout.tv_usec = 0; if(select(FD_SETSIZE,&set, NULL,NULL,&timeout)==1) Do_stuff(); else return TIMEOUT; but if i use following i can see the data being printed char ch; while(1) { read(fd,&ch,1); printf("\n0x%X",ch); } Please note: about command in system() function,i got it by issuing stty -F /dev/USB0 -g after having GTKterm opened on /dev/ttyUSB0.(thats when i was able to talk to my modem from my program) so made a guess that GTKterm configured the port,and i used the exact same configuration. A: If you are using select() in a loop (I suppose you do) take care to set fd_set() and tv_sec, tv_usec on every iteration of the loop, Also: your printf format does not end in an \n so output will not be flushed. Instead it starts with a \n so it will be flushed before the relevant output appears. A: The first argument to select() is the highest file descriptor in the set plus one. Your statement should be: if (select(fd + 1,&set, NULL,NULL,&timeout) == 1) { ... } EDIT: Also you assume if select() doesn't return 1, it's due to a timeout issue, which is only true if 0 is returned. Check for -1 return and report the value of errno. Also ensure that the file descriptor is in non-blocking mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieving the last modified file in a directory over FTP using a bash script with curl I'm writing a bash script and one of the tasks which needs performing is to connect to an FTP server via curl and find the name of the last modified .zip file. The name format of the files we are looking at is MM_DD_YYYY_ALL.zip. So far I have, with omissions in << >>: export FILEPATTERN=_ALL.zip for FILE in `curl -u << SERVER INFO >> 2> /dev/null | grep ${FILEPATTERN} | awk -F\ '{print $9}'` do ... # Do stuff with each file to determine most recent version. ... done The fact that the file name isn't formatted YYYY_MM_DD seems to be the main reason this can't be done with some quick trimming and calculations. Is there an efficient way to pull the name of the most recent modified zip file from this list? Or is there some processing which can be done whilst the list is being generated? Cheers. A: You can sort the filenames in one shot with a multi-key sort command and grab the last line with tail to get the latest file. You'll need to specify -t- to use a dash as sort's field separator, -n to get a numeric sort, and list each field in the order of its priority. The format for a field specifier is: -k, --key=POS1[,POS2] start a key at POS1 (origin 1), end it at POS2 (default end of line) So for the year, field 3, you'll need to list it with its 4-character width as -k3,4. If you sort by the year, month, and day fields in that order, you'll end up with a list that has all the files in date order. So instead of the for loop above, you can use: FILE=`curl -u << SERVER INFO >> 2> /dev/null | grep ${FILEPATTERN} | awk -F\ '{print $9}' | sort -n -t- -k3,4 -k1,2 -k2,2 |tail -1` A: Edit: Sorry I just realised that the files you need were on the remote FTP server. I had thought they were local, and you were hoping to upload to FTP. So everything below is irrelevant. Typically I do something like: ls -1rt /path/to/zips/*.zip | tail -n1 This is not always a good idea, spaces in file names etc. But it will return the most recent file name in the directory. There's also find. You can specify a date range, and name. Depending on what you are doing, you might opt to scan a directory every x minutes for files created in the last x minutes. This has the advantage that it will pick up multiple new files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to draw a line to join buttons in relative layout of Android App I am using Eclipse to write an Android app that has a column of buttons, and when one is pressed it will open another column of buttons next to it that corresponds to the button pressed. What I would like to do is add a solid line that connects the button pressed to the new column so visually it can be seen which button the new column relates too (not worried about the vertical relationship) e.g. [B1] [B5] [B2]---[B6] [B3] [B7] [B4] I had a look at the "How to draw a line in android" post, but I was wondering if it would work in my case as I'm using Relative Layout? Thinking that if the app was to change devices (namely screen size) would the line then be misplaced with respect to the buttons. I could be wrong as I'm very new to Android and Java but thought it worth asking. One way I was thinking may work, if it's possible, would be to somehow have the line connected/linked to the buttons??? Thank you, Markus A: I would use a vertical LinearLayout (or RelativeLayout) for each column and instead of just one button per row, I would use an horizontal LinearLayout with both the button and the line per row, like so: [B1, L1][B5] [B2, L2][B6] [B3, L3][B7] [B4, L4] The line view would only be visible in the selected row. The line view could be any transparent view (ImageView, LinearLayout, RelativeLayout, FrameLayout, etc...) with a background set to a Drawable (the line). The drawable can be created programmatically or loaded from a resource. Assuming you're doing something in the likes of hierarchical tabs, consider using toggle buttons.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jsFiddle works. Implementation on webpage doesn't? This js fiddle runs with no errors or problems: http://jsfiddle.net/3j45B/2/ However, when embedded within http://www.zabb.co.uk/untitled6.html it does not work? Any suggestions please? EDIT: Further to your comments and suggestions below a solution has been found, thank you all: $(document).ready(function() { $('.thumbnail2').click(function() { src = $(this).attr('src'); if (src != $('.img').attr('src')) { $('.img').fadeOut(250, function() { $(this).attr('src', src).fadeIn(250); }); } }); });​ Important bit to ensure event works is to wrap your jQuery code within: $(document).ready(function() { // ... });​ See following link for further information regarding this function: Introducing $(document).ready() A: Wrap your embedded script in a $(...) or $(document).ready(...) jsfiddle did that for you (see the dropdown box on the left that says "onLoad"?). A: Nothing wrong with your code. But you probably forgot to include a plugin called Galleria, I get Galleria not defined.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unknown syntax error on creating a simple widget in Tkinter I was following this tutorial (http://sebsauvage.net/python/gui/#add_button) on making widgets with Tkinter. I have been making sure to follow it very carefully but, when I run it now in step 10, I get an "Invalid Syntax" Error. Here the code: import tkinter class simpleapp_tk(tkinter.Tk): def __init__(self,parent): tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): self.grid() self.entry = tkinter.Entry(self) self.entry.grid(column=0,row=0,sticky='EW') button = tkinter.Button(self,text=u"Click me !") button.grid(column=1,row=0) if __name__ == "__main__": app = simpleapp_tk(None) app.title('my application') app.mainloop() The IDLE points the error is in this line, selecting the second quotation marks: button = tkinter.Button(self,text=u"Click me !**"**) The tutorial was written in Python 2, but I'm using Python 3. Can anyone see what is the error and what to do to fix it (in Python 3)? Thanks in advance for any help, I am new to programming and English is not my native language. A: Replace u"Click me !**" with "Click me !**" The u indicates a Unicode string (type unicode instead of str) in Python 2, but in Python 3, the distinction between the str and unicode types is gone and the u is scrapped. A: There is no u prefix for unicode strings in Python 3.
{ "language": "en", "url": "https://stackoverflow.com/questions/7568139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }