text
stringlengths
8
267k
meta
dict
Q: Maven and Eclipse Lift Project Errors I made a new project through the m2eclipse wizard and selected the blank liftweb archetype. The project was created and I added the scala nature to the project (I don't have the maven-scala plugin installed for the time being). I am able to run the project using the goal jetty:run. However, I still have the following errors showing up in eclipse (cleaning the project didn't do anything): Description Resource Path Location Type error while loading Helpers, Scala signature Helpers has wrong version expected: 5.0 found: 4.1 in C:\Users\Ken\.m2\repository\net\liftweb\lift-webkit\0.8\lift-webkit-0.8.jar(net/liftweb/util/Helpers.class) first Unknown Scala Problem error while loading LiftRules, Scala signature LiftRules has wrong version expected: 5.0 found: 4.1 in C:\Users\Ken\.m2\repository\net\liftweb\lift-webkit\0.8\lift-webkit-0.8.jar(net/liftweb/http/LiftRules.class) first Unknown Scala Problem error while loading Loc, Scala signature Loc has wrong version expected: 5.0 found: 4.1 in C:\Users\Ken\.m2\repository\net\liftweb\lift-webkit\0.8\lift-webkit-0.8.jar(net/liftweb/sitemap/Loc.class) first Unknown Scala Problem error while loading MainGenericRunner, Scala signature MainGenericRunner has wrong version expected: 5.0 found: 4.1 in C:\Users\Ken\.m2\repository\org\scala-lang\scala-compiler\2.7.1\scala-compiler-2.7.1.jar(scala/tools/nsc/MainGenericRunner.class) first Unknown Scala Problem error while loading Menu, Scala signature Menu has wrong version expected: 5.0 found: 4.1 in C:\Users\Ken\.m2\repository\net\liftweb\lift-webkit\0.8\lift-webkit-0.8.jar(net/liftweb/sitemap/Menu.class) first Unknown Scala Problem Plugin execution not covered by lifecycle configuration: org.scala-tools:maven-scala-plugin:2.15.2:compile (execution: default, phase: compile) pom.xml /first line 76 Maven Project Build Lifecycle Mapping Problem Plugin execution not covered by lifecycle configuration: org.scala-tools:maven-scala-plugin:2.15.2:testCompile (execution: default, phase: test-compile) pom.xml /first line 76 Maven Project Build Lifecycle Mapping Problem Here is a screenshot of the errors (may be easier to read, click the image for full size): Does anybody know what is happening here? Any suggestions? Additional information: The following warnings come up when I run the project: [WARNING] [WARNING] Some problems were encountered while building the effective model for com.kpthunder.lift:first:war:0.0.1-SNAPSHOT [WARNING] 'build.plugins.plugin.version' for org.mortbay.jetty:maven-jetty-plugin is missing. @ line 87, column 15 [WARNING] 'build.plugins.plugin.version' for net.sf.alchim:yuicompressor-maven-plugin is missing. @ line 95, column 15 [WARNING] 'build.plugins.plugin.version' for org.scala-tools:maven-scala-plugin is missing. @ line 72, column 15 [WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-eclipse-plugin is missing. @ line 109, column 15 [WARNING] 'reporting.plugins.plugin.version' for org.scala-tools:maven-scala-plugin is missing. @ line 133, column 15 [WARNING] [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build. [WARNING] [WARNING] For this reason, future Maven versions might no longer support building such malformed projects. [WARNING] [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! A: I am new to lift, but used the explanations here, and were able to make it to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7621999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android: Making Https Request How do I avoid the "javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated" exception and the Android Apache lib gap "The constructor SSLSocketFactory(SSLContext) is undefined" in making an Https request? A: This method takes an HttpClient instance and returns a ready-for-https HttpClient instance. private HttpClient sslClient(HttpClient client) { try { X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[]{tm}, null); SSLSocketFactory ssf = new MySSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = client.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); return new DefaultHttpClient(ccm, client.getParams()); } catch (Exception ex) { return null; } } Because the Android org.apache.http.conn.ssl.SSLSocketFactory does not have the SSLSocketFactory(SSLContext) constructor, I have extended the class as follows. public class MySSLSocketFactory extends SSLSocketFactory { SSLContext sslContext = SSLContext.getInstance("TLS"); public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(truststore); TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; sslContext.init(null, new TrustManager[] { tm }, null); } public MySSLSocketFactory(SSLContext context) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException { super(null); sslContext = context; } @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public Socket createSocket() throws IOException { return sslContext.getSocketFactory().createSocket(); } } Excellent article here: http://javaskeleton.blogspot.com/2010/07/avoiding-peer-not-authenticated-with.html And some help here: Trusting all certificates using HttpClient over HTTPS A: I had similar problem which is more like this question but the root cause was completely different from those mentioned in both questions. I was using DefaultHttpClient as httpclient for requesting https://maps.googleapis.com like links. I was trying whole banch of proposed solutions but none worked for me. After some more hours trying to solve it found root cause: My device was connected to a guest WIFI which probably has some specific filtering rules which blocked relevant network parts. Switching to a different network solved my problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Creating charts in MS Word using from regular MS Word tables I'm working on a program that can generate MS Word files containing tables. I want to design a macro that would take the data in the tables contained in the MS Word file and create a chart from it (bar, pie or line charts). So far I've been able to: * *Select the portion of the table I need for source data, *Insert an inline Excel worksheet into the MS Word file. However, I'm unable to paste the selected portion of the table into the inline worksheet in order to draw a chart. How can I do this? A: The solution below should work for Word 2007 SP2 and Word 2010. It was based on code found in a fantastic article entitled "Creating Charts with VBA in Word 2010" by Peter Gruenbaum which can be read here: Creating Charts with VBA in Word 2010 It is important to note that for this VBA code to work properly, it should contain a reference to the Microsoft Excel 14.0 Object Library (for those that do not know how to do this, the article linked to above explains how to add this reference in detail). Sub MakeChartFromTable() Dim myTable As Table Dim salesChart As Chart Dim chartWorkSheet As Excel.Worksheet Dim x As Integer Dim RowCount As Integer Dim ColumnCount As Integer Dim LastColumn As String For Each myTable In ActiveDocument.Tables myTable.Range.Copy 'Create Chart Set salesChart = ActiveDocument.Shapes.AddChart.Chart Set chartWorkSheet = salesChart.ChartData.Workbook.Worksheets(1) 'Determine size of table RowCount = myTable.Rows.Count ColumnCount = myTable.Columns.Count 'Determine spreadsheet column letter for last column of table If ColumnCount < 26 Then LastColumn = Chr(64 + ColumnCount) Else LastColumn = Chr(Int(ColumnCount / 26) + 64) & Chr((ColumnCount Mod 26) + 64) End If 'Resize chart data area to table size and paste table data With chartWorkSheet .ListObjects("Table1").DataBodyRange.Delete .ListObjects("Table1").Resize chartWorkSheet.Range("A1:" & LastColumn & RowCount) .Range("A1:" & LastColumn & RowCount).Select .Paste End With salesChart.ChartData.Workbook.Close Next End Sub This code creates charts from entire Word tables, so incorporating your code for selecting partial tables (as indicated in your question) will be required. Additional code will also be needed to position the charts within the Word document. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: win7 rails aptana studio 3 + rmagick + bundler cannot start debug server i've been trying to start 'debug server' for a rails application in aptana studio 3 but i never succeeded. every time i tried to start debug server, exception thrown: Uncaught exception: Could not load the bundler gem. Install it with gem install bundler. * *i followed the aptana studio 3 getting started guide and installed everything except rvm (i don't know how to install it on windows). is it really necessary for aptana studion 3 on windows? i have only 1 ruby version installed. *i installed rmagick successfully and i put 'require rubygems' and 'require RMagick' in preinitializer.rb. am i putting them at the right place? *i use bundler for gem management and i can successfully start the server by running "ruby script/server". i just don't know what's wrong with the debug environment. am i missing some PATH setting? *any body running smooth with aptana studio 3, rmagick and bundler. can tell me your settings? thx. windows 7 prof 64bit aptana studio 3 ruby 1.8.7 rails 2.3.14 ruby-debug-base 0.10.4 ruby-debug-ide 0.4.16 rmagick 2.12.0 (C:\Ruby\lib\ruby\gems\1.8\gems\rmagick-2.12.0-x86-mswin32) imagemagick (C:\Program Files (x86)\ImageMagick-6.5.6-Q8) bundler 1.0.18 gemfile (gem "rmagick", "2.12.0") preinitializer.rb require 'rubygems' require 'RMagick' require 'bundler' batterhead A: Ah found the problem. The environment needs to have a ‘MAGICK_CODER_MODULE_PATH’ variable added that points to your ImageMagick modules/coders installation path. You can add this in the "Environment" tab of your debug configuration for the project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Login on website with java I would like to login to a website with java. I use the org.apache.http and I already written HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("https://accounts.google.com/ServiceLogin? service=mail&passive=true&rm=false&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F%3Fhl%3Dsl%26tab%3Dwm%26ui%3Dhtml%26zy%3Dl&bsv=llya694le36z&scc=1&ltmpl=default&"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("vb_login_username", "XXX")); nameValuePairs.add(new BasicNameValuePair("vb_login_password", "XXX")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } It sends the post form correctly i have tested, though i still cant login. The website I want to login is http://www.xtratime.org/forum/ Any ideas for this or is there a different way? A: <form action="login.php?do=login" method="post" onsubmit="md5hash(vb_login_password, vb_login_md5password, vb_login_md5password_utf, 0)"> * *Before submit the page encode the password (onsubmit). You should do the same in the code. *The value of the action attribute does not match with your code (https://accounts.google.com...). You should send the post request to the login.php?do=login. And there are a lot of hidden fields: <input type="hidden" name="s" value="b804473163cb55dce0d43f9f7c41197a" /> <input type="hidden" name="securitytoken" value="0dcd78b4c1a376232b62126e7ad568e0d1213f95" /> <input type="hidden" name="do" value="login" /> <input type="hidden" name="vb_login_md5password" /> <input type="hidden" name="vb_login_md5password_utf" /> You should send these parameters too. Usually it's easier to install an HttpFox Firefox Add-on an inspect the request for the post parameters than decoding the javascript. My browser sends these post parameters (captured with HttpFox, the password is pass1): vb_login_username: user1 vb_login_password: s: 5d8bd41a83318e683de9c55a38534407 securitytoken: 0dcd78b4c1a376232b62126e7ad568e0d1213f95 do: login vb_login_md5password: a722c63db8ec8625af6cf71cb8c2d939 vb_login_md5password_utf: a722c63db8ec8625af6cf71cb8c2d939 Edit: The following works for me, I can get the "Thank you for logging in" message in the printed html code: final HttpClient client = new DefaultHttpClient(); final HttpPost post = new HttpPost( "http://www.xtratime.org/forum/login.php?do=login"); try { final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("vb_login_username", "my user")); nameValuePairs.add(new BasicNameValuePair("vb_login_password", "")); nameValuePairs.add(new BasicNameValuePair("s", "")); nameValuePairs.add(new BasicNameValuePair("securitytoken", "inspected with httpfox, like f48d01...")); nameValuePairs.add(new BasicNameValuePair("do", "login")); nameValuePairs.add(new BasicNameValuePair("vb_login_md5password", "inspected with httpfox, like 8e6ae1...")); nameValuePairs.add(new BasicNameValuePair( "vb_login_md5password_utf", "inspected with httpfox, like 8e6ae1...")); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); final HttpResponse response = client.execute(post); final BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); } } catch (final IOException e) { e.printStackTrace(); } A: I suggest you to use htmlunit: HtmlUnit is a "GUI-Less browser for Java programs". It models HTML documents and provides an API that allows you to invoke pages, fill out forms, click links, etc... just like you do in your "normal" browser. It has fairly good JavaScript support (which is constantly improving) and is able to work even with quite complex AJAX libraries, simulating either Firefox or Internet Explorer depending on the configuration you want to use. It is typically used for testing purposes or to retrieve information from web sites.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: matlab and c differ with cos function I have a program implemented in matlab and the same program in c, and the results differ. I am bit puzzled that the cos function does not return the exact same result. I use the same computer, Intel Core 2 Duo, and 8 bytes double data type in both cases. Why does the result differ? Here is the test: c: double a = 2.89308776595231886830; double b = cos(a); printf("a = %.50f\n", a); printf("b = %.50f\n", b); printf("sizeof(a): %ld\n", sizeof(a)); printf("sizeof(b): %ld\n", sizeof(b)); a = 2.89308776595231886830106304842047393321990966796875 b = -0.96928123535654842068964853751822374761104583740234 sizeof(a): 8 sizeof(b): 8 matlab: a = 2.89308776595231886830 b = cos(a); fprintf('a = %.50f\n', a); fprintf('b = %.50f\n', b); whos('a') whos('b') a = 2.89308776595231886830106304842047393321990966796875 b = -0.96928123535654830966734607500256970524787902832031 Name Size Bytes Class Attributes a 1x1 8 double Name Size Bytes Class Attributes b 1x1 8 double So, b differ a bit (very slightly, but enough to make my debuging task difficult) b = -0.96928123535654842068964853751822374761104583740234 c b = -0.96928123535654830966734607500256970524787902832031 matlab I use the same computer, Intel Core 2 Duo, and 8 bytes double data type. Why does the result differ? does matlab do not use the cos function hardware built-in in Intel? Is there a simple way to use the same cos function in matlab and c (with exact results), even if a bit slower, so that I can safely compare the results of my matlab and c program? Update: thanks a lot for your answers! So, as you have pointed out, the cos function for matlab and c differ. That's amazing! I thought they were using the cos function built-in in the Intel microprocessor. The cos version of matlab is equal (at least for this test) to the one of matlab. you can try from matlab also: b=java.lang.Math.cos(a) Then, I did a small MEX function to use the cos c version from within matlab, and it works fine; This allows me to debug the my program (the same one implemented in matlab and c) and see at what point they differ, which was the purpose of this post. The only thing is that calling the MEX c cos version from matlab is way too slow. I am now trying to call the Java cos function from c (as it is the same from matlab), see if that goes faster. A: Floating point numbers are stored in binary, not decimal. A double precision float has 52 bits of precision, which translates to roughly 15 significant decimal places. In other words, the first 15 nonzero decimal digits of a double printed in decimal are enough to uniquely determine which double was printed. As a diadic rational, a double has an exact representation in decimal, which takes many more decimal places than 15 to represent (in your case, 52 or 53 places, I believe). However, the standards for printf and similar functions do not require the digits past the 15th to be correct; they could be complete nonsense. I suspect one of the two environments is printing the exact value, and the other is printing a poor approximation, and that in reality both correspond to the exact same binary double value. A: Using the script at http://www.mathworks.com/matlabcentral/fileexchange/1777-from-double-to-string the difference between the two numbers is only in the last bit: octave:1> bc = -0.96928123535654842068964853751822374761104583740234; octave:2> bm = -0.96928123535654830966734607500256970524787902832031; octave:3> num2bin(bc) ans = -.11111000001000101101000010100110011110111001110001011*2^+0 octave:4> num2bin(bm) ans = -.11111000001000101101000010100110011110111001110001010*2^+0 One of them must be closer to the "correct" answer, assuming the value given for a is exact. >> be = vpa('cos(2.89308776595231886830)',50) be = -.96928123535654836529707365425580405084360377470583 >> bc = -0.96928123535654842068964853751822374761104583740234; >> bm = -0.96928123535654830966734607500256970524787902832031; >> abs(bc-be) ans = .5539257488326242e-16 >> abs(bm-be) ans = .5562972757925323e-16 So, the C library result is more accurate. For the purposes of your question, however, you should not expect to get the same answer in matlab and whichever C library you linked with. A: The result is the same up to 15 decimal places, I suspect that is sufficient for almost all applications and if you require more you should probably be implementing your own version of cosine anyway such that you are in control of the specifics and your code is portable across different C compilers. They will differ because they undoubtedly use different methods to calculate the approximation to the result or iterate a different number of times. As cosine is defined as an infinite series of terms an approximation must be used for its software implementation. The CORDIC algorithm is one common implementation. Unfortunately, I don't know the specifics of the implementation in either case, indeed the C one will depend on which C standard library implementation you are using. A: As others have explained, when you enter that number directly in your source code, not all the fraction digits will be used, as you only get 15/16 decimal places for precision. In fact, they get converted to the nearest double value in binary (anything beyond the fixed limit of digits is dropped). To make things worse, and according to @R, IEEE 754 tolerates error in the last bit when using the cosine function. I actually ran into this when using different compilers. To illustrate, I tested with the following MEX file, once compiled with the default LCC compiler, and then using VS2010 (I am on WinXP 32-bit). In one function we directly call the C functions (mexPrintf is simply a macro #define as printf). In the other, we call mexEvalString to evaulate stuff in the MATLAB engine (equivalent to using the command prompt in MATLAB). prec.c #include <stdlib.h> #include <stdio.h> #include <math.h> #include "mex.h" void c_test() { double a = 2.89308776595231886830L; double b = cos(a); mexPrintf("[C] a = %.25Lf (%16Lx)\n", a, a); mexPrintf("[C] b = %.25Lf (%16Lx)\n", b, b); } void matlab_test() { mexEvalString("a = 2.89308776595231886830;"); mexEvalString("b = cos(a);"); mexEvalString("fprintf('[M] a = %.25f (%bx)\\n', a, a)"); mexEvalString("fprintf('[M] b = %.25f (%bx)\\n', b, b)"); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { matlab_test(); c_test(); } copmiled with LCC >> prec [M] a = 2.8930877659523189000000000 (4007250b32d9c886) [M] b = -0.9692812353565483100000000 (bfef045a14cf738a) [C] a = 2.8930877659523189000000000 ( 32d9c886) [C] b = -0.9692812353565484200000000 ( 14cf738b) <--- compiled with VS2010 >> prec [M] a = 2.8930877659523189000000000 (4007250b32d9c886) [M] b = -0.9692812353565483100000000 (bfef045a14cf738a) [C] a = 2.8930877659523189000000000 ( 32d9c886) [C] b = -0.9692812353565483100000000 ( 14cf738a) <--- I compile the above using: mex -v -largeArrayDims prec.c, and switch between the backend compilers using: mex -setup Note that I also tried to print the hexadecimal representation of the numbers. I only managed to show the lower half of binary double numbers in C (perhaps you can get the other half using some sort of bit manipulations, but I'm not sure how!) Finally, if you need more precision in you calculations, consider using a library for variable precision arithmetic. In MATLAB, if you have access to the Symbolic Math Toolbox, try: >> a = sym('2.89308776595231886830'); >> b = cos(a); >> vpa(b,25) ans = -0.9692812353565483652970737 So you can see that the actual value is somewhere between the two different approximations I got above, and in fact they are all equal up to the 15th decimal place: -0.96928123535654831.. # 0xbfef045a14cf738a -0.96928123535654836.. # <--- actual value (cannot be represented in 64-bit) -0.96928123535654842.. # 0xbfef045a14cf738b ^ 15th digit --/ UPDATE: If you want to correctly display the hexadecimal representation of floating point numbers in C, use this helper function instead (similar to NUM2HEX function in MATLAB): /* you need to adjust for double/float datatypes, big/little endianness */ void num2hex(double x) { unsigned char *p = (unsigned char *) &x; int i; for(i=sizeof(double)-1; i>=0; i--) { printf("%02x", p[i]); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to bind in XAML to a static property? I am trying to bind a static property of a different class to the Text Property of a TextBlock and can get the binding to work, but there's is no update to the Text Property when the static property's value has changed. I have read that I cannot use INotifyPropertyChanged because the property is static and have seen a number of solutions that suggest to use a Dependency Property. I am very new to C# and do not really understand how to use Dependency Properties, but have made a couple of attempts which do not seem to work for two reasons. 1. My static property has custom getter and setter and 2. The static property is used in a number of static methods which I can't figure out how to make work using a Dependency Property. I do not know how to use a custom getter and setter when using a Dependency Property or if this can even be done or how to continue using the static property in static methods after I change it to a Dependency Property. Here is the current code for the static property: public class Helper { public static string Token { get { using (StreamReader streamReader = new StreamReader("Token.ini")) { return streamReader.ReadLine(); } } set { using (StreamWriter streamWriter = new StreamWriter("Token.ini")) { streamWriter.WriteLine(value); } } } public static MethodThatUsesToken(){} public static OtherMethodThatUsesToken(){} And here the current XAML for the binding which works but doesn't update: <Window.Resources> <local:Helper x:Key="helper"/> </Window.Resources> <TextBlock Text="{Binding Source={StaticResource helper},Path=Token Converter={StaticResource NameConverter}}"/> I really appreciate any help! A: This is not currently possible, but will be in .NET 4.5: Also see "WPF 4.5 – Part 9 : binding to static properties" There is a workaround posted in this SO thread: Binding to static property A: In case this helps anyone else out I figured I'd post my final solution which works quite well for my purpose. Since it turns out not to be possible without .NET 4.5 I ended up changing the property and methods to no longer be static and changed the class to a singleton then implemented INotfiyPropertyChanged and changed the XAML binding source to x:Static instead of creating an instance in Window.Resources. A: Binding to static property is a problem (and unavailable in WPF) becuse of change notification (implementing INotifyPropertyChanged for static properties). Binding to static property will be introduced in WPF 4.5 (you can check it by installing .NET 4.5 Developer Preview). More details about it can be found here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is it necessary to add escape sequences to a binary string when storing to a MySQL Database? The whole point of designating data as binary is to simply treat the binary sequence as a raw, untouched sequence of bytes. => Given that MySQL has BLOB, BINARY and VARBINARY data types, why isn't it possible to store and retrieve any arbitrary binary stream of data from a php script without having the need to escape the sequence with mysql_real_escape_string or addslashes? A: Because binary data are still serialized to a string… So, for example, imagine your $binary_data had the value a 'b" c. Then the query INSERT INTO foo VALUES $binary_data would fail. A: The whole point of designating data as binary is to simply treat the binary sequence as a raw, untouched sequence of bytes. you are wrong. the only point of designating data as binary is just to mark it to be not a subject of character set recoding. that's all. why isn't it possible to store and retrieve any arbitrary binary stream of data from a php script without having the need to escape the sequence with mysql_real_escape_string or addslashes? who said it's impossible? it's quite possible, both to store and retrieve. The whole point of prepared statements is to send an arbitrary binary stream directly to mysql. Why is it necessary to add escape sequences to a binary string when storing to a MySQL Database? If you are talking of SQL, you have to understand what it is first. SQL is a programming language. And as any language has it's own syntax to follow. And if you're going to add your raw binary data to this program, you have to make this data satisfy these rules. That's what escaping for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Pygame not working with sockets I created one program with pygame, imageGrab and sockets but it doesn't work. It should take a printscreen of the server with ImageGrab, convert it to a string, and send it to the client. However, the client upon receiving the information and converting it to an image raises an error: image = pygame.image.frombuffer(img, (800,600), "RGB") ValueError: Buffer length does not equal format and resolution size code Server import sys, os, socket, pygame from PIL import ImageGrab from pygame.locals import * print "streaming sever 0.1" try: socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: print "Error creating socket" sys.exit(1) host = "127.0.0.1" port = raw_input("Port:") socket.bind((host, int(port))) socket.listen(2) socket2,client = socket.accept() print "Client conectado: " + str(client[0]) + "\nPorta usada: " + str(client[1]) #Capture and send while True: img=ImageGrab.grab().resize((800,600)) img.tostring() socket2.sendall(img) socket2.close() code Client import sys, os, socket, pygame from PIL import ImageGrab from pygame.locals import * print "streaming client 0.1" pygame.init() try: s_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) print "streaming protocol started" except socket.error: print "Error creating socket" sys.exit(1) host = "127.0.0.1" porta = raw_input("Port:") q_bytes = raw_input("Enter the number of MBs to transfer: ") t_bytes = 1024*1024*int(q_bytes) try: s_client.connect((host,int(porta))) except socket.error: print "Error connecting to: " + host sys.exit(1) print "Conectado!" size = width, height = 800, 600 screen = pygame.display.set_mode(size) num = 0 while True: img = s_client.recv(t_bytes) image = pygame.image.frombuffer(img, (800,600), "RGB") screen.blit(image,(0,0)) pygame.display.flip() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() os._exit(1) #recebimento s_client.close() A: The deal with sockets is you have to know exactly how long the message you're receiving is if you plan keep using the same socket connection. You seem to have some idea of this with your q_bytes = raw_input("Enter the number of MBs to transfer: "), but we need to know exactly, not to the nearest MB. Sometimes this information is sent at the front part of the data, so we can read it first and then know when to stop reading. The exception to this is if we don't need the connection anymore; we just want this one picture. In that case, it's fine to ask for as much data as we want, we'll get an empty string back at the end. As for the max_bytes argument to recv, that's just one maximum - there's another hardware-dependent maximum imposed on us, for my tests it was 1MB. The code below just keeps asking for data, stops when it receives an empty string because there is no more data, then combines all this gathered data into the full string. There are many levels of abstraction that could (and should) be built up to distance us from these complications, but the code below is just yours, working, with some irrelevant bits taken out. Client.py import sys, os, socket, pygame from pygame.locals import * pygame.init() s_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM) host = "127.0.0.1" porta = 12350 t_bytes = 1024*1024*1 s_client.connect((host,int(porta))) print "Conectado!" size = width, height = 300, 500 screen = pygame.display.set_mode(size) message = [] while True: s = s_client.recv(t_bytes) if not s: break else: message.append(s) full_s = "".join(message) print 'string received size', len(full_s) image = pygame.image.frombuffer(full_s, size, "RGB") #image = pygame.image.fromstring(s, size, "RGB") screen.blit(image,(0,0)) pygame.display.flip() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() os._exit(1) raw_input() s_client.close() Server.py import sys, os, socket, pygame from pygame.locals import * socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "127.0.0.1" port = 12350 socket.bind((host, int(port))) socket.listen(2) socket2,client = socket.accept() print "Client conectado: " + str(client[0]) + "\nPorta usada: " + str(client img = Image.open('tiny.jpg').resize((300, 500)) s = img.tostring() print 'size of string', len(s) socket2.sendall(s) socket2.close() edit: As per Mark's correction, len() calls were previously __sizeof__() method calls. __sizeof__ returns the size of the python object in bytes, not the number of bytes/characters in the string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UITextField not updating I'm having trouble updating the UITextField for an iPhone app. I've set the layout with the Interface Builder, created an instance of the text field in the ViewController, and set the ViewController as the delegate for the text field. The text field object in code doesn't seem to be responding when I enter in information and press Done. Does anyone have any ideas why its not working? A: If you are creating the text field in interface builder, you don't need to also alloc and init it in code. Link the text field to files owner in IB (I'm assuming files owner is your view controller) as the delegate. If you need to refer to it specifically, also create and outlet in your view controller and link that to your text field. This is covered in the most basic tutorial apps in the docs. To respond when the done button is pressed, implement the textFieldShouldReturn method from the UITextFieldDelegate protocol. Resign first responder in that method and return YES. A: Is your text field connected to the IBOutlet in your code? Maybe if you post some related code it would be helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing stored procedures on a code generated DbContext with Entity Framework 4.1 with DDD I'm working on a large project using ASP.Net MVC 3, EF 4.1 and Ninject for Dependecy Injection. I've read through many of the existing questions here regarding DDD, EF and the Repository Pattern but I can't seem to find anyone incorporating stored procedures with these patterns. I don't like the idea of implementing yet another repository pattern on top of what seems to already be a UnitOfWork/RepositoryPattern already defined with a DbContext. Also, I generally don't like the idea of creating Service and Repository classes for every type of entity in the system if possible. The source of my problem stems from this common repository interface which everyone seems to use. public interface IRepository<TEntity> where TEntity : class { TEntity Get(Expression<Func<TEntity, bool>> whereClause); IEnumerable<TEntity> List(); IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> whereClause); void Add(TEntity entity); void Delete(TEntity entity); // And so on... } That's great if all your queries can be in context of a single entity. Where this breaks for me is when I want to access a stored procedure. With EF 4.1 & Code Generatrion you can add stored procedures (e.g. SelectUser) and it will generate a context which looks something like this. namespace MyCompany.Data.Database { using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Objects; using MyCompany.Domain.Entities; using MyCompany.Domain.Contracts; public partial class MyCompanyEntities : DbContext { public MyCompanyEntities() : base("name=MyCompanyEntities") { this.Configuration.LazyLoadingEnabled = false; this.Configuration.ProxyCreationEnabled = false; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } public DbSet<Order> Orders { get; set; } public DbSet<User> Users { get; set; } public virtual ObjectResult<User> SelectUser(Nullable<int> userId) { ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace.LoadFromAssembly(typeof(User).Assembly); var userIdParameter = userId.HasValue ? new ObjectParameter("UserId", userId) : new ObjectParameter("UserId", typeof(int)); MyCompanyEntities x; x. return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<User>("SelectUser", userIdParameter); } public virtual ObjectResult<User> SelectUser(Nullable<int> userId, MergeOption mergeOption) { ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace.LoadFromAssembly(typeof(User).Assembly); var userIdParameter = userId.HasValue ? new ObjectParameter("UserId", userId) : new ObjectParameter("UserId", typeof(int)); return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<User>("SelectUser", mergeOption, userIdParameter); } } } As part of my DDD setup I have a UserService class and I would like to 'inject' a repository to its constructor. Many examples suggest that the constructor should accept an (IRepository<User> userRepository). This doesn't work for me. Stored procedures are generated on the DbContext class as a method and I am unable to see it. The only thing I can think of is to either create another interface with the stored procedure methods on it. I don't really want to add it to the generic IRepository because then when you have an instance of IRepository<Order> you'll still see SelectUser which seems a bit odd. Maybe it's not a big deal? Perhaps I'm going about this the wrong way. Should I not be bothering with creating an interface on top of my DbContext if I'm not trying to create a whole new repository pattern? I was really creating it for the dependency injection. Would it be wrong if the UserService constructor took a MyCompanyEntities instance instead of an interface? A: What you found is natural. The problem is that generic repository is insufficient for real scenarios. It is only good for "base" implementation. You need specific repository for User entity which will expose method wrapping call to context exposed stored procedure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Ignore trailing slash with Apache Rewrite I'm using mod_rewrite to redirect like so: RewriteRule (work)/?$ $1.php [L] This sends any URL ending in /work or /work/ to work.php The problem is, when a trailing slash is included, it treats it as a directory, and not the file that it really is. This, of course, breaks all of my relative paths in the file. I don't mind having a slash in the URL, but is there any way to use Apache to ignore the trailing slash, and treat the URL as a file, just as it would without the slash? A: Since you don't want the URL to look like www.domain.com/work/ here's what you can do: RewriteEngine On RewriteRule ^work/$ http://www.domain.com/work%{REQUEST_URI} [R=301,L,NC] RewriteRule (work)$ $1.php [L,QSA,NC] This will redirect /work/ to /work and /work/?page=main to /work?page=main
{ "language": "en", "url": "https://stackoverflow.com/questions/7622024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Notification icons for android platforms 1.5 - 3.2 My app targets Android 1.5 to 3.2 and I'm making notification icons specific to those platforms. I'm finding it difficult to correctly to organize the icons for all these versions, including h/d/ldpi versions. I know in 3.2, the qualifiers changed, so I'm trying to account for this as well. Currently, when I launcher in 3.2, it uses an icon for 2.3. My folder structure at the moment is as follows: * *drawable *drawable-hdpi *drawable-hdpi-v9 *drawable-ldpi-v9 *drawable-mdpi-v11 *drawable-mdpi-v9 *drawable-v11 *drawable-xlarge Question is which folder (including any missing ones) should I put the platform & display/density specific icons in so I target 1.5 - 3.2 correctly? A: You might try the Android Asset Studio for generating notification icons that follow conventions for different platform versions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AjaxUploader error in Opera I'm trying to integrate AjaxUploader into my site, but only in Opera browser I have an error, in other browsers it forks fine Besides, if I testing this code on new test server it forks fine in Opera browser too. I can't understand what's going on, help me please. Here is the stacktraca from Opera debugger: Uncaught exception: ReferenceError: Security error: attempted to read protected variable Error thrown at line 2216, column 2 in <anonymous function: Sizzle>(query, context, extra, seed) in http://site/assets/js/jquery1.6.js: if ( !seed && context.nodeType === 9 && !isXML(context) ) called from line 292, column 3 in <anonymous function: find>(selector) in http://site/assets/js/jquery1.6.js: jQuery.find( selector, this[0], ret ); called from line 230, column 4 in <anonymous function: submit>() in http://site/assets/js/ajaxupload.js: var response = iframe.contents().find('body').html(); called from line 2693, column 4 in <anonymous function: handle>(event) in http://site/assets/js/jquery1.6.js: var ret = handler.apply(this, arguments); called via Function.prototype.apply() from line 2467, column 4 in <anonymous function: add>() in http://site/assets/js/jquery1.6.js: return typeof jQuery !== "undefined" && !jQuery.event.triggered ? A: Looks like built-in cross-site scripting attack prevention. In some form or another (are you using iFrames?) you are trying to access a resource on one site from another site in a way that the browser is disallowing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DialogFragment and back button Is there any possibility to intercept the key button in DialogFragment? sorry for the naive question.. the onBackPressed of my FragmentActivity is never called. thanks in advance if (imageFile.exists()) { ShowPicDialog newFragment = ShowPicDialog.newInstance(); FragmentTransaction ft = manager.beginTransaction(); Fragment prev = manager.findFragmentByTag("picDialog"); if (prev != null) { ft.remove(prev); } ft.addToBackStack("picDialog"); newFragment.getArguments().putString("path", imageFile.getAbsolutePath()); newFragment.show(ft, "picDialog"); } sorry I added the snip of code I use to show the dialog. A: Rahul Pundhir's answer works great if you aren't using the builder pattern. If you are using the Builder pattern on your dialog you can instead do this: @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog alertDialog = new AlertDialog.Builder(getContext()) .setTitle(...) .setPositiveButton(...) .setNegativeButton(...) .setMessage(...) .create(); alertDialog.setOnKeyListener((dialog, keyCode, event) -> { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) { // TODO do the "back pressed" work here return true; } return false; }); return alertDialog; } This works by mimicking how the system calls onBackPressed() in the first place (ignoring the tracking and listening for ACTION_UP). See the source on Dialog A: It's hard to say for sure what the issue is, since you haven't posted any code. But my first guess is that you haven't added the DialogFragment to the back stack by calling the addToBackStack method of the FragmentTransaction that you're using to add your fragment to the activity. There are examples right in the Android documentation pages that give examples of a good pattern for using a DialogFragment in your Activity. Since you are displaying a Dialog, the created Dialog will receive the key events, not the parent Activity. So, set a Dialog.OnKeyListener when you create the Dialog's fragment, and call setCancelable(false) on the Dialog to prevent the back key from dismissing it. You can then handle the back key in your OnKeyListener's onkey method. A: Best way to Handle DialogFragment with back button: @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new Dialog(getActivity(), getTheme()){ @Override public void onBackPressed() { // On backpress, do your stuff here. } }; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Using Clojure with an annotation-based REST Server I am considering writing a REST Server using Clojure. I have experience using RESTEasy with Java. It uses annotations to associate URLs, template parameters, and query parameters with Java classes, methods, and method parameters. I believe that the Jersey REST Server also uses annotations (since it, too, is based on JAX-RS). Is it possible to use these frameworks with Clojure? Is there an official way to associate annotations with functions? A: I found the answer in the forth-coming book "Clojure Programming", by Chas Emerick, Brian Carper, and Christophe Grand. If you define a new type with deftype, you can add annotations the newly created class: (ns my.resources (:import (javax.ws.rs Path PathParam Produces GET))) (definterface PersonService (getPerson [^Integer id])) (deftype ^{Path "/people/{id}"} PersonResource [] PersonService (^{GET true Produces ["text/plain"]} getPerson [this ^{PathParam "id"} id] ; blah blah blah )) I'm not sure if this will work with gen-class. I'll need to experiment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to add lines to a levelplot made using lattice (abline somehow not working)? I want to draw horizontal and vertical lines on my level plot corresponding to x values from 74 to 76 and y values from 28 to 32. Below is my R code. But when I run the following,I get the levelplots but no lines. I also recieve no error from R. The default theme on my installation is something which maps the values to pink and cyan. I have also tried using the panel function but no luck with that as well. levelplot(d_fire_count_nom ~ longitude + latitude | factor(day)+factor(year), data = asia, subset = (month == 10), aspect="iso", contour = FALSE, layout=c(1,1), main="If a fire occured in a region (low confidence) in October during 2001-2008", scales=list(x=list(at=seq(from=60,to=98, by=1)), y=list(at=seq(from=5,to=38,by=1)),cex=.7, alternating=3), xlim=c(60, 98), ylim=c(5, 38), abline=list(h=74:76, v=28:32, col="grey")) A: That's not how lattice graphics work. In fact, if you read ?levelplot you'll see that there is no argument to that function called abline, so I'm not sure where you got that syntax from. You add things to lattice graphics by altering the panel function. There are many panel.* functions for doing various things, like plotting points, lines, scatterplot smoothers, etc. In this case there's a panel.abline that we'd like to use. So we define our own panel function. This uses the very first example from ?levelplot: x <- seq(pi/4, 5 * pi, length.out = 100) y <- seq(pi/4, 5 * pi, length.out = 100) r <- as.vector(sqrt(outer(x^2, y^2, "+"))) grid <- expand.grid(x=x, y=y) grid$z <- cos(r^2) * exp(-r/(pi^3)) levelplot(z~x*y, grid, panel = function(...){ panel.levelplot(...) panel.abline(h = 2.5) panel.abline(v = 2.5) }, cuts = 50, scales=list(log="e"), xlab="", ylab="", main="Weird Function", sub="with log scales", colorkey = FALSE, region = TRUE) Our new panel function needs to first draw the levelplot, so we have it call panel.levelplot first. Then we want to add some lines, so we add panel.abline for that purpose.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Remove contents of href attribute with with RegEx For example, I have this HTML snippet: <a href="/sites/all/themes/code.php">some text</a> The question is - how to cut the text /sites/all/themes/code.php from the href with preg_replace(); which pattern could I use? A: I would strongly recommend against using regular expressions to parse any SGML derivative. For HTML use some DOM parser. For PHP specifically there is DOMDocument. A: pattern: (<a .*?href=")([^"]*) replacement: $1 A: you don't have to do a "replace" (?<=<a href=")[^"]*(?=">) brings you what you want directly. test with grep: kent$ echo '<a href="/sites/all/themes/code.php">some text</a>'|grep -oP '(?<=<a href=")[^"]*(?=">)' /sites/all/themes/code.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7622042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: illegal start of expression error public Properties prop = new Properties(); I get an illegal start of expression error when I try this code snippet. I couldnt figure out what was wrong though. A: Most probably you have used this construction inside of a method or constructor. "public" keyword is allowed for classes, class fields, and methods, but is not allowed for local variables. Solution: remove "public" from your prop declaration. Properties prop = new Properties();
{ "language": "en", "url": "https://stackoverflow.com/questions/7622044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: genfromtxt dtype=None returns wrong shape I'm a newcomer to numpy, and am having a hard time reading CSVs into a numpy array with genfromtxt. I found a CSV file on the web that I'm using as an example. It's a mixture of floats and strings. It's here: http://pastebin.com/fMdRjRMv I'm using numpy via pylab (initializing on a Ubuntu system via: ipython -pylab). numpy.version.version is 1.3.0. Here's what I do: Example #1: data = genfromtxt("fMdRjRMv.txt", delimiter=',', dtype=None) data.shape (374, 15) data[10,10] ## Take a look at an example element '30' type(data[10,10]) type 'numpy.string_' There are no errant quotation marks in the CSV file, so I've no idea why it should think that the number is a string. Does anyone know why this is the case? Example #2 (skipping the first row): data = genfromtxt("fMdRjRMv.txt", delimiter=',', dtype=None, skiprows=1) data.shape (373,) Does anyone know why it would not read all of this into a 1-dimensional array? Thanks so much! A: In your example #1, the problem is that all the values in a single column must share the same datatype. Since the first line of your data file has the column names, this means that the datatype of every column is string. You have the right idea in example #2 of skipping the first row. Note however that 1.3.0 is a rather old version (I have 1.6.1). In newer versions skiprows is deprecated and you should use skip_header instead. The reason that the shape of the array is (373,) is that it is a structured array (see http://docs.scipy.org/doc/numpy/user/basics.rec.html), which is what numpy uses to represent inhomogeneous data. So data[10] gives you an entire row of your table. You can also access the data columns by name, for example data['f10']. You can find the names of the columns in data.dtype.names. It is also possible to use the original column names that are defined in the first line of your data file: data = genfromtxt("fMdRjRMv.txt", dtype=None, delimiter=',', names=True) then you can access a column like data['Age'].
{ "language": "en", "url": "https://stackoverflow.com/questions/7622045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ViewModel updates every second? Iam writing an app that shows a list of the remaining time a user has on a course. I want the list to dynamically update every second so the user has the full overview. public class ReservationCustomerList : INotifyPropertyChanged { public int UnitsLeft { get; set; } public DateTime? OnCircuitSince { get; set; } public TimeSpan? TimeLeftDate { get { if (OnCircuitSince.HasValue) return TimeSpan.FromSeconds((OnCircuitSince.Value - DateTime.Now).TotalSeconds - UnitsLeft); return TimeSpan.FromSeconds(UnitsLeft); } } private void FireEverySecond() { PropertyChanged.Fire(this, x => x.TimeLeftDate); } } As you can see above the idea is that the model knows when the customer entered the circuit and the time the have left. As you can see iam thinking of using the INotifyPropertyChanged interface and then actually having a timer on every viewmodel. However this is my concern. Adding a Timer on every viewmodel seems very bloated, is this really the best way to achieve this ? Second concern is that if the timer is never stopped wouldn't this result in a memory leak since the timer would never stop and keep the viewmodel alive ? If this is the case my Viewmodel would also need to implement IDisposable and i would need to remember to run through all viewmodels and dispose them to make sure that these are garbage collected. Are my concerns correct ? Thanks. Yes i was thinking of having a timer service to prevent having multiple timers, however having to manually unregister would surely at some point introduce memoery leaks. So the idea with Weak Events is great. Iam thinking of doing it something like this: public class TimerService { static Timer Timer; static FastSmartWeakEvent<EventHandler> _secondEvent = new FastSmartWeakEvent<EventHandler>(); static FastSmartWeakEvent<EventHandler> _minuteEvent = new FastSmartWeakEvent<EventHandler>(); static DateTime LastTime; public static event EventHandler SecondEvent { add { _secondEvent.Add(value); } remove { _secondEvent.Remove(value); } } public static event EventHandler MinuteEvent { add { _minuteEvent.Add(value); } remove { _minuteEvent.Remove(value); } } static TimerService() { Timer = new Timer(TimerFire, null, 1000, 1000); } static void TimerFire(object state) { _secondEvent.Raise(null, EventArgs.Empty); if (LastTime.Minute != DateTime.Now.Minute) _minuteEvent.Raise(null, EventArgs.Empty); LastTime = DateTime.Now; } } Do you have any comments ? I Know i could use a singleton GetInstance (or IoC) however this would just make it more inconvinient to use. Iam using the WeakEvent implementation that Daniel Grunwald wrote on codeproject. (it gives a very clean class and not much overhead). http://www.codeproject.com/KB/cs/WeakEvents.aspx A: You could have a timer service with a private timer and a public event, that notifies all the viewmodels every second. Regarding the memory issues, you could register your viewmodel with the timer service when your page is navigated (OnNavigatedTo) and unregister it when the view is closed (OnNavigatedFrom). This way the viewmodels wouldn't have any reference with the timer service when they go out of scope, and they would be garbage collected properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: jQuery get and text return replacement character. How to solve? If I use: $.get("url",function(data){$("#destination").text(data);}) in the .text of #destination the letters like èéàòùì become the replacement character. How do I solve it? Set the charsets is useless; I don't want to use .replace("strange character","");.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does this TLS code only runs in debugging mode? I'm getting a strange error: The handshake failed due to an unexpected packet format if I directly run my code without debugging. And If I set a break point and then debug the code line by line it works fine. Here is the detail exception The handshake failed due to an unexpected packet format. at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest) at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult) at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation) at System.Net.Security.SslStream.AuthenticateAsClient(String targetHost) at Searock_IM.Facebook.LoginForm.StartTls() in D:\Projects\Searock IM\Facebook\LoginForm.cs:line 456 at Searock_IM.Facebook.LoginForm.button2_Click(Object sender, EventArgs e) in D:\Projects\Searock IM\Facebook\LoginForm.cs:line 137 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at Searock_IM.Program.Main() in D:\Projects\Searock IM\Program.cs:line 18 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() and here is the code: class Connection : IDisposable { private readonly Socket _socket; private NetworkStream _networkStream; private SslStream _sslStream; private int _bufferStartIndex; private readonly byte[] _buffer = new byte[0x8000]; private StringBuilder _recievedText = new StringBuilder(); public StringBuilder Debug { get; private set; } public bool UseSecure { get; set; } public void StartTls() { UseSecure = true; if (_networkStream == null) _networkStream = new NetworkStream( _socket ); if (_sslStream != null) return; _sslStream = new SslStream(_networkStream); _sslStream.AuthenticateAsClient("chat.facebook.com"); lock (Debug) Debug.AppendFormat( "** Started TLS **<br/>" ); } public Connection() { Debug = new StringBuilder(); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.Connect("chat.facebook.com", 5222); } public void Dispose() { if (_sslStream != null) _sslStream.Dispose(); if (_networkStream != null) _networkStream.Dispose(); } public void Send(string text) { if (String.IsNullOrEmpty( text )) return; lock (Debug) Debug.AppendFormat( "Out: {0} <br/>", HttpUtility.HtmlEncode(text) ); byte[] outp = Encoding.UTF8.GetBytes(text); if (UseSecure) _sslStream.Write(outp); else _socket.Send(outp); } public string Recieve() { if (_socket.Available == 0) return null; int bytesRead = 0; if (UseSecure) bytesRead = _sslStream.Read(_buffer, _bufferStartIndex, _buffer.Length - _bufferStartIndex); else bytesRead = _socket.Receive(_buffer, _bufferStartIndex, _buffer.Length - _bufferStartIndex, SocketFlags.None); ReadBytes( bytesRead ); var incomming = ClearStringBuffer(); lock (Debug) Debug.AppendFormat( "In: {0}<br/> ", HttpUtility.HtmlEncode( incomming )); return incomming; } private void ReadBytes( int bytesRead ) { // http://en.wikipedia.org/wiki/UTF-8#Design // Top 2 bits are either; // 00xx xxxx => 6 bit ASCII mapped character // 11xx xxxx => multi byte chatacter Start // 10xx xxxx => multi byte chatacter Middle of definition // So while last character in buffer is 'middle of definition' rewind end buffer pointer int endOfBuffer = bytesRead + _bufferStartIndex; if (endOfBuffer == 0) return; int end = endOfBuffer; while ((_buffer[end - 1] & 0xC0) == 0x80) --end; string part = Encoding.UTF8.GetString( _buffer, 0, end ).TrimEnd( '\0' ); if (end != endOfBuffer) { _bufferStartIndex = endOfBuffer - end; for (int i = 0; i < _bufferStartIndex; i++) _buffer[i] = _buffer[i + end]; } lock (_recievedText) _recievedText.Append( part ); } private string ClearStringBuffer() { string result; lock (_recievedText) { result = _recievedText.ToString(); _recievedText = new StringBuilder(); } return result; } } I get the error The handshake failed due to an unexpected packet format at line: _sslStream.AuthenticateAsClient("chat.facebook.com"); I'm calling this class from a windows form and I haven't used any threads in this form. Can someone point me in a right direction? Thanks. A: Is it possible that http://chat.facebook.com:5222 does not require a secure connection? See this Facebook help article. if you telnet to that address and send some dummy data you will get an xml response as <?xml version="1.0"?> <stream:stream id="none" from="chat.facebook.com" version="1.0" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams"> <stream:error> <xml-not-well-formed xmlns="urn:ietf:params:xml:ns:xmpp-streams"/> </stream:error>
{ "language": "en", "url": "https://stackoverflow.com/questions/7622051", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Creating a minimized overlapped window (Win32) I'd like to create an overlappedwindow that starts out visible (so the taskbar button shows) but minimized. Creating the window with WS_MINIMZED (or WS_MAXIMIZE for that matter) does nothing. Using ShowWindow(hWnd,SW_SHOWMINIMIZED) gives a critical error. I suspect it has something to do with STARTUPINFO but I can't find any info on how to adjust/change/hijack it. hWnd = CreateWindowA( (LPCSTR)atom, "Window Name", WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_MINIMZED, // doesn't work CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, hInstance, 0); ShowWindow(hWnd,SW_SHOWMINIMIZED); // gives critical error A: @Kaisha, you are right: if you start an executable using CreateProcess, then the visibility of the window will be influenced by STARTUPINFO. To start an application with its window minimized, do this: ZeroMemory(&startupInfo, sizeof(startupInfo)); startupInfo.cb = sizeof(startupInfo); startupInfo.dwFlags = STARTF_USESHOWWINDOW; startupInfo.wShowWindow = SW_SHOWMINNOACTIVE; I used this approach in an application which repeatedly started the command-line version of WinZip, and it worked fine. A: Citing the MSDN, function ShowWindow, parameter nCmdShow: Controls how the window is to be shown. This parameter is ignored the first time an application calls ShowWindow, if the program that launched the application provides a STARTUPINFO structure. So I'm guessing that your window is the first window created by the application, and as such, the parameter of ShowWindow is ignored. Another little known fact is seen in the docs for CreateWindow, parameter y (yes, y): If an overlapped window is created with the WS_VISIBLE style bit set and the x parameter is set to CW_USEDEFAULT, then the y parameter determines how the window is shown. If the y parameter is CW_USEDEFAULT, then the window manager calls ShowWindow with the SW_SHOW flag after the window has been created. If the y parameter is some other value, then the window manager calls ShowWindow with that value as the nCmdShow parameter. Probably it is better if you create the window hidden (without WS_VISIBLE) and/or passing 0 as the y parameter of CreateWindow. Other options would be to create a dummy window first, show it, and destroy it quickly, some like a splash-screen. That would consume the STARTUPINFO command.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DokuWiki nested lists regexp How can i replace DokuWiki nested list string with using one or two regexps in Ruby? For example, if we have this string: * one * two * three * four we should get this HTML: * *one *two * *three *four I've made a regexp replacing the whole list. E.g.: s.sub!(/(^\s+\*\s.+$)+/m, '<ul>\1</ul>') And it works as it should. But how to replace the single list items? A: The regex : Here are some example lists : * first item * second item No longer a list * third item? no, it's the first item of the second list * first item * second item with linebreak\\ second line * third item with code: <code> some code comes here </code> * fourth item The regex for matching all lists (?<=^|\n)(?: {2,}\*([^\n]*?<code>.*?</code>[^\n]*|[^\n]*)\n?)+ View it in action : http://rubular.com/r/VMjwbyhJTm The code : Surround all lists with a <ul>...</ul> s.sub!(/(?<=^|\n)(?: {2,}\*(?:[^\n]*?<code>.*?<\/code>[^\n]*|[^\n]*)\n?)+/m, '<ul>\0</ul>') Add missing <li>s (s2 in the following code is the string with <ul>...</ul> added) s2.sub!(/ {2,}\*([^\n]*?<code>.*?<\/code>[^\n]*|[^\n]*)\n?/m, '<li>\1</li>') Note : Nested lists can not be handled with this regex. If this is a requirement, a parser will be more adapted !
{ "language": "en", "url": "https://stackoverflow.com/questions/7622056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How using pinvoke to force change border style to none of window? Is it possible to change border style of window to have no border, using pinvoke? If it isn't possible, how can i get the client rectangle without borders? I am standing over problem where each computer opens this window with another param size. I have specific window with its intPtr hwnd. A: You can use SetWindowLong winapi function to set window style. Just use only necessary styles that do not include WS_THICKFRAME or WS_BORDER or similar SetWindowLong and List of windows styles Here is the similar question
{ "language": "en", "url": "https://stackoverflow.com/questions/7622069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Basic Asyncronous TCP server in Java I'm trying to create a very basic asynchronous server in Java (similar to http://msdn.microsoft.com/en-us/library/fx6588te.aspx in C#). All of the libraries I've seen for Java are way too complex for what I need and I'm wondering if there are any libraries that are simple and have a syntax similar to the C# example. Edit: Why does plain sockets require root access to listen on the loopback, but nio doesn't require root? A: try AsynchronousServerSocketChannel & AsynchronousSocketChannel A: This sounds like a job for Java's NIO (New I/O) ServerSocketChannel. Be forewarned, though: this doesn't guarantee better performance. See: * *Java in 2011: threaded sockets VS NIO: what to choose on 64bit OS and latest Java version? *http://www.thebuzzmedia.com/java-io-faster-than-nio-old-is-new-again/
{ "language": "en", "url": "https://stackoverflow.com/questions/7622070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get a disclosure indicator in my tableview header section? I'm customizing my headers in my Tableview and I want to add a discloure indicator (arrow) to my header that is clickable, is that possible? A: If you already customized your header view you can simply add a custom UIButton with an image of a discloure indicator add add it as a subview to your header view. If you need further help you are most welcome. EDIT Jonathan is right, the UIButton has a UIButtonTypeDetailDisclosure so there is no need for a custom image. A: You can fetch the header view using - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section Then fetch the actual header view UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view; Create a button with detail disclosure UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; Then set the frame of this button and add it to the header view
{ "language": "en", "url": "https://stackoverflow.com/questions/7622074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In IntelliJ IDEA, how can I create a key binding that executes a shell script with the current file as a parameter? In IntelliJ IDEA, how can I create a key binding that executes a shell script with the current file as a parameter? For exanmple, if I am in a test file (entity.spec.js), I want to save and hit a key binding to trigger a shell script with that file as the parameter: ./run_test.sh /full/path/to/entity.spec.js Any idea how to do that? A: You can do it using the External Tools. Then you can assign a keyboard shortcut to your tool in Settings | Keymap. Please note that you should specify your shell interpreter as a Program for the external tool (such as /bin/bash) and pass your script path and the file name as Parameters. Use Insert Macro button to add a macro for the current editor file path.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Programming for Android in a 100% C++ Environment? I've been working on a game engine runtime environment in C++ for my future games, and have started to consider android as a platform. I noticed that it was tightly bound to Java and uses Java VMs heavily. But is it possible to sustain a full C++ runtime environment in Android NDK? I have nothing against Java and am prepared to use it if I have to, but performance is one of my prime concerns (I intend for my games to be resource-intensive), especially on phones. And if a full C++ environment is possible, how exactly would I implement it in Eclipse Indigo CDT? Would I be able to create a compiled game executable for Android ahead of time for maximum performance? And would there be any additional plugins I'd need to install in Eclipse? Could I use MinGW for compiling my games, or would I need to use a different compiler? If I had to use Java in one way or another, would compilation of the C++ code even be required? These are all questions I'd like to answer to get a sturdy development environment going in the Eclipse IDE. Please know that I'm still fairly new to Android development, and multiplatform programming in general. My goal is to create a game engine that'll take the most advantage of the new hardware out there, especially on phones! Thanks for any advice you guys can give! A: NativeActivity, added in Android 2.3 (API 9) might be what you're looking for in terms of writing Android games using only C++. http://developer.android.com/reference/android/app/NativeActivity.html However since you say you're new to this you may want to start with one of the currently available Android game engines instead of writing your own right away. Mobile devices have a very different set of constraints than other platforms. A phone isn't very useful if the battery dies mid-afternoon, so starting a project with the stated goal of being "resource-intensive" is already getting off to a bad start. Few people will want to play your games for 20 minutes here and there if it means they won't be able to make a phone call in the evening. If what you meant is that you are shooting for high-end graphics, keep in mind that devices have a wide range of capability in this area and targeting only the high end limits your audience. Different GPUs have very different strategies and performance characteristics and all have cases where they shine or lag behind. The most successful mobile games aren't the ones with the highest polycounts or the most complex lighting shaders, they're the games that achieve a consistently smooth framerate and have a distinctive style. Have a look at some of the existing game engines for Android and try them out. Write a couple small games to take them for a test drive and see where they do and don't mesh with what you're trying to do. If you find yourself feeling limited with what's available, take what you've learned and try to write your own engine that fits with the types of games you want to make. Here are some links to get you started. These engines power some very popular games on Android Market and many developers have found them useful: http://www.andengine.org/ andengine is written in Java and is open source. http://unity3d.com/ Unity is based on C# and Mono. http://www.madewithmarmalade.com/ Marmalade, formerly Airplay SDK is based on C++. A: The answer you want to pay close attention to is @adamp's. Ignore his answer at your own peril. To address a couple of other points in your question, though: Would I be able to create a compiled game executable for Android ahead of time for maximum performance? No, insofar as Android does not use "compiled game executables". Your C/C++ code will be compiled into a Linux shared object (.so) file and packaged with other stuff (like your manifest) in an APK file. Compiling the .so will be ahead of time, though. Could I use MinGW for compiling my games would I need to use a different compiler? I get the distinct impression that you will claw your eyes out trying to do NDK development in Cygwin on Windows. I heartily encourage you to do your NDK development on OS X or Linux. At least set up a VirtualBox with Ubuntu or something in it to do your NDK compiles. Regardless, the NDK comes with its own GCC compiler. AFAIK, MinGW is not a cross-compiler, and most Android devices are not running on x86 CPUs. If I had to use Java in one way or another, would compilation of the C++ code even be required? Yes. Now, for Honeycomb, you have the option of using Renderscript for OpenGL work -- that amounts to a C99 environment whose code you will not need to compile with the NDK. A: I've tried a bunch of them, and one of the best I found that cross compiles instantly to a bunch of other devices and let's you program your goodies in HTML5/C++ combo (sweeeeet) is MoSync (http://www.mosync.com/) and another little known one that is a little more setup friendly is MotoDev by Motorola (http://developer.motorola.com/tools/motodevstudio/?utm_campaign=mhp01092012&utm_source=mhp&utm_medium=mws) I've noticed there is some virtual machine images and tutorials you can use to prevent the setting up hassle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: How to read GRIB files with R / GDAL? I'm trying to read a GRIB file wavedata.grib with wave heights from the ECMWF ERA-40 website, using an R function. Here is my source code until now: mylat = 43.75 mylong = 331.25 # read the GRIB file library(rgdal) library(sp) gribfile<-"wavedata.grib" grib <- readGDAL(gribfile) summary = GDALinfo(gribfile,silent=TRUE) save(summary, file="summary.txt",ascii = TRUE) # >names(summary): rows columns bands ll.x ll.y res.x res.y oblique.x oblique.y rows = summary[["rows"]] columns = summary[["columns"]] bands = summary[["bands"]] # z=geometry(grib) # Grid topology: # cellcentre.offset cellsize cells.dim # x 326.25 2.5 13 # y 28.75 2.5 7 # SpatialPoints: # x y # [1,] 326.25 43.75 # [2,] 328.75 43.75 # [3,] 331.25 43.75 myframe<-t(data.frame(grib)) # myframe[bands+1,3]=331.25 myframe[bands+2,3]=43.75 # myframe[1,3]=2.162918 myframe[2,3]=2.427078 myframe[3,3]=2.211989 # These values should match the values read by Degrib (see below) # degrib.exe wavedata.grib -P -pnt 43.75,331.25 -Interp 1 > wavedata.txt # element, unit, refTime, validTime, (43.750000,331.250000) # SWH, [m], 195709010000, 195709010000, 2.147 # SWH, [m], 195709020000, 195709020000, 2.159 # SWH, [m], 195709030000, 195709030000, 1.931 lines = rows * columns mycol = 0 for (i in 1:lines) { if (mylat==myframe[bands+2,i] & mylong==myframe[bands+1,i]) {mycol = i+1} } # notice mycol = i+1 in order to get values in column to the right myvector <- as.numeric(myframe[,mycol]) sink("output.txt") cat("lat:",myframe[bands+2,mycol],"long:",myframe[bands+1,mycol],"\n") for (i in 1:bands) { cat(myvector[i],"\n") } sink() The wavedata.grib file has grided SWH values, in the period 1957-09-01 to 2002-08-31. Each band refers to a pair of lat/long and has a series of 16346 SWH values at 00h of each day (1 band = 16346 values at a certain lat/long). myframe has dimensions 16438 x 91. Notice 91 = 7rows x 13columns. And the number 16438 is almost equal to number of bands. The additional 2 rows/bands are long and lat values, all other columns should be wave heights corresponding to the 16436 bands. The problem is I want to extract SWH (wave heights) at lat/long = 43.75,331.25, but they don't match the values I get reading the file with Degrib utility at this same lat/long. Also, the correct values I want (2.147, 2.159, 1.931, ...) are in column 4 and not column 3 of myframe, even though myframe[16438,3]=43.75 (lat) and myframe[16437,3]=331.25 (long). Why is this? I would like to know to which lat/long do myframe[i,j] values actually correspond to or if there is some data import error in the process. I'm assuming Degrib has no errors. Is there any R routine to easily interpolate values in a matrix if I want to extract values between grid points? More generally, I need help in writing an effective R function to extract wave heights like this: SWH <- function (latitude, longitude, date/time) Please help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Suggest a weekend learning track for MVC3 for someone familiar ASP.NET web forms development I have a "green field" project I'll be starting monday, and it's an intranet business application that wants to do all the typical stuff like workflow, alerts. The Model is done with EF and has all the core entities that a 50 person company would be expected to have plus a model of business specific accounting procedures - every entity corresponds to a noun in the employees' nomenclature. I spent a good deal of spare time in the past few months learning sharepoint 2010 and it definately has facilities for everything this project wants to be (think enthusiastic business owner who recently woke up to the possibilities of life beyond excel sheets). I may not have the opportunity to get up on the sharepoint curve quickly enough and this means writing it from scratch. The main things I need to deal with are: - grid style data forms - active directory based authentication - email integrated alerts and event driven workflow - professional appearance similar to default sharepoint 2010 theme I know how I'd do it with web forms. It would not be trivial by any means - Providers, .ASCX Controls, Validators, Masterpages, Themes, Skins, tied together with a project specific class library to support cross-cutting issues. I have this architecture in my mind and it's worked for me on other projects - I can predict to myself the success and schedule, which makes my stress level manageable. That said, I get the distinct imppression from the "blog-o-sphere" that I'd be doing myself a disservice if I didn't at least try to use MVC for this. I started researching and found the Documentation Resources for ASP.NET MVC 3 and, well, I just don't know where to begin. I have this weekend to decide if I can do it because Monday I've gotta go in with a game plan. If, from my description, someone could recommend a tutorial and/or a clean open source example, I'd be very thankful. A: For me, a real world sample is always the most useful where to start : http://www.asp.net/entity-framework/tutorials/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application There is a real world sample there called The Contoso University Web Application The following conference session videos are great the start with also : MVC 3 – 101 by Scott Hanselman : http://channel9.msdn.com/Events/DevDays/DevDays-2011-Netherlands/Devdays002 ASP.NET MVC 3 @:The Time is Now by Phil Haack : http://channel9.msdn.com/Events/MIX/MIX11/FRM03 ASP.NET + Packaging + Open Source = Crazy Delicious by Scott Hanselman : http://channel9.msdn.com/Events/PDC/PDC10/FT01 And there are so many out there on Channel9 A: I suggest you get this book (e-book version). It contains a real walk through example on the first chapter that you can follow, and then as you move along, the author also tells you why you do certain things the way the are. I'm sure with your experience (as you describe) with webforms, this book should be sufficient for you to make a decision over the weekend. Just out of curiosity though (in a pragmatic point of view), if you believe you can do this easily using webforms, why the trouble learning MVC over the weekend? Wouldn't you be disservicing yourself then :)? A: http://www.asp.net/mvc has pretty much what you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Rails: possible to check if a string is binary? In a particular Rails application, I'm pulling binary data out of LDAP into a variable for processing. Is there a way to check if the variable contains binary data? I don't want to continue with processing of this variable if it's not binary. I would expect to use is_a?... In fact, the binary data I'm pulling from LDAP is a photo. So maybe there's an even better way to ensure the variable contains binary JPEG data? The result of this check will determine whether to continue processing the JPEG data, or to render a default JPEG from disk instead. A: There is actually a lot more to this question than you might think. Only since Ruby 1.9 has there been a concept of characters (in some encoding) versus raw bytes. So in Ruby 1.9 you might be able to get away with requesting the encoding. Since you are getting stuff from LDAP the encoding for the strings coming in should be well known, most likely ISO-8859-1 or UTF-8. In which case you can get the encoding and act on that: some_variable.encoding # => when ASCII-8BIT, treat as a photo Since you really want to verify that the binary data is a photo, it would make sense to run it through an image library. RMagick comes to mind. The documentation will show you how to verify that any binary data is actually JPEG encoded. You will then also be able to store other properties such as width and height. If you don't have RMagick installed, an alternative approach would be to save the data into a Tempfile, drop down into Unix (assuming you are on Unix) and try to identify the file. If your system has ImageMagick installed, the identify command will tell you all about images. But just calling file on it will tell you this too: ~/Pictures$ file P1020359.jpg P1020359.jpg: JPEG image data, EXIF standard, comment: "AppleMark" You need to call the identify and file commands in a shell from Ruby: %x(identify #{tempfile}) %x(file #{tempfile})
{ "language": "en", "url": "https://stackoverflow.com/questions/7622095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: PHP IF statement not reacting how I think it should? I am having a little trouble with the following php statement: if (!userIsLoggedIn()) { $prPrice = (empty($prPrice2)) ? $prPrice1 : $prPrice1; } else { $prPrice = (empty($prPrice2)) ? $prPrice1 : $prPrice2; } Here is an example of two products: product 1 -> price1 = 1.00 product 1 -> price2 = 0.00 product 2 -> price1 = 1.00 product 2 -> price2 = 0.80 If a user is not logged into our website (userIsLoggedIn function) Then they should only be able to see the product price1, regardless if product price2 exists or not. On the other hand, When a user has logged into our website. Then they should be able to see price2 for products where it exists, or they will simply see price1. Now the problem with me code, is this: A user is not logged on, they see price1 regardless of whether an item has a price2 set or not. When a user has logged in, they see price2 for items that have a price two, but this is the strange part, for items that do not have a price2, it simply displays 0, Where it should display price1. Does anyone have any input as to why the mentioned code is producing this effect? I can provide further code relating to the userIsLoggedIn function, on request. Thank you to anyone that would like to help!! A: The code is working as it should - price2 for your product 1 should not return true on a call to empty() because it has a value of 0.00. Maybe you should check if a value is 0 or not instead? A: Your code looks fine to me. You could verify that the variables hold the value you expect by using var_dump(). Also your code might be shortened like this. However if you have to check a lot of prices it's probably not adviseable to execute userIsLoggedIn() in each check but instead save that result in a variable. $prPrice = ($prPrice2 != 0 && userIsLoggedIn()) ? $prPrice2 : $prPrice1;
{ "language": "en", "url": "https://stackoverflow.com/questions/7622101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android: Gridview force closes I am following a good tutorial on using a gridview. I have been unable to get the code to work however as ever time I compile and run the app force closes. Logcat says its "unable to instantiate activity CompnentInfo" amount a series of other errors. I'm not to handy with debugging so I'm at an impasse. This is my code: public class GridViewDemo extends Activity { public String[] filenames = { "File 1", "File 2", "Roflcopters" }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new ButtonAdapter(this)); } //Classes public class ButtonAdapter extends BaseAdapter { private Context mContext; // Gets the context so it can be used later public ButtonAdapter(Context c) { mContext = c; } // Total number of things contained within the adapter public int getCount() { return filenames.length; } // Require for structure, not really used in my code. public Object getItem(int position) { return null; } // Require for structure, not really used in my code. Can // be used to get the id of an item in the adapter for // manual control. public long getItemId(int position) { return position; } @SuppressWarnings("null") public View getView(int position, View convertView, ViewGroup parent) { Button btn = null; btn.setOnClickListener(new MyOnClickListener(position)); if (convertView == null) { // if it's not recycled, initialize some attributes btn = new Button(mContext); btn.setLayoutParams(new GridView.LayoutParams(100, 55)); btn.setPadding(8, 8, 8, 8); } else { btn = (Button) convertView; } btn.setText(filenames[position]); // filenames is an array of strings btn.setTextColor(Color.WHITE); btn.setBackgroundResource(R.drawable.icon); btn.setId(position); return btn; } } class MyOnClickListener implements OnClickListener { private final int position; public MyOnClickListener(int position) { this.position = position; } public void onClick(View v) { // Preform a function based on the position // someFunction(this.position) Toast.makeText(getApplicationContext(), this.position, Toast.LENGTH_SHORT).show(); } } XML: <?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="90dp" android:numColumns="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:stretchMode="columnWidth" android:gravity="center" /> Manifest xml: <?xml version="1.0" encoding="utf-8"?> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".GridviewActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> Any ideas why this crashes? This is the logcat output: A: First, I would recommend learning how to debug [see this article and this one for example]. It will become handy very soon... Second, next time please add a log from logcat, which shows the details for the exception which caused the "force close". Regarding your problem, you are trying to call a method on a null object: Button btn = null; btn.setOnClickListener(new MyOnClickListener(position)); which causes a null pointer exception. You should add the listener only after you assigned an object to btn, which is after the if-else blocks. One more things - you suppressed the null warning (@SuppressWarnings("null")), to avoid the warning, instead of taking care of it, and this way you got the null pointer exception. Unless you are hundred percents sure, don't ignore the warnings. Edit: Looking at your manifest, this is a small typo. It should be <activity android:name=".GridViewActivity" Instead of: <activity android:name=".GridviewActivity"
{ "language": "en", "url": "https://stackoverflow.com/questions/7622102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot instantiate abstract class in C++ error I want to implement an interface inside a "Dog" class, but I'm getting the following error. The final goal is to use a function that recieves a comparable object so it can compare the actual instance of the object to the one I'm passing by parameter, just like an equals. An Operator overload is not an option cause I have to implement that interface. The error triggers when creating the object using the "new" keyword. " Error 2 error C2259: 'Dog' : cannot instantiate abstract class c:\users\fenix\documents\visual studio 2008\projects\interface-test\interface-test\interface-test.cpp 8 " Here is the code of the classes involved: #pragma once class IComp { public: virtual bool f(const IComp& ic)=0; //pure virtual function }; #include "IComp.h" class Dog : public IComp { public: Dog(void); ~Dog(void); bool f(const Dog& d); }; #include "StdAfx.h" #include "Dog.h" Dog::Dog(void) { } Dog::~Dog(void) { } bool Dog::f(const Dog &d) { return true; } #include "stdafx.h" #include <iostream> #include "Dog.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { Dog *d = new Dog; //--------------ERROR HERE** system("pause"); return 0; } A: bool f(const Dog &d) is not an implementation of bool f(const IComp& ic), so the virtual bool f(const IComp& ic) still isn't implemented by Dog A: Your class Dog does not implement the method f, because they have different signatures. It needs to be declared as: bool f(const IComp& d); also in the Dog class, since bool f(const Dog& d); is another method altogether. A: bool f(const Dog& d); is not an implementation for IComp's virtual bool f(const IComp& ic)=0; //pure virtual function Your definition of Dog's f is actually hidding the pure virtual function, instead of implementing it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Performing simultaneous unrelated queries in EF4 without a stored procedure? I have a page that pulls together aggregate data from two different tables. I would like to perform these queries in parallel to reduce the latency without having to introduce a stored procedure that would do both. For example, I currently have this: ViewBag.TotalUsers = DB.Users.Count(); ViewBag.TotalPosts = DB.Posts.Count(); // Page displays both values but has two trips to the DB server I'd like something akin to: var info = DB.Select(db => new { TotalUsers = db.Users.Count(), TotalPosts = db.Posts.Count()); // Page displays both values using one trip to DB server. that would generate a query like this SELECT (SELECT COUNT(*) FROM Users) AS TotalUsers, (SELECT COUNT(*) FROM Posts) AS TotalPosts Thus, I'm looking for a single query to hit the DB server. I'm not asking how to parallelize two separate queries using Tasks or Threads Obviously I could create a stored procedure that got back both values in a single trip, but I'd like to avoid that if possible as it's easier to add additional stats purely in code rather than having to keep refreshing the DB import. Am I missing something? Is there a nice pattern in EF to say that you'd like several disparate values that can all be fetched in parallel? A: This will return the counts using a single select statement, but there is an important caveat. You'll notice that the EF-generated sql uses cross joins, so there must be a table (not necessarily one of the ones you are counting), that is guaranteed to have rows in it, otherwise the query will return no results. This isn't an ideal solution, but I don't know that it's possible to generate the sql in your example since it doesn't have a from clause in the outer query. The following code counts records in the Addresses and People tables in the Adventure Works database, and relies on StateProvinces to have at least 1 record: var r = from x in StateProvinces.Top("1") let ac = Addresses.Count() let pc = People.Count() select new { AddressCount = ac, PeopleCount = pc }; and this is the SQL that is produced: SELECT 1 AS [C1], [GroupBy1].[A1] AS [C2], [GroupBy2].[A1] AS [C3] FROM ( SELECT TOP (1) [c].[StateProvinceID] AS [StateProvinceID] FROM [Person].[StateProvince] AS [c] ) AS [Limit1] CROSS JOIN ( SELECT COUNT(1) AS [A1] FROM [Person].[Address] AS [Extent2] ) AS [GroupBy1] CROSS JOIN ( SELECT COUNT(1) AS [A1] FROM [Person].[Person] AS [Extent3] ) AS [GroupBy2] and the results from the query when it's run in SSMS: C1 C2 C3 ----------- ----------- ----------- 1 19614 19972 A: You should be able to accomplish what you want with Parallel LINQ (PLINQ). You can find an introduction here. A: It seems like there's no good way to do this (yet) in EF4. You can either: * *Use the technique described by adrift which will generate a slightly awkward query. *Use the ExecuteStoreQuery where T is some dummy class that you create with property getters/setters matching the name of the columns from the query. The disadvantage of this approach is that you can't directly use your entity model and have to resort to SQL. In addition, you have to create these dummy entities. *Use the a MultiQuery class that combines several queries into one. This is similar to NHibernate's futures hinted at by StanK in the comments. This is a little hack-ish and it doesn't seem to support scalar valued queries (yet).
{ "language": "en", "url": "https://stackoverflow.com/questions/7622108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is creating a reference to a nonexistant array item undefined behavior? With my compiler at least, creating a reference implies no dereferencing. Therefore, code like the following works: int trivialExample(char* array, int length) { char& ref = array[6]; if (length > 6) { std::cout << ref << std::endl; } } That is, given a char array and its length (and assuming a bunch of trivialities like the array elements are all initialized and the passed length is correct), it will print the seventh character only if it actually exists. Is this relying on undefined behavior? A: Actually, this is conceptually (and practically) not different than the following: int trivialExample(char* array, int length) { char *ptr = &array[6]; if (length > 6) { std::cout << (*ptr) << std::endl; } } My educated guess is that you intend to call it this way: char buffer[4]; trivialExample(buffer, sizeof(buffer)); And in C++, as in C, just obtaining a pointer to outside of the declared array (other than the next-to-last) invokes undefined behaviour, even if not dereferenced. The rationale is that there may be (are?) architectures that faults just by loading an invalid address in a CPU register. UPDATE: After some research, and hints from other SO users, I've becomed convinced that C++ does not allow to take a reference outside of the declaring object, not even to the next-to-last element. In this particular case, the results are the same, except for the element number 6, that would be allowed in the pointer version and not in the reference one. A: The behavior is undefined. Quoting from the C++ 2003 standard (ISO/IEC 14882:2003(E)), 8.3.2 paragraph 4: A reference shall be initialized to refer to a valid object or function. Which also implies that initializing a reference to just past the end of an array is undefined behavior, since there's no valid object there. A: char& ref = array[6]; This is okay as long as the size of array is minimum 7. Otherwise it is undefined behavior (UB). std::cout << ref << std::endl; This is okay as long as array[6] is initialized or assigned with some value. Otherwise it is UB. A: I don't know about creating references, but accessing an element outside the bounds of the array is undefined behavior. So yes, your code is relying on undefined behavior. A: No, it is not undefined behavior. It is just like defining a pointer. A reference is a pointer with a friendlier and less error prone syntax.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to disable all buttons in Java, Android I create an app which need to disable all buttons to allow user to leave the application - back button, menu button, camera button, call button, etc, and app should have 1 button for exit. I don't know how to disable all buttons. Tell me please, thank you A: The Physical buttons? No, you can't disable all of them. Home button needs to work... Android - Is It possible to disable the click of home button Related: Android: mass enable/disable buttons A: Try this: when you enter the activity, call getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); and when you exit the activity, call getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION);
{ "language": "en", "url": "https://stackoverflow.com/questions/7622116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQLite add column, keep data I have a database with 4 columns: @Override public void onCreate(SQLiteDatabase database) { database.execSQL("CREATE TABLE " + DATABASENAME + " (name TEXT, latitude REAL, longitude REAL, country TEXT);"); } Now I want to add another column, but keep the rows that are already in the database. How should I do this? I can't find any useful references to this. @Override public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) { //What to do here? } EDIT I have modified my onCreate to: @Override public void onCreate(SQLiteDatabase database) { database.execSQL("CREATE TABLE " + DATABASENAME + " (name TEXT, latitude REAL, longitude REAL, country TEXT, code TEXT);"); } and my onUpgrade to: @Override public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) { Logger.log("Updating userstations database from " + arg1 + " to " + arg2 + "."); if (arg1 == 2 && arg2 == 3) { db.execSQL("ALTER TABLE " + DATABASENAME + " ADD COLUMN code TEXT;"); } else if(arg1 == 1){ db.execSQL("DROP TABLE IF EXISTS " + DATABASENAME); } onCreate(db); } However, now I get this stacktrace: 10-01 21:24:19.581: ERROR/Database(21434): Failure 1 (table userstations already exists) on 0x19c378 when preparing 'CREATE TABLE userstations (name TEXT, latitude REAL, longitude REAL, country TEXT, code TEXT);'. 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): Couldn't open userstations for writing (will try read-only): 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): android.database.sqlite.SQLiteException: table userstations already exists: CREATE TABLE userstations (name TEXT, latitude REAL, longitude REAL, country TEXT, code TEXT); 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.database.sqlite.SQLiteDatabase.native_execSQL(Native Method) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1763) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.myapp.myapp.databases.UserStationsOpenHelper.onCreate(UserStationsOpenHelper.java:25) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.myapp.myapp.databases.UserStationsOpenHelper.onUpgrade(UserStationsOpenHelper.java:36) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:132) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.myapp.myapp.databases.UserStationsOpenHelper.getStations(UserStationsOpenHelper.java:43) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.myapp.myapp.Data.readUserStations(Data.java:369) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.myapp.myapp.Data.getUserStations(Data.java:210) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.myapp.myapp.stationstab.StationsActivity.newStations(StationsActivity.java:190) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.myapp.myapp.stationstab.StationsActivity.refresh(StationsActivity.java:129) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.myapp.myapp.stationstab.StationsActivity.onCreate(StationsActivity.java:108) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.ActivityThread.startActivityNow(ActivityThread.java:1598) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.myapp.myapp.stationstab.StationsActivityGroup.onCreate(StationsActivityGroup.java:38) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.ActivityThread.startActivityNow(ActivityThread.java:1598) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:654) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.widget.TabHost.setCurrentTab(TabHost.java:326) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.widget.TabHost.addTab(TabHost.java:216) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.myapp.myapp.TreinVerkeer.setupTab(TreinVerkeer.java:131) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.myapp.myapp.TreinVerkeer.initTabs(TreinVerkeer.java:108) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.myapp.myapp.TreinVerkeer.onCreate(TreinVerkeer.java:62) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.ActivityThread.access$1500(ActivityThread.java:123) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.os.Handler.dispatchMessage(Handler.java:99) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.os.Looper.loop(Looper.java:123) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at android.app.ActivityThread.main(ActivityThread.java:3835) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at java.lang.reflect.Method.invokeNative(Native Method) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at java.lang.reflect.Method.invoke(Method.java:507) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 10-01 21:24:19.611: ERROR/SQLiteOpenHelper(21434): at dalvik.system.NativeStart.main(Native Method) 10-01 21:24:19.621: DEBUG/AndroidRuntime(21434): Shutting down VM 10-01 21:24:19.621: WARN/dalvikvm(21434): threadid=1: thread exiting with uncaught exception (group=0x4018a560) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): FATAL EXCEPTION: main 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.myapp/com.myapp.myapp.TreinVerkeer}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.myapp/com.myapp.myapp.stationstab.StationsActivityGroup}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.myapp/com.myapp.myapp.stationstab.StationsActivity}: android.database.sqlite.SQLiteException: Can't upgrade read-only database from version 2 to 3: /data/data/com.myapp.myapp/databases/userstations 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.ActivityThread.access$1500(ActivityThread.java:123) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.os.Handler.dispatchMessage(Handler.java:99) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.os.Looper.loop(Looper.java:123) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.ActivityThread.main(ActivityThread.java:3835) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at java.lang.reflect.Method.invokeNative(Native Method) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at java.lang.reflect.Method.invoke(Method.java:507) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at dalvik.system.NativeStart.main(Native Method) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.myapp/com.myapp.myapp.stationstab.StationsActivityGroup}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.myapp/com.myapp.myapp.stationstab.StationsActivity}: android.database.sqlite.SQLiteException: Can't upgrade read-only database from version 2 to 3: /data/data/com.myapp.myapp/databases/userstations 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.ActivityThread.startActivityNow(ActivityThread.java:1598) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:654) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.widget.TabHost.setCurrentTab(TabHost.java:326) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.widget.TabHost.addTab(TabHost.java:216) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at com.myapp.myapp.TreinVerkeer.setupTab(TreinVerkeer.java:131) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at com.myapp.myapp.TreinVerkeer.initTabs(TreinVerkeer.java:108) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at com.myapp.myapp.TreinVerkeer.onCreate(TreinVerkeer.java:62) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): ... 11 more 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapp.myapp/com.myapp.myapp.stationstab.StationsActivity}: android.database.sqlite.SQLiteException: Can't upgrade read-only database from version 2 to 3: /data/data/com.myapp.myapp/databases/userstations 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.ActivityThread.startActivityNow(ActivityThread.java:1598) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at com.myapp.myapp.stationstab.StationsActivityGroup.onCreate(StationsActivityGroup.java:38) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): ... 22 more 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): Caused by: android.database.sqlite.SQLiteException: Can't upgrade read-only database from version 2 to 3: /data/data/com.myapp.myapp/databases/userstations 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:199) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at com.myapp.myapp.databases.UserStationsOpenHelper.getStations(UserStationsOpenHelper.java:43) 10-01 21:24:19.641: ERROR/AndroidRuntime(21434): at com.myapp.myapp A: A better approach @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { switch (oldVersion) { case 1: db.execSQL(SQL_MY_TABLE); case 2: db.execSQL("ALTER TABLE myTable ADD COLUMN myNewColumn TEXT"); } } Lets say in case 1, you upgraded to db version 2. You created a new table but forgot the myNewColumn you will see in case 2. What this will do is if you change the db version to 3, case 2 will get ran if its upgrading from 2 to 3. A: Please see this page for the syntax to create a new column on a table. Basically it is: ALTER TABLE mytable ADD COLUMN mycolumn TEXT In your onUpgrade method, it would look something like this: @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String upgradeQuery = "ALTER TABLE mytable ADD COLUMN mycolumn TEXT"; if (oldVersion == 1 && newVersion == 2) db.execSQL(upgradeQuery); } A: I have not worked with android, but sqlite provides 'alter table' as most SQL implementations does: SQLite alter table A: The right way to add new column to DB, for example in version 2, would be: @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion < 2) { db.execSQL("ALTER TABLE mytable ADD COLUMN mycolumn TEXT"); } } It covers all pitfalls, including major issue with the selected answer: if a user goes from version 1 to 3 they will miss the upgrade query completely! These users will be in an awkward limbo where they are missing a few of the intermediate updates and do not have the expected sql schema. Also don't forget to alter the create statement adding new column.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: CSS Menu Dropdown IE7 float left I made a nice menu, and I also wrote a new design for only IE. In IE7 the text next to image doesn`t go next to it. It goes to next line. Anybody knows how can I fix it ? http://tinyurl.com/6yzd2jc A: you can apply the background-image to the anchor tag. example jsfiddle So replace: ul ul a div {float:left;display:block;width:7px;height:10px;background-color:transparent;padding:0;margin:0 5px 0 0;position:relative;top:3px;} ul ul a:hover div {display:block;background-image:url(http://ctuchicago.squarespace.com/storage/jquery/dot.png);width:7px;height:10px;} With: ul ul a:hover {background:transparent url(http://ctuchicago.squarespace.com/storage/jquery/dot.png) no-repeat left center;} Also increase the <a> left padding (from padding:3px 16px 3px 4px; to padding:3px 16px 3px 14px;) ul ul li a { font-weight:normal; color: #FFF; padding:3px 16px 3px 14px; } and remove the empty <div>s nested in the anchors A: Why You are Using div inside a tag ? remove div from a tag and apply CSS Style background-image in a tag Check this http://jsfiddle.net/MNwD3/40/
{ "language": "en", "url": "https://stackoverflow.com/questions/7622124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drop-down menus in Emacs.app 23 (Lion) only work after several clicks I am using Emacs.app 23.3.1 on MacOS 10.7.1 (Lion). When I try to use the GUI drop-down menus, they will not appear unless I click on the menu several times. The top-level menu item (e.g., File, Edit, Options) will highlight to acknowledge the click, but the menu will not appear. I have seen this question, but no fix ever appeared. I am not using Synergy. It is obviously not the end of the world, but it is an annoyance. I would prefer not to use the text-only menubar system. This behavior does not appear in Aquamacs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622125", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: lookuperror unknown encoding cp720 in django when running on diffrent computer I have a django site that when I run it on my computer,every thing is good,but when I run it on another computer,I can't login with my username and password and that sounds like the user is not in my database while the user is in user auth table in sqlite. then I go to shell to create another user,but it doesn't let me create a new user and have this error: lookuperror unknown encoding cp720 what should I do about it? Solution: chcp 1250 A: You should find out why the other machine doesn't have the full set of codecs installed, and rectify that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Payment form on my webpage I know I can't create my own payment gateway except if I don't have anything to do for two years from now :p. But still I've seen a lot of websites that have a payment form on their website, like godaddy.com or panic.com (when buying Coda) and I didn't really found any website that offer this service, Paypal and 2CheckOut generally send the user to their website. I've read some articles where they said that I can use the paypal API to have my own payment form and "communicate" with paypal. I've been developing systems in php since a long time now but I'm really new to the world of online payment: I don't want a complete answer or walkthought just some tips or where to start. Adv thanks PS: I did a quick search on SO and didn't find exactly what I needed but If I'm mistaken and there's already a similar question I would delete this one. A: Please take a look at PayProGlobal. They handle all the e-commerce side, and integrate into your business. Although the "forms" are hosted on their site, you provide the templates so the forms can have your site's "look and feel". Hosting payment forms directly on your web site is very problematic, since you'll have to deal with credit card data storage and transmission, VISA requirements compliance etc. Outsourcing all this, including fraud management and such, is a better idea. PayProGlobal is one of the few "independent" providers left, most others were bought by DigitalRiver and run into the ground, I would stay away from DigitalRiver as long as possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: preventing a specific mysqli_fetch_assoc() from sending a warning I use a specific query that is acting weird: On my local environment, it works perfect and sends no warning. Online, the query itself works fine, however, mysqli_fetch_assoc($result) is producing the 'mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given' warning. I never occured a query that was causing this warning AND got the right info from the DB. This is why I tend to believe the problem is not in the code. Is there a way to shut off the warnings only for this one specific query? EDIT - PROBLEM SOLVED. it is really strange to me, but the problem was an incorrect script src path for dojo.js. I have no idea what's the connection, but fixing the path prevented mysqli warnings. A: You should be checking if $result == false before you call mysqli_fetch_assoc. Generally you catch it first by checking mysqli_connect_errno() but the general idiom is to proactively check before fetching rows
{ "language": "en", "url": "https://stackoverflow.com/questions/7622147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Date search Sql Query im storing the timestamp in mysql database in (INT) column, And i want to search the rows with between the dates. Anyone would please help what should be the Sql query to find the rows between two dates? dates are entered like FROM DATE = 15-10-2011 END DATE = 01-11-2011 A: It depends on what algorithm you use to convert the date strings to int values. If the algoritm is mototonic, for example: If a day (say 15-10-2011) is converted to n (say 5037), then the next day (16-10-2011) is always converted to n+1 (so 5038 in this example.) then you could just use: WHERE IntField BETWEEN MySpecialConvertDateToIntFunction('15-10-2011') AND MySpecialConvertDateToIntFunction('01-11-2011') If your field stores different timsetamps as different integers (and the conversion is monotonic), you could change the above code slightly to: WHERE IntField >= MySpecial...Function('15-10-2011') AND IntField < MySpecial...Function('02-11-2011') --- notice the date+1 But it's usually better to use a field of the MySQL DATE type for storing dates. Unless you want to store dates before 1000 or after 9999 off course. If you want to store timestamps, there's also a TIMESTAMP type. Read the MySQL docs: DATETIME, DATE, and TIMESTAMP Types A: You can use The BETWEEN operator, which selects a range of data between two values. The values can be numbers, text, or dates. You can see there: http://w3schools.com/sql/sql_between.asp A: I would ask you to set data type as timestamp/datestamp & then //php code $date1=date ('Y-m-d' , strtotime ( "15-10-2011") ); $date2=date ('Y-m-d' , strtotime ( "01-11-2011") ); //sql code SELECT * FROM tbl_mytbl WHERE DATE(attr_date) <'$date2' AND DATE(attr_date) >'$date1' A: Can you use the mysql FROM_UNIXTIME function dev.mysql.com - function from_unixtime SELECT * FROM 'table' WHERE FROM_UNIXTIME(intTimestamp) BETWEEN date ('Y-m-d' , strtotime ( '15-10-2011') ) AND ('Y-m-d' , strtotime ( '01-11-2011')); I had made a mistake with the date input but have fixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OSX/Cocoa : setting up service in menu for right click and services list I have followed all the Apple documentation for setting up a service for a right click menu list and for the services list: * *I have made all the relevant info.plist entries. (send types, port name, menu title, instance method, etc.) *I have created the method which handles services. *I have added service registration code in the app. *I built my app, put it in the application directory, logged out and back in. Despite all this I cannot see my service in any menu item. EDIT** Here is the services part of my info.plist: <key>NSServices</key> <array> <dict> <key>NSMenuItem</key> <dict> <key>default</key> <string>MyApp/Send to MyApp</string> </dict> <key>NSMessage</key> <string>contentService</string> <key>NSPortName</key> <string>MyApp</string> <key>NSSendTypes</key> <array> <string>NSStringPboardType</string> <string>NSFileContentsPboardType</string> </array> </dict> </array> What am I doing wrong? thanks in advance. A: I have followed all the Apple documentation for setting up a service… Ah, that's the problem: You stopped there. You also need to add the NSRequiredContext key to your service to get it to be enabled by default on Snow Leopard and later. Fortunately, while the Services documentation doesn't mention that NSRequiredContext is required, the Information Property List Key Reference does explain the value you must provide for it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Qt Creator and GCC How I can build native C++ files using Qt Creator. I want to write native C++ programs in Qt Creator and then build them using GCC. How I can do it? P.S. I am on Ubuntu 10.04 with Qt Creator 2.1.1 A: 1) Create a folder where you will store you project and run command: qmake -project && qmake your_project.pro && make 2) Open your_project.pro and put some flags etc... like #c++0x QMAKE_CXXFLAGS += -std=c++0x #obj foldr unix:OBJECTS_DIR = ../your_project/obj 3) Go and open pro file with your qtcreator. 4) Enjoy coding :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7622155", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible & efficient to put a LinearView and ExpandableListView inside a ScrollView I'm making a GUI with two different parts. The first part (at the top) is composed of some banners, several fixed buttons. So I think using LinearLayout is the most straightforward way to implement. The second part is composed of several similar items grouped together which can be implemented by using ExpandableListView, I think. However the problem is that the content exceeds the screen size. So I intend to put two of them into a ScrollView. I checked several sources, it seems that putting "ExpandableListView" inside a ScroolView is NOT possible, or not efficent, so I'm afraid... * *Would you help to confirm if this is possible? efficient ? *If no, would you give me some recommendations for this layout design? I'm indeed looking forward to your supports. Sincerely. A: If you have a fixed header at the top of a list, use ListView's header view feature. Putting ListViews in ScrollViews fundamentally makes no sense and here is why: ListView has one purpose: to efficiently display unbounded data sets. Since these can be extremely large (tens of thousands of items and more) you do not want to create a View for each item up front. Instead, ListView asks its Adapter for Views only for the items that currently fit in the ListView's measured space on screen. When an item's View is scrolled out of sight, ListView disconnects that View and hands it back to the adapter to fill out with new data and reuse to show other items. (This is the convertView parameter to an Adapter's getView method.) ScrollView also has one purpose: to take a single child view and give it "infinite" vertical space to fit within. The user can then scroll up and down to see the full content. Now given this, how many item Views would a ListView create for a 100,000 item Adapter if it had infinite height available to fill? :) By putting a ListView inside a ScrollView you defeat ListView's key purpose. The parent ScrollView will give the ListView effectively infinite height to work with, but ListView wants to have a bounded height so that it can provide a limited window into a large data set. A: Well Expandable List View itself has scrollable property by placing it in scroll view is really undesirable.As the both scroll would contradict and smooth scrolling can't be obtained in that case.. If we have any data to be shown prior or later to list... Best way is to use header and footer view to list... I recommend you use header and footer in your case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android, Is it possible to run Dalvik VM on any kind of OSs in order to run Android Applications? I have some operating systems such as Windows 7 and Linux. Is it possible to run Dalvik on this Win7 and after that running an Android application or game? Thanks A: One solution is to install Android-x86 (Android for Intel or AMD CPUs) either natively or in a virtual machine. If you only want to play some games and not to dual-boot with Windows and Android, you can use the excellent Android emulator Bluestacks. Just a warning, depending on your hardware (or virtual hardware) one version of Android-x86 may work better than another, you have to try. In a virtual machine most likely the virtual graphics card won't be detected properly, so you have to run it in VESA mode. I recommend editing the boot entry before running it and adding the commands: nomodeset xforcevesa vga=ask Then choose graphics mode to run Android-x86. This forces a specific VESA mode and most of the times the graphics are presented properly with correct colors on screen. Of course in that case you have a performance penalty. Some games may need to enable Developer Options and then force software rendering to be able to run them. A: Android's virtual machine is tightly integrated with the OS (Linux). So, it is impossible to run it on Windows. The lower-level components (OS and native libraries) in the Android system provide many services that Dalvik merely "translates" for the consumption of Java programs. So porting Dalvik to Windows is probably very hard and rather pointless. A: dalvik can definitely run on (normal) linux, and it's likely it can also run in a cygwin environment on windows. As for being able to run Android applications, that is quite a bit more complicated. However, the AOSP source does have a "simulator" build, which does just that - runs dalvik natively on the host machine and provides an android framework etc, for running android applications. Keep in mind however that the simulator environment isn't actively maintained, and will probably require quite a bit of "love" to get it to work. A: You can install Android on your PC with VirtualBox. Check out this tutorial.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Python Newbie Questions - Not printing correct values I am newbie to python and I doing doing some OOPS concept exploring in Python. Following is my Account class: class Account: def __init__(self,balance): self.__balance=int(balance) def deposit(self,deposit_amt): self.__balance=self.__balance + int(deposit_amt) def withdraw(self,withdraw_amt): withdraw_amt=int(withdraw_amt) self.__balance=self.__balance -- int(withdraw_amt) print(self.__balance) print("Subtracting" + str(withdraw_amt)) def get___balance(self): return(self.__balance) def __str__(self): return("The Balance in the Account is " + str(self.get___balance())) The account_test program: import account def main(): balance_amt = input("Enter the balance amount \t") new_account=account.Account(int(balance_amt)) deposit_amt=input("Enter the Deposit Amount \t") new_account.deposit(deposit_amt) print(new_account) withdraw_amt=input("Enter the Withdraw Amount \t") new_account.withdraw(withdraw_amt) print(new_account) main() But I am getting the wrong output: Enter the balance amount 3000 Enter the Deposit Amount 400 The Balance in the Account is 3400 Enter the Withdraw Amount 300 3700 Subtracting 300 The Balance in the Account is 3700 When I do withdraw I am getting the amount added instead of subtracted. What am I doing wrong here? Since I am newbie, I need some suggestion in my programming practice. Is my coding style appropriate? A: With the double -- (negative) you are subtracting a negative value (i.e. adding a positive value). A more clear explanation would look like: self.__balance = self.__balance - (0 - int(withdraw_amt)) Therefore, change this: self.__balance=self.__balance -- int(withdraw_amt) To this: self.__balance=self.__balance - int(withdraw_amt) Or better yet, to this: self.__balance -= int(withdraw_amt) A: self.__balance=self.__balance -- int(withdraw_amt) is actually parsed as self.__balance=self.__balance - (- int(withdraw_amt)) which is to say, it is adding the withdraw amount. try with a single -
{ "language": "en", "url": "https://stackoverflow.com/questions/7622159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# System.Management has only 1 class? I have been trying to utilize WMI for my code, I cannot use the System.Management classes as they are not there. I have tried it on 3.5 and 4 Net. Nothing works. I have not found any solutions to the issue and was wondering if any of you have ever encountered this? If so, why is it that i only have: System.Management.Instrumentation My using block below: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Management; using System.IO; using System.Security.Permissions; using Microsoft.Win32; using System.Collections; using System.Management.Instrumentation; Info: Visual Studio 2010 Ultimate Using net 3.5 - Net 4. Not sure what I am missing here. A: System.Management.Instrumentation isn't a class, it's a namespace. Given the using directives you've got, if you've got a reference to System.Management.dll, you should be able to write code such as: ObjectQuery query = new ObjectQuery("..."); A: Did you add a reference to System.Management? Also make sure the framework version you're targeting isn't the Client Profile. A: MSDN lists quite a lot of classes under the System.Management.Instrumentation namespace: DefaultManagementInstaller Class DefaultManagementProjectInstaller Class IEvent Interface IgnoreMemberAttribute Class IInstance Interface Instance Class InstanceNotFoundException Class Instrumentation Class InstrumentationBaseException Class InstrumentationClassAttribute Class InstrumentationException Class InstrumentationManager Class InstrumentationType Enumeration InstrumentedAttribute Class ManagedCommonProvider Class ManagedNameAttribute Class ManagementBindAttribute Class ManagementCommitAttribute Class ManagementConfigurationAttribute Class ManagementConfigurationType Enumeration ManagementCreateAttribute Class ManagementEntityAttribute Class ManagementEnumeratorAttribute Class ManagementHostingModel Enumeration ManagementInstaller Class ManagementKeyAttribute Class ManagementMemberAttribute Class ManagementNameAttribute Class ManagementNewInstanceAttribute Class ManagementProbeAttribute Class ManagementQualifierAttribute Class ManagementQualifierFlavors Enumeration ManagementReferenceAttribute Class ManagementRemoveAttribute Class ManagementTaskAttribute Class WmiConfigurationAttribute Class WmiProviderInstallationException Class These live in System.Management.dll - make sure you add a reference to it. A: I believe you need to add references to System.Management.*.dll files. If you come from a C++ background like me I'm guessing you have the same conceptual issue I had in the past when I took the view of using statements in c# as analogous to include statements in C/C++. It's a subtle difference but it led me to years of very slight confusion that finally cleared up when I got a hold of reflector a few years ago... A: Right-click on the References folder for the project, then choose Add Reference... and from the .NET tab choose System.Management.dll. (You may have to wait a short while for the DLL to appear, this list is lazily-loaded.) Also, make sure in Project Properties that you're not targetting the .NET Framework Client Profile: you'll most likely need the full .NET Framework 4.0. Why do you see anything at all without doing this? Rather confusingly there isn't necessarily a one-to-one relationship between assemblies and namespaces in the .NET libraries. So, even if you don't include a reference to the System.Management.dll assembly, you will still see one class in the System.Management namespace -- this is included in one of the other assemblies you've referenced already, or the system core assembly itself. You can try this trick yourself by adding your own class to the System.Management namespace: namespace System.Management { public class MyClass { } } This will end up in the assembly named in your project properties, but will belong to the namespace System.Management. Note, it gets terribly confusing to break the relationship between namespace names and assembly names, so don't!
{ "language": "en", "url": "https://stackoverflow.com/questions/7622161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Send JSON string to a C# method In my ASP.NET page I have the following method: public static void UpdatePage(string accessCode, string newURL) { HttpContext.Current.Cache[accessCode] = newURL; } It actually should receive the accessCode and newURL and update the Cache accordingly. I want to pass the values to that method from JavaScript, using an AJAX request. The code for it is as follows: function sendUpdate() { var code = jsGetQueryString("code"); var url = $("#url_field").val(); var dataToSend = [ {accessCode: code, newURL: url} ]; var options = { error: function(msg) { alert(msg.d); }, type: "POST", url: "lite_host.aspx/UpdatePage", data: {"items":dataToSend}, contentType: "application/json; charset=utf-8", dataType: "json", async: false, success: function(response) { var results = response.d; } }; $.ajax(options); } However this doesn't seem to work. Could anybody help me figure out where the bug is? A: UpdatePage is a void method that doesn't return anything, so there is nothing to look at in the response. You could look at the HTTP return code and check that it was 200 OK or you could modify the web method: public static bool UpdatePage(string accessCode, string newURL) { bool result = true; try { HttpContext.Current.Cache[accessCode] = newURL; } catch { result = false; } return result } Edit: It looks like your JSON arguments to the WebMethod are incorrect, you don't need the "items" in your JSON. The arguments should match your webmethod exactly. function sendUpdate() { var code = jsGetQueryString("code"); var url = $("#url_field").val(); var options = { error: function(msg) { alert(msg.d); }, type: "POST", url: "lite_host.aspx/UpdatePage", data: {'accessCode': code, 'newURL': url}, contentType: "application/json; charset=utf-8", dataType: "json", async: false, success: function(response) { var results = response.d; } }; $.ajax(options); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Filtering a list based on another list - LINQ I have two IEnumerable lists. I want to populate values into the second list based upon the results in the first. The first IEnumerable list is populated like this: IEnumerable<SelectListItem> selectedList = CategoryServices.GetAttributesByCategoryID(categoryID); // it returns selected attributes for a particular category I have a function to get all attributes. Now I want to get another list which contains all other attributes (ie, the items not present in selectedList). I tried this: IEnumerable<SelectListItem> available = CategoryServices.GetAllAttributes().Where(a => !selectedList.Contains(a)); But its not filtering. I am getting all attributes... Any ideas? A: Make sure your SelectListItem class implements IEquatable<SelectListItem> so the Contains() method has a proper means for determining equality of instances. A: I think this will help you int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB); Console.WriteLine("Numbers in first array but not second array:"); foreach (var n in aOnlyNumbers) { Console.WriteLine(n); } Result Numbers in first array but not second array: 0 2 4 6 9 A: GetAllAttributes() will probably get you a new round of objects, they will not be the same as those returned by GetAttributesByCategoryID(...). You need to compare something better than object references. You can implement System.IEquatable<T> to change the default comparer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Changing the background color of a section I'm trying to use jQuery to change the background color of a <div> section when pressing on a button, and below is the code to do that. Why isn't it working? HTML file <html> <head> <script type="text/javascript" src="jquery-1.6.4.js"></script> <script type="text/javascript" src="script.js"></script> <style type="text/css"> #name{ background-color: #FFFFF2; width: 100px; } </style> </head> <body> <input type="button" id="bgcolor" value="Change color"/> <div id="name"> Abder-Rahman </body> </html> script.js $("bgcolor").click(function(){ $("#name").animate( {backgroundColor: '#8B008B'}, "fast");} ); Thanks. A: You have several problems: * *Your selector is wrong: $("#bgcolor") *You're missing a closing </div> tag. *You need jQueryUI to animate background-color. HTML: <input type="button" id="bgcolor" value="Change color"/> <div id="name"> Abder-Rahman </div> JS: $("#bgcolor").click(function(){ $("#name").animate( {backgroundColor: '#8B008B'}, "fast");} ); Your code, fixed (and working with jQueryUI included): http://jsfiddle.net/andrewwhitaker/rAVj9/ A: From the jQuery website: All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, width, height, or left can be animated but background-color cannot be.) Use jquery UI package to animate colors. A: Ensure you include the CSS selector inside the jQuery that you wish to target. $("bgcolor").click(function(){ Should be: $("#bgcolor").click(function(){ Because you are targeting an ID.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Open a URL based on search query without php "?q=(myTerm)" and instead with a simple "/(myTerm)" This is driving me up the wall. I obviously don't understand soemthing pretty fundamental, I'm hoping someone can shed light on the matter. <form action="/tagged" method="get"> <input type="text" name="q" value="{SearchQuery}"/> <input type="submit" value="Search"/> </form> On this page gives me http://syndex.me/tagged?q=yellow But if I change /tagged to /search (the default state for tumblr search form) it actually does the right thing and gives a url to the effect of http://syndex.me/search/yellow. All this just because, tumblrs search is actually broken. That's right. A company valued at $800 million does not have a viable search feature. The thing is if you go to http://syndex.me/tagged/yellow It actually works!. SO I'm just trying to hack the service and switch /search to tagged. Pretty mental. I'm happy to hack that any way possible... jQuery? Thanks so much. A: The parts of your page are the core behind the search function: JavaScript: function handleThis(formElm){ window.location="http://syndex.me/tagged/"+formElm.q.value+""; return false; } HTML: <form onsubmit="return handleThis(this)" > <input type="text" name="q" value=""/> </form> An event listener is bound to your form, using onsubmit="return handleThis(this)". * *onsubmit is triggered when the user presses enter, or hits the Search button. *Inside the onsubmit attribute (aka event handler), you notice return handleThis(this). This function (which is defined at the same page; look ahead) is called with the this keyword as first argument. this from within the context of an event handler refers to the event listener's owner element, in this case <form>. In handleThis(formElm), you notice "http://syndex.me/tagged/"+formElm.q.value. formElm.q refers to an input element called q within the form element. formElem.q.value holds the value of the input element, which contains the search keywords. The just constructed URL is assigned to window.location, which initiates a new request to http://syndex.me/tagged/search_terms. After that line, you see return false. Inside the onsubmit event handler, you've seen return handleThis(this). The return value of handleThis is passed to the onsubmit event handler. So, the statement equals onsubmit="return false". This means that the form does not submit itself any more. *The action attribute is not defined. As mentioned previously, this is not needed, because the form is not submitted due return false. When an error occurs, or if a user has disabled JavaScript, the form will submit itself to the URL as defined at action. Because the action attribute is not specified, the page's current URL is used instead, http://syndex.me/ in this case. All named form elements are added to the request, so the final URL will be http://syndex.me/?q=search_terms To get back to your question, <form action="/tagged"method="get">`: * *No onsubmit event handler. *Because the onsubmit event handler is not specified, the HTML form will be submitted by the browser (an imaginary onsubmit handler would equal return true. *The action URL is defined to be /tagged, which translates to a file called "tagged" at the ROOT directory of your host. In this case: http://syndex.me/tagged?q=search_terms. (q=.. is a result from the input element called q). When you change action to /tagged/ instead of /tagged, the submitted form will request the following page: http://syndex.me/tagged/?q=search_terms When you change /tagged to /search, your form submits to http://syndex.me/search?q=.... As seen through the headers, this location redirects to http://syndex.me/search/....This behaviour is likely achieved using a rule defined in .htaccess: RewriteEngine On RewriteRule ^/search\?q=(.*)$ /search/$1 [L,R=301] Understood?
{ "language": "en", "url": "https://stackoverflow.com/questions/7622181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create web applications to run R scripts Is there anything similar to the Rwui package to create web applications to run R scripts? A: Please do not cross-post simultaneously to r-help and StackOverflow. As I just mentioned in my reply on r-help, there is an entire section of the R FAQ devoted to this question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: XCode4 does not produces archives. At all I am attempting to create my first ever app to be tested/deployed via: * *XCode 4.0.1 *TestFlight I cannot get archive to actually produce an archive in XCode. It always says it has succeeded in building the archive (see image), but I cannot find it in the Organiser and it doesn't appear in Finder either. I am doing it for Ad Hoc distribution as per TestFlight instructions for Xcode4 I have done the following. * *Created development certificate for the app *Created app ID for the app *Assigned a device The green lights appear for Enabled for development and Enabled for Production, and Game Center / In App Purchase are active/green. *Created a development provisioning profile *Downloaded all provisioning profiles. *I can launch the app successfully in my device. Now we get onto distribution. * *In certificates, created a 'Current Distribution Certificate' for the app *In provision, created a 'Distribution profile' where 'Ad hoc' is selected, the app id is selected and the device is selected Now we get onto following the TestFlight instructions for XCode4 I can do everything except the last part, Archiving and Packaging 1. Select the iOS Device option in the Schemes drop-down *Under the Product menu, select Archive *In the Organizer window that appears (go to Window -> Organizer if it does not), select Archives at the top, your application on the left, and the most recent archive at the bottom, and click Share It simply does not list/show or apparently create the archive. * *I ensured that the archive and all adhoc setup is as the instructions say. *I clean the product, save it as a workspace (this is not in the TestFlight docs, but in Apple's docs), and verify again that it will deploy in the device. But when I try to archive it, no archive ever appears. I have no idea how to solve this, its really annoying. One video I've seen shows a guy click "Enable entitlements", but I cannot find this option -- is this only in the latest Xcode? There must be an easier way to do all this! Any help on this would be very useful. Edits: I have a video of the process I have taken, if people are interested. I have no idea what I am doing wrong. I can find no video that documents this specific process. A full breakdown of the exact steps I do and use; Steps @date: 05-10-2011 Sidebar: Certificates > [Distribution tab] * *Clicked Request certificate button *Generate CSR with keychain Online certificate status protocol = off Certificate revocation list = off a. Request CSR from Certifcate Authority b. Enter credentials EXACTLY as they are when I signed up to Apple c. Keysize = 2048, Algorithm = RSA *Upload this CSR via "Choose file" button & submit *Download 'distribution_identity.cer' *Double click, it say "Do you want to add the certificate from the file 'distribution_identify.cer' to a keychain?" with "login" selected. I press OK. Sidebar: Provisioning > [Distribution provisioning tab] * *Click new profile *Select 'Ad hoc' *Enter profile name of "{name of app profile}" *Select App ID of "helloWorld_3oct" *Select iPod to distribute to. Note: it says "the final application will run only on these selected devices." Note: Not sure if I'm meant to say "Yes" but I do anyway. *Distribution provisioning profile is now created. *Download the "{nameofapp}.mobileprovision" *Double click on it. *It now appears in the organizer *Close organizer. *Open project. *Add icon and [email protected] to project. They appear in .plist file for the project They also appear under Targets > Summary *Under project > info a. Create duplicate release configuration b. Name it "Ad Hoc" *Under project > build settings a. Make sure everything is set under "iPhone distribution (Amarjit Deo)" no codes appear in this title. ie: In the development one there is a code in brackets next to the name. *Under targets > build settings a. Change code signing identity to "iPhone distribution (Amarjit Deo)" no codes appear in this title. *Go to Edit Schemes. *In Archive select Build configuration to be "Ad Hoc" *Press "OK" *Make sure "iOS device" is selected (it is not plugged in) *Run Product > Clean *Run Product > Archive. No errors. Success is reported. Go to organizer. No product archives exist at all in the organizer. *Try doing skip install trick Tried Yes/No/Yes combination for both product & target, then Product > Archive = No archive Tried all permutations, still no joy. A: I've resolved the issue now! Okay, it turns out either XCode was corrupted in download or was conflicting with earlier builds (Even if you uninstall it for some odd reason). Here's what I did. 1) Re-downloaded XCode (via a better/faster connected line, ie: University) 2) Used sudo /Developer/Library/uninstall-devtools --mode=all To uninstall Xcode. 3) Removed all references to XCode that I could find. For some reason Xcode installed in Developer and Developer (null) so both these folders I deleted. 4) Checked existence of ~/Library/Developer/Xcode/Archives and deleted this folder 5) Cleared out all keychain certificates and re-downloaded all required certificates, including the ones at this address http://www.apple.com/certificateauthority/ 6) Went through the entire process with a fine tooth comb, ensured and double checked everything. 7) Got an archive for a simple app! Picture included. Thank goodness for that. I'm backing up my computer and all these files and I'm going onto the next stage, TestFlight!
{ "language": "en", "url": "https://stackoverflow.com/questions/7622197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Return multidimensional char array in C In C, how can I create a function which returns a string array? Or a multidimensional char array? For example, I want to return an array char paths[20][20] created in a function. My latest try is char **GetEnv() { int fd; char buf[1]; char *paths[30]; fd = open("filename" , O_RDONLY); int n=0; int c=0; int f=0; char tmp[64]; while((ret = read(fd,buf,1))>0) { if(f==1) { while(buf[0]!=':') { tmp[c]=buf[0]; c++; } strcpy(paths[n],tmp); n++; c=0; } if(buf[0] == '=') f=1; } close(fd); return **paths; //warning: return makes pointer from integer without a cast //return (char**)paths; warning: function returns address of local variable } I tried various 'settings' but each gives some kind of error. I don't know how C works A: You can't safely return a stack-allocated array (using the array[20][20] syntax). You should create a dynamic array using malloc: char **array = malloc(20 * sizeof(char *)); int i; for(i=0; i != 20; ++i) { array[i] = malloc(20 * sizeof(char)); } Then returning array works A: You should just return array (return array;). the ** after declaration are used for dereferencing. Also, make sure the the memory for this array is allocated on the heap (using malloc or simillar function)
{ "language": "en", "url": "https://stackoverflow.com/questions/7622199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSmutablearray adding unknown amount of images I have an array i'm filling with images with a loop items = [[NSMutableArray alloc] init]; for (int i=0; i<43; i++) { NSString *filepath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d",i] ofType:@"png"]; UIImage *image = (UIImage*)[UIImage imageWithContentsOfFile:filepath]; [items addObject:image]; } it works as long as I set the max amount to match my test images. (in this case 43) if I set the max to a higher number, say 200 it of course crashes cause its trying to add nil objects to the array. How would I go about being able to add the random number of images with that naming scheme to that array? I have heard mention of using NSFileManager to add the files to array, is that the better method?
{ "language": "en", "url": "https://stackoverflow.com/questions/7622200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Keeping/Dropping Variables in SAS I want to remove columns/variables from a large SAS dataset, call it 'data'. I have all of the column names that I want to drop stored in another SAS dataset - let's call it 'var', it has a single column with header column. How do I drop all of the variables contained in 'var' from my original dataset 'data' with the drop function? Thanks! A: You can use the "into" clause of proc sql to copy the column of variable names from the "vars" data set into a macro variable that you then pass to the drop= statement in a data step. See below: proc sql noprint; select <name_of_column> into: vars_to_drop separated by " " from var; quit; data data; set data (drop= &vars_to_drop); run;
{ "language": "en", "url": "https://stackoverflow.com/questions/7622204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How should I check to see a if value exists in PHP? There are many ways to see if a value exists using PHP. There's isset, !=false, !==false, !empty, etc. Which one will be the best (fast and accurate) one to use in the following situation? if($_GET['test']) ... A: if (isset($_GET['test'])) { // use value } A: if(array_key_exists($_GET, "test")) array_key_exists return true if a key exists in an array, isset will return true if the key/variable exists and is not null. A: Isset is probably best because it checks if the url contains a "?test=". If you want to make sure it is not empty you have to check further. A: I'd go with the php5 one type of get: $test = filter_input(INPUT_GET, 'test', FILTER_SANITIZE_STRING); if($test){ //do something } Reference here, you can validate and sanitize with them. you can use "filter_input_array" for the full input types. A: isset function only checks for its avaliability you have to use empty function too in order to see if it is set and not empty also as: if (isset($_GET['test']) && !empty($_GET['test'])) {
{ "language": "en", "url": "https://stackoverflow.com/questions/7622213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: jQuery slider with content I want to ask you, how to do the icons menu with slider. So I mean how to have this content slider to move in more html contents. Example www.tapmates.com (the apps menu). A: This is often referred to as the Coda slider, after the Coda site by Panic, but it's found in many other guises. A: I've actually made one which we currently use at work on our mobile pages. It slides whatever content you put inside the "frames". You can check it out here - http://dezignhero.github.io/swiper/ It's designed primarily for webkit devices and recognizes touch swipe gestures, but also works on desktop too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create a custom aggregator in Mule? What is the recommended way to create a completely custom aggregator in mule 3.x? By completely custom, I mean according to my own logic, not using correlation IDs, message counts, etc. The documentation on the mulesoft site is outdated, saying to use AbstractEventAggregator which does not exist in 3.x: http://www.mulesoft.org/documentation/display/MULE3USER/Message+Splitting+and+Aggregatio Digging deeper, it looks like this class has been renamed to AbstractAggregator in 3.x: http://www.mulesoft.org/docs/site/3.2.0/apidocs/org/mule/routing/AbstractAggregator.html However, there are no examples that show how to use this. The LoanBroker example described in the first link above actually uses a correlation aggregator (in the 2.x examples, which I assume is what the document is referring to). At one point, there was an abstract class that had abstract methods shouldAggregate and doAggregate. This is the kind of class I would like to extend. A: Look at TestAggregator below for an example of subclassing AbstractAggregator. import org.mule.DefaultMuleEvent; import org.mule.DefaultMuleMessage; import org.mule.api.MuleContext; import org.mule.api.MuleEvent; import org.mule.api.store.ObjectStoreException; import org.mule.api.transformer.TransformerException; import org.mule.routing.AbstractAggregator; import org.mule.routing.AggregationException; import org.mule.routing.EventGroup; import org.mule.routing.correlation.CollectionCorrelatorCallback; import org.mule.routing.correlation.EventCorrelatorCallback; import org.mule.util.concurrent.ThreadNameHelper; import java.util.Iterator; public class TestAggregator extends AbstractAggregator { @Override protected EventCorrelatorCallback getCorrelatorCallback(MuleContext muleContext) { return new CollectionCorrelatorCallback(muleContext,false,storePrefix) { @Override public MuleEvent aggregateEvents(EventGroup events) throws AggregationException { StringBuffer buffer = new StringBuffer(128); try { for (Iterator<MuleEvent> iterator = events.iterator(); iterator.hasNext();) { MuleEvent event = iterator.next(); try { buffer.append(event.transformMessageToString()); } catch (TransformerException e) { throw new AggregationException(events, null, e); } } } catch (ObjectStoreException e) { throw new AggregationException(events,null,e); } logger.debug("event payload is: " + buffer.toString()); return new DefaultMuleEvent(new DefaultMuleMessage(buffer.toString(), muleContext), events.getMessageCollectionEvent()); } }; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding context menu for VS 2010 Add-In on loading I'm creating an Add-In for Visual Studio 2010. I want to add the context menu item to the tab during Add-In loading (in OnConnect method of the Add-In): I do know how to add the menus using CommandBars. I already added commands into "Tools" and "Solution Explorer" menus. I just cannot find the CommandBar responsible for the menu, I need. Can anybody help me? A: Solution found. You can enable logging of chosen menus. Details: http://blogs.msdn.com/b/dr._ex/archive/2007/04/17/using-enablevsiplogging-to-identify-menus-and-commands-with-vs-2005-sp1.aspx http://blogs.msdn.com/b/dr._ex/archive/2007/04/17/using-ivsproffercommands-to-retrieve-a-visual-studio-commandbar.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7622221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Removing newlines in php Following is the syntax for preg_replace() function in php: $new_string = preg_replace($pattern_to_match, $replacement_string, $original_string); if a text file has both Windows (rn) and Linux(n) End of line (EOL) characters i.e line feeds. then which of the following is the correct order of applying preg_replace() to get rid of all end of line characters? * *remove cr first $string = preg_replace('|rn|','',$string); $string = preg_replace('|n|','',$string); *remove plain nl first $string = preg_replace('|n|','',$string); $string = preg_replace('|rn|','',$string); A: I would recommend to use: (Windows, Unix and Mac EOL characters) $string = preg_replace('/\r|\n/m','',$string); Notice m multiline modifier. A: Using the power of regular expressions, you could specify something like '|[\r][\n]|' which specifically mean, 0 or 1 '\r', then 0 or 1 '\n' which would match the end of a row under both linux and windows. EDIT: Using the build-in function trim would achieve the same result in an even better manner, but only if the newline characters are located at the beginning or end of the string. A: which of the following is the correct order of applying preg_replace to get rid of all end of line characters? $string = preg_replace("!\r|\n!m",'',$string);
{ "language": "en", "url": "https://stackoverflow.com/questions/7622228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to set a pixel as transparent for 8-bit pngs when encoding with libpng? I'm trying to mark pixels as transparent when encoding rgb data to 8-bit png image (palette) using libpng. If I create a separate alpha channel in this case, the alpha channel is getting ignored. Is there a way to set the pixels as opaque or transparent when using 8-bit color palette ? Thanks A: To mark some palette index(es) as transparent, you must create a tRNS chunk. In libpng, I guess you must use the function png_set_tRNS()
{ "language": "en", "url": "https://stackoverflow.com/questions/7622231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I make an element's height equal to the height of the screen? I tried height: auto; but that doesn't work. Any ideas? A: html, body { height: 100%; } #container { height: 100%; background: red; width: 200px; } Is this what you are trying to do? Please provide some code. A: You have a few options. You can do: .element{ position:absolute; top:0px; right:0px; left:0px; bottom:0px; } That way it will be 0px from every side of the first parent element with position other than static. If it's the first element on the page, it will fill the entire document body. see here for what happens: http://jsfiddle.net/4QH8H/embedded/result/ http://jsfiddle.net/4QH8H/light/ You can also do: .element{ height:100%; width:100%; } Although, those attributes only make it as tall and wide as it's parent element, and sometimes the body will only wrap around the content and not fill the page, so you have to do: html, body{ height:100%; width:100%; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone - Catching the end of a grouped animation I animate 2 views, each one with its CAAnimationGroup that contains 2 CAAnimations. They are launched at the same time (if computing time is negligible), and have the same duration. How may I do to know when both grouped animation is finished. I put the - (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag delegate method, but... What may I test ? Sounds simple, but I don't see the way of doing this. A: You can use two variables to track whether the animations have completed: BOOL firstAnimFinished; BOOL secondAnimFinished; then in your animationDidStop delegate you check which animation is calling the method and set the flags appropriately. The catch is that you'll need to add a key to identify the animations when they call the delegate (the animations you created will not be the ones calling the delegate, which is a subject for another question/rant). For example: // when you create the animations [firstAnmim setValue: @"FirstAnim" ForKey: @"Name"]; [secondAnmim setValue: @"SecondAnim" ForKey: @"Name"]; // Your delegate - (void)animationDidStop:(CAAnimation*)theAnimation finished:(BOOL)flag { NSString* name = [theAnimation valueForKey: @"Name"]; if ([name isEqualToString: @"FirstAnim"]) { firstAnimFinished = YES; } else if ([name isEqualToString: @"SecondAnim"]) { secondAnimFinished = YES; } if (firstAnimFinished && secondAnimFinished) { // ALL DONE... } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7622249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: java String split + patterns I'm using this method to split some text: String[] parts = sentence.split("[,\\s\\-:\\?\\!\\«\\»\\'\\´\\`\\\"\\.\\\\\\/]"); Which will split me the text according to the specified symbols. One of the symbols is "-", because my text have weird things like this: "-------------- words --- words2 --words3--words4". Which will match my needs because it wont divide like this (in case i dont add "-"): "---words3---words4 (which will be considered a word in case i dont add "-"). But there is a tricky thing. I want to allow words like this: "aaa-bbb", which is is verified by this pattern: Pattern pattern = Pattern.compile("(?<![A-Za-z-])[A-Za-z]+-[A-Za-z]+(?![A-Za-z-])"); allow: aaa-bb, aaa-bbbbbbb not allow: aaa--bb, aa--bbb-cc So my question is, is it possible to split my text applying the split above, but also considering this pattern is a word separator(for words like aaa-bbb) ? Thanks in advances, Richard A: From what I gather you are after the following: String[] parts = sentence.split(/[\-]{2,}/);
{ "language": "en", "url": "https://stackoverflow.com/questions/7622250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is this an NPE? Why do I get an NPE at Drawable pic = (Drawable) i.getDrawable();?????? I am trying to get the height and width of a drawable in order to set its scale to be fit the XY of an imageview in an imageswitcher via a matrix (using a matrix to enable multitouch). public View makeView() { ImageView i = new ImageView(this); Drawable pic = (Drawable) i.getDrawable(); float displayHeight = i.getHeight(); float imageHeight = pic.getIntrinsicHeight(); float displayWidth = i.getWidth(); float imageWidth = pic.getIntrinsicWidth(); float scaleX = (float) displayWidth / (float) imageWidth; float scaleY = (float) displayHeight / (float) imageHeight; matrix.setScale(scaleX, scaleY); i.setBackgroundColor(0xFF000000); i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); i.setImageMatrix(matrix); i.setScaleType(ScaleType.MATRIX); Error Log: E/AndroidRuntime(22016): FATAL EXCEPTION: main E/AndroidRuntime(22016): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ben.test/com.ben.test.ImageSwitch1}: java.lang.NullPointerException E/AndroidRuntime(22016): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) E/AndroidRuntime(22016): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) E/AndroidRuntime(22016): at android.app.ActivityThread.access$1500(ActivityThread.java:117) E /AndroidRuntime(22016): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) E/AndroidRuntime(22016): at android.os.Handler.dispatchMessage(Handler.java:99) E/AndroidRuntime(22016): at android.os.Looper.loop(Looper.java:123) E/AndroidRuntime(22016): at android.app.ActivityThread.main(ActivityThread.java:3683) E/AndroidRuntime(22016): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime(22016): at java.lang.reflect.Method.invoke(Method.java:507) E/AndroidRuntime(22016): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) E/AndroidRuntime(22016): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) E/AndroidRuntime(22016): at dalvik.system.NativeStart.main(Native Method) E /AndroidRuntime(22016): Caused by: java.lang.NullPointerException E/AndroidRuntime(22016): at com.ben.test.ImageSwitch1.makeView(ImageSwitch1.java:185) E/AndroidRuntime(22016): at android.widget.ViewSwitcher.obtainView(ViewSwitcher.java:80) E/AndroidRuntime(22016): at android.widget.ViewSwitcher.setFactory(ViewSwitcher.java:99) E/AndroidRuntime(22016): at com.ben.test.ImageSwitch1.onCreate(ImageSwitch1.java:100) E/AndroidRuntime(22016): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) E/AndroidRuntime(22016): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) E/AndroidRuntime(22016): ... 11 more W/ActivityManager( 1106): Force finishing activity com.ben.test/.ImageSwitch1 W/ActivityManager( 1106): Force finishing activity com.ben.test/.LP A: getDrawable() is almost certainly returning a null value. Which isn't a problem in itself, but then you get an NPE when you try to cast that null value to a Drawable. The underlying problem is that a newly created ImageView won't have a drawable associated with it yet (as is evidenced by the fact that it returns null)
{ "language": "en", "url": "https://stackoverflow.com/questions/7622251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Eclipse Android Graphical Layout is not giving the options on properties window Eclipse Android Graphical Layout is not giving the options on properties window. example: When i select any widget on my graphical layout editor to show the properties, when i click on "Text" property (value field) it shows the "..." button to select a string. When i click on the button, nothing happens and i have to fill it by myself. The same for other properties like Gravity (i have to fill it by myself instead of show me the options like "center", etc. I've just updated to the last version available, anyway, this installation is very fresh (last weekend). I'm running on a ubuntu 11.04 also updated today. But this always happened to me, it never worked actually :( very frustrating. A: I submitted this to android-developers mailing list and found that there is a bug (fortunately already fixed) on ADT for linux: http://code.google.com/p/android/issues/detail?id=18348 the solution is: Download the ADT r14 preview available here: http://tools.android.com/download/adt-14-preview many other bugs, mainly on interface design layout issues were fixed lately (and many linux-specific bugs). A: On the Outline window, Right click on the relative layout (lets say) tree choose "other properties" and then "All By Name". a window should pop up for you to enter the desired action. the only thing that worked for me in order to relate action to button in Graphic layout on eclipse (using windows 7 X64 Build: v22.3.0- 887826)
{ "language": "en", "url": "https://stackoverflow.com/questions/7622252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to skip row when importing bad MySQL dump Given bad mysqldump that causes error on import: namtar backups # mysql -p < 2010-12-01.sql Enter password: ERROR 1062 (23000) at line 8020: Duplicate entry 'l�he?' for key 'wrd_txt' Is there an easy way to tell import to just skip given row and continue? (Yes, I know I can manually edit the file or parse output, but it's not very convinient) A: If you can make the dump again you could add --insert-ignore to the command-line when dumping. Or you can try using the mysqlimport command with --force,which will continue even if it encounters MySQL Errors. A: mysql -f -p < 2010-12-01.sql the -f (force) being the operative option here, worked for me. A: Great tip. I did it a little different but same result. perl -pi -e 's/INSERT INTO/INSERT IGNORE INTO/g' filename.sql A: The other options certainly are viable options, but another solution would be to simply edit the .sql file obtained from the mysqldump. Change: INSERT INTO table_name ... TO INSERT IGNORE INTO table_name ... A: Following the advice from jmlsteele's answer and comment, here's how to turn the inserts into INSERT IGNORE on the fly. If you're importing from an sql file: sed -e "s/^INSERT INTO/INSERT IGNORE INTO/" < 2010-12-01.sql | mysql -p If you're importing from a gz file, just pipe the output from gunzip into sed instead of using the file input: gunzip < 2010-12-01.sql.gz | sed -e "s/^INSERT INTO/INSERT IGNORE INTO/" | mysql -p A: Just a thought did you delete the MySQL directives at the top of dump? (I unintentionally did when I restarted a restore after deleting all the records/tables I'd already inserted with a sed command). These directives tell MySQL ,among other things, not to do unique tests, foreign key tests etc) /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
{ "language": "en", "url": "https://stackoverflow.com/questions/7622253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "49" }
Q: second parameter in Symfony routing job_show_user: url: /job/:company/:location/:id/:position class: sfDoctrineRoute options: { model: JobeetJob, type: object } param: { module: job, action: show } requirements: id: \d+ sf_method: [get] in template i use: url_for('job_show_user', $job) earlier (without routing) i used url_for('job/show?id=', $id) how can i make this in routing? i dont have $job, but i know $id - where this i must redirect. if i use url_for('job_show_user', 2) then i have error - second parameter must be array. A: You should try url_for('job_show_user', array('id' => 2)), or url_for('@job_show_user?id=2'), but you probably be asked to provide the other parameters too...
{ "language": "en", "url": "https://stackoverflow.com/questions/7622255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alarm Manager doesn't go off I'm building an Alarm Application. for it, I'm need to supply a time as input. I'm trying following code but alarm doesnt' trigger. I searched online and modified the code much alot but still no luck. Can someone help me out. Thanks in advance. Intent intent = new Intent(NapAppActivity.this, OnetimeAlarmReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(NapAppActivity.this, 1, intent, 0); Calendar cur_cal = new GregorianCalendar(); cur_cal.setTimeInMillis(System.currentTimeMillis()); Calendar cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR)); cal.set(Calendar.HOUR_OF_DAY, 12); cal.set(Calendar.MINUTE, 17); cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND)); cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND)); cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE)); cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH)); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent); A: I think that you should use cal=Calendar.getInstance() to get the current date/time instead of using GregorianCalendar constructor. Then, just set HourOfDay and Minutes, do not touch the other fields. A: <receiver android:name=".OnetimeAlarmReceiver" android:process=":remote" /> have you declared receiver in your manifest. Also preceed Receiver name with full package declaration at place of . If your Receiver is in another package I have used "." in above declaration ... With Regards, Arpit
{ "language": "en", "url": "https://stackoverflow.com/questions/7622256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why has this approach been taken in this class? In the base class inside generic views django creates a method view at runtime , attaches it to the generic view class and then calls the dispatch method on that class I did not understand the purpose of this approach , why did not the dispatch method was called directly from the as_view method ? class View(object): """ Intentionally simple parent class for all views. Only implements dispatch-by-method and simple sanity checking. """ http_method_names = ['get', 'post', 'put', 'delete', 'head', 'options', 'trace'] def __init__(self, **kwargs): """ Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things. """ # Go through keyword arguments, and either save their values to our # instance, or raise an error. for key, value in kwargs.iteritems(): setattr(self, key, value) @classonlymethod def as_view(cls, **initkwargs): """ Main entry point for a request-response process. """ # sanitize keyword arguments for key in initkwargs: if key in cls.http_method_names: raise TypeError(u"You tried to pass in the %s method name as a " u"keyword argument to %s(). Don't do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError(u"%s() received an invalid keyword %r" % ( cls.__name__, key)) def view(request, *args, **kwargs): self = cls(**initkwargs) return self.dispatch(request, *args, **kwargs) # take name and docstring from class update_wrapper(view, cls, updated=()) # and possible attributes set by decorators # like csrf_exempt from dispatch update_wrapper(view, cls.dispatch, assigned=()) return view def dispatch(self, request, *args, **kwargs): # Try to dispatch to the right method; if a method doesn't exist, # defer to the error handler. Also defer to the error handler if the # request method isn't on the approved list. if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed self.request = request self.args = args self.kwargs = kwargs return handler(request, *args, **kwargs) def http_method_not_allowed(self, request, *args, **kwargs): allowed_methods = [m for m in self.http_method_names if hasattr(self, m)] logger.warning('Method Not Allowed (%s): %s' % (request.method, request.path), extra={ 'status_code': 405, 'request': self.request } ) return http.HttpResponseNotAllowed(allowed_methods) A: In class based generic views, any request should have it's own instance of the MyView class. Here is our urls.py: from foo.views import AboutView .... (r'^about/', AboutView.as_view()), urls.py is imported once per django thread. This means that calling as_view does not create an instance of AboutView. When a request is processed by the urlconf, the view() method is called and only then an AboutView instance is created, passing and populating it with all the relevant data needed for this particular request. Using : (r'^about/', AboutView().dispatch), #WRONG!!!! will cause all requests to share the same instance of the view, including possible properties that should not be re used by different requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Edit the tag with jQuery or PHP I have some home made blog, and when viewing blog posts I'd like to change the title tag for adding the post title, so when I use the Twitter's tweet button, it adds the new button. I tried: <script type="text/javascript"> $(document).ready(function() { $(this).attr("title", "<?php echo $tagValue["title"]." - YourCloud"; ?>"); }); </script> And: $(document).ready(function() { document.title = "<?php echo $tagValue["title"]." - YourCloud"; ?>"; }); </script> But the Tweet Button still has the title I set up at the start, how can I fix this? EDIT: In my index.php I add the title tag, I want to modify it so when you see the source it already appears modified A: I think you want to set the text of the tweet, because by default the document title is tweeted. Well, you can modify the tweet button code to achieve this. See the href of the anchor element below where I added a 'text' parameter. <a href="https://twitter.com/share?text=any_text_you_want" class="twitter-share-button">Tweet</a> More here- https://dev.twitter.com/docs/tweet-button A: Try instead $("title").text("<?php echo $tagValue['title']." - YourCloud"; ?>"); A: $("title").html("<?php echo $tagValue['title']." - YourCloud"; ?>"); A: document.title is what you should use to change the title of the page, f.ex: document.title = 'Foo bar'; But it sounds like you are trying to change the title of the tweet button? A: First of all, yes I know this has an accepted answer - but I wasn't sure if it was exactly what he was after. I'm not sure that anyone understands your questions properly - and after reading through the question/answers I'm still non the wiser. Also, document.title over jQuery in this instance. You're saying that $("title").html("<?php echo $tagValue['title']." - YourCloud"; ?>"); is showing the original title? Well of course it is. All the PHP is executed BEFORE the JavaScript, so the echo $tagValue['title'] is essentially a static value throughout your JavaScript. Therefore, you're loading the same title into the title bar every time you try and change it. By the time your PHP reaches the browser, it's no longer $("title").html("<?php echo $tagValue['title']." - YourCloud"; ?>");, it's $("title").html("My Title - YourCloud"); Unless of course I'm understanding the question wrong. You really are missing so many details. Where is $tagValue['title'] being set - what is the value. I'm presuming that PHP is parsing your JS correctly so I won't bother asking whether you're using an external script. What do you expect the answer to be. But from everything I've read and understood from your script - why are you changing the title with JavaScript at all. If PHP is putting a static value into your page, then you may as well just put <title><?php echo $tagValue['title']." - YourCloud"; ?></title> in the head of your HTML. The only reason that I can see for the title changing with JavaScript is when an event happens that the user needs notifying about - or if you're using something like Ajax to have a dynamic site. I'll update this post with more details if you can comment back and, well, help me/everyone to understand your question. EDIT: If you want to edit the title by pressing a button: Why not place an onclick on the button itself and just do something like: function test() { if(document.title.indexOf(" - YourCloud")==-1){ document.title += " - YourCloud"; } } Not tested, but, surely that could work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scheme -> Clojure: multimethods with predicates in the methods? I'm converting some Scheme code to Clojure. The original uses a dispatching pattern that's very similar to multimethods, but with an inverted approach to the matching predicates. For example, there a generic function "assign-operations". The precise implementation details aren't too important at the moment, but notice that it can take a list of argument-predicates. (define (assign-operation operator handler . argument-predicates) (let ((record (let ((record (get-operator-record operator)) (arity (length argument-predicates))) (if record (begin (if (not (fix:= arity (operator-record-arity record))) (error "Incorrect operator arity:" operator)) record) (let ((record (make-operator-record arity))) (hash-table/put! *generic-operator-table* operator record) record))))) (set-operator-record-tree! record (bind-in-tree argument-predicates handler (operator-record-tree record))))) The dispatched functions supply these predicates, one per argument in the arity of the function. (assign-operation 'merge (lambda (content increment) content) any? nothing?) (assign-operation 'merge (lambda (content increment) increment) nothing? any?) (assign-operation 'merge (lambda (content increment) (let ((new-range (intersect-intervals content increment))) (cond ((interval-equal? new-range content) content) ((interval-equal? new-range increment) increment) ((empty-interval? new-range) the-contradiction) (else new-range)))) interval? interval?) Later, when the generic function "merge" is called, each handler is asked if it works on the operands. As I understand multimethods, the dispatch function is defined across the set of implementations, with dispatch to a specific method based on the return value of the dispatch-fn. In the Scheme above, new assign-operation functions can define predicates arbitrarily. What would be an equivalent, idiomatic construct in Clojure? EDIT: The code above comes from "The Art of the Propagator", by Alexey Radul and Gerald Sussman. A: You can do this with Clojure's multimethods fairly easily - the trick is to create a dispatch function that distinguishes between the different sets of predicates. The easiest way to do this is probably just to maintain a vector of "composite predicates" that apply all of the individual predicates to the full argument list, and use the index of this vector as the dispatch value: (def pred-list (ref [])) (defn dispatch-function [& args] (loop [i 0] (cond (>= i (count @pred-list)) (throw (Error. "No matching function!")) (apply (@pred-list i) args) i :else (recur (inc i))))) (defmulti handler dispatch-function) (defn assign-operation [function & preds] (dosync (let [i (count @pred-list)] (alter pred-list conj (fn [& args] (every? identity (map #(%1 %2) preds args)))) (defmethod handler i [& args] (apply function args))))) Then you can create operations to handle whatever predicates you like as follows: (assign-operation (fn [x] (/ x 2)) even?) (assign-operation (fn [x] (+ x 1)) odd?) (take 15 (iterate handler 77)) => (77 78 39 40 20 10 5 6 3 4 2 1 2 1 2)
{ "language": "en", "url": "https://stackoverflow.com/questions/7622269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: IOS iPhone use MPMusicPlayerController to play external music file, and display iPod interface I'm trying to use the standardized "iPod" audio player to play some MP3 tracks in an iPhone app I'm building. The tracks are downloaded from the internet and stored in the app's "Documents" directory. I thought of using a MPMusicPlayerController to do this, but I don't seem to be able to get it to work. Also, I've seen the AVAudioPlayer, but that just plays the audio without an interface. Any suggestions? A: The MPMusicPlayerController is for playing items out of the iPod library (songs sync'd via iTunes) so you won't be able to use it for this. You can get the NSData for your audio using... NSData* data = [NSMutableData dataWithContentsOfFile:resourcePath options:0 error:&err]; Then use an AVAudioPlayer created from that data and call play. AVAudioPlayer* player = [[AVAudioPlayer alloc] initWithData:data error:&err]; [player play];
{ "language": "en", "url": "https://stackoverflow.com/questions/7622271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android touchevent on view even with dialog in front I am making video playback controls. All my code is present to make it work and it does, except for one thing. When I touch the surfaceview the controls come up, but once they are up, my surfaceview no longer has focused and doesn't receive touch events. What I need is for the surface view to still get touch events even with the dialog open. Also my dialog must also be able to receive touch events. How do I do this? A: Use another View in the same layout that sits layered on top of your SurfaceView for controls rather than a Dialog. Dialogs are meant for modal interactions - they are intended to block you from interacting with whatever is underneath.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nested inheritance trouble in Visual Studio 2008 I am currently working on a widget-based graphical user interface. It is structured as a tree with Widgets as the leaves and Containers as the nodes of the tree. The (solvable) problem with this structure is that the Widget-class takes a reference to the Container that is its parent. However, this makes it impossible for the Container class to access the protected members of the Widget-class (here the "draw" member is causing trouble). Here is the core of the code causing the problem. Of course this can be solved by making the members public. However, that is not the style that I would like. ClassesTest.h: class Container; class Widget { public: Widget(Container *parent); virtual ~Widget(); protected: Container *parent; virtual void draw(); }; class Container : public Widget { public: Container(Container *parent); virtual ~Container(); protected: std::list<Widget *> childs; private: friend Widget::Widget(Container *); friend Widget::~Widget(); virtual void draw(); void addChild(Widget *child); void removeChild(Widget *child); }; ClassesTest.cpp #include "stdafx.h" #include "ClassesTest.h" Widget::Widget(Container *parent) { this->parent = parent; parent->addChild(this); } Widget::~Widget() { parent->removeChild(this); } void Widget::draw() { //Draw the leaf } Container::Container(Container *parent) : Widget(parent) {} Container::~Container() {} void Container::draw() { //Draw all the childs for (std::list<Widget *>::iterator i = childs.begin(); i != childs.end(); i++) { (*i)->draw(); } } void Container::addChild(Widget *child) { childs.push_back(child); } void Container::removeChild(Widget *child) { childs.remove(child); } int main(int argc, char* argv[]) { //Do something useful! return 0; } And this is the output Visual Studio 2008 gives me when I am trying to compile my code: 1>------ Build started: Project: ClassesTest, Configuration: Debug Win32 ------ 1>Compiling... 1>ClassesTest.cpp 1>e:\visual studio 2008\projects\classestest\classestest\classestest.cpp(26) : error C2248: 'Widget::draw' : cannot access protected member declared in class 'Widget' 1> e:\visual studio 2008\projects\classestest\classestest\classestest.h(14) : see declaration of 'Widget::draw' 1> e:\visual studio 2008\projects\classestest\classestest\classestest.h(6) : see declaration of 'Widget' 1>Build log was saved at "file://e:\Visual Studio 2008\Projects\ClassesTest\ClassesTest\Debug\BuildLog.htm" 1>ClassesTest - 1 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== Any suggestions would be appreciated! Filip A: Your code is essentially equal to this, with regard to your specific problem: class Base { protected: virtual void f() {} }; class Derived : public Base { void h() { Base().f(); // no can do - Base() creates another instance. f(); // sure, why not. it's the same instance, go ahead. Derived().f(); // sure, why not. it's the same type, go ahead. } }; The problem is that although Derived inherits from Base, it still doesn't have access to Base's protected members. The way access rights works here is as follows: * *Derived can not access Base's protected stuff if Base is a different instance. *Derived can access Base's protected stuff in it's own instance. *Derived can access another Derived's private stuff. The quickest way to solve your problem would probably make Container::draw() a friend of Widget.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the order in which a POSIX system clears the file locks that were not unlocked cleanly? The POSIX specification for fcntl() states: All locks associated with a file for a given process shall be removed when a file descriptor for that file is closed by that process or the process holding that file descriptor terminates. Is this operation of unlocking the file segment locks that were held by a terminated process atomic per-file? In other words, if a process had locked byte segments B1..B2 and B3..B4 of a file but did not unlock the segments before terminating, when the system gets around to unlocking them, are segments B1..B2 and B3..B4 both unlocked before another fcntl() operation to lock a segment of the file can succeed? If not atomic per-file, does the order in which these file segments are unlocked by the system depend on the order in which the file segments were originally acquired? The specification for fcntl() does not say, but perhaps there is a general provision in the POSIX specification that mandates a deterministic order on operations to clean up after a process that exits uncleanly or crashes. A: There's a partial answer in section 2.9.7, Thread Interactions with Regular File Operations, of the POSIX specification: All of the functions chmod(), close(), fchmod(), fcntl(), fstat(), ftruncate(), lseek(), open(), read(), readlink(), stat(), symlink(), and write() shall be atomic with respect to each other in the effects specified in IEEE Std 1003.1-2001 when they operate on regular files. If two threads each call one of these functions, each call shall either see all of the specified effects of the other call, or none of them. So, for a regular file, if a thread of a process holds locks on segments of a file and calls close() on the last file descriptor associated with the file, then the effects of close() (including removing all outstanding locks on the file that are held by the process) are atomic with respect to the effects of a call to fcntl() by a thread of another process to lock a segment of the file. The specification for exit() states: These functions shall terminate the calling process with the following consequences: * *All of the file descriptors, directory streams[, conversion descriptors, and message catalog descriptors] open in the calling process shall be closed. *... Presumably, open file descriptors are closed as if by appropriate calls to close(), but unfortunately the specification does not say how open file descriptors are "closed". The 2004 specification seems even more vague when it comes to the steps of abnormal process termination. The only thing I could find is the documentation for abort(). At least with the 2008 specification, there is a section titled Consequences of Process Termination on the page for _Exit(). The wording, though, is still: * *All of the file descriptors, directory streams, conversion descriptors, and message catalog descriptors open in the calling process shall be closed. UPDATE: I just opened issue 0000498 in the Austin Group Defect Tracker. A: I don't think the POSIX specification stipulates whether the releasing of locks is atomic or not, so you should assume that it behaves as inconveniently as possible for you. If you need them to be atomic, they aren't; if you need them to be handled separately, they're atomic; if you don't care, some machines will do it one way and other machines the other way. So, write your code so that it doesn't matter. I'm not sure how you'd write code to detect the problem. In practice, I expect that the locks would be released atomically, but the standard doesn't say, so you should not assume.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Emacs codepage problems: Terminus font, utf-8 and cyrillic-translit input I love the cyrillic-translit input method for Emacs. However, after I set the wonderful Terminus as my default font, the Russian characters appear in Arial or something (in any case it's not Terminus). How do I fix this? Setting the default font to UTF-8 (Emacs equivalent "-outline-Terminus-normal-normal-normal-mono-16-*-*-*-c-*-iso10646-1") doesn't help. I guess this possibly means that Terminus lacks decent UTF-8 support? Anyhow, I'm using the following snippet for switching between cyrillic-translit input method and the "normal" mode: (defun toggle-cyrillic-input-method () "toggle between French and no input method" (interactive) (if (string= current-input-method "cyrillic-translit") (set-input-method nil) (set-input-method "cyrillic-translit"))) (global-set-key [f9] 'toggle-cyrillic-input-method) Now -- is there a way to make the snippet not only switch over to cyrillic-translit but also switch the codepage when I press F9? In other words, how do I make it also toggle the font between "-outline-Terminus-normal-normal-normal-mono-16-*-*-*-c-*-iso8859-1" (Latin) and "-outline-Terminus-normal-normal-normal-mono-16-*-*-*-c-*-iso8859-5" (Russian)? It's the only workaround I (as a non-programmer) could think of. Any other ideas are welcome, too. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7622283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I use MailMerge and MS Words as Report Generator instead of Access Report? This is not about coding question. It's about Software (Database) Design. Background: My office has a ADP database as front and SQL Server is a backend. There are a dozen of basic standard reports in the ADP file. End users slightly change reports every year such as adding some texts, changing logo, bolds, highlights. I help them back and forth for updating these. After they are ok with the report, I upload to the server so other users can use it. I do this over and over over the time (hundreds times). I think there should be a better way. Recently, I test a new design by splitting Report and Database. I let user create a words file for the report that they like. I add MailMerge fields in the report after they're done. My users are very good in MS Words. In the database, I add standard MailMerge code. When users pick what template (docx) they want for a report then runs it, it works fine. Question: Can I use MailMerge and MS Words as Report Generator instead of Access Report? if it's work fine, I will rollout to all the reports. I just want to miss anything before doing so. Pro(s) - Users can add any complex format to a report (almost anything you can imagine in MS Words, which you can't do in Access) - I have less work. No recode, recomplie, or reupload. Con(s) - Report Desinger is run faster than MailMerge for a large report. - Train user how to update MailMerge fields A: Yes, you can use Word and MailMerge to create reports. However, keep in mind that you're giving up control, since users could edit the templates in a way that breaks your MailMerge.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: is there a c++ library for ordinary differential equation (ODE) solvers? More specifically, i'm interested in 8th order Dormand-Prince embedded method, it's based on Runge-Kutta, and stiff equations. I use Numerical Recipes 3 but i often have trouble compiling their libraries. I'd like to know of alternatives. A: The GNU Scientific Library has several differential equation solvers. They have one that uses Prince-Dormand. It's written in C so you shouldn't have trouble compiling it. A: You can also try odeint. It has the classical Runge-Kutta solvers, Rosenbrock4 for stiff systems and some multi-step method. It is header-only, but you need the boost libraries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: How To Structure Large OpenCL Kernels? I have worked with OpenCL on a couple of projects, but have always written the kernel as one (sometimes rather large) function. Now I am working on a more complex project and would like to share functions across several kernels. But the examples I can find all show the kernel as a single file (very few even call secondary functions). It seems like it should be possible to use multiple files - clCreateProgramWithSource() accepts multiple strings (and combines them, I assume) - although pyopencl's Program() takes only a single source. So I would like to hear from anyone with experience doing this: * *Are there any problems associated with multiple source files? *Is the best workaround for pyopencl to simply concatenate files? *Is there any way to compile a library of functions (instead of passing in the library source with each kernel, even if not all are used)? *If it's necessary to pass in the library source every time, are unused functions discarded (no overhead)? *Any other best practices/suggestions? Thanks. A: I don't think OpenCL has a concept of multiple source files in a program - a program is one compilation unit. You can, however, use #include and pull in headers or other .cl files at compile time. You can have multiple kernels in an OpenCL program - so, after one compilation, you can invoke any of the set of kernels compiled. Any code not used - functions, or anything statically known to be unreachable - can be assumed to be eliminated during compilation, at some minor cost to compile time. A: In OpenCL 1.2 you link different object files together.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Queue using two stacks I implemented it as an array with two stacks adjacent to each other, but their tops on the either ends. That is, if top(stack1) is at the beginning of keys, top(stack2) is at the end of keys. Bottom(Stack1) and Bottom(Stack2) should be adjacent, but anywhere between top(Stack1) and top(Stack2). To delete, I am poping from Top(Stack1), and for inserting, I am pushing in Top(stack2). Could somebody pls tell me if it is correct to do it this way? When I read CLRS, I solved the que this way, and had no way to know that it was ryt or not. But it was asked in today's exam, and everyone later on was discussing the way given officially (here and everywhere else on net), so it seems I am the only one to do it such a way. I really wanna know if this is wrong or right ? Please help A: Queues and stacks are abstract data structures which have well defined behaviors and any implementation of these data structures should respect this contract. Your idea of using a single array to implement two stacks is good. But, the inserts and deletes should happen on both stacks. For eg. lets say you have this setup 2 3 4 5 6 top(stack1) is 2 bottom(stack1) is 4 top(stack2) is 6 bottom(stack2) is 5 after popping from stack1 3 times you would have reached the bottom of your stack i.e 4 and no longer able to pop anything even though there are two more elements in your QUEUE implementation. So, a few corrections to your implementation is required. So, if I were to implement two stacks which emulate a QUEUE, this is how I would do it. Stack1: 2 3 4 5 6 which is essentially an array 2 is the bottom of the stack and 6 is the top of the stack. Stack2: empty Insert an element to Queue: This is very simple. Just add to the end of array i.e stack1 stack1:2 3 4 5 6 7 Now 7 is the top of the stack. Delete an element from Queue: 1. Pop all elements in stack1 and insert them to stack2. So, your array will be reversed stack1:empty stack2: 7 6 5 4 3 2 . Now 2 is at the top of the stack. 2. Now your top(stack2) will be pointing to 2. Just pop it. 7 6 5 4 3 3. Now for the remaining elements in stack2, pop from stack2 and insert them to stack1. stack2:empty stack1:3 4 5 6 7 PS: The above algorithm assumes that you know how to manage memory for arrays as it shrinks or expands. A: I think you actually can implement a queue using two adjacent stacks as you described. The problem is that you cannot implement those two adjacent stacks with an array efficiently. I mean your queue seems OK, but when you try to use the underlying stacks, you encounter the problem how to insert a new item at the beginning of the array (i.e. push to stack1). You need to move (copy) all items in your array to push an item into stack1. And that's ill design. A: For those who are looking for the solution, a sample one is this: Let's say we have two stacks S1 and S2. A queue has the given two behaviours: * *Enqueue: Insert an element into the queue. For this, simply push into S1. *Dequeue: Pop all elements from from S1 one by one, simultaneously pushing them into S2. Now pop from S2. The popped element is the desired result of Dequeue. Readers are encouraged to find more optimized solutions to this and post them here if possible :) A: Here is an example in python using the built in array/list for two stacks. class Queue2Stacks(object): def __init__(self): self.in_stack = [] self.out_stack = [] def enqueue(self, element): self.in_stack.append(element) def dequeue(self): if not self.out_stack: while self.in_stack: self.out_stack.append(self.in_stack.pop()) return self.out_stack.pop()
{ "language": "en", "url": "https://stackoverflow.com/questions/7622297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQLite where clause acting strange with TEXT fields I've searched up and down sqlite.org and can't figure this one out. I'm used to MySQL so I think maybe I am overlooking something. See the following code: sqlite> select id,event_number,must_say from events where id=28; 28|'28'|'AFK' sqlite> select id,event_number,must_say from events where must_say='AFK'; sqlite> select id,event_number,must_say from events where must_say like 'AFK'; sqlite> select id,event_number,must_say from events where must_say like 'A%'; sqlite> select id,event_number,must_say from events where must_say=='AFK'; sqlite> Needless to say, I really was expecting the following to be returned for ALL of the above queries, not just the first one: 28|'28'|'AFK' I'm getting this behavior on all TEXT fields. It seems I can't search at all. Here is the schema of my events table, with the irrelevant fields omitted: CREATE TABLE events ( id INTEGER PRIMARY KEY AUTOINCREMENT, EVENT_NUMBER INTEGER, MUST_SAY TEXT ); Any ideas? I just want to be able to search by arbitrary text fields in the table. Edit: I'm using SQLite3. A: You may also have whitespace in your columns. You can see spaces with select '|' || must_say || '|' from events You can see unprintables with select hex(must_say) from events
{ "language": "en", "url": "https://stackoverflow.com/questions/7622299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: explicitly setting "pretty print" formatting for Graph API request When querying the Graph API with a 'known' browser the JSON output is formatted in a way to make it easy for humans to read. If the query is done with any other browser then it outputs everything on one line. How do you explicitly make the request so that the formatting is not done? I'm sure I've seen it somewhere, but I can't seem to find it now. A: The pretty parameter controls it. So https://graph.facebook.com/foo?pretty=0 always prints without extra whitespace, while https://graph.facebook.com/foo?pretty=1 always prints with extra whitespace, and omitting it causes the default behavior of switching based on user-agent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Carrierwave image upload in nested form still creating record even no file is specified I have a Carrierwave image upload in a nested simple_form which works (sort of) unless the user does not specify a file, in which case a blank Picture object is created unless there was a previously existing one. Not quite sure how to make it so that if the user doesn't specify a "new" image to upload, the old one isn't deleted and/or a blank record without a file is created. One (maybe odd) thing I am doing is always sending the logged in @user to the user#edit action, then building a @user.picture if it doesn't exist. I am thinking this is where my bad design is. # user.rb class User < ActiveRecord::Base [...] has_one :picture, :dependent => :destroy accepts_nested_attributes_for :picture [...] end # picture.rb class Picture < ActiveRecord::Base attr_accessible :image, :remove_image belongs_to :user mount_uploader :image, ImageUploader end # users_controller.rb def edit if @user.picture.nil? @user.build_picture end end #_form.html.erb <%= simple_form_for @user, :html => {:multipart => true} do |f| %> <%= render "shared/error_messages", :target => @user %> <h2>Picture</h2> <%= f.simple_fields_for :picture do |pic| %> <% if @user.picture.image? %> <%= image_tag @user.picture.image_url(:thumb).to_s %> <%= pic.input :remove_image, :label => "Remove", :as => :boolean %> <% end %> <%= pic.input :image, :as => :file, :label => "Picture" %> <%= pic.input :image_cache, :as => :hidden %> <% end %> <br/> #rest of form here <% end %> A: I think I had the same issue which I solved by adding a reject_if option to the accepts_nested_attribute. So in your example, you could do something like class User < ActiveRecord::Base [...] has_one :picture, :dependent => :destroy accepts_nested_attributes_for :picture, :reject_if => lambda { |p| p.image.blank? } [...] end A: When you use build_* it sets the foreign key on the object. ( similar to saying Picture.new(:user_id => id) ) Try This # users_controller.rb def edit if @user.picture.nil? @user.picture = Picture.new end end A: Today I had the same problem, I solved this like: accepts_nested_attributes_for :photos, :reject_if => :all_blank
{ "language": "en", "url": "https://stackoverflow.com/questions/7622303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Counting the size of a group in T-sql I'd like to count the size of a group. My table looks like that: Name Number Renee Scott 1 Bruno Cote 1 Andree Scott 2 Renee Scott 2 Pierre Dion 2 Pierre Dion 3 Louise Tremblay 3 Renee Scott 3 Andree Scott 3 Jean Barre 3 Bruno Cote 3 There are 2 Name associated with the Number 1, 3 Name with Number 2 and 6 Name with 3. I'd like to select this table where the Number is associated with 3 name or more. Thank you. A: SELECT * FROM TABLENAME WHERE NUMBER IN ( SELECT NUMBER FROM TABLENAME GROUP BY NUMBER HAVING COUNT(*)>3 )
{ "language": "en", "url": "https://stackoverflow.com/questions/7622306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: System.out.println doesn't work? When I write this in the main method: System.out.println("Hello"); Nothing is outputted on the output console. It just says "Build successful (total time: 0 seconds)". What's the problem? Here is my full program: package names; public class myName { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("test"); } } Here's the window after I debug the program: Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jsfd.jar Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/laf.jar Have no file for /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/sunrsasign.jar BUILD SUCCESSFUL (total time: 1 second) A: On netbeans right click and click run file. It would run. Seems like you're building the project, and not executing it. Don't debug it. Run it. A: I'm nearly sure it's due to an IDE issue: the ant/build output is being redirected to a different place (not stdout) and you're seeing that "other place" as a "Console". Please let us know your IDE and as much code as you can. A: You have to run it then. In netbeans, to run you can press F6 - http://netbeans.org/kb/docs/java/quickstart.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7622309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Writing binary data to a file I want to temporarily cache binary data before I can write it to a file. This was my idea. Since I have to insert a header before this data that indicates how much data will follow after the header, I needed a way to keep this data cached before it is written to ofstream file. I decided to create ostream buffer(); wherein I could dump all this data without writing it to the file. After the header was written, I'd just do file << buffer to dump the data. I'm still struggling with compiler errors such as this one: error: no matching function for call to ‘TGA2Converter::writePixel(std::ostream (&)(), uint32_t&)’ note: candidate is: void TGA2Converter::writePixel(std::ostream&, uint32_t) Why am I getting this message? And, perhaps more importantly, am I approaching the problem in the most effective and convenient way? Edit: people have been asking for code. I tried to narrow it down to this... // This is a file. I do not want to write the binary // data to the file before I can write the header. ofstream file("test.txt", ios::binary); // This is binary data. Each entry represents a byte. // I want to write it to a temporary cache. In my // real code, this data has to be gathered before // I can write the header because its contents depend // on the nature of the data. stringstream cache; vector<uint32_t> arbitraryBinData; arbitraryBinData.resize(3); arbitraryBinData[0] = 0x00; arbitraryBinData[1] = 0xef; arbitraryBinData[2] = 0x08; // Write it to temporary cache for (unsigned i = 0; i < arbitraryBinData.size(); ++i) cache << arbitraryBinData[i]; // Write header uint32_t header = 0x80; // Calculation based on the data! file << header; // Write data from cache file << cache; I fully expected this binary data to be written to the file: 0000000: 8000 ef08 But I got this: 0000000: 3132 3830 7837 6666 6638 6434 3764 3139 0000010: 38 Why am I not getting the expected result? A: ostream buffer(); is declaring a function called buffer taking no arguments and returning an ostream. Also ostream is a base class, you should be using strstream instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Displaying images in uiwebview from core data record So I have an app I've written for the iPad, and I'd like to be able to allow users to insert images into their documents by selecting an image from an album or the camera. All that works great. Because the user might keep the document longer than they keep the image in an album, I make a copy of it, scale it down a bit, and store it in a core data table that is just used for this purpose. I store the image like this: NSManagedObjectContext* moc=[(ActionNote3AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; NSString* imageName=[NSString stringWithFormat:@"img%lf.png",[NSDate timeIntervalSinceReferenceDate]]; Image* anImage = [NSEntityDescription insertNewObjectForEntityForName:@"Image" inManagedObjectContext:moc]; anImage.imageName=imageName; anImage.imageData=UIImagePNGRepresentation(theImage); NSError* error=nil; if(![moc save:&error]) {... I sub-class NSURLCache, as suggested on Cocoa With Love, and ovverride cachedResponseForRequest thusly: - (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request { NSString *pathString = [[[request URL] absoluteString]lastPathComponent]; NSData* data = [Image dataForImage:pathString]; if (!data) { return [super cachedResponseForRequest:request]; } NSURLResponse *response =[[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:[NSString stringWithString:@"image/png"] expectedContentLength:[data length] textEncodingName:nil] autorelease]; NSCachedURLResponse* cachedResponse =[[[NSCachedURLResponse alloc] initWithResponse:response data:data] autorelease]; return cachedResponse; } I also make sure the app uses the sub-classed NSURLCache by doing this in my app delegate in didFinishLaunchingWithOptions: ANNSUrlCache* uCache=[[ANNSUrlCache alloc]init]; [NSURLCache setSharedURLCache:uCache]; The method that returns the image data from the core data record looks like this: +(NSData*)dataForImage:(NSString *)name { NSData* retval=nil; NSManagedObjectContext* moc=[(ActionNote3AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Image" inManagedObjectContext:moc]; NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; [request setEntity:entityDescription]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"imageName==%@", name]; [request setPredicate:predicate]; NSError* error=nil; NSArray *array = [moc executeFetchRequest:request error:&error]; if ([array count]>0) { retval=((Image*)[array objectAtIndex:0]).imageData; } return retval; } To insert the image into the web view, I have an html img tag where the name in src="" relates back to the name in the image table. The point of the NSURLCache code above is to watch for a name we have stored in the image table, intercept it, and send the actual image data for the image requested. When I run this, I see the image getting requested in my sub-classed NSURLCache object. It is finding the right record, and returning the data as it should. However, I'm still getting the image not found icon in my uiwebview: So Marcus (below) suggested that I not store the image data in a core data table. So I made changes to accomodate for that: Storing the image: NSString* iName=[NSString stringWithFormat:@"img%lf.png",[NSDate timeIntervalSinceReferenceDate]]; NSData* iData=UIImagePNGRepresentation(theImage); NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString* documentsDirectory = [paths objectAtIndex:0]; NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:iName]; [iData writeToFile:fullPathToFile atomically:NO]; Retrieving the image: - (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request { NSString *pathString = [[[request URL] absoluteString]lastPathComponent]; NSString* iPath = [Image pathForImage:pathString]; if (!iPath) { return [super cachedResponseForRequest:request]; } NSData* idata=[NSData dataWithContentsOfFile:iPath]; NSURLResponse *response =[[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:[idata length] textEncodingName:nil] autorelease]; NSCachedURLResponse* cachedResponse =[[[NSCachedURLResponse alloc] initWithResponse:response data:idata] autorelease]; return cachedResponse; } In debug mode, I see that idata does get loaded with the proper image data. And I still get the image-not-found image! Obviously, I'm doing something wrong here. I just dont know what it is. So... What am I doing wrong here? How can I get this to work properly? Thank you. A: I would strongly suggest that you do not store the binary data in Core Data. Storing binary data in Core Data, especially on an iOS device, causes severe performance issues with the cache. The preferred way would be to store the actual binary data on disk in a file and have a reference to the file stored within Core Data. From there it is a simple matter to change the image url to point at the local file instead. A: So it turns out I was way overthinking this. When I write the HTML, I just write the path to the image in with the image tag. Works like a charm. I would love to know why the solution I posed in my question did not work, though. And, I did wind up not storing the images in a table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get an element before its added to the DOM? How can you get an element before its added to the DOM (before append()) $('#enclosure_balance'+id).css({background:'red'}) A: As far as I know, the only way is by reference if you control or have access to the construction of it. var s = $('<div id="stupid"/>') Reference the variable / property which contains it. Since it hasn't been appended it's not accessible via the DOM methods. If you want the element to be visibly hidden just append it to a container element that has offsetting css values ( eg position absolute, top -999em, left -999em ) EDIT: There are also document fragments: http://ejohn.org/blog/dom-documentfragments/#postcomment but since they're not in the document itself, you can't reference the elements inside with document.getElementById and such. A: I suppose the element is in a jQuery object. Do either obj.filter( selector ) or obj.find( selector ) where obj is the jQuery object which contains your element, and selector is the selector which is supposed to match your element. filter works if your element is one of the elements of the jQuery object. find works when your jQuery object contains one or more elements which in turn have ancestors, and your element is among those ancestors. A: The answer is in the question. You already have a reference to the element, else you couldn't call append. If you have this: $("#parent").append("<div />"); Modify it to this: var child = $("<div />"); child.css({ background: "red" }); $("#parent").append(child);
{ "language": "en", "url": "https://stackoverflow.com/questions/7622313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: VB.NET: How to make a webRequest async I think this is a simple question for you, but I don't understand other cases of webRequests, so I asked here: How can I make this webRequest asynchronous? Dim sBuffer As String Dim oRequest As WebRequest = WebRequest.Create(url) oRequest.Method = "GET" Dim oResponse As WebResponse = oRequest.GetResponse() Dim oStream As New StreamReader(oResponse.GetResponseStream()) sBuffer = oStream.ReadToEnd() oStream.Close() oResponse.Close() Return sBuffer Thank you for your help! Regards, Flo A: a function with a simple return value cannot be sinmply made asynchronous, you need to find another method of handling the data that comes back. I would suggest using System.Net.WebClient which is a much easier wrapper on what you've done above, with this class asynch is really easy. Dim wc As New WebClient AddHandler wc.DownloadStringCompleted, AddressOf DownloadCompletedHander wc.DownloadStringAsync(url) ... Public Shared Sub DownloadCompletedHander(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs) If e.Cancelled = False AndAlso e.Error Is Nothing Then Dim myString As String = CStr(e.Result) 'Do stuff with data End If End Sub I don't really speak VB.net but i think thats right from some googling
{ "language": "en", "url": "https://stackoverflow.com/questions/7622318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find the optimum length of transfer in fread function There are files with unknown file size ( not included in header as content-length) I am trying to copy them to my server using this: $file=''; do{ $line = @fread ( $fp, 16384 ); $file .= $line; }while ( strlen($line)> 0 ); the file is always pdf content. The problem is sometimes it gets the file (153 Kb) and sometimes it gets the part of file (3kb) and sometimes it hangs and the cpu of my computer works with 100% usage!! what do you suppose to do ? any thisg wrong with length ( 16384 ) ? =============== edit ================ more information $request = $method . " " . $url . " HTTP/1.1" . $nn . "Host: " . $host . $nn . "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14" . $nn . "Accept: */*" . $nn . "Accept-Language: en-us;q=0.7,en;q=0.3" . $nn . "Accept-Charset: utf-8,windows-1251;q=0.7,*;q=0.7" . $nn . "Pragma: no-cache" . $nn . "Cache-Control: no-cache" . $nn . ($Resume ["use"] === TRUE ? "Range: bytes=" . $Resume ["from"] . "-" . $nn : "") . $http_auth . $proxyauth . $referer .($XMLRequest ? "X-Requested-With: XMLHttpRequest" . $nn : ""). $cookies . "Connection: Close" . $nn . $content_tl . $nn . $postdata; $fp = @fsockopen($Host , $Port, $errno, $errstr, 15); fputs ( $fp, $request ); fflush ( $fp ); $file=''; do{ $line = @fread ( $fp, 16384 ); $file .= $line; }while ( strlen($line)> 0 );
{ "language": "en", "url": "https://stackoverflow.com/questions/7622321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: issue with MAX statement in t-sql code This is the code: Select BCPP.* from ViewPBCPP BCPP inner join ( Select MBC.PC PC ,MRT.Name CT ,Max(dbo.CalcDatefromUTC(MBC.CreatedDate)) as LRDate from TableBACC MBC inner join TableSC.RT MRT ON MBC.RTid = MRT.id where MBC.Isdeleted = 'False' and MBC.PC <> 'NULL' Group by MBC.PC ,MRT.Name ) MBCR ON BCPP.P_id = MBCR.PC and BCPP.CreatedDate = MBCR.LRDate and BCPP.CT = MBCR.CT Now Max(dbo.CalcDatefromUTC(MBC.CreatedDate)) is actually a function Query above works fine with Max(dbo.CalcDatefromUTC(MBC.CreatedDate)) Now when I write Max(dbo.CalcDatefromUTC(MBC.CreatedDate)) + Min(dbo.CalcDatefromUTC(MBC.CreatedDate)) I cannot extract any values at all from this query written above If I write just (dbo.CalcDatefromUTC(MBC.CreatedDate)) it gives me error that it does not contained aggregate function or the group by function I actually want this (dbo.CalcDatefromUTC(MBC.CreatedDate)) so that I can use all the values of this function rather than just MAX values of it How can I change this code written above to achieve my objective?? Anyone?? A: You can't have dbo.CalcDatefromUTC(MBC.CreatedDate) in the SELECT list as neither you can have MBC.CreatedDate because it's not in the GROUP BY list. You can have MAX(MBC.CreatedDate) though because it uses an aggregate function (MAX) on thta column. You can also have: dbo.CalcDatefromUTC(MAX(MBC.CreatedDate)) as LRDate which is the same actually (although maybe a bit faster), as: MAX(dbo.CalcDatefromUTC(MBC.CreatedDate)) as LRDate From your comments, I assume the above is not very helpful. Perhaps grouping by MBC.CreatedDate as well is what you want: Select BCPP.* from ViewPBCPP BCPP inner join ( Select MBC.PC PC ,MRT.Name CT ,dbo.CalcDatefromUTC(MBC.CreatedDate) as LRDate from TableBACC MBC inner join TableSC.RT MRT ON MBC.RTid = MRT.id where MBC.Isdeleted = 'False' and MBC.PC <> 'NULL' Group by MBC.PC ,MBC.CreatedDate --- added ,MRT.Name ) MBCR ON BCPP.P_id = MBCR.PC and BCPP.CreatedDate = MBCR.LRDate and BCPP.CT = MBCR.CT
{ "language": "en", "url": "https://stackoverflow.com/questions/7622325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to handle this error in jquery library I am using particular library for constrain on my textbox it giving me following error. How can I resolve it... $.constrain usage: //jquery.constrain.js: 5Uncaught SyntaxError: Unexpected identifier link for library is at http://jsfiddle.net/U9N63/ A: add // before this line, looks like a part of a comment A: The code you posted is not actually JavaScript code, but is a JavaScript comment excerpted from this plugin source file. Note the /* and */ wrapping several lines of text at the top of that file. Those character sequences represent the beginning and end of multi-line comments in JavaScript. Most likely, your file is missing at least the opening /*.
{ "language": "en", "url": "https://stackoverflow.com/questions/7622330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ear-javaee6 archetype doesn't allow Java files I created a new Maven Project and selected the org.codehaus.mojo.arhcetypes ear-javaee6 archetype. When I try to add a Java class to the project I get "Source folder is not a java project". So we are not supposed to add Java classes to out .ear files now. What are these guys thinking when they create a project for a .ear but don't allow for Java classes? What archetype should I use for creating Java EE 6 .ear files? A: From Wikipedia, EAR (file format): EAR (Enterprise Archive) is a file format used by Java EE for packaging one or more modules into a single archive [...] Create an EJB (ejb-javaee6 archetype) or WAR project (webapp-javaee6 archetype for example) for your java codes and refer to it from the Ear plugin configuration (and add as dependency too).
{ "language": "en", "url": "https://stackoverflow.com/questions/7622331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }