text
stringlengths
8
267k
meta
dict
Q: Calculate Totals for a column of Text Values I have a column of data that contains various string values, (Grade 01, Grade 02, Grade 03, etc...). What I would like to calculate total number of each value. Example: * *Total Grade 01 = *Total Grade 02 = *Total Grade 03 = etc.. How do I go about calculating the sum for each individual column value? Any help is greatly appreciated. A: If that's the entirety of the report: * *Group by the grade field. *Insert a summary in the group header or footer. Summarize on the grade field (in fact the field doesn't matter), and specify Count as the summary formula. *Suppress the detail section. If this is just a part of the report, insert a subreport, with no linked fields, and follow those steps in the subreport instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Execute 3 functions that return true/false and if all return true do something or else, no short circuiting I have 3 JS functions a() b() c() I want to execute all 3 and also check if all 3 return true then I want to call function yeah() or else call function boo() I can use && but it will short circuit and may not execute all 3 functions if first or second returns false So if(a() && b() && c()) { yeah(); } else { boo(); } wouldn't work! Can you suggest a better single line code? A: If you want a one-liner, you can also use & instead of &&: if(a() & b() & c()) { yeah(); } else { boo(); } Or you can do this if you want to know exactly how many functions returned true: if(a() + b() + c() == 3) { yeah(); } else { boo(); } Sample: http://jsfiddle.net/DQkpM/1/ A: A & b & c will do the trick. It will execute all three functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Enable hyperlink field in gridview while all other controls are disabled I have to disable all the controls on my gridview for business purposes. Me.gvLineItems.Enabled=False However, I need to enable one hyperlink field enabled so I tried this: For Each Row As GridViewRow In Me.gvLineItems.Rows Dim hrf As HyperLink hrf = CType(Row.Cells(16).Controls(0), HyperLink) hrf.Enabled = True Next I debug the code and it sets the hyperlink field enabled to true, but when I run the app the field is still disabled... But If I get rid of the Me.gvLineItems.Enabled=False just comment that out and change my code to DISABLE the hyperlink field: For Each Row As GridViewRow In Me.gvLineItems.Rows Dim hrf As HyperLink hrf = CType(Row.Cells(16).Controls(0), HyperLink) hrf.Enabled = False Next This works fine... But that is not what I need :(, just trying to reenable the link field... Edit I also tried this in the rowdatabound event: If Me.gvLineItems.Enabled = False Then For i As Integer = 0 To e.Row.Cells.Count - 1 If TypeOf (e.Row.Cells(i).Controls(0)) Is HyperLink Then Dim h As HyperLink = CType(e.Row.Cells(i).Controls(0), HyperLink) h.Enabled = True Exit For End If Next End If A: You'll need to use some type of recursive logic to loop through all the cells and disable the controls, with a condition to exclude HyperLink controls. By disabling the controls at the row level, the enabled state of the parent container (i.e. GridViewRow) will always override the enabled state of the control. I would add some recursive logic in the RowDataBound event. Try something like this: protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { DisableControls(e.Row); } private void DisableControls(WebControl parentCtrl) { if (parentCtrl.HasControls()) { foreach (WebControl ctrl in parentCtrl.Controls) { ctrl.Enabled = ctrl is HyperLink; DisableControls(ctrl); } } else { parentCtrl.Enabled = parentCtrl is HyperLink; } } A: I got it with this: For i As Integer = 0 To e.Row.Cells.Count - 1 If TypeOf (e.Row.Cells(i).Controls(0)) Is HyperLink Then Dim h As HyperLink = CType(e.Row.Cells(i).Controls(0), HyperLink) h.Enabled = True Exit For Else e.Row.Cells(i).Enabled = False End If Next
{ "language": "en", "url": "https://stackoverflow.com/questions/7586556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Storing workflows (state machines) in the DB. What's the best way? I am using workflow gem (htts://rubygems.org/gems/workflow), inside a RoR model (User) to model a simple state machine (actually many workflow with the same root). The state machine is hardcoded in the model, but I need a way to allow the administrators to customize the workflows. So, I think, that I have to find out a solution to store all the workflows (the state machines) to the DB. Do you know some lib or gems to do that ? (I have seen many state machines gem but they don't manage workflow stored in the tables) Many Thanks A: Don't know of any gems... but, you could use meta-programming to load how your workflows function. Let's say you could store your workflow definitions in the database. Something like: Account.new.extend_workflow(@user.account_workflows) The #extend_workflow and the account_workflows are completely custom and written by you... in this way, your Account could have custom state machine definitions and rulesets. Not for the faint of heart, but could solve your problem here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to send POST data with code in an android webview I have an android application that consists of a WebWiew and I need to login to a site automatically using code. I've tried using postUrl() and it seems to work... but only on some sites. Here's the code I'm using: public class webviewActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView webview = new WebView(this); setContentView(webview); WebSettings webSettings = webview.getSettings(); webSettings.setJavaScriptEnabled(true); webview.setWebViewClient(new WebViewClient()); String postData = "login_email=myEmail@gmail.com&login_password=myPassword"; webview.postUrl("https://www.dropbox.com/login", EncodingUtils.getBytes(postData, "utf-8")); } } This Works great for dropbox.com, but other sites like google.com, facebook.com, etc. just load the login page or give an error (google.com gives an error saying I need to enable cookies). Right now I'm just going the post data by hand; looking at the login form for the site and putting the name/value fields in the postData in my code. On sites like google, the login form has many hidden fields and I've been adding those to the postData also. If anyone could give me any idea of something I'm doing wrong please let me know, I'm pretty confused about this. A: WebView myWebView = (WebView) findViewById(R.id.webview); String url="http://www.example.org/login"; String postData= "username="+URLEncoder.encode("abc","UTF8")+ "&password="+URLEncoder.encode("***", "UTF-8"); myWebView.postUrl(url,postData.getBytes()); A: Try replacing "utf-8" (in the 2nd param) with "BASE64". A: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WebView webView = new WebView(this); setContentView(webView); String url = "http://example.com/somepage.php"; String postData = "postvar=value&postvar2=value2"; webView.postUrl(url, EncodingUtils.getBytes(postData, "base64")); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7586564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Boolean assignment in Prolog all. I want to assign a boolean value to a variable. I've tried stuff like. Diagonal is (XPiece = XFinal) Diagonal is (XPiece =:= XFinal) Diagonal is (XPiece is XFinal) None work... Any solutions? A: Prolog's built-in predicate is/2 evaluates the right-hand side of the expression as an arithmetic expression and unifies the result with the left-hand side. Also, prolog doesn't have a boolean type. Prolog's built-in types are * *integer *float *atom *unbound variable *compound term You could elect to represent a boolean value as the atoms true/false (useful for readability), or you could represent a boolean value as the integer values 1/0 (useful for computation). The way most procedural languages, like C, evaluate arithmetic values as booleans is broken WRT formal logic, though: falsity is single-valued (0) and truth multi-valued (non-zero), meaning that which is not false. In formal logic, truth is single-valued and falsity is defined as that which is not true. So you might want to consider the semantics of your representation and build some predicates to manipulate your booleans, possibly adding some operators to "extend" prolog a bit. A: Use an if-then-else: (XPiece = XFinal -> Diagonal = true ; Diagonal = false ) or use 1/0, or whatever you want. Alternatively, use CLP(FD), that supports the idiom you want: use_module(library(clpfd)). diag(XPiece, XFinal, Diagonal) :- Diagonal #= (XPiece #= XFinal). A: What about diagonal(XPiece, XFinal) :- XPiece = XFinal.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586566", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: MVC 3 Selectlist/DropDownList Is Not Updating My Model I hope someone can help with this one. I have three Model classes like this: public class Provider { public Guid ProviderId { get; set; } public string Name { get; set; } public Guid LocationId { get; set; } public virtual Location Location { get; set; } } public class Location { public Guid LocationId { get; set; } public string NameOrCode { get; set; } public string Description { get; set; } public string StreetNumber { get; set; } public string StreetAddress1 { get; set; } public string StreetAddress2 { get; set; } public string City { get; set; } public int? StateId { get; set; } public string Zip { get; set; } public string ContactPhone { get; set; } public virtual State State { get; set; } } public class State { public int StateId { get; set; } public string Name { get; set; } public string Abbreviation { get; set; } } As you can see, a Provider has a Location (separate class for reuse elsewhere), and a Location has a State (which is null until selected). My Controller looks like this for my Create methods: public class ProviderController : BaseController { private SetupContext db = new SetupContext(); // other CRUD methods ... // // GET: /Provider/Create public ActionResult Create() { Location location = new Location() { LocationId = Guid.NewGuid(), NameOrCode = Resources.BillingLocation, Description = Resources.BillingLocationDescription }; Provider provider = new Provider() { ProviderId = Guid.NewGuid(), LocationId = location.LocationId, Location = location }; ViewBag.StateId = new SelectList(db.States, "StateId", "Name", provider.Location.StateId); return View(provider); } // // POST: /Provider/Create [HttpPost] public ActionResult Create(Provider provider) { if (ModelState.IsValid) { db.Locations.Add(provider.Location); db.Providers.Add(provider); db.SaveChanges(); return RedirectToAction("Index"); } ViewBag.StateId = new SelectList(db.States, "StateId", "Name", provider.Location.StateId); return View(provider); } // other CRUD methods ... } Finally, my View looks like this: <div class="editor-label"> @Html.LabelFor(model => model.Location.StateId, @Resources.Location_State_Display_Name) </div> <div class="editor-field"> @Html.DropDownList("StateId", @Resources.ChooseFromSelectPrompt) @Html.ValidationMessageFor(model => model.Location.StateId) </div> My problem is that the state the user selects in the DropDownList never gets set on my Model on the Create POST. I have similar code in my Edit View and the state is populated correctly in that View (that is, the state associated with an existing Provider.Location shows selected in the DropDownList for the user to edit if desire), but in both the Create and the Edit Views the selection made by the user is never registered in my Model (specifically the Provider.Location.StateId) coming in from the POST. Looking at the HTML produced I see this: <div class="editor-label"> <label for="Location_StateId">State/Territory</label> </div> <div class="editor-field"> <select id="StateId" name="StateId"><option value="">[Choose]</option> <option value="1">Alabama</option> <option value="2">Alaska</option> <!-- more options ... --> </select> <span class="field-validation-valid" data-valmsg-for="Location.StateId" data-valmsg-replace="true"></span> </div> I suspect I need to somehow convey the Location.StateId relationship instead of just StateId as I see above but I can't figure out the correct syntax to do that. I've tried changing my ViewBag dynamic property to Location_StateId like this: ViewBag.Location_StateId = new SelectList(db.States, "StateId", "Name", provider.Location.StateId); And the DropDownList in my View like this: @Html.DropDownList("Location_StateId", @Resources.ChooseFromSelectPrompt) I figured then perhaps that notation would work because the label beside my DropDownList was rendered as: <div class="editor-label"> <label for="Location_StateId">State/Territory</label> </div> This attempt did not work. Can you help me out? Thanks in advance. A: @Html.DropDownList("Location.StateId", @Resources.ChooseFromSelectPrompt) Also the following line doesn't do anything useful: ViewBag.StateId = new SelectList(db.States, "StateId", "Name", provider.Location.StateId); You are assigning a SelectList to something that is supposed to be a scalar property. You probably wanted to pass the collection as ViewBag: ViewBag.States = new SelectList(db.States, "StateId", "Name", provider.Location.StateId); and then in the view: @Html.DropDownList("Location.StateId", (SelectList)ViewBag.States)
{ "language": "en", "url": "https://stackoverflow.com/questions/7586573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is a session variable stored by default in a cookie? When I use session variable for a website in PHP, is that information stored in a cookie? Or is it just on the server and it times out? I want to store information about which usergroup and security groups a person is in so I don't have to access the database each time a page is loaded. I thought I would get all that information once, store it in a session variable, and access the variable when the page loads. No passwords, just groups. It is an intranet application. Thanks. A: When I use session variable for a website in PHP, is that information stored in a cookie? No. A session id is stored in the cookie. The session variables are stored against that id on the server. A: No, that data is not stored in a cookie, it is stored on a server. The application uses a cooke, called a session token, that is sent to the server on each request to tell the server which session belongs to which client. So the cookie allows the server to keep track. Storing that data in the session is just fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Synchronous vs asynchronous ioctl in worker thread In a simple MFC application, I need to have a worker thread that constantly poll an ioctl for an event. At first, I attempted to achieve this using non-overlapped ioctl inside a while loop. The way I figured it is that if the ioctl does not complete io request immediately the thread will transfer control or context switch to another thread(the main thread or the MFC message control loop) but instead it locks up the application. In a second attempt I use an overlapped and the problem is gone. But it seems to me that the two methods are identical in behavior since I use WaitForSingleObject which waits for the event (io request to finish) to trigger. The basic layout is the following. Note that following code is incomplete and there to show only the construct Synchronous: WaitForIo { do { DeviceIoControl(hDevice,ioctl_code, ..., NULL); do something after io request completed } while(1); return; } Asynchronous: WaitForIo { do { Overlapped ov; //CreateEvent DeviceIoControl(hDevice,ioctl_code, ..., &ov); WaitForSingleObject do something after io request completed } while(1); } why is the two methods behave differently? Is there something wrong in my logic? A: If it locks the thread, it means you need to give back the processor by making it sleep or something like that. WaitForSingleObject does exactly that by default when you call it. I'm not sure about it, but I think that putting null in the DeviceIoControl function made it wait while keeping control over the thread - and so locks the thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Comparing two Wireshark capture files I want to use iperf to send some packets and receive the same at the client (which might have gone through different OSI layer processings). I want to check the packets sent are same as the received ones. * *Can I use Wireshark to capture the streams? *Is there any way to compare them with the wireshark? Or is there any other better way of doing this? A: You can use Wireshark to perform the capture, select the packets of each stream and export to text files (one per stream): File -> Export -> as "Plain Text" file: - Check "Selected packet only" - Check "Packet summary line" - Check "Packet details: All expanded" Then perform the diff with regular text tools as gnu diff, WinMerge or gvimdiff. A: * *yes you'll be able to but this will be difficult as the goal of iPerf is to send a lot of packets, the capture will include a big flow of it. *strangely there is not a diff-like tool to compare 2 captures. Instead the doc[1] propose a workaround : to merge both and stats on their diffs. NB :I wonder myself doing such a usefull tool,in addition this is in the Wireshark wishlit. [1] source : http://www.wireshark.org/docs/wsug_html_chunked/ChStatCompareCaptureFiles.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7586585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Bash process substitution and exit codes I'd like to turn the following: git status --short && (git status --short | xargs -Istr test -z str) which gets me the desired result of mirroring the output to stdout and doing a zero length check on the result into something closer to: git status --short | tee >(xargs -Istr test -z str) which unfortunately returns the exit code of tee (always zero). Is there any way to get at the exit code of the substituted process elegantly? [EDIT] I'm going with the following for now, it prevents running the same command twice but seems to beg for something better: OUT=$(git status --short) && echo "${OUT}" && test -z "${OUT}" A: Look here: $ echo xxx | tee >(xargs test -n); echo $? xxx 0 $ echo xxx | tee >(xargs test -z); echo $? xxx 0 and look here: $echo xxx | tee >(xargs test -z; echo "${PIPESTATUS[*]}") xxx 123 $echo xxx | tee >(xargs test -n; echo "${PIPESTATUS[*]}") xxx 0 Is it? See also Pipe status after command substitution A: I've been working on this for a while, and it seems that there is no way to do that with process substitution, except for resorting to inline signalling, and that can really be used only for input pipes, so I'm not going to expand on it. However, bash-4.0 provides coprocesses which can be used to replace process substitution in this context and provide clean reaping. The following snippet provided by you: git status --short | tee >(xargs -Istr test -z str) can be replaced by something alike: coproc GIT_XARGS { xargs -Istr test -z str; } { git status --short | tee; } >&${GIT_XARGS[1]} exec {GIT_XARGS[1]}>&- wait ${GIT_XARGS_PID} Now, for some explanation: The coproc call creates a new coprocess, naming it GIT_XARGS (you can use any name you like), and running the command in braces. A pair of pipes is created for the coprocess, redirecting its stdin and stdout. The coproc call sets two variables: * *${GIT_XARGS[@]} containing pipes to process' stdin and stdout, appropriately ([0] to read from stdout, [1] to write to stdin), *${GIT_XARGS_PID} containing the coprocess' PID. Afterwards, your command is run and its output is directed to the second pipe (i.e. coprocess' stdin). The cryptically looking >&${GIT_XARGS[1]} part is expanded to something like >&60 which is regular output-to-fd redirection. Please note that I needed to put your command in braces. This is because a pipeline causes subprocesses to be spawned, and they don't inherit file descriptors from the parent process. In other words, the following: git status --short | tee >&${GIT_XARGS[1]} would fail with invalid file descriptor error, since the relevant fd exists in parent process and not the spawned tee process. Putting it in brace causes bash to apply the redirection to the whole pipeline. The exec call is used to close the pipe to your coprocess. When you used process substitution, the process was spawned as part of output redirection and the pipe to it was closed immediately after the redirection no longer had effect. Since coprocess' pipe's lifetime extends beyond a single redirection, we need to close it explicitly. Closing the output pipe should cause the process to get EOF condition on stdin and terminate gracefully. We use wait to wait for its termination and reap it. wait returns the coprocess' exit status. As a last note, please note that in this case, you can't use kill to terminate the coprocess since that would alter its exit status. A: #!/bin/bash if read q < <(git status -s) then echo $q exit fi
{ "language": "en", "url": "https://stackoverflow.com/questions/7586589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Unix: traverse a directory I need to traverse a directory so starting in one directory and going deeper into difference sub directories. However I also need to be able to have access to each individual file to modify the file. Is there already a command to do this or will I have to write a script? Could someone provide some code to help me with this task? Thanks. A: The find command is just the tool for that. Its -exec flag or -print0 in combination with xargs -0 allows fine-grained control over what to do with each file. Example: Replace all foo's by bar's in all files in /tmp and subdirectories. find /tmp -type f -exec sed -i -e 's/foo/bar/' '{}' ';' A: for i in `find` ; do if [ -d $i ] ; then do something with a directory ; fi if [ -f $i ] ; then do something with a file etc. ; fi done This will return the whole tree (recursively) in the current directory in a list that the loop will go through. A: This can be easily achieved by mixing find, xargs, sed (or other file modification command). For example: $ find /path/to/base/dir -type f -name '*.properties' | xargs sed -ie '/^#/d' This will filter all files with file extension .properties. The xargs command will feed the file path generated by find command into the sed command. The sed command will delete all lines start with # in the files (feed by xargs). Command combination in this way is very flexible. For example, find command have different parameters so you can filter by user name, file size, file path (eg: under /test/ subfolder), file modification time. Another dimension of flexibility is how and what to change in your file. For ex, sed command allows you to make changes on file in applying substitution (specify via regular expressions). Similarly, you can use gzip to compress the file. And so on ... A: You would usually use the find command. On Linux, you have the GNU version, of course. It has many extra (and useful) options. Both will allow you to execute a command (eg a shell script) on the files as they are found. The exact details of how to make changes to the file depend on the change you want to make to the file. That is probably best scripted, with find running the script: POSIX or GNU: find . -type f -exec your_script '{}' + This will run your script once for a group of files with those names provided as arguments. If you want to do it one file at a time, replace the + with ';' (or \;). A: I am assuming SearchMe is the example directory name you need to traverse completely. I am also assuming, since it was not specified, the files you want to modify are all text file. Is this correct? In such scenario I would suggest using the command: find SearchMe -type f -exec vi {} \; If you are not familiar with vi editor, just use another one (nano, emacs, kate, kwrite, gedit, etc.) and it should work as well. A: Bash 4+ shopt -s globstar for file in ** do if [ -f "$file" ];then # do some processing to your file here # where the find command can't do conveniently fi done
{ "language": "en", "url": "https://stackoverflow.com/questions/7586591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert MySQL query into PostgreSQL I have this query: DROP TABLE IF EXISTS tmp_table; CREATE TEMPORARY TABLE tmp_table(id int primary key) IGNORE ( SELECT user2role.userid AS userid FROM user2role INNER JOIN users ON users.id=user2role.userid INNER JOIN role ON role.roleid=user2role.roleid WHERE role.parentrole like 'H1::H2::H3::H4::H5::%') UNION ( SELECT groupid FROM groups WHERE groupid IN (2,3,4)); This query was originally written in MySQL and instead of DROP TABLE IF EXISTS it used IF NOT EXISTS. I changed that part, but I don't know what to do about the IGNORE. First off, what is IGNORE doing? I tried looking for PostgreSQL equivalents, but they all seem to involve complicated procedures. Do I have to write a procedure for this? And if I have to write one, what would it look like? Could I just emulate IGNORE using some PHP code instead? (The SQL queries are generated by PHP.) A: You would write like this in postgres. IGNORE is irrelevant here, as the table has just been recreated and is guaranteed to be empty. And UNION guarantees there are no duplicate rows inserted. DROP TABLE IF EXISTS tmp_table; CREATE TEMP TABLE tmp_table(id int4 primary key); INSERT INTO tmp_table SELECT user2role.userid::int4 AS id FROM user2role JOIN users ON users.id = user2role.userid JOIN role ON role.roleid = user2role.roleid WHERE role.parentrole like 'H1::H2::H3::H4::H5::%' UNION SELECT groupid::int4 FROM groups WHERE groupid in (2,3,4); If duplicates in the SELECT cannot occur, you might consider the faster UNION ALL instead of UNION. Otherwise you need UNION to eliminate possible dupes. Read here. If your dataset is large you might consider creating the primary key after the INSERT. That's faster. Read the mySQL docs on effects of IGNORE. On revisiting the page I realized you mention IF NOT EXISTS in the original code. You don't say so, but that only makes sense if the original code created the table only if it didn't exist already, which introduces the possibility of it being not empty before the INSERT. In this case IGNORE is relevant and needs an equivalent in PostgreSQL. So here is alternative answer for that interpretation of your question. CREATE TEMP TABLE IF NOT EXISTS has been implemented in PostgreSQL 9.1. For older version I posted a solution on SO recently. CREATE TEMP TABLE IF NOT EXISTS tmp_table(id int4 primary key); INSERT INTO tmp_table SELECT x.id FROM ( SELECT user2role.userid::int4 AS id FROM user2role JOIN users ON users.id = user2role.userid JOIN role ON role.roleid = user2role.roleid WHERE role.parentrole like 'H1::H2::H3::H4::H5::%' UNION SELECT groupid::int4 FROM groups WHERE groupid in (2,3,4) ) x LEFT JOIN tmp_table t USING (id) WHERE t.id IS NULL; LEFT JOIN ... WHERE t.id IS NULL excludes any id that might already be present in tmp_table. UNION goes into a sub-select, so that clause needs only be applied once. Should be fastest. More on LEFT JOIN here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: x and y coordinates for drawing text on (rotated) canvas? I'm trying to drawText on a Canvas using Paint and I can't seem to figure out the proper x and y to give it. If I log the getWidth and getHeight, I can see that the View is actually giving the width and height of the rotated canvas. Thus, its something like 20 X 240. What I have is close, but I just want the text to be centered both vertically and horizontally. Any ideas on how I can do that? Here's what it looks like now: Here's my code: public class VerticalText extends View { private Paint mTextPaint; private String mText; private int mAscent; public ListLabelView(Context context) { super(context); initListLabel(); this.setBackgroundColor(Color.BLUE); } private final void initListLabel() { mTextPaint = new Paint(); mTextPaint.setStyle(Paint.Style.FILL); mTextPaint.setAntiAlias(true); mTextPaint.setTextSize(12); mTextPaint.setColor(Color.WHITE); setPadding(3, 3, 3, 3); invalidate(); } /** * sets the text to display in this label * @param text */ public void setText(String text) { mText = text; requestLayout(); invalidate(); } /** * sets the text color for this label * @param color */ public void setTextColor(int color) { mTextPaint.setColor(color); invalidate(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measureHeight(widthMeasureSpec), measureWidth(heightMeasureSpec)); } /** * Determines the width of this view * @param measureSpec A measureSpec packed into an int * @return The width of the view, honoring constraints from measureSpec */ private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text result = (int) mTextPaint.measureText(mText) + getPaddingLeft() + getPaddingRight(); if (specMode == MeasureSpec.AT_MOST) { // Respect AT_MOST value if that was what is called for by measureSpec result = Math.min(result, specSize); } } return result; } /** * Determines the height of this view * @param measureSpec A measureSpec packed into an int * @return The height of the view, honoring constraints from measureSpec */ private int measureHeight(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); mAscent = (int) mTextPaint.ascent(); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else { // Measure the text (beware: ascent is a negative number) result = (int) (-mAscent + mTextPaint.descent()) + getPaddingTop() + getPaddingBottom(); if (specMode == MeasureSpec.AT_MOST) { // Respect AT_MOST value if that was what is called for by measureSpec result = Math.min(result, specSize); } } return result; } @Override protected void onDraw(Canvas canvas) { canvas.rotate(-90, getWidth()/2, getHeight()/2); // mTextPaint.measureText(mText); Log.v("width x height:", getWidth() + " X " + getHeight()); canvas.drawText(mText, (getWidth() - (getWidth())) - 50, getHeight()/2, mTextPaint); super.onDraw(canvas); } } A: I faced the same problem. Here's what worked for me: Rect tb = new Rect(); mTextPaint.getTextBounds(mText, 0, mText.length(), tb); canvas.drawText(mText, getWidth() / 2f, getHeight() / 2f + Math.abs(tb.top) / 2f, mTextPaint); Your text should be centered: mTextPaint.setTextAlign(Align.CENTER);
{ "language": "en", "url": "https://stackoverflow.com/questions/7586597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the 4th factor in 4 factor authentication The Principle for 3-Factor authentication is Something you have (like a smartcard) Something you know (like a pin) Something you are (like a fingerprint) Then what is the 4th factor. Is it like 4D :) A: I don't think 4-factor authentication is a well defined concept - it'd just be called "multi-factor". Probably somewhere you are! You can only log in if you and device are in a certain location, for example. A: THe 4 are something you know (e.g. password), something you have (e.g. card) something you are (biometric), and more recently where you are (location). Note that one can argue biometric are really something you know (behiavorial like signature) or something you have physical (finger/face) that are simply harder to share/steal. As Mikko points out, non-revocable biometrics are weak because they cannot be cancled, new revocable ones are better. The new 4th factor, my location, is still controversial, useful when used in conjunction as others since it makes it harder to spoof when I am in say Colorado springs this am, and someone tries to authenticate as me in Nigeria this afternoon. A: Four factor authentication is a series of having 4 levels Level 1. Passwords Level 2. Smart Cards Level 3. Bio-metrics Level 4. GPS
{ "language": "en", "url": "https://stackoverflow.com/questions/7586602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Use X509Certv3 from string for WCF Service Endpoint? I have exported a key pair (public and private key) into a single cert from a Win2k8 server. I then used OpenSSL to convert it to a pem: openssl pkcs12 -in cert.pfx -out cert.pem -nodes I then put the contents of the .pem in a MSSQL table, Varchar(max) column type. Using .NET Framework 4.0 only. I get the cert like this: var bytes = Encoding.UTF8.GetBytes("certstringfromdatabase"); var cert = new X509Certificate(bytes, passwordstring); I get an error "Cryptographic Exception was unhandled Cannot find the specified object." Am I converting to byte[] incorrectly? This is for a custom WCF service with TCP binding, I am trying to use the certificate for SSL without touching the internal store (because this will be one day migrated to Azure worker role I can't use a cert store or filesystem). Thanks for all ideas. A: There is much more involved than what I was doing. Check out http://www.codeproject.com/KB/security/CertificatesToDBandBack.aspx and that's that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scala pattern matching against URLs Is there a Scala library/example that will parse a URL/URI into a case class structure for pattern matching? A: I would suggest to use the facility provided by extractors for regular expressions. For instance: val URL = """(http|ftp)://(.*)\.([a-z]+)""".r def splitURL(url : String) = url match { case URL(protocol, domain, tld) => println((protocol, domain, tld)) } splitURL("http://www.google.com") // prints (http,www.google,com) Some explanations: * *The .r method on strings (actually, on StringLikes) turns them into an instance of Regex. *Regexes define an unapplySeq method, which allows them to be used as extractors in pattern-matching (note that you have to give them a name that starts with a capital letter for this to work). *The values that are going to be passed into the binders you use in the pattern are defined by the groups (...) in the regular expression. A: You can use java's URL which can parse an URL for its different components and is completely Scala compatible. A: Here's an extractor that will get some parts out of a URL for you: object UrlyBurd { def unapply(in: java.net.URL) = Some(( in.getProtocol, in.getHost, in.getPort, in.getPath )) } val u = new java.net.URL("http://www.google.com/") u match { case UrlyBurd(protocol, host, port, path) => protocol + "://" + host + (if (port == -1) "" else ":" + port) + path } A: The following library can help you parse URIs into an instance of a case class. (Disclaimer: it is my own library) https://github.com/theon/scala-uri You parse like so: import com.github.theon.uri.Uri._ val uri:Uri = "http://example.com?one=1&two=2" It provides a DSL for building URLs with query strings: val uri = "http://example.com" ? ("one" -> 1) & ("two" -> 2)
{ "language": "en", "url": "https://stackoverflow.com/questions/7586605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Weird query: "equal slash id" (=/id) gives weird error: 501 This is the weirdest problem of my life, and can't even Google it. It's happening on an Apache powered website written in PHP, which uses mod_rewrite (but that's not the issue, I tried removing the .htaccess file, problem still exists). If I have a query string that looks exactly or similar to: =/id I get an 501 response: Method Not Implemented GET to / not supported. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request. I never written such error page, never sent an 501 response, don't have the slightest clue where this thing is coming from. Originally I had a long URL giving me a similar error, but I stripped down to this little snippet above. If I remove or change any character, the error's gone. If that helps: my website is commentards.net, and the original URL was an openid login request which looks like this: http://commentards.net/q/user/auth?openid_identifier=https://www.google.com/accounts/o8/id from which the query string is: ?openid_identifier=https://www.google.com/accounts/o8/Fid A: I asked the support team, and they said it was mod_security, and disabled it for my website. And now it works fine. I should have started with that. Anyway, thanks for your help. A: Urlencode your query string parameter(s). https://www.google.com/accounts/o8/id becomes https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2FFid http://commentards.net/q/user/auth?openid_identifier=https%3A%2F%2Fwww.google.com%2Faccounts%2Fo8%2FFid works fine, so HerrSerker already answered your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails 3 : Mass-assignment with ActiveAdmin and has_one I am developing a rails application in which I have two models User and Client. User is backed by devise and is responsible for authentication and has_one Client which holds the client details for a given user. This relation is always present as I ensure that a Client model is created whenever I create a User. For the administration area I am using ActiveAdmin. Now, when I try to create a User through the administration interface I use a form like this: form do |f| f.inputs :username, :email, :password f.inputs :name => "Client", :for => :client do |client| client.inputs :name, :address, ... end end The problem is that either the User nor the Client are saved and the page is reloaded with validation errors. I have checked rails console and there's a WARNING: Can't mass-assign protected attributes: client_attributes message every time I try to create a User. I have searched over this issue and found that in order to allow for mass-assignment one had to define attr_accessible for each of the fields allowed for the assignment. So, I had put this directive in Client model for each of the fields mentioned above and the message keeps appearing, preventing the models to be properly saved. Does anyone have a clue on this? A: The problem is not in your Client model, but in your User model - because this is the primary model you are trying to create. All you need to do is to add client_attributes to the list of attr_accessible attributes in your User model, just as the error message in the log files says, e.g.: class User < ActiveRecord::Base attr_accessible :client_attributes end I imagine you already have a list of accessible attributes in the User class. So just add client_attributes to the end of that list. The changes you made to your Client model (i.e. adding a list of attributes to attr_accessible) is not needed for this to work. If you want, you can also go ahead and undo that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Random number In C# Possible Duplicate: Random number generator not working the way I had planned (C#) I created a method that returns me a random number: public static int SelectRandomMachine(int max) { int seed = (int)DateTime.Now.Ticks; Random rndNumber = new Random(seed); int randMachine = rndNumber.Next(0, max); return randMachine; } if I call the method two times, currently it's return me the same random number: randM1 = SelectRandomMachine(maxNumber); randM2 = SelectRandomMachine(maxNumber); any suggestion would be highly appreciated. A: Hint look at this line: int seed = (int)DateTime.Now.Ticks; If you execute that line twice in quick succession, what do you think the values will be? For example: int seed1 = (int)DateTime.Now.Ticks; int seed2 = (int)DateTime.Now.Ticks; // Write it out *after* executing; console output can take a while Console.WriteLine(seed1); Console.WriteLine(seed2); See my article on randomness for solutions and more information. EDIT: Here's a quick and dirty example of the lack of thread safety causing problems: using System.Collections.Generic; using System.Threading; class Program { const int Iterations = 1000000; static readonly Random rng = new Random(); static void Main(string[] args) { List<Thread> threads = new List<Thread>(); for (int i = 0; i < 8; i++) { Thread t = new Thread(ExerciseRandom); threads.Add(t); t.Start(); } foreach (Thread t in threads) { t.Join(); } Console.WriteLine(rng.Next()); Console.WriteLine(rng.Next()); Console.WriteLine(rng.Next()); } static void ExerciseRandom() { for (int i = 0; i < Iterations; i++) { rng.Next(); } } } Output on my box: 0 0 0 A: You need to create a single instance of a Random object and call it several times. Since you are basing your seed on time (number of ticks), quick calls in succession will end up generating the same seed value, hence the pseudo-random number generator will generate the same sequence. A: Make the Random instance static: static Random rndNumber = new Random((int)DateTime.Now.Ticks); public static int SelectRandomMachine(int max) { int randMachine = rndNumber.Next(0, max); return randMachine; } A: You need to have a private static Random() and refer to it to get the random numbers, Jon and Oded are right, you can't call in quick succession. private static Random _rnd = new Random(); public static int SelectRandomMachine(int max) { //int seed = (int)DateTime.Now.Ticks; //Random rndNumber = new Random(seed); int randMachine = _rnd.Next(0, max); return randMachine; } A: Random number generators generate numbers using an algorithm. If you seed the algorithm with the same number, it will generate the same sequence of numbers. This means if you seed the rand with a number each time and then pull the first number of the sequence you will always get the same number. You need to seed the rand once and then use Next() repeatedly on the same Rand object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Open_basedir restriction oddness I'm having a problem with move_uploaded_file in PHP, with the returned error message telling me that the open_basedir restriction is in place (which I've set) and that on the path I'm attempting to write to is not within the allowed paths, but it is (and is clearly displayed on the error message). Has anyone come across this before? Edit: Sorry, the error message might help!: Unhandled Error (/var/www/vhosts/(myhost)/libs/imanager.php, 226): 2, '...move_uploaded_file() [function.move-uploaded-file]: open_basedir restriction in effect. File(/var/www/vhosts/(myhost)/httpdocs/tributes/images/precrop/1317227884228.jpg) is not within the allowed path(s): (/var/www/vhosts/(myhost)/httpdocs/tributes/images/precrop/:/tmp)...' A: Not come across this before. You can only use move_uploaded_file if the file you are trying to move was uploaded using PHP. Try removing the trailing '/' from your precrop directory in the configuration. There's some extra open_basedir information here: http://www.bigsoft.co.uk/blog/index.php/2007/12/30/fixing-php-s-require-open_basedir-restri A: There is PHP bug ("Regression (5.3.3-5.3.4) in open_basedir with a trailing forward slash"), that is triggered when open_basedir have trailing slash. As workaround remove trailing slash from path in open_basedir. This bug should be fixed in recent versions of PHP. A: Note that open_basedir will also fail if you have symlinks along the path. From http://php.net/open_basedir: All symbolic links are resolved, so it's not possible to avoid this restriction with a symlink. Please check if /var/www/vhosts/(yourhost)/httpdocs/tributes/images/precrop/ is a real directory path, not symlinked one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Line numbers do not appear in stack trace of exceptions thrown from COM+ Applications. Why? The title basically summarizes it. I have a COM+ Server Application implemented using VB.NET 2010, that was configured to gather data from its own .config file by using the procedure described in http://msdn.microsoft.com/en-us/library/windows/desktop/ms685134(v=vs.85).aspx . So far, it seems to work like a charm. And I, foolishly, assumed that should be enough for it to know where to pick the .pdb files containing debug info, and include such info when unexpected exceptions arise from it. (The .pdb files are there, btw... right next to the .dll files that comprise the COM+ Application). Looks like I was wrong, after all; all exceptions thrown from the COM+ Application show the functions being called, but not the related line numbers. Do I need to do something else in order to make my COM+ Application to return not only function names, but also line numbers in the stack trace returned by exceptions being raised on it? A: Bingo! After 1 year of intermittently looking for the answer, I think I finally found something that works. You see, as a recommended practice, MS asks you to place your COM+-exposed assemblies in the GAC. Guess what? If you place the .pdb files inside the GAC folder that contains these assemblies, all of a sudden, .NET can now find the damn .pdb files! And now all stack traces have the line numbers in them! YAY me! UNFORTUNATELY, there doesn't seem to be a way to (or tool that) places .pdb files automatically next to the .dll files in the GAC. Oh well, guess I'll have to do it on the installer... But for now, mission accomplished!
{ "language": "en", "url": "https://stackoverflow.com/questions/7586617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to create iphone adhoc release for my client, i have client's apple dev account This is my first app and apple's devel/distro profiles, certs, etc are eating my head for the last day. i could not figure out the requirements of them and how to do this obvious thing. I developed an app for my client. They have a company account at apple. In that account they have added multiple devices too. Now i want to build the app for ad hoc distribution to test on those devices. They have given me their account login too. Now i am stuck at what to do, (i have successfully added my developer account(nonpaid) to their team using the portal).. I tried many things which i cant even remember.. every time the xcode organizer shows 'invalid signing identity..' error. Any helps would be thankful.. A: If they have created a development certificate already, you will need to get the private key from them. If they have not, log in using THIER AppleID (for what you need to do it is not enough to be on the team). Create a private key and upload it to get the development certificate from the provisioning portal. Then with the development certificate sorted out, you can create an ad-hoc certificate (again you must be logged into the portal using the account they have, not your own). Download that, install it in organizer. Now in XCode4, you can run "Archive" with the "device" build selected. After that you will get an archive in the organizer, from that you can select "share" and build an IPA to distribute. A: Kendall is correct about the developer certificate. The proper terminology for ad-hoc distribution is a PROVISIONING PROFILE (Kendall refers to as "ad-hoc certificate"). This is what ties the developer certificate to the list of devices (UDID's). On iTunesConnect simply create a provisioning profile, download it, then install into your XCode project under Build Settings | Code Signing Identity | Release. Then do the Build|Archive as described already.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: selectOneMenu with primefaces 2.2.1 I have a problem with p:selectOneMenu in primefaces 2.2.1. I want to add a new component "selectoneMenu" into primefaces2.2.1.jar. Any idea please. A: The <p:selectOneMenu> is introduced in PrimeFaces 3.0. It is not present in PrimeFaces 2.2. So you have 2 options: * *Upgrade to PrimeFaces 3.0 (warning: it's still in development and not stable!) *Just use standard JSF <h:selectOneMenu>.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Read a local HTML file with Mechanize I am building a crawler, I know how to use ruby mechanize to read a page from the net using this code: require 'mechanize' agent = Mechanize.new agent.get "http://google.com" But can I use Mechanize to read an HTML file from the file system? How? A: I was unable to get the file:// protocol to work correctly for me. Instead I used Fakeweb by saving a web page locally and registering the URI stream = File.read("saved_google_page.html") FakeWeb.register_uri(:get, "http://www.google.com", :body => stream, :content_type => "text/html") and having Fakeweb return it behind the scenes with a normal Mechanize process agent = Mechanize.New page = agent.get("http://www.google.com/") See How to test a ruby application which uses mechanize A: just using the file:// protocol worked great for me: html_dir = File.dirname(__FILE__) page = agent.get("file:///#{html_dir}/example-file.html") and about the raised question why someone would use mechanize to read local html files: I found it necessary for testing purposes - just store an example file locally and run your rspec against it. A: Basing on @Stephens answer; as fakeweb wasnt updated for a longer while and the maintainer situation is unclear, here an answer working around the issue using webmock, for whoever is in a hurry: require 'webmock' include WebMock::API WebMock.enable! stub_request(:get, "www.example.com").to_return(body: File.read("page.html")) agent = Mechanize.New page = agent.get("http://www.example.com/") # ... A: IMHO it doesn't make sense trying to use mechanize for such a situation. Maybe you would like to parse HTML. Then try nokogiri (mechanize uses it for parsing too) e.g. use Nokogiri::HTML(open('index.html')) instead of session.get('http://www.google.com')
{ "language": "en", "url": "https://stackoverflow.com/questions/7586627", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: strip_tags() giving "can't use function return value in write context" when not writing I got the error Can't use function return value in write context when trying to do assignment with empty(strip_tags($string)) as the conditional in a ternary statement. So for testing, I got rid of the assignment and the ternary statement. But I'm still getting this error when it's apparently not in a write context. Come to think of it, I'm not sure what write context means -- I thought it had to do with assignment, but I can't say that I know that for sure. Why doesn't this work like I think it should? It seems pretty straight-forward to me. What am I missing? $ cat test.php <? $string = "<br/>"; if ( empty(strip_tags($string)) ) { echo "It's empty.\n"; } else { echo "It's not empty.\n"; } $ php test.php PHP Fatal error: Can't use function return value in write context in test.php on line 5 A: empty() is requiring you to act on a variable, rather than the output of a function. Instead, store the output of strip_tags() into a variable. $stripped = strip_tags($string); if ( empty($stripped) ) { echo "It's empty.\n"; } else { echo "It's not empty.\n"; } This is explained in the empty() documentation: Note: empty() only checks variables as anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). A: empty requires a variable. You pass a function return value, that's different. You can work around that by putting it into brackets: if ( empty((strip_tags($string))) ) { But better do like Michael wrote, this suggestion is some kind of a dirty hack. If interested, has been discussed in Parentheses altering semantics of function call result and the PHP Bug Report: #55222 Fatal Error disappears when using paranthesis.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Implementing explicit interface members with generics I have a nongeneric interface to a generic class group. I have a method which uses covariance to return a strongly typed instance in a class derived from an abstract implementation of the non-generic class group. So basically with this setup, I have a number of classes, e.g. ActualThing1 and ActualThing2. These classes have a Clone method which returns a strongly-typed clone of themselves. Below is how I've structured the interface & classes. I am not sure this is right. Normally, I wouldn't have the non-generic abstract class at all. But this is necessary because there is a situation where I have to do something to child objects, referencing an internal method _SomethingNeededInternally. This can't be done using the interface, since it's protected, nor can it be done from inside the generic class, since the children might not be the same type (they might be a different type derived from the interface). Hence the non-generic base class Something. This works, but what doesn't quite make sense to me is the explicit implementation of ISomething.Clone that is needed in my abstract Something class. It has to be there, but it shouldn't be implemented, since I want that implementation deferred to the generic class that derives from it. But there's no such syntax as abstract ISomething ISomething.Clone(). But that code (where the exception is throw) can't ever execute, can it, since I don't have any non-generic implementations of this object? I guess I'm wondering if there is a better way to do this, because it seems not right. That is, I am depending on the fact that a non-generic class is never created from the interface, which smells funny. public interface ISomething { // ... ISomething Clone(); } public abstract class Something: ISomething { ISomething ISomething.Clone() { throw new Exception("This should not be happening"); } protected int _SomethingNeededInternally; } public abstract class Something<T>: Something, ISomething where T: ISomething, new() { public abstract T Clone(); ISomething ISomething.Clone() { return Clone(); } } public interface IActualThing {} // this could be any interface public class ActualThing: Something<ActualThing>, IActualThing { public override ActualThing Clone() { return new ActualThing(); // do cloning here } } A: Would adding required method as implementation of Clone work for you? (I'm still not exactly sure what your whole problem is, this will just solve syntax for abstract explicit interface implementation.) public abstract class Something: ISomething { ISomething ISomething.Clone() { return CloneYouMust(); } abstract ISomething CloneYouMust(); } A: I think this might work better: public interface ISomething { ISomething Clone(); } public abstract class Something : ISomething { protected abstract ISomething CloneInternal(); ISomething ISomething.Clone() { return CloneInternal(); } } public abstract class Something<T>: Something, ISomething where T: ISomething, new() { protected override ISomething CloneInternal() { return Clone(); } public abstract T Clone(); } public class ActualThing: Something<ActualThing>, IActualThing { public override ActualThing Clone() { } } A: First of all, I think that having two Clone() methods inside Something<T> is redundant. Since you've already constrained T to both being an ISomething and new(), why not do this: public abstract class Something<T>: Something, ISomething where T: ISomething, new() { public override ISomething Clone() { return new T().Clone(); //alternatively may have to use Activator.CreateInstance() here } } Secondly I'm not entirely clear on whether _SomethingNeededInternally needs to be abstract or virtual, but it isnt marked either. My interpretation is that it should be virtual, but maybe you'll need to tweak that. Anyway here is the overall scheme that seems to work well for me and make the most sense. Note that I was able to make the Clone() method abstract in the abstract class 'Something': public interface IActualThing { } public interface ISomething { ISomething Clone(); } public abstract class Something: ISomething { public abstract ISomething Clone(); protected virtual void _SomethingNeededInternally() { throw new NotImplementedException(); } } public abstract class Something<T>: Something, ISomething where T: ISomething, new() { public override ISomething Clone() { return new T().Clone(); } } public class ActualThing: Something<ActualThing>, IActualThing { public override ISomething Clone() { throw new NotImplementedException(); } } Also note that you need to mark the return type as ISomething in the final 'ActualThing' class. Of course you would be returning an 'ActualThing' in reality, but the method needs to conform to the interface nevertheless. A: Your complaint about abstract ISomething ISomething.Clone is valid but there's nothing about interfaces that states you must explicitly declare them. The code below shows a working example and removes the requirement of the generic class. interface Igloo { Igloo Clone(); } abstract class Alpha : Igloo { public abstract Igloo Clone(); } class Bravo : Alpha { public override Igloo Clone() { /* implement */ return null; } } A: I would suggest that you define and implement interfaces ISelf<T>, containing a single Self property of type T, and ICloneable<out T>, deriving from ISelf<T>, with a method Clone() of type T. Then a class which implements ICloneable<ItsOwnType> can implement it with a method returning ItsOwnType; that method should call then a virtual InternalClone method to do the actual work (otherwise, calling Clone on a variable of base type might end up calling the base-type Clone method rather than a derived one).
{ "language": "en", "url": "https://stackoverflow.com/questions/7586629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Looking for a good boolean algebra library I'm writing a tool that deals with some boolean algebra. It's basically a tool to create a state machine based on a user-defined file that contains state names, conditions, and transition information. The method by which state transitions occur is to basically look at a boolean logic table. e.g. transition from State1 to State2 if: (A & B) | (C & ~D) | (E) I've got this all implemented, but now I need to add the ability to do some fun stuff like inverting the whole shebang: ~((A & B) | (C & ~D) | (E)) = (via DeMorgan) (~A & ~C & ~E) | (~A & D & ~E) | (~B & ~C & ~E) | (~B & D & ~E) The result must be in Disjunctive Normal Form. Basically, I don't want to write this myself and I'm hoping there's a library somewhere that knows how to deal with stuff like this. I've come across SymPy, but I'm not sure if there is a boolean algebra module. My app is written in C (probably shouldn't be), but anything will help. A: Rather than incorporate code, I found a few great applications that are free for any use (via the University of California). A tool called Logic Friday has a nice front end to a few other applications: misii and espresso (included in the install), that perform symbolic Boolean algebra. There isn't a great command line interface, but you can pass files around to do the job. This performs the minimization I was looking for. A: You can try out this open source project, although its not a library you can just copy the Boolean Algebra Class to add to your project
{ "language": "en", "url": "https://stackoverflow.com/questions/7586634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Accessing a NSMutableArray from another class I have a NSMutableArray and I need to access it from another class. This is what I have done so far; * *I declared NSMutableArray *muArr in the .h file, and @property(nonatomic, retain) NSMutableArray *muArr. *@synthasize muArr; in the .m file, and finally populated it: [muArr addObject: @"First"]; *Now in SecondView I added the import statement #import "FirstView.h" and wrote: FirstView *frv = [[FirstView alloc]init]; then NSLog(@"%i",[frv.muArr count]); These lines of code are written in the viewDidLoad method. and when the NSLog was printed I got 0 records instead of 1. Why is this? what have I done wrong, and can someone show me a sample code/tutorial? A: You are populating muArr in didSelectRowAtIndexPath, which doesn't get called until you select a row. By calling init on your FirstView, you create a new FirstView then immediately check the count of muArr. The count is 0, because you haven't selected any rows yet.. A: You need to create a property(in the same fashion as you create muArr) in SecondView class Step 1) : Lets say arrOfSecondView and you synthesize it Step 2) Now you can add your muArr data to arrOfSecondView SecondView *secondView = [[SecondView alloc]init]; secondView .arrOfFirstView = muArr; //and i guess you are pushing to secondView controller Step 3) Check the arrOfFirstView count A: Do you allocate the array? Before you add items to it, you have to allocate it with myArr = [[NSMutableArray alloc] init]; If you don't do that, the [addObject] call will not crash the program, but won't have any effect. And array's count will remain zero forever. @synthesize, contrary to a popular belief, does not allocate the ivar. It just generates a getter method and, optionally, a setter method in the class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586636", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Horizontal Scroll View Width in Android? How can I set a width for Horizontal Scroll View? myHorizontalScrollView.setWidth(); This doesnt appear to work, I need to limit the scroll views width. A: ViewGroup.LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT ,LayoutParams.FILL_PARENT); myHScrollView.setLayoutParams(lp); You can set the width and height using the layout parameters object. To set exact number as width you need to use the TypedValue class int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, (float) 200, getResources().getDisplayMetrics()); And the int should be set in the LayoutParams constructor. A: ViewGroup.LayoutParams lp = new LayoutParams(width ,height); myHScrollView.setLayoutParams(lp); Also you can set width and height to wrap_content and fill_parent A: Set your scrollview to fill the parent's width and make that parent 200dp wide
{ "language": "en", "url": "https://stackoverflow.com/questions/7586637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Unexpected result using WebDriver's findelements(By.cssSelector) method in loop I am using WebDriver to verify elements on a page by css selector. With the following method 'checkTablesByHeader' that I have created. public static void checkTablesByHeader(WebDriver driver, String[] columnHeaderValues, String tableID, String selector){ String elementSelector = "#" + tableID + " "+selector; List<WebElement> elements = driver.findElements(By.cssSelector(elementSelector)); int i = 0; for (WebElement e : elements){ Assert.assertTrue(e.getText().contains(columnHeaderValues[i])); i++; } My problem lies with using this method in a loop as seen below. The first pass works perfectly and only grabs nine elements in the List. The second pass should have the same exact number, but is returning 300 + elements. I am doing this because I have tables that have very similar structure, but only different ids. I have checked and rechecked that the id on the second pass can only possibly return 9 elements with the current code. for(int i=1; i<6; i++){ SeleniumUtil.checkTablesByHeader(driver, stringArrayNine, ("mqContent_a_" + i), "th"); } Anyone have any ideas? Thank you in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook api not working in subdirectories Trying to plug in the new login api from a test script in a subdirectory of my site, and seeing that when I call getUser() I'm getting back a Facebook user id of 0. When I move the same script into my domain root, I get what I expect - my FB uid. This obviously puts me at a serious disadvantage as far as testing goes. Is it possible to use the new api from a subdirectory, and if so, what do I need to do?
{ "language": "en", "url": "https://stackoverflow.com/questions/7586642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MongoDb Norm serialization I know this is subjective, but how good is the norm serializer, particularly related to serialization of complex objects that are cyclic. Essentially I have big chunk of deserialized xml message, coming in over the wire, several hundred times a minute, which has some 47 or 57 classes when deserialized. Would Norm be able to handle it, in a normal run of the mill fashion. Any experiences to share would be welcome. Bob. A: NoRM is no longer being actively maintained. I used the 10gen C# provider instead and it dealt with very deep cyclic serialization easily. I recommend it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Backbone problem with this object This is my View in Backbone framework: jQuery(document)ready(function() { com.company.View = Backbone.View.extend({ initialize : function() { myCollection.bind('add', this.onSuccess); }, onSuccess : function(model) { // do something this.somethingElse(); }, somethingElse : function() { // do something else } }); }); Now the problem is inside onSuccess function the this object doesn't belong to the View anymore, it belongs to model. So, when I call this.somethingElse() I got undefined. How can I successfully call this.somethingElse inside onSuccess? A: The problem is you're relying on this to point to the original object. Unlike many languages this in Javascript changes based on the manner in which a method is called. Often in a callback it's invoked with this pointing to a different object or simply none at all (undefined). One way to work around this is to remove the reliance on this in favor of a function local variable which can't be interferred with. For example com.company.View = Backbone.View.extend( return function() { var self = {} self.initialize = function() { myCollection.bind('add', self.onSuccess); }; self.onSuccess = function(model) { // do something self.somethingElse(); }; self.somethingElse = function() { // do something else }; return self; }(); }); A: You want to bind your function to the context of the View object. In initialize, do this: initialize : function() { _.bindAll(this, "onSuccess"); myCollection.bind('add', this.onSuccess); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7586655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to display MSSQL varbinary(3072) image in PHP? I have an bitmap image stored in MSSQL, datatype of the column is varbinary(3072). All I want to do with the image in PHP is to display it + store it into a file. How to do that? Couldn't find anything useful on Google nor here on SO. Only thing I have found is usage of some framework - that's not what I want. Here is an example image: 0x444453207C0000000710080010000000100000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000400000044585431000000000000000000000000000000000000000000000000000000000000000000000000000000001B021A02555555551B021A02555555551B021A02555555551B021A02555555559DBFA7110D3FD555FFFF115E02080F05FEDF4E03C0A0E070555DE819635EFAC3F69DE609DC706BEFFCBFA4010B0BADDDFBC74F4458B808A8B475271A60ACA67757AFA9335F7E5456ED3345091BA280A058972C3BE063E9F5104D683A55FD8383 A: Well, here is the answer (thx NullUserException ఠ_ఠ): header('Content-Type: image/bmp'); $h2 = '424D36030000000000003600000028000000100000001000000001001800000000000003000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA0D2FD3BA5FC39A9FC4BABFC77BDFD50ADFC38A5FC37A5FC4DACFC87C6FDE3F2FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDBEEFE39A3FC4CCDFE56D7FE3FC0FD57D8FE61E3FF61E3FF59DAFE3DBDFD289DFBABD7FEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF91CAFD2BAAFC6CEFFF6BEDFF46C4E83AB6E13AB6E140BDE46CEEFF59DBFE209EFCACD7FEFFFFFFFFFFFFFFFFFFEBF6FF30A0FB55D6FE63E5FC28A2D528A2D539B6E139B6E11C94CD1287C565E7FC5ADBFE249AFBE5F3FFFFFFFFFFFFFF93CBFD3ABAFD6CEEFF28A2D555D5F466E8FF66E8FF66E8FF66E8FF49C8EC1C94CD6CEEFF3DBDFD86C5FDFFFFFFFFFFFF52AEFC55D6FE69ECFF66E8FF66E8FF66E8FF66E8FF66E8FF66E8FF66E8FF44C2E869EBFF58DAFE4BABFCFFFFFFFFFFFF37A4FC5FE1FF68EAFF8CEEFFD9F9FFBCF5FF66E8FF66E8FFBCF5FFD9F9FF8CEEFF67E9FF62E3FF35A4FBFFFFFFFFFFFF36A3FC5FE1FF7AEDFFFFFFFF6F6F6F5F5F5F9FF1FF9FF1FF6F6F6F4F4F4FFFFFFF79ECFF61E3FF36A5FBFFFFFFFFFFFF54AFFC54D5FE85F0FFFFFFFF0F0F0F000000A9F2FFA9F2FF0F0F0F000000EFEFEF85EFFF58D9FE4CACFCFFFFFFFFFFFF97CDFD38B8FD6CEEFFF5FEFF9F9F9F9F9F9F82ECFF82ECFF9F9F9F8F8F8FF5FEFF6CEEFF3BBBFD8AC7FDFFFFFFFFFFFFEDF7FF2B9CFB50C9EF6CB5BFACE5EFB2F3FF66E8FF66E8FF95EFFFB2F3FF86F1FF58D9FE269AFBE8F4FFFFFFFFFFFFFFFFFFFFBBDFFE1C7FCD0000000E1E2049A3B068EAFF5BCEE050B2C03D87901029301B80CEB5DCFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBADEFE165A951C5C7F35869F59D4F0429BB015364019526F135286B2DAFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFECF6FF98CDFD57B0FC38A4FC37A4FC55AFFC93CBFDEAF5FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF'; $s = pack('H*', strtolower($h2)); echo $s; The only problem is that the image I posted seems to be in some strange format.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: SSH error? - PTY allocation request failed on channel 0 [OSX 10.7.1 Lion] I've connected to this server many times before so I'm not sure why I'm getting this error. I did a verbose to get some further details it seems as though there's something wrong with my key but I'm really doubtful that's what it is. ~/key $ sudo ssh -vvv -i pinnacle.pem ec2-user@ec2-50-16-112-153.compute-1.amazonaws.com OpenSSH_5.6p1, OpenSSL 0.9.8r 8 Feb 2011 debug1: Reading configuration data /etc/ssh_config debug1: Applying options for * debug2: ssh_connect: needpriv 0 debug1: Connecting to ec2-50-16-112-153.compute-1.amazonaws.com http://50.16.112.153 port 22. debug1: Connection established. debug1: permanently_set_uid: 0/0 debug3: Not a RSA1 key file pinnacle.pem. debug2: key_type_from_name: unknown key type '-----BEGIN' debug3: key_read: missing keytype debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug3: key_read: missing whitespace debug2: key_type_from_name: unknown key type '-----END' debug3: key_read: missing keytype debug1: identity file pinnacle.pem type -1 debug1: identity file pinnacle.pem-cert type -1 debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3 debug1: match: OpenSSH_5.3 pat OpenSSH* debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_5.6 debug2: fd 3 setting O_NONBLOCK debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1 debug2: kex_parse_kexinit: ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-dss-cert-v00@openssh.com,ssh-rsa,ssh-dss debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96 debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96 debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib debug2: kex_parse_kexinit: none,zlib@openssh.com,zlib debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: first_kex_follows 0 debug2: kex_parse_kexinit: reserved 0 debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1 debug2: kex_parse_kexinit: ssh-rsa,ssh-dss debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96 debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96 debug2: kex_parse_kexinit: none,zlib@openssh.com debug2: kex_parse_kexinit: none,zlib@openssh.com debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: debug2: kex_parse_kexinit: first_kex_follows 0 debug2: kex_parse_kexinit: reserved 0 debug2: mac_setup: found hmac-md5 debug1: kex: server->client aes128-ctr hmac-md5 none debug2: mac_setup: found hmac-md5 debug1: kex: client->server aes128-ctr hmac-md5 none debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP debug2: dh_gen_key: priv key bits set: 127/256 debug2: bits set: 515/1024 debug1: SSH2_MSG_KEX_DH_GEX_INIT sent debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY debug3: check_host_in_hostfile: host ec2-50-16-112-153.compute-1.amazonaws.com filename /var/root/.ssh/known_hosts debug3: check_host_in_hostfile: host ec2-50-16-112-153.compute-1.amazonaws.com filename /var/root/.ssh/known_hosts debug3: check_host_in_hostfile: match line 1 debug3: check_host_in_hostfile: host 50.16.112.153 filename /var/root/.ssh/known_hosts debug3: check_host_in_hostfile: host 50.16.112.153 filename /var/root/.ssh/known_hosts debug3: check_host_in_hostfile: match line 1 debug1: Host 'ec2-50-16-112-153.compute-1.amazonaws.com' is known and matches the RSA host key. debug1: Found key in /var/root/.ssh/known_hosts:1 debug2: bits set: 510/1024 debug1: ssh_rsa_verify: signature correct debug2: kex_derive_keys debug2: set_newkeys: mode 1 debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug2: set_newkeys: mode 0 debug1: SSH2_MSG_NEWKEYS received debug1: Roaming not allowed by server debug1: SSH2_MSG_SERVICE_REQUEST sent debug2: service_accept: ssh-userauth debug1: SSH2_MSG_SERVICE_ACCEPT received debug2: key: /Users/jwmann/.ssh/id_rsa (0x101724f30) debug2: key: /Users/jwmann/key/pinnacle/james (0x101725540) debug2: key: pinnacle.pem (0x0) debug1: Authentications that can continue: publickey debug3: start over, passed a different list publickey debug3: preferred publickey,keyboard-interactive,password debug3: authmethod_lookup publickey debug3: remaining preferred: keyboard-interactive,password debug3: authmethod_is_enabled publickey debug1: Next authentication method: publickey debug1: Offering RSA public key: /Users/jwmann/.ssh/id_rsa debug3: send_pubkey_test debug2: we sent a publickey packet, wait for reply debug1: Remote: Forced command: /home/ec2-user/bin/gl-auth-command jwmann debug1: Remote: Port forwarding disabled. debug1: Remote: X11 forwarding disabled. debug1: Remote: Agent forwarding disabled. debug1: Remote: Pty allocation disabled. debug1: Server accepts key: pkalg ssh-rsa blen 277 debug2: input_userauth_pk_ok: fp 64:37:c3:30:c5:72:0b:e3:94:0b:0f:6f:40:5d:bf:78 debug3: sign_and_send_pubkey: RSA 64:37:c3:30:c5:72:0b:e3:94:0b:0f:6f:40:5d:bf:78 debug1: Remote: Forced command: /home/ec2-user/bin/gl-auth-command jwmann debug1: Remote: Port forwarding disabled. debug1: Remote: X11 forwarding disabled. debug1: Remote: Agent forwarding disabled. debug1: Remote: Pty allocation disabled. debug1: Authentication succeeded (publickey). Authenticated to ec2-50-16-112-153.compute-1.amazonaws.com (http://50.16.112.153:22). debug1: channel 0: new client-session debug3: ssh_session2_open: channel_new: 0 debug2: channel 0: send open debug1: Requesting no-more-sessions@openssh.com debug1: Entering interactive session. debug2: callback start debug2: client_session2_setup: id 0 debug2: channel 0: request pty-req confirm 1 debug1: Sending environment. debug3: Ignored env TERM debug3: Ignored env SSH_AUTH_SOCK debug3: Ignored env __CF_USER_TEXT_ENCODING debug3: Ignored env PATH debug1: Sending env LANG = en_CA.UTF-8 debug2: channel 0: request env confirm 0 debug3: Ignored env HOME debug3: Ignored env DISPLAY debug3: Ignored env SHELL debug3: Ignored env LOGNAME debug3: Ignored env USER debug3: Ignored env USERNAME debug3: Ignored env MAIL debug3: Ignored env SUDO_COMMAND debug3: Ignored env SUDO_USER debug3: Ignored env SUDO_UID debug3: Ignored env SUDO_GID debug2: channel 0: request shell confirm 1 debug2: fd 3 setting TCP_NODELAY debug2: callback done debug2: channel 0: open confirm rwindow 0 rmax 32768 debug2: channel_input_status_confirm: type 100 id 0 PTY allocation request failed on channel 0 Anybody have an idea? A: How did you generate your key? GitHub has a tutorial on generating SSH keys. The exact command would be: ssh-keygen -t rsa -C "your_email@youremail.com" I'm not sure what type of encryption your service is using (as you can see, this command uses rsa), so you'd need to adjust it to your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Count items in datasource of gridview (.net) I have a GridView and bind a list to it: List<T> items = T.GetItems(); GridView.DataSource = items.OrderBy(x => x.SomeValue); GridView.DataBind(); Now in the process of databinding, I would like to access the total number of items in the datasource. protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e) { //access total number of datasource items } GridView.Rows or GridView.DataKeys is no help because the gridview is being built at this point. Of course, I could use items.Count() but I would prefer to access the underlying datasource directly. Update The solutions posted work without the OrderBy statement which I included later. A: protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e) { var count = ((ICollection<T>)GridView.DataSource).Count; } A: I guess you could access the count of items by doing something like below: int count = (GridView1.DataSource as List<T>).Count; Hope this Helps!! Edit 1: Added full method used. protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { int count = (GridView1.DataSource as List<string>).Count; } A: With my update included, the items count can be accessed with var count = ((IEnumerable<T>)GridView.DataSource).Count();
{ "language": "en", "url": "https://stackoverflow.com/questions/7586663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where do I get the device token that Urban Airship requires for iOS registration? From the online API: An HTTP PUT to /api/device_tokens/ registers a device token on our end. This lets us know that the device token is active, and should happen every time the application is opened to ensure that the list of device tokens remains up-to-date. How do I go about acquiring the device token in the first place? A: I believe you need to look here: implement the application:didRegisterForRemoteNotificationsWithDeviceToken method to receive the device token. EDIT: the Urban Airship guide is at http://urbanairship.com/docs/apns_test_client.html. EDIT: The only way to send an APNS message is using the device token: you have to pass the device token back to whichever non-Apple server is the origination point for the notification. There are 3 logical entities in the transaction: the device, the APNS server (Apple's backend), and the originating server (in this case Urban Airship's server). The device and Apple's backend have the token already (or can generate it). The Urban Airship server only gets that token when you send it to them from the device. It can then use that token to communicate with the APNS backend and identify the device. What you do is you use the application:didRegisterForRemoteNotificationsWithDeviceToken callback and then you send (via HTTP, or whatever other wire protocol you so choose) that token to the originating server (the Urban Airship docs show you how do that with their library). Their server can now use that token to communicate with the APNS backend. A: To get the device token, you have a few options: Option 1 You can find it as one of the arguments sent in your app delegate's application:didRegisterForRemoteNotificationsWithDeviceToken: method. Option 2 You can get it as an NSString by calling [[UAPush shared] deviceToken] after your device has successfully registered for remote notifications. Option 3 If you don't have access to the code. You can find it by reading your app's calls to urban airship. You can do this with Charles proxy. Full instructions at this link. To sum it up: * *Install the Charles certificate on your iOS device be going to http://charlesproxy.com/charles.crt in safari on your device. *Proxy your device's wireless connection through Charles *Enable SSL Proxying in Charles for *.urbanairship.com on port 443. *Run your app and look for calls to urls that mention "urbanairship" that have been recorded in Charles. They should be decrypted and some will include info about your device token.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to ensure that only one XMPPConnection will be created? Use singletons? I'm dealing with creating a web service which will receive requests to send messages via XMPP. However, all messages will be sent from one account (the server logs in and sends notifications to users). Here comes the problem - how to implement it? I was trying to implement the XMPPConnection class as a singleton, but I got stuck at passing arguments to constructors containing the hostname, port, JID etc As I've read here, a singleton with parameters is not a singleton... Hence, I thought about solving it as follows (is it some kind of factory?): public class XMPPConnectionSingleton { private volatile static XMPPConnectionSingleton anInstance; private volatile static XMPPConnection connection; public static XMPPConnectionSingleton getInstance() { if(anInstance == null) { synchronized (XMPPConnectionSingleton.class) { if(anInstance == null) anInstance = new XMPPConnectionSingleton(); } } return anInstance; } public void init(String server, int port, String jid, String password, String resource) { ConnectionConfiguration conf = new ConnectionConfiguration(server, port); connection = new XMPPConnection(conf); // logging in, etc. } } Is it a good way to go? Or maybe it is better to make a wrapping class for XMPPConnection, accepting a constructor with no parameters? A: You can use a ~singleton, read this question and the related pages here and here. The cleanest is to initialize in a static block, but that is obiously not always possible. The obious, simple, approach is to synchronize on a single instance and all WS calls wait. This will work great for low capacity. Using ReentrantLock might enhance that logic somewhat - for example sending a timeout WS reponse rather than having the whole HTTP call out. If you need many concurrent sessions, consider checking out whether the server can log in with multiple clients and then initialize as many clients as you want - then use the ReentrantLock in some way to determine which is currently free. Depending on the logic in your WS calls (does it need confirmation that message is sent to XMPP?) you might consider queueing up the calls and serving them from another thread, returning the WS call before the actual message is sent (http hold time is normally 30 second, but can be changed). Might even be possible to let each WS session connect and have its own session for the duration of the call. Edit:I suggest you go with // Correct lazy initialization in Java @ThreadSafe class Foo { private static class HelperHolder { public static Helper helper = new Helper(); } public static Helper getHelper() { return HelperHolder.helper; } } where Helper is * *a helper class which pull the login info from somewhere, wraps the XMPP client class, or *the XMPP client class itself with hardcoded login info. Then simply use synchronized operator on the returned object. A: It sounds to me like the wrong approach altogether. Why not simply have the WS requests put in a queue and have a single thread read the requests and write the messages via xmpp. There would only be a single connection, but there is no need to create any custom code to create a singleton connection at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: quick-sorts iterator requirements tl;dr: Is it is possible to implement quicksort on a doubly linked list efficiently? My understanding before thinking about it was, no, its not. The other day I had an opportunity to consider the iterator requirements for the basic sorting algorithms. The basic O(N²) ones are fairly straightforward. * *Bubble sort - 2 forward iterators will do nicely, one dragging after the other. *Insertion sort - 2 bidirectional iterators will do. One for the out-of-order element, one for the insertion point. *Selection sort - A little bit trickier but forward iterators can do the trick. Quicksort The introsort_loop in std::sort (as in the gnu standard library/ hp(1994) / silicon graphics(1996) ) requires it to be random_access. __introsort_loop(_RandomAccessIterator __first, _RandomAccessIterator __last, _Size __depth_limit, _Compare __comp) As I have come to expect. Now upon closer inspection I cant find the real reason to require this for quicksort. The only thing that explicitly requires random_access_iterators is the std::__median call that requires the middle element to be calculated. The regular, vanilla quicksort does not calculate the median. The partitioning consists of a check if (!(__first < __last)) return __first; Not really a useful check for bidirectionals. However one should be able to replace this with a check in the previous partitioning travel (from left to right/ right to left) with a simple condition of if ( __first == __last ) this_partitioning_is_done = true; Is it possible to implement quicksort fairly efficiently using only bidirectional iterators? The recursive depth can still be guarded. NB. I have yet not attempted an actual implementation. A: You need random access iterators because you typically want to pick the pivot element from the middle of the list. If you choose the first or last element as the pivot instead, bidirectional iterators are sufficient, but then Quicksort degenerates to O(n^2) for pre-sorted lists. A: tl;dr: Yes As you say, the problem is to find the pivot element, which is the element in the middle, finding this with random access takes O(1), finding it with bidirectional iterators takes O(n) (n/2 operations, to be precise). However, in each step you have to create to sub containers, the left and the right containing smaller and bigger numbers respectively. This is where the main work of quick sort takes place, right? Now, when building the sub containers (for the recursion step) my approach would be to create an iterator h pointing to their respective front element. Now whenever you choose a next element to go to the sub container, simply advance h every second time. This will have h point to the pivot element once you are ready to descend to the new recursion step. You only have to find the first pivot which does not matter really, because O(n log n + n/2) = O(n log n). Actually this is just a runtime optimisation, but has no impact on the complexity, because whether you iterate over the list once (to put each value in the respective sub container) or twice (to find the pivot and then put each value in the respective sub container) is all the same: O(2n) = O(n). It's simply a question of execution time (not complexity). A: There's absolutely no problem with implementing quick-sort strategy on a doubly-linked list. (I think it can also be easily adapted to a singly-linked list as well). The only place in the traditional quick-sort algorithm that depends on the random-access requirement is the setup phase that uses something "tricky" to select the pivot element. In reality all these "tricks" are nothing more than just heuristics that can be replaced with pretty much equally effective sequential methods. I have implemented quick-sort for linked lists before. There's nothing special about it, you just need to pay close attention to the proper element relinking. As you probably understand, large part of the value of list-sorting algorithms comes from the fact that you can reorder elements by relinking, instead of explicit value-swapping. Not only it could be faster, it also (and often - more importantly) preserves the value-validity of external references that might be attached to the elements of the list. P.S. However, I'd say that for linked lists the merge-sort algorithm results in a significantly more elegant implementation, which has equally good performance (unless you are dealing with some cases that perform better with quick-sort specifically).
{ "language": "en", "url": "https://stackoverflow.com/questions/7586674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Adjust Text Field Size Based on current language iOS Is it possible to dynamically set the size of a text field, button or other visual atributes based on the current user selected language? Code sample would be great! Thanks for the help A: You can easily adjust the size of a text field, for example depending on the text it contains. NSString *localizedText; textField.text = localizedText; [textField sizeToFit]; textField.text = @""; You can generate localizedText dynamically with methods such as stringFromDate etc. or keep an NSDictionary with appropriate strings and the locales as keys.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create non English directories in PHP I want to be able to create folders for the registered users under their names. Their info is stored in my db in Cyrillic characters and pulled from their when creating the folder. The thing is if the info is in English everything is ok, if in Cyrillic I get something like Кульчманова. Everything is set to utf-8. If I set folder name to i.e 'фыва' it creates it no problem. $this->load->model('users_model'); $i=$this->session->userdata('uid'); $new_name=$this->input->post('doc_name'); $folder=$this->users_model->getFullName($i); //$folder='фыва' works fine if(!is_dir("./uploads/".$folder)){ mkdir("./uploads/".$folder , 0777); } $config['file_name'] = $new_name; $config['upload_path'] = './uploads/'.$folder.'/'; Will appreciate any help A: I strongly recommend you to use only plain ASCII characters in directory names on servers, or even better: only numbers, lowercase letters, and underscore. Using special characters quite always brings trouble, and seems like you are already having some. I suggest you to name the directory as the numeric user ID (they surely have one), padding with zeroes if you find it looks better (all the names have equal length).
{ "language": "en", "url": "https://stackoverflow.com/questions/7586686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Add selectors to multiple segmented controls in NIB file I have two UIbuttons, and I want to assign the two buttons to a UITextView so that when one of the buttons is pressed, the text view content changes from what it had when previous button was pressed. I want to do this using a segmented control. How do I assign each segmented control different selectors in the NIB file? A: As mentioned you have to connect your IBAction to your UISegmentedControl in IB with the valueChanged: option (i think you usually set touchUpInside for uibuttons), then try this - (IBAction)changeType:(id)sender{ //segControl is an instance of UISegmentedControl segControl = sender; if(segControl.selectedSegmentIndex==0){ //do something } else if (segControl.selectedSegmentIndex==1){ }//and so on } Hope this helps. A: You can assign the segment control to a single IBAction. In that method use segment control's selectedSegmentIndex to identify which section is pressed and call the later functions accordingly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL Double Order Is there a better way to write SELECT users.id FROM `users`,`profiles` WHERE users.id = profiles.id && profiles.zipcode = '$zipcode' && users.id != '1' && users.id != '2' && profiles.picture != '' ORDER BY users.last_activity DESC LIMIT 0,11 (The code above is suppose to find all the users with a certain zipcode, and order them by the last_activity timestamp) Also, is there anyway to sort it by last_activity and gender? A: SELECT users.id FROM `users` JOIN `profiles` ON users.id = profiles.id WHERE profiles.zipcode = '$zipcode' AND users.id NOT IN (1,2) AND profiles.picture != '' ORDER BY users.last_activity DESC, users.gender LIMIT 0,11 A: Just add gender: ORDER BY users.last_activity DESC, users.gender Note that ordering by the second one (in this case gender) will only happen if two users have the same last_activity value. Consider it a "tie-breaker" ordering.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is 2d array a double pointer? int main() { matrix[2][4] = {{11,22,33,99},{44,55,66,110}}; int **ptr = (int**)matrix; printf("%d%d",**matrix,*ptr); } But when a 2-d array is passed as a parameter it is typecasted into (*matrix)[2] .. what type does the compiler store this array as... is it storing as a 2-d array or a double pointer or an pointer to an array .. If it is storing as an array how does it interprets differently at different situations like above. Please help me understand. A: Is 2d array a double pointer? No. This line of your program is incorrect: int **ptr = (int**)matrix; This answer deals with the same topic If you want concrete image how multidimensional arrays are implemented: The rules for multidimensional arrays are not different from those for ordinary arrays, just substitute the "inner" array type as element type. The array items are stored in memory directly after each other: matrix: 11 22 33 99 44 55 66 110 ----------- the first element of matrix ------------ the second element of matrix Therefore, to address element matrix[x][y], you take the base address of matrix + x*4 + y (4 is the inner array size). When arrays are passed to functions, they decay to pointers to their first element. As you noticed, this would be int (*)[4]. The 4 in the type would then tell the compiler the size of the inner type, which is why it works. When doing pointer arithmetic on a similar pointer, the compiler adds multiples of the element size, so for matrix_ptr[x][y], you get matrix_ptr + x*4 + y, which is exactly the same as above. The cast ptr=(int**)matrix is therefore incorrect. For once, *ptr would mean a pointer value stored at address of matrix, but there isn't any. Secondly, There isn't a pointer to matrix[1] anywhere in the memory of the program. Note: the calculations in this post assume sizeof(int)==1, to avoid unnecessary complexity. A: In C, there's nothing special you need to know to understand multi-dimensional arrays. They work exactly the same way as if they were never specifically mentioned. All you need to know is that you can create an array of any type, including an array. So when you see: int matrix[2][4]; Just think, "matrix is an array of 2 things -- those things are arrays of 4 integers". All the normal rules for arrays apply. For example, matrix can easily decay into a pointer to its first member, just like any other array, which in this case is an array of four integers. (Which can, of course, itself decay.) A: No. A multidimensional array is a single block of memory. The size of the block is the product of the dimensions multiplied by the size of the type of the elements, and indexing in each pair of brackets offsets into the array by the product of the dimensions for the remaining dimensions. So.. int arr[5][3][2]; is an array that holds 30 ints. arr[0][0][0] gives the first, arr[1][0][0] gives the seventh (offsets by 3 * 2). arr[0][1][0] gives the third (offsets by 2). The pointers the array decays to will depend on the level; arr decays to a pointer to a 3x2 int array, arr[0] decays to a pointer to a 2 element int array, and arr[0][0] decays to a pointer to int. However, you can also have an array of pointers, and treat it as a multidimensional array -- but it requires some extra setup, because you have to set each pointer to its array. Additionally, you lose the information about the sizes of the arrays within the array (sizeof would give the size of the pointer). On the other hand, you gain the ability to have differently sized sub-arrays and to change where the pointers point, which is useful if they need to be resized or rearranged. An array of pointers like this can be indexed like a multidimensional array, even though it's allocated and arranged differently and sizeof won't always behave the same way with it. A statically allocated example of this setup would be: int *arr[3]; int aa[2] = { 10, 11 }, ab[2] = { 12, 13 }, ac[2] = { 14, 15 }; arr[0] = aa; arr[1] = ab; arr[2] = ac; After the above, arr[1][0] is 12. But instead of giving the int found at 1 * 2 * sizeof(int) bytes past the start address of the array arr, it gives the int found at 0 * sizeof(int) bytes past the address pointed to by arr[1]. Also, sizeof(arr[0]) is equivalent to sizeof(int *) instead of sizeof(int) * 2. A: If you can use the stack for that data (small volume) then you usually define the matrix: int matrix[X][Y] When you want to allocate it in the heap (large volume), the you usually define a: int** matrix = NULL; and then allocate the two dimensions with malloc/calloc. You can treat the 2d array as int** but that is not a good practice since it makes the code less readable. Other then that **matrix == matrix[0][0] is true
{ "language": "en", "url": "https://stackoverflow.com/questions/7586702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "44" }
Q: Add paperclip new style doesn't affect old uploaded images I have Company model with logo image has_attached_file :logo I have created many companies with their logos. Now, I need to add new style has_attached_file :logo, :styles => { :small => "30x15>", :medium => "155x85>" } Should I re-upload all my old data to regenerate the new styles? I don't think so.... Or is there any rake task can regenerate styles? A: See Thumbnail-Generation. If the rake task doesn't work for you, you should be able to use a snippet in the console to invoke reprocess! on the companies in question
{ "language": "en", "url": "https://stackoverflow.com/questions/7586703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: PhoneGap Sencha Blackberry I'm having a hard time creating a project that allows me to run sencha touch on a blackberry using phonegap I can run a phonegap example, I can run sencha touch in IOS and a webbrowser but I can't figure out how to link everything together. I'm using ant and I'm completely new to it I have no idea how to modify PhoneGap sample to include sencha touch anybody can help me with this set up ? Cheers Jason A: I anwser this question in the google group of Phonegap: http://groups.google.com/group/phonegap/browse_thread/thread/3bddd6fd63e2ca88 Good Luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7586705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Exclude advertisements from social sharing thumbnail options Awhile back I noticed that social linking sites such as Reddit, StumbleUpon and Facebook would often grab advertisements running on my site as the thumbnail image for shared pages. I didn't want that to happen, obviously, so I added a default image link to the header: <link rel="image_src" href="http://gapersblock.com/gfx/default_thumb.jpg"/> Problem half-solved. Now the default image is the only image sharing sites see, whether there are other images on the page or not. I'd like readers to be able to choose other images from the page if they want. Is there some code I can wrap our ad invocation code in to "hide" it from sharing sites, or at least make it less? Is there a way to tell these sites' thumbnail generators "Pick whatever you want, except this ad right here, or use this default image if that's all you can find"? Relevant background: I'm using Movable Type, so Wordpress advice is useless to me. I'm comfortable with HTML and CSS, but a novice on javascript or php. A: You would just need to add multiple image_src tags for all the images you want users to be able to pick from.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: c# profiling aspx page loadtime I would like to profile the loading of an aspx page to determine the bottlenecks, without using an outside tool. How can I do this? Thanks. A: Page Tracing might give you a start but this doesn't give you memory usage etc, only timings. A: ANTS Memory Pro filer is the best tool I have found for things like that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a "startswith" method in pyparsing Hey I have written a very simple parser with pyparsing which detects some tokens in a text and then replaces them with a different string. The problem is that right now my code only works with exact matches. What I'd like to do is detect partial matches too. For example if the token is "foobar" I'd like to match a word like "foobarfoo". Is there a way to do that with pyparsing? I have looked at the examples and did some research but I came up with nothing. Thanks EDIT: I have a list of tokens to match and a list of words in the text. So I want a solution which takes into account this fact. The list of tokens can be quite big. A: Literal('foobar')+Word(pyp.alphas) defines a pyparsing ParseExpression which requires the text to startwith 'foobar' followed by any alphacharacter. For example: import pyparsing as pyp ident = pyp.Combine(pyp.Literal('foobar')+pyp.Word(pyp.alphas))('foo') for match in ident.searchString('bar foobarfoo bar foobarbafoo'): print(match.foo) yields foobarfoo foobarbafoo A: Simplest would be to use a pyparsing Regex expression in your grammar: startsWithFoobar = Regex(r"foobar[a-zA-Z0-9_]+")
{ "language": "en", "url": "https://stackoverflow.com/questions/7586722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Verify web service is available I have a C++ program that will be retrieving a url which specifies a wsdl. My program is simply middleware and doesn't perform any wsdl related requests; it will literally read the data and pass it on to whomever will use the url. That being said, within Linux, can I test to see if the webservice is available within my code? A sort of a wsdl ping would be what I'm looking for. A: Just HTTP GET the WSDL. Or HEAD it. If you use libcurl, here's the docs for it A: use curl, ping the url, and check the response code. Look here for a bunch of libcurl examples
{ "language": "en", "url": "https://stackoverflow.com/questions/7586723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Facebook PHP SDK clear session data? I want people to be able to remove my app from their facebook-account from my app. This is easily done with: $fb->api('/'.$fbUid.'/permissions','DELETE'); The problem is that if the user loads another page on my website the facebook php sdk still seem to think that the user is "logged in". I think this is because the facebook php sdk (v 3.1.1) stores user data in sessions. Is there a good way of clearing these sessions? (i mean a best practice way, of course i could loop through the sessions and delete all beginning with "fb_"). There is a $fb->clearAllPersistentData() but it's protected. Or will i actually have to redirect the user to the logoutUrl to do this? EDIT: Redirecting to logoutUrl doesn't make any difference, i still have the sessions variables. A: You can use session_destroy() but this will destroy all the session data, including any your own apps may be using. Another solution is to extend the class and expose the protected method via your own wrapper function. However I agree that this is slightly broken and I have a few fixes that I'll push to the sdk this week.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using PHP, how do I trigger something once every 100 visits? Thanks for reading my question, here is what I'm trying to achieve: * *I have a PHP web page that people visit. *I want to trigger a job that does something approximately every 100 visits(on average) to my PHP page. The frequency does not have to be extremely accurate, but in the long run, the stats should approach 100 or so. *I can not write to disk, and can not use database(due to load/performance concern). So I think this has to be done in the PHP code and some how link it to something like time. (something like generate a random number, then match it to the time, if match do the triggered job, if not match, continue). I'm open to any ideas or suggestions. Please provide me with the sample code if possible. Thanks! A: Just do something like: <?php $random = mt_rand(1,100); if ($random == 100) { trigger_your_job_here; } ?> Edit: I had originally used rand(), but Alix Axel edited my response to use mt_rand() instead. This is, of course, the right thing to do, as mt_rand() is not only faster than rand() (by a factor of four according to PHP's documentation), it also fixes some deficiencies of rand() on various sytems (like on Windows, where you can only get random numbers up to 32767). Of course, both are pseudo-random number generators and don't give proper random numbers, but for your purposes that's sufficient. You're not picking lottery numbers, for example. A: You could write to a RAM disk, or memcached, if your hosting configuration supports it. That said, have you tried writing to (normal) disk to see if it really causes performance problems? The best approach here is to try it and get some metrics.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Where can I find WSDLs in Websphere web console interface Yep, that's the question. I didn't manage to find web service endpoints in websphere console. But I'm pretty sure they must be there, please help. A: For JAX-WS services you can find it in two places: * *Applications > WebSphere enterprise applications > applicationName > Publish WSDL files *or Sercices > Service providers > serviceName > View WSDL And you can access it via service url also: http://host:port/context/serviceName?wsdl A: In order to find or set the web service endpoint in administration console(for WAS version 6.1) go to: Applications>Enterprise Applications>App Name>Provide HTTP endpoint URL information A: Go to Enterprise Applications > -> Service providers(under Web Service Properties) >, you will see the wsdl file. even it can be found Enterprise Applications > > Publish WSDL files(its under Web Service Properties)
{ "language": "en", "url": "https://stackoverflow.com/questions/7586732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: tsql query - select records from 2 tables without joining them I have 2 table as follows: emp_id emp_name emp_add emp_no dept_name 1 sss hhh 0 hhh 2 wsss ddd 0 hhh 2nd table is as follows: dep_name dept_no hhh 1 I have select records only from table 1 where dept_name matches with the second table. I cannot use joins because there are 300 records in table with matches with table 1 records. and also I want to set the value of emp_no in table 1 as dept_no of table 2. Any help? A: I see absolutely no reason to avoid using a join. UPDATE t1 SET emp_no = t2.dept_no FROM table1 t1 INNER JOIN table2 t2 ON t1.dept_name = t2.dept_name A: Try this select t1.*, (select top 1 dept_name from table2 t2 where t2.dept_no = t1.dept_no) from table1 t1
{ "language": "en", "url": "https://stackoverflow.com/questions/7586734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to catch interrupts generated by TimeConstrained? Mathematica has the CheckAbort function which allows to catch and handle user-generated and programmatic Aborts. But it does not allow to catch interrupts generated by such functions as TimeConstrained and MemoryConstrained: TimeConstrained[CheckAbort[Pause[100], Print["From CheckAbort"]], 1] (does not print "From CheckAbort"). Is there a way to catch such interrupts in Mathematica? EDIT: I do know that third argument of TimeConstrained and MemoryConstrained allows to evaluate some code in the case of interrupt but this way is not what I need: I need a way to handle such interrupts entirely inside of my function allowing a user do not care of its internals. P.S. The reason why I need this is that I have a function that creates MathLink objects which must be closed in the case of any interrupts or aborts but not in other cases. A: Here is improved version of WReach's solution (he suggested it in a comment to the answer by Daniel Lichtblau). I should redefine my function f as follows (and now call it as ff): ClearAll[ff]; SetAttributes[ff, HoldAllComplete]; ff[expr_] /; (Unset[done]; True) := Internal`WithLocalSettings[Null, done = f[expr], AbortProtect[If[! ValueQ[done], Print["Interrupt!"]]; Unset[done]]] Examples: ff[1 + 1] (*=>f[2]*) TimeConstrained[ff[Pause[10]; 1 + 1], 1] (*=> prints "Interrupt!"*) TimeConstrained[ff[Pause[.10]; 1 + 1], 1] (*=>f[2]*) A: The construct for this is available in undocumented form. Internal`WithLocalSettings[ preprocessing, code, postprocessing] will cause postprocessing to take place before returning from aborts or various types of jumps. See also: Reliable clean-up in Mathematica Import big files/arrays with mathematica Daniel Lichtblau A: TimeConstrained[Pause[100], 1, Print["-->Aborted"]] and MemoryConstrained[100!, 1, Print["-->Aborted"]] A: I am putting this here just to flesh out Danny's answer. I think this is clearly a bug in CheckAbort, and would use this as a workaround: Attributes[myCheckAbort] = {HoldAll}; myCheckAbort[arg1_, arg2_] := Block[ {res, aborted}, WithCleanup[ aborted = True , res = arg1; aborted = False; res , If[aborted, arg2; res = $Aborted ] ] ]
{ "language": "en", "url": "https://stackoverflow.com/questions/7586735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: app does not load engine's assets via sprockets I am trying to rewrite an app using rails 3.1 making use of engines. Somehow the test dummy app does not pick up my assets and I don't know what would be causing this. i.e. stylesheets from the engine are are not included, same for javascript, and probably every thing else. Anyone mind to have a look at https://github.com/janlimpens/portfolio-engine?
{ "language": "en", "url": "https://stackoverflow.com/questions/7586739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Organized library with Fortran functions I am trying to make a library of useful functions. I yet don't know much about this, but apparently most of them, if not all, need to be included in a module (or in a interface inside the program, but since the point of this is to make a library, that doesn't seem to be a choice) or else the programs in which I'll use them won't recognize them. I could make a long file with one module including all this functions, but I would like to keep the different functions in different short files. If I do this, however, I would have to make a different module for each function, and If I want to use them all in a program, I would have a very long USE declaration list (not to mention the number of .mod files that would be produced). The only possible solution for this I could come up with, was to make another module with just the USE declarations for all other modules, but I think there must be another way to have a library containing functions that is not so far fetched. Also, why is it that I have this problem with functions but not with subroutines? Is it because the command CALL immediately identifies the line as a subroutine call whereas functions are called just by name with no command to tell the compiler "hey, this is a function", so it has to know what is a function and what not beforehand? I am including an example (following the instructions in http://www.oceanographers.net/forums/showthread.php?378-How-to-make-a-FORTRAN-library, and using the correct 'path'). TestFunc.F90 FUNCTION SumNum(nNum1,nNum2) RESULT(nResult) IMPLICIT NONE INTEGER,INTENT(IN) :: nNum1,nNum2 INTEGER :: nResult nResult=nNum1+nNum2 RETURN;END FUNCTION TestProg.F90 PROGRAM TestProg IMPLICIT NONE WRITE(6,*) SumNum(2,2) STOP;END PROGRAM Command Line > gfortran -c TestFunc.F90 -o TestFunc.o > ar ruv libmylib.a *.o > gfortran TestProg.F90 -o Test.x -L/path -lmylib.a TestProg.F90:6.12: WRITE(6,*) SumNum(2,2) 1 Error: Function 'sumnum' at (1) has no IMPLICIT type A: My recommendation is to place both your functions and subroutines into a module, then use that module. Place ones that are logically related into the same module. Using one module per procedure seems very inconvenient -- why do you prefer this approach? The reason to place procedures (functions and subroutines) into a module and then "use" that module is that it makes the interface "explicit" so that the compiler can check consistency between the actual arguments in call and the dummy arguments of the procedure. This will find many types of bugs and save effort in your programming. It is easy and automatic compared to writing a declaration ("interface"). You don't have to write the procedure declaration AND the interface, and you don't have to keep them consistent when revisions are made. Yes, the "call" statement is helping the compiler identify subroutines, but the advantage of making the interface explicit via a module needs the module for both function and subroutine. EDIT to answer comment: Yes, even if the procedures are being placed into a library, I'd place them into a single module. If the procedures are totally unrelated, then they probably belong in separate libraries and separate modules. If related, then in the same library and the same module. Fortran provides features to manage possible "issues" with having many procedures in the same module: you can make clear which procedures you are using in a "use" statement and avoid name clashes by using an "only" clause, listing only the procedures that are used. You can even rename a procedure that you want to use if the default name clashes with another name. A: You don't need to put subroutines in modules in order to make a library. What I usually do is have subroutines in separate files, build object files (.o) out of them, and then archive them into a library, e.g.: ar ruv mylib.a *.o Then all it takes is to specify mylib.a during linking with the main program which calls the subroutine. It does not make a difference whether your procedure is a subroutine or a function. EDIT1: Your main program needs to have a function declaration: PROGRAM TestProg IMPLICIT NONE INTEGER :: sumnum WRITE(6,*) SumNum(2,2) STOP;END PROGRAM Then: gfortran -c *.f90 ar ruv mylib.a testfunc.o gfortran testprog.o -o x mylib.a When I run x, I get correct output. A: To answer the question regarding the difference between function and subroutine with the implicit interfaces: functions are used like variables, and there type needs to be known, thus you need to declare them with the external attribute. However, I also would strongly recommend M. S. B.s answer, that you should put everything into modules, by this you get explicit interfaces for all your routines, and such problems are avoided. One more comment, the return statement in your sample code is unnecessary, as well as the stop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Usercontrol blendability wp7 Hi I'd like to make a simply user control <UserControl x:Class="TestDependencyProps.controls.TestControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" DataContext="{Binding RelativeSource={RelativeSource Self}}" d:DesignHeight="480" d:DesignWidth="480"> <Grid x:Name="LayoutRoot" > <TextBlock Height="30" Margin="31,140,27,0" Name="textBlock1" Text="{Binding testMessage}" VerticalAlignment="Top" /> </Grid> </UserControl> Code behind: public partial class TestControl : UserControl { public string testMessage { get { return (string)GetValue(testMessageProperty); } set { SetValue(testMessageProperty, value); } } public static readonly DependencyProperty testMessageProperty = DependencyProperty.Register("testMessage", typeof(string), typeof(TestControl),new PropertyMetadata("test in a message",null) ); public TestControl() { InitializeComponent(); } } now all works but is not blendable ... and in Cider I can't see "test in a message" there's a way that works :) without involve xmlns:MyControl=... A: Most people consder that a control is Blendable if you can edit its template. To do this, you will have to change it from a user-control to a custom-control so that its template is defined in gerenic.xaml. However, from your comments it sounds like you need design-time data, rather than to be able to make the control Blendable. Take a look at the MSDN section on design-time attributes in Silverlight. Specifically d:DataContext, this works just fine in WP7. A: in addition to ColinE's answer, you might need to change a bit of your code to get your dependency property working with design time data, public string testMessage { get { return (string)GetValue(testMessageProperty); } set { SetValue(testMessageProperty, value); } } public static readonly DependencyProperty testMessageProperty = DependencyProperty.Register("testMessage", typeof(string), typeof(TestControl), new PropertyMetadata("test in a message", PropertyChangedCallback)); private static void PropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e) { if (e.NewValue != null) { var c = (TestControl)sender; // assign value to the TextBlock here c.textBlock1.Text = e.NewValue.ToString(); } } and remove the binding in your TextBlock Text="{Binding testMessage}". To display the text in design time, you need to add a design time DataContext (like what ColinE suggested), <Grid x:Name="LayoutRoot" d:DataContext="{d:DesignInstance design:DesignMainViewModel, IsDesignTimeCreatable=True}"> <xxx:TestControl testMessage={Binding SomeText} /> </Grid> Hope this helps. :) EDIT Actually as Colin pointed out, you don't need the callback, if you name your usercontrol and use ElementName binding instead of the normal binding. <UserControl x:Name="myUserControl" ... Inside the TextBlock, you do Text="{Binding testMessage, ElementName=myUserControl}" Simply bind to testMessage wouldn't work because this property is of the UserControl.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Limiting concurrency and rate for Python threads Given a number threads I want to limit the rate of calls to the worker function to a rate of say one per second. My idea was to keep track of the last time a call was made across all threads and compare this to the current time in each thread. Then if current_time - last_time < rate. I let the thread sleep for a bit. Something is wrong with my implementation - I presume I may have gotten the wrong idea about how locks work. My code: from Queue import Queue from threading import Thread, Lock, RLock import time num_worker_threads = 2 rate = 1 q = Queue() lock = Lock() last_time = [time.time()] def do_work(i, idx): # Do work here, print is just a dummy. print('Thread: {0}, Item: {1}, Time: {2}'.format(i, idx, time.time())) def worker(i): while True: lock.acquire() current_time = time.time() interval = current_time - last_time[0] last_time[0] = current_time if interval < rate: time.sleep(rate - interval) lock.release() item = q.get() do_work(i, item) q.task_done() for i in range(num_worker_threads): t = Thread(target=worker, args=[i]) t.daemon = True t.start() for item in xrange(10): q.put(item) q.join() I was expecting to see one call per second to do_work, however, I get mostly 2 calls at the same time (1 for each thread), followed by a one second pause. What is wrong? Ok, some edit. The advice to simply throttle the rate at which items are put in the queue was good, however I remembered that I had to take care of the case in which items are re-added to the queue by the workers. Canonical example: pagination or backing-off-retry in network tasks. I came up with the following. I guess that for actual network tasks eventlet/gevent libraries may be easier on resources but this is just an example. It basically uses a priority queue to pile up the requests and uses an extra thread to shovel items from the pile to the actual task queue at an even rate. I simulated re-insertion into the pile by the workers, re-inserted items are then treated first. import sys import os import time import random from Queue import Queue, PriorityQueue from threading import Thread rate = 0.1 def worker(q, q_pile, idx): while True: item = q.get() print("Thread: {0} processed: {1}".format(item[1], idx)) if random.random() > 0.3: print("Thread: {1} reinserting item: {0}".format(item[1], idx)) q_pile.put((-1 * time.time(), item[1])) q.task_done() def schedule(q_pile, q): while True: if not q_pile.empty(): print("Items on pile: {0}".format(q_pile.qsize())) q.put(q_pile.get()) q_pile.task_done() time.sleep(rate) def main(): q_pile = PriorityQueue() q = Queue() for i in range(5): t = Thread(target=worker, args=[q, q_pile, i]) t.daemon = True t.start() t_schedule = Thread(target=schedule, args=[q_pile, q]) t_schedule.daemon = True t_schedule.start() [q_pile.put((-1 * time.time(), i)) for i in range(10)] q_pile.join() q.join() if __name__ == '__main__': main() A: It seems weird to me to try and limit the rate across multiple threads. If you limit each thread independently you can avoid all the locking nonsense. Just a guess, but I think you want to set last_time[0] to time.time() (not current_time) after the sleep. A: I get mostly 2 calls at the same time (1 for each thread), followed by a one second pause. What is wrong? That's exactly what you should expect from your implementation. Lets say the time t starts at 0 and the rate is 1: Thread1 does this: lock.acquire() # both threads wait here, one gets the lock current_time = time.time() # we start at t=0 interval = current_time - last_time[0] # so interval = 0 last_time[0] = current_time # last_time = t = 0 if interval < rate: # rate = 1 so we sleep time.sleep(rate - interval) # to t=1 lock.release() # now the other thread wakes up # it's t=1 and we do the job Thread2 does this: lock.acquire() # we get the lock at t=1 current_time = time.time() # still t=1 interval = current_time - last_time[0] # interval = 1 last_time[0] = current_time if interval < rate: # interval = rate = 1 so we don't sleep time.sleep(rate - interval) lock.release() # both threads start the work around t=1 My advice is to limit the speed at which the items are put into the queue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586743", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Getting an image url from sql database using php I'm trying to retrieve an image url from a database called flags in the image field to use. Where am I going wrong with this? <?php connect(); $sql = ("SELECT image FROM members, flags WHERE members.member_id = '$_SESSION[id]' AND flags.id = members.country"); $result = mysql_query($sql); ?> <div id="flag"> <img id="flag" src="$result" width="16px" height="11px"/> A: You are using the $row variable from the last mysql_fetch, instead of $row4 in your new fetch: while ($row4=mysql_fetch_array($sql3)){ $sql4 = $row4['image']; //$row4 here instead of $row } And like @halfdan commented, you don't need to use while loops when you're only dealing with one row, and you can replace those two queries with one join query A: $result = mysql_query($sql); it's only to run the query you need to add one more statement which fetches the record from talbe, it could be: * *$result_set = mysql_fetch_object($result); *$result_set = mysql_fetch_array($result); if you are using 1 get value by $result_set->image; if you are using 2 get value by $result_set['image'];
{ "language": "en", "url": "https://stackoverflow.com/questions/7586745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I overload an array subscript operator in PHP? I have a class with an internal array, and I'd like to overload the subscript operator to access the internal array and provide debug/logging actions. Is there any possible way to overload the [] operator in PHP, or is there another option I should be chasing in this case? A: Yes, with the ArrayAccess interface. Although you won't be able to cast the object to a proper array. With ArrayObject (as mentioned in the duplicate question) you can however. Also see this comment on php.net on how to achieve this when you are extending ArrayObject.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: gcc Atomic Operations Causing SEGV I've been using a gcc atomic operation for quite a while in a multi-threaded application, and yesterday, ran into an interesting scenario that I cannot explain. These atomic functions are overloaded and can use datatypes that are 1, 2, 4, or 8-bytes wide. In particular, I use the bool_compare_and_swap (CAS) operation succesfully a lot. The issue that arises here is repeatable, and only occurs when I compile optimized code (O3). The issue does not arise when I compile unoptimized (O0). Keep this in mind, since I believe the optimizer is doing something funky in the case I'm presenting here. What I typically do is create a union of a struct containing named types (chars, shorts, etc.), and data type that is the appropriate size that "fits" that struct into one object (i.e. a long long), In this case, I have an 8-byte (long long) in a union whose struct counterpart contains bitfields. The example data type definition is shown below. The thought is that bitfields can be changed by assignment statements, and once all assignments are done, the 8-byte datatype is the one that is then CAS'd. Specifically, I'm using: bool __sync_bool_compare_and_swap (type *ptr, type oldval type newval, ...) wrapped in a macro as such: define THD_CAS(ptr, oldVal, newVal) __sync_bool_compare_and_swap(ptr, oldVal, newVal) I have a struct defined as follows: typedef union _TSynchro { struct { int *pFirstSynchWork; unsigned short idTransaction; unsigned short fNewTrans :1, fFileBad :1, fOpComplete :1, fCancelWork :1, fPurged :1, fStatRequired :1; } Data; // above struct is overlayed by this struct so we can CAS all values with a single 64 bit cas long long n64; } TSynchro; So, I have a concurrency loop (while(1)) in code that grabs a "snapshot" of the current data value and store in Old, sets bits in a new copy (New) of the data, and then trys the CAS operation. If the CAS succeeds, I'm the thread that changed the data and I break out of the loop. If the CAS failed, then some other thread changed the data under me, and I retry, grabbing another "snapshot" of the current data. void NewSynchro(TSynchro *pSynchro) { volatile TSynchro New; volatile TSynchro Old; while (1) // concurrency loop { Old.n64 = pSynchro->n64; New.n64 = Old.n64; New.Data.fOpComplete = 1; New.Data.fStatRequired = 0; if (fFileBad) { New.Data.fFileBad = 1; } else { New.Data.fReleased = 0; New.Data.fFileBad = 0; } if (THD_CAS(&pSynchro->n64, Old.n64, New.n64)) break; // success } } Now, here is what's interesting...see that I'm declaring the Old and New as volatile? Well, if BOTH Old AND New do not have the volatile modification, I get a SEGV when I step into the very next function call after the call to NewSynchro(). If EITHER OLD or NEW or BOTH have the volatile modifier, the application code never SEGVs. In development, I'm only running 1 thread right now (no real threat of contention for changing the value), so I also tried getting rid of the CAS and replacing with a simple assignment (i.e., pSynchro->n64 = New.n64), and the application runs fine, too. I've been using the 8-byte CAS in other spots and it appears to be working fine. One difference here is that I think this is the first time I'm using bitfields in a struct. Thoughts? A: Let me give a few thoughts: A union is normally intended to be used either-or: Either long long, or struct. In this case you use both, and it just works like on most simple processors. However, if you have a complex pipelined processor, you might run into necessities for memory barriers or similar. More concrete: Setting a bit in a bit-field is a read-modify-write operation. The problem might occur when you perform these operations in such an order: New.n64 = Old.n64; New.Data.fOpComplete = 1; Because of the union, the read to set the bit can be started before the write of n64 is finished. This pipelining can be countered by the compiler inserting pipeline-flushes or memory barriers. But using a union, the compiler can assume the elements to be separate: "A union can contain only one of its component values at a time." (H&S5, 5.7.1) It will not be inclined to insert any flush/barrier, especially when using aggressive optimization like -O3. And using volatile for New will also direct the compiler (even with -O3) to make sure the read/write are properly separated. Why declaring Old volatile prevents your problems, I cannot say. Then I'd have to see and compare the generated assembly code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: transpose an image in cuda I am having a problem of transposing an image: I call the kernel method: // index of the pixel on the image int index_in = index_x + index_y * width; int index_out = index_x + index_y*height; // Allocate the shared memory __shared__ unsigned int onchip_storage[16][16]; // Load the inputs to the shared memory onchip_storage[threadIdx.y][threadIdx.x] = in[index_in]; // Save the output value to the memory out[index_out] = onchip_storage[threadIdx.x][threadIdx.y]; I got the image rotated but somehow the colors are not as original. Any idea? Thanks in advance. A: Assuming your RGB components are interleaved, then your algorithm is not handling the three components correctly. You really need to make your tile size a multiple of 3 in width, e.g. 18 x 18. Then when you do the transpose you need to transpose elements which are 3 x 4 = 12 bytes wide. A: Can you just use matrix transpose routines, with the "Matrix" being width * height of int3 elements? Those are already optimized really well - in particular the "diagonal" variant in Nvidia's sample code is tons faster than the naive implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a table/grid with a frozen column and frozen headers I am working on a small Android app. Part of what I need for this android app is to have a grid that is both horizontally and vertically scroll-able. However, the leftmost column needs to be frozen (always on screen, and not part of the horizontal scrolling). Similarly, the top header row needs to be frozen (not part of the vertical scrolling) This picture will hopefully describe this clearly if the above doesn't make too much sense: Key: * *White: Do not scroll at all *Blue: scroll vertically *Red: scroll horizontally *Purple: scroll both vertically and horizontally To do one of these dimensions is easy enough, and I have done so. However, I am having trouble getting both of these dimensions to work. (i.e., I can get the bottom portion to be all blue, or I can get the right portion to be all red, but not entirely as above) The code I have is below, and will basically produce the following: result_grid.xml: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/lightGrey"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_below="@id/summaryTableLayout" android:layout_weight="0.1" android:layout_marginBottom="50dip" android:minHeight="100dip"> <ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content" android:scrollbars="vertical"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TableLayout android:id="@+id/frozenTable" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginTop="2dip" android:layout_marginLeft="1dip" android:stretchColumns="1" /> <HorizontalScrollView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_toRightOf="@id/frozenTable" android:layout_marginTop="2dip" android:layout_marginLeft="4dip" android:layout_marginRight="1dip"> <TableLayout android:id="@+id/contentTable" android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="1"/> </HorizontalScrollView> </LinearLayout> </ScrollView> </LinearLayout> <LinearLayout android:layout_height="wrap_content" android:layout_width="fill_parent" android:orientation="vertical" android:layout_weight="0.1" android:layout_alignParentBottom="true"> <Button android:id="@+id/backButton" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="Return"/> </LinearLayout> </RelativeLayout> Java code: private boolean showSummaries; private TableLayout summaryTable; private TableLayout frozenTable; private TableLayout contentTable; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.result_grid); Button backButton = (Button)findViewById(R.id.backButton); frozenTable = (TableLayout)findViewById(R.id.frozenTable); contentTable = (TableLayout)findViewById(R.id.contentTable); ArrayList<String[]> content; // [Removed Code] Here I get some data from getIntent().getExtras() that will populate the content ArrayList PopulateMainTable(content); } private void PopulateMainTable(ArrayList<String[]> content) { // [Removed Code] There is some code here to style the table (so it has lines for the rows) for (int i = 0; i < content.size(); i++){ TableRow frozenRow = new TableRow(this); // [Removed Code] Styling of the row TextView frozenCell = new TextView(this); frozenCell.setText(content.get(i)[0]); // [Removed Code] Styling of the cell frozenRow.addView(frozenCell); frozenTable.addView(frozenRow); // The rest of them TableRow row = new TableRow(this); // [Renoved Code] Styling of the row for (int j = 1; j < content.get(0).length; j++) { TextView rowCell = new TextView(this); rowCell.setText(content.get(i)[j]); // [Removed Code] Styling of the cell row.addView(rowCell); } contentTable.addView(row); } } This is what it looks like: So this is what it looks like with a little bit of horizontal scrolling This is what it looks like when scrolling vertically, note that you lose the headers! This is a problem! Two last things to note! First off, I cannot believe that this doesn't exist somewhere already. (I do not own an Android, so I have not been able to look around for apps that may do this). However, I have searched for at least two days within StackOverflow and in the Internet at large looking for a solution for either GridView or TableLayout that will provide me for what I'd like to do, and have yet to find a solution. As embarrassed as I would be for having missed it, if someone knows of a resource out there that describes how to do this, I would be grateful! Secondly, I did try to "force" a solution to this, in that I added two LinearLayouts, one capturing the "Header" part of the grid I want to create, and another for the bottom "content" part of the grid I want to create. I can post this code, but this is already quite long and I'm hoping that what I mean is obvious. This partially worked but the problem here is that the headers and content columns were never lined up. I wanted to use getWidth() and setMinimumWidth() on the TextViews within the TableRows, but as described here this data was inaccessible during onCreate (and was also inaccessible within onPostCreate). I have been unable to find a way to get this to work, and a solution in this realm would be wonderful as well! If you made it this far to the end, kudos to you! A: About a week ago I revisited this problem and came up with a solution. The solution requires me to do a lot of manual width setting for the columns in this grid, and I consider that to be extremely sub-par in this day and age. Unfortunately, I have also continued to look for a more well-rounded solution native to the Android platform, but I have not turned anything up. The following is the code to create this same grid, should any one following me need it. I will explain some of the more pertinent details below! The layout: grid.xml: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@color/lightGrey"> <TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:layout_marginBottom="2dip" android:layout_weight="1" android:minHeight="100dip"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TableLayout android:id="@+id/frozenTableHeader" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginTop="2dip" android:layout_marginLeft="1dip" android:stretchColumns="1" /> <qvtcapital.mobile.controls.ObservableHorizontalScrollView android:id="@+id/contentTableHeaderHorizontalScrollView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_toRightOf="@id/frozenTableHeader" android:layout_marginTop="2dip" android:layout_marginLeft="4dip" android:layout_marginRight="1dip"> <TableLayout android:id="@+id/contentTableHeader" android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="1"/> </qvtcapital.mobile.controls.ObservableHorizontalScrollView> </LinearLayout> <ScrollView android:id="@+id/verticalScrollView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:scrollbars="vertical"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TableLayout android:id="@+id/frozenTable" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginTop="2dip" android:layout_marginLeft="1dip" android:stretchColumns="1" /> <qvtcapital.mobile.controls.ObservableHorizontalScrollView android:id="@+id/contentTableHorizontalScrollView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_toRightOf="@id/frozenTable" android:layout_marginTop="2dip" android:layout_marginLeft="4dip" android:layout_marginRight="1dip"> <TableLayout android:id="@+id/contentTable" android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="1"/> </qvtcapital.mobile.controls.ObservableHorizontalScrollView> </LinearLayout> </ScrollView> </TableLayout> The activity: Grid.java: public class ResultGrid extends Activity implements HorizontalScrollViewListener { private TableLayout frozenHeaderTable; private TableLayout contentHeaderTable; private TableLayout frozenTable; private TableLayout contentTable; Typeface font; float fontSize; int cellWidthFactor; ObservableHorizontalScrollView headerScrollView; ObservableHorizontalScrollView contentScrollView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.result_grid); font = Typeface.createFromAsset(getAssets(), "fonts/consola.ttf"); fontSize = 11; // Actually this is dynamic in my application, but that code is removed for clarity final float scale = getBaseContext().getResources().getDisplayMetrics().density; cellWidthFactor = (int) Math.ceil(fontSize * scale * (fontSize < 10 ? 0.9 : 0.7)); Button backButton = (Button)findViewById(R.id.backButton); frozenTable = (TableLayout)findViewById(R.id.frozenTable); contentTable = (TableLayout)findViewById(R.id.contentTable); frozenHeaderTable = (TableLayout)findViewById(R.id.frozenTableHeader); contentHeaderTable = (TableLayout)findViewById(R.id.contentTableHeader); headerScrollView = (ObservableHorizontalScrollView) findViewById(R.id.contentTableHeaderHorizontalScrollView); headerScrollView.setScrollViewListener(this); contentScrollView = (ObservableHorizontalScrollView) findViewById(R.id.contentTableHorizontalScrollView); contentScrollView.setScrollViewListener(this); contentScrollView.setHorizontalScrollBarEnabled(false); // Only show the scroll bar on the header table (so that there aren't two) backButton.setOnClickListener(backButtonClick); InitializeInitialData(); } protected void InitializeInitialData() { ArrayList<String[]> content; Bundle myBundle = getIntent().getExtras(); try { content = (ArrayList<String[]>) myBundle.get("gridData"); } catch (Exception e) { content = new ArrayList<String[]>(); content.add(new String[] {"Error", "There was an error parsing the result data, please try again"} ); e.printStackTrace(); } PopulateMainTable(content); } protected void PopulateMainTable(ArrayList<String[]> content) { frozenTable.setBackgroundResource(R.color.tableBorder); contentTable.setBackgroundResource(R.color.tableBorder); TableLayout.LayoutParams frozenRowParams = new TableLayout.LayoutParams( TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT); frozenRowParams.setMargins(1, 1, 1, 1); frozenRowParams.weight=1; TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams( TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT); tableRowParams.setMargins(0, 1, 1, 1); tableRowParams.weight=1; TableRow frozenTableHeaderRow=null; TableRow contentTableHeaderRow=null; int maxFrozenChars = 0; int[] maxContentChars = new int[content.get(0).length-1]; for (int i = 0; i < content.size(); i++){ TableRow frozenRow = new TableRow(this); frozenRow.setLayoutParams(frozenRowParams); frozenRow.setBackgroundResource(R.color.tableRows); TextView frozenCell = new TextView(this); frozenCell.setText(content.get(i)[0]); frozenCell.setTextColor(Color.parseColor("#FF000000")); frozenCell.setPadding(5, 0, 5, 0); if (0 == i) { frozenCell.setTypeface(font, Typeface.BOLD); } else { frozenCell.setTypeface(font, Typeface.NORMAL); } frozenCell.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize); frozenRow.addView(frozenCell); if (content.get(i)[0].length() > maxFrozenChars) { maxFrozenChars = content.get(i)[0].length(); } // The rest of them TableRow row = new TableRow(this); row.setLayoutParams(tableRowParams); row.setBackgroundResource(R.color.tableRows); for (int j = 1; j < content.get(0).length; j++) { TextView rowCell = new TextView(this); rowCell.setText(content.get(i)[j]); rowCell.setPadding(10, 0, 0, 0); rowCell.setGravity(Gravity.RIGHT); rowCell.setTextColor(Color.parseColor("#FF000000")); if ( 0 == i) { rowCell.setTypeface(font, Typeface.BOLD); } else { rowCell.setTypeface(font, Typeface.NORMAL); } rowCell.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize); row.addView(rowCell); if (content.get(i)[j].length() > maxContentChars[j-1]) { maxContentChars[j-1] = content.get(i)[j].length(); } } if (i==0) { frozenTableHeaderRow=frozenRow; contentTableHeaderRow=row; frozenHeaderTable.addView(frozenRow); contentHeaderTable.addView(row); } else { frozenTable.addView(frozenRow); contentTable.addView(row); } } setChildTextViewWidths(frozenTableHeaderRow, new int[]{maxFrozenChars}); setChildTextViewWidths(contentTableHeaderRow, maxContentChars); for (int i = 0; i < contentTable.getChildCount(); i++) { TableRow frozenRow = (TableRow) frozenTable.getChildAt(i); setChildTextViewWidths(frozenRow, new int[]{maxFrozenChars}); TableRow row = (TableRow) contentTable.getChildAt(i); setChildTextViewWidths(row, maxContentChars); } } private void setChildTextViewWidths(TableRow row, int[] widths) { if (null==row) { return; } for (int i = 0; i < row.getChildCount(); i++) { TextView cell = (TextView) row.getChildAt(i); int replacementWidth = widths[i] == 1 ? (int) Math.ceil(widths[i] * cellWidthFactor * 2) : widths[i] < 3 ? (int) Math.ceil(widths[i] * cellWidthFactor * 1.7) : widths[i] < 5 ? (int) Math.ceil(widths[i] * cellWidthFactor * 1.2) :widths[i] * cellWidthFactor; cell.setMinimumWidth(replacementWidth); cell.setMaxWidth(replacementWidth); } } public void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldX, int oldY) { if (scrollView==headerScrollView) { contentScrollView.scrollTo(x, y); } else if (scrollView==contentScrollView) { headerScrollView.scrollTo(x, y); } } The scroll view listener (to hook the two up): HorizontalScrollViewListener.java: public interface HorizontalScrollViewListener { void onScrollChanged(ObservableHorizontalScrollView scrollView, int x, int y, int oldX, int oldY); } The ScrollView class that implements this listener: ObservableHorizontalScrollView.java: public class ObservableHorizontalScrollView extends HorizontalScrollView { private HorizontalScrollViewListener scrollViewListener=null; public ObservableHorizontalScrollView(Context context) { super(context); } public ObservableHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public ObservableHorizontalScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public void setScrollViewListener(HorizontalScrollViewListener scrollViewListener) { this.scrollViewListener = scrollViewListener; } @Override protected void onScrollChanged(int x, int y, int oldX, int oldY) { super.onScrollChanged(x, y, oldX, oldY); if (null!=scrollViewListener) { scrollViewListener.onScrollChanged(this, x, y, oldX, oldY); } } } The really important part of this is sort of three-fold: * *The ObservableHorizontalScrollView allows the header table and the content table to scroll in sync. Basically, this provides all of the horizontal motion for the grid. *The way in which they stay aligned is by detecting the largest string that will be in a column. This is done at the end of PopulateMainTable(). While we're going through each of the TextViews and adding them to the rows, you'll notice that there are two arrays maxFrozenChars and maxContentChars that keep track of what the largest string value we've seen is. At the end of PopulateMainTable() we loop through each of the rows and for each of the cells we set its min and max width based on the largest string we saw in that column. This is handled by setChildTextViewWidths. *The last item that makes this work is to use a monospaced font. You'll notice that in onCreate I am loading a consola.ttf font, and later applying it to each of the grid's TextViews that act as the cells in the grid. This allows us to be reasonably sure that the text will not be rendered larger than we have set the minimum and maximum width to in the prior step. I am doing a little bit of fanciness here, what with the whole cellWidthFactor and the maximum size of that column. This is really so that smaller strings will fit for sure, while we can minimize the white space for larger strings that are (for my system) not going to be all capital letters. If you ran in to trouble using this and you got strings that did not fit in the column size you set, this is where you would want to edit things. You would want to change the replacementWidth variable with some other formula for determining the cell width, such as 50 * widths[i] which would be quite large! But would leave you with a good amount of whitespace in some columns. Basically, depending on what you plan on putting in your grid, this may need to be tweaked. Above is what worked for me. I hope this helps someone else in the future! A: TableFixHeaders library might be useful for you in this case. A: Off the top of my head, this is how I would approach this: 1) Create an interface with one method that your Activity would implement to receive scroll coordinates and that your ScrollView can call back to when a scroll occurs: public interface ScrollCallback { public void scrollChanged(int newXPos, int newYPos); } 2) Implement this in your activity to scroll the two constrained scrollviews to the position that the main scrollview just scrolled to: @Override public void scrollChanged(int newXPos, int newYPos) { mVerticalScrollView.scrollTo(0, newYPos); mHorizontalScrollView.scrollTo(newXPos, 0); } 3) Subclass ScrollView to override the onScrollChanged() method, and add a method and member variable to call back to the activity: private ScrollCallback mCallback; //... @Override protected void onScrollChanged (int l, int t, int oldl, int oldt) { mCallback.scrollChanged(l, t); super.onScrollChanged(l, t, oldl, oldt); } public void setScrollCallback(ScrollCallback callback) { mCallback = callback; } 4) Replace the stock ScrollView in your XML with your new class and call setScrollCallback(this) in onCreate().
{ "language": "en", "url": "https://stackoverflow.com/questions/7586753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Draggable and offset coordinates I've been trying to get the final offset coord for a draggable box but it doesn't show both the final x and the final xmax and same for the y axis.i've debugged it and it shows that the problem arises from putting in the variable finalxmPos and appending the text in the list with id finalXm because if i remove those two lines it works but i don't get the final xmin and xmax just the xmin. The code is right here http://jsfiddle.net/DGbT3/133/. any help will be appreciated.. A: Working Example: http://jsfiddle.net/DGbT3/137/ You just had some casing errors. The o in offset should have been uppercase. Also the call to Width() should have been width() Checkout the comments $('#dragThis').draggable( { containment: $('body'), drag: function(){ var offset = $(this).offset(); var xPos = offset.left; var xmPos = offset.left + $('#dragThis').outerWidth(); var yPos = offset.top; var ymPos = offset.top + $('#dragThis').outerHeight(); $('#posX').text('x: ' + xPos); $('#posmX').text('xm: ' + xmPos); $('#posY').text('y: ' + yPos); $('#posmY').text('ym: ' + ymPos); }, stop: function(){ var finalOffset = $(this).offset(); var finalxPos = finalOffset.left; var finalxmPos = finalOffset.left + $('#dragThis').width(); //needed to uppercase o in finalOffset //also changed Width to width() var finalyPos = finalOffset.top; $('#finalX').text('Final X: ' + finalxPos); $('#finalXm').text('Final Xmax: ' + finalxmPos); $('#finalY').text('Final Y: ' + finalyPos); } }); $('#dropHere').droppable( { accept: '#dragThis', over : function(){ $(this).animate({'border-width' : '5px', 'border-color' : '#0f0' }, 500); $('#dragThis').draggable('option','containment',$(this)); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7586758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delete rule for one-to-one relationship I have 2 entities: Department <---->> Employee. So, the department has a one-to-many relationship with employee, and employee has a one-to-one relationship with department. What should be the delete rule of the one-to-one relationship? If I choose cascade, I can see that the department is deleted when I delete an employee and of course I don't want that. I think the logical option for the delete rule would be "No Action", but then I get a warning. Am I missing something, or should the delete rule really be "No Action" in this scenario? A: Nullify. If you choose no action, then the employee will still be in the department's list of employees, but will be deleted. Likely a crash. Nullify in this context means when you delete an employee, remove that employee from the inverse relationship (employees) of its department.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can i share an Xcode 4 project with multiple developers using Subversion We are multiple developers working on the same Xcode 4 iOS project. We are trying to commit to use Subversion but we keep getting conflicts with project.pbxproj when 2 developers add a new target or change the project structure. What is the proper way to go about this issue? A: Commit & update more often, or modularize your app into several projects if possible. There’s also mandatory locking available in Subversion (svn:needs-lock), but I’m not sure if that’s worth the trouble. A: I have had this problem. The way we solved it was by also committing the projectName.xcodeproj file. Basically, the whole top level directory that contained the resource files and project files were committed. We use the subversion system in the organizer. I'm not sure whether you are or are not committing the project file; but if you aren't I suggest you commit that too. Since we started doing that, we have stopped having conflicts over the project file. There is one other thing (and this is if you are committing the .xcodeproj file); when you commit, there is an unchecked check box under the .xcodeproj package. Make sure you check that. That way, the project structure changes will be relayed to all the other developers as well. :) Hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails 3 routing error in a relationship in a has_many => through association I have my models setup as follows: class User has_many :memberships, :dependent => :destroy has_many :groups, :through => :memberships Class Group has_many :memberships, :dependent => :destroy has_many :users, :through => :memberships Class Membership attr_accessible :user_id, :group_id belongs_to :user belongs_to :group My MembershipController#create def create @membership = current_user.memberships.build(:group_id => params[:group_id]) if @membership.save flash[:notice] = "You have joined this group." redirect_to :back else flash[:error] = "Unable to join." redirect_to :back end end I have resources :memberships in my routes so that it can find the create action. Finally in my Group#show action I want a user to be able to join a group. So I created this form_tag <%= form_tag(membership_path) do %> <%= hidden_field_tag @group.id %> <%= submit_tag "Join Group"%> <% end %> This returns the following error: Routing Error No route matches [POST] "/memberships/1" I have run a rake routes to try and understand what I am missing here: memberships GET /memberships(.:format) {:action=>"index", :controller=>"memberships"} POST/memberships(.:format) {:action=>"create", controller=>"memberships"} new_membership GET /memberships/new(.:format) {:action=>"new",controller=>"memberships"} edit_membership GET /memberships/:id/edit(.:format){:action=>"edit", controller=>"memberships"} membership GET /memberships/:id(.:format) {:action=>"show", :controller=>"memberships"} PUT /memberships/:id(.:format){:action=>"update", :controller=>"memberships"} DELETE /memberships/:id(.:format) {:action=>"destroy", :controller=>"memberships"} Anyone see the error of my ways? A: Don't you want to be posting to memberships_path rather than membership_path? It looks like the error is indicating it can't find a POST route for a membership due to the fact that there is actually no route for :membership for POST, :only memberships. A: My quick glance at this; shouldn't <%= form_tag(membership_path) do %> be <%= form_tag(@membership) do %>'or <%= form_tag(membership_path(@membership)) do %>. A: the path is "new_membership" right? new_membership_path if you are doing a form_tag.Or you can always use a form_for and render it through a partial in your view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mongoose - Form to save model with embedded documents Having trouble saving an embedded array to a Mongoose model. Please see Edit at bottom. I have a form to create BlogPost in Express using Mongoose to store data in mongo. I can create and view new blogposts however I just added an embedded document schema Feed into the BlogPost model and I can't get Feed arrays to save from the form into the model code: BlogPosts.js var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/my_database'); var Schema = mongoose.Schema , ObjectId = Schema.ObjectId; var Feeds = new Schema({ name : { type: String } , key : { type: String } }); var BlogPost = new Schema({ author : ObjectId , title : { type: String, required: true, index: { unique: true } } , date : { type: Date, required: true, default: Date.now } , feeds : [Feeds] }); mongoose.model('BlogPost', BlogPost); web.js ... app.get('/blogpost/new', function(req, res) { res.render('blogposts/blogpost_new.jade', { locals: { title: 'New BlogPost' } }); }); app.post('/blogpost/new', function(req, res){ var b = new BlogPost(req.body.b) b.save(function() { b.feeds.push(); res.redirect('/blogposts'); }); }); ... var BlogPost = mongoose.model('BlogPost', BlogPost); Jade form form( method="post") div div span Title : input(type="text", name="b[title]", id="editBlogPostTitle") div span Feeds : ul li span name textarea( name="f[name]", rows=20, id="editBlogPostBodyName") li span key textarea( name="f[key]", rows=20, id="editBlogPostBodyKey") div#editBlogPostSubmit input(type="submit", value="Send") If I fill out this form, the model posts and saves but the feeds data isn't there ("feeds" : [ ]). How should I properly submit the feeds data to save to the array? Edit So I have managed to set up a form to save a Feed object with name and key within a BlogPost doing the following. However, this still needs to be improved to allow for multiple Feeds to be saved at the time of creating a single BlogPost. With my current solution I can only save one Feed properly. Thoughts? blogposts.js (just change Feeds to Feed var Feed = new Schema({ ... web.js (just moved the push) app.post('/blogpost/new', function(req, res){ var b = new BlogPost(req.body.b) b.feeds.push(req.body.feed); b.save(function() { res.redirect('/blogposts'); }); }); form (just change feed names) li span name textarea( name="feed[name]", rows=20, id="editBlogPostBodyKey") li span key textarea( name="feed[key]", rows=20, id="editBlogPostBodyKey") This saves properly, I just can't create multiple feeds within a blogpost at the time of saving. Any help greatly appreciated. thanks. A: For the routes: You do not need to do b.feeds.push(); on the post side. I have a push on the get side when creating a new object, but only because I expect there to be at least 1 nested model. Then again, seeing as how you have a list you may want to add the b.feeds.push(); on the get side as well. For the view, you need to keep the model intact. Assuming b is blogpost and it is your parent to the f list, then you'd want: span Feeds : - var i = 0; ul - each feed in blogPost.feeds li span name textarea( name="blogPost[feeds][i][name]", rows=20, id="editBlogPostBodyName")=feed.name li span key textarea( name="blogPost[feeds][i][key]", rows=20, id="editBlogPostBodyKey")=feed.key - i++ routes.js (or routes/blogPosts.js): app.get('/blogpost/new', function(req, res) { post = new BlogPost(); post.feeds.push(new Feed()); res.render('blogposts/blogpost_new.jade', { locals: { title: 'New BlogPost', blogPost: post } }); }); edit i changed b to blogPost and f to feed in the view. also added the "new" logic in the routes definition. On a side note, keep in mind that any routes will not be editable in this case. It should, in theory, drop and save any new feeds in the even of editing them (if you were to have an update action). If you want them to be independent entities that can be edited, then you need to provide them ids and have add a means of getting them by id. That approach is outlined on mongoosejs.com i believe. A: For what it's worth, I did get this to work. See my edit above which worked once I added an [] to the feed name: "feed[0][name]" and "feed[0][key]", and then "feed[1][name]" and "feed[1][key]". Thanks Chance for some good ideas. For me it didn't work to put that logic in the 'get' route, it needed to be in the 'post'. Thanks a lot tho.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to fix the StrongNameKeyPair error in .Net for using Moq? As far as I can see, it is necessary to have access to write in the machine key store. So how do I assign this permission to a user? I need to ask support people to grant a user the necessary permissions to run Moq, but I don't know what exactly to ask for. UPDATE: As Tim requested below, I'm updating with some information that might be useful to the problem understanding, as follows: Apparently, Moq relies on Castle to build mock objects, and the Castle framework needs to write to machine key store. When I try to run the tests, the testing framework return the error "Unable to obtain public key for StrongNameKeyPair". When I went to support guys, they temporarily gave me administrative privileges, and everything ran as expected. Even after they removed the admin permissions, I was able to execute my tests. My conclusion of this was that I need some permission to write on this machine key store. What I need to know is where exactly I need to have writing permissions, so I could ask support for a specific writing permission instead of admin permissions, for the other development environments, what would be denied for sure. Thanks in advance! A: After some research, I was able to find the exact directory I need to have write permission in order to execute Moq (in fact, it's a Castle requirement). The user must have acces to the following folder: C:\Documents and Settings\AllUsers\ApplicationData\Microsoft\Crypto\RSA\MachineKeys (Assuming "C" is your system folder) With this permission, the user running a mocking project with Moq won't need admministrative privileges in the local machine. Here is a reference: MVC Testing using a mocking framework (Moq) Hope it helps. A: I've never needed to install any keys to run Moq, neither locally on my workstation nor on our build server. I think you might need to put a bit more work into your question. Are you getting some sort of error? Perhaps if you posted the message you might get a better response.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Named elements in a FlowDocument from a ResourceDictionary I have a FlowDocument (a template for a report I need to produce) stored as a resource. This seems to work well but if I name the elements I can't get a reference to them with FindName(). Here is the resource dictionary: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <FlowDocument x:Key="ReportStructure"> <Paragraph Name="ClientAddressParagraph" /> </FlowDocument> </ResourceDictionary> And here is my code: Dim _ReportResources = New ResourceDictionary() With {.Source = New Uri("/Reports/Statement.xaml", UriKind.Relative)} Dim _FlowDocument As FlowDocument = _ReportResources.Item("ReportStructure") Dim _Paragraph As Paragraph = _FlowDocument.FindName("ClientAddressParagraph") ' _Paragraph is Nothing (null) at this point. Any ideas? Do I need to do some kind of initialisation on the flow document so that it registers the names of named elements?
{ "language": "en", "url": "https://stackoverflow.com/questions/7586772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: On shutdown, MAMP sometimes asks me for username and password, but not always When I log onto my Mac OSX admin account, I have MAMP automatically start so I can get right to managing my server content. But every now and then, when I shut down my computer, the MAMP window opens up and asks for my admin name and password, and the shut down process halts until this is entered. Any reason why it would only ask me in certain cases when I shut down, and not all the time? It's sometimes annoying when you shut down and it shows up when I don't expect it. I don't know what are the conditions for MAMP to ask for your admin info if you request to close the program. A: MAMP requires sudo password for shutting down the apache and/or mysql server when ports smaller than 1024 have been configured. on UNIX like systems (like Mac OS) you need "su" privileges to start/stop this IP services. note: probably when it does not explicitly asks you for a password, you where using it a moment ago for another activity. A: Go to preferences in mamp and click reset mamp ports, it will change the ports to default. For Apache (8888) [default for MAC OS X] For MySQL (8889) [default for MAC OS X]
{ "language": "en", "url": "https://stackoverflow.com/questions/7586774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Socket Connect to 8443 ok but not 443? I'm doing a little bit of socket programming on android (note I said socket, not HttpClient or HttpUrlConnection) and I'm running into a very strange issue where I cannot make a connection to my tomcat server on port 443 but 8443 is fine. My code is very simple, this is all there is to it: public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); try{ Socket s = new Socket(); InetSocketAddress addr = new InetSocketAddress("10.1.1.1", 443); s.setKeepAlive(true); s.setSoTimeout(300000); s.connect(addr); }catch{<my catch statement>} } That's all. I push the program to my device and launch it but it always throws a SocketException: Operation Timed Out error. However, if I switch the port on both the serverside and code side to 8443, my device can connect no problem. I am doing nothing more than changing the number in the server.xml file. Couple of things that are interesting to note as well, if I run the same exact thing in an emulator on my computer, it works just fine. I also ran wireshark on the connection between the device and my computer and it looks like it keeps throwing back an ICMP Destination Unreachable: Destination Port Unreachable. How can that be when I can ping it from my device? I looked to see if this was more appropriate on serverfault but from the FAQ over there, it seems more geared towards professional rather than personal server issues. Does anyone have any idea why an android device can't connect to certain ports on my server when my emulator can? And why does the switch to 8443 suddenly allow the connection to work? A: Is there a firewall between your Android device and your server that isn't present between your desktop (the emulator) and your server?
{ "language": "en", "url": "https://stackoverflow.com/questions/7586778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the regex to return the following I need the regex that returns the following from a webpage's code, I'm searching whithin Dreamweaver in the code of the page: <body> **** lines of HTML code (anything)*** <div class="pg"> sorry I'm into a situation that only regex is the solution, i'm so new to it. A: You could try something like: <body>[\s\S]*<div> class="pg"> you need [\s\S] because . probably won't match \n (unless Dreamweaver has a checkbox for multiline mode or something)
{ "language": "en", "url": "https://stackoverflow.com/questions/7586783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Could not find devise-1.4.6 in any of the sources I have installed devise 1.4.6 succesfully on my local development environment. I have this in my bundle file: gem 'devise' But when I want to deploy it to heroku, it says "Could not find devise-1.4.6 in any of the sources". What should I do? Thanks! A: Add the following line just at the beginning of your Gemfile: source "http://rubygems.org" Heroku doesn't seem to have RubyGems in their list of sources for gems. Alternatively you might want to execute bundle update to update your gems to the newest version (iirc, devise 1.4.7 is out) and then push to heroku again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: perl: can I wait 15 minutes, and then if a key has not been pressed, do something? here's my first ever perl program: I want to make sure that if I'm away from my machine for a while, then this script ssh's to our main server and kills all my processes there. (I keep forgetting to kill them when I go for lunch and they hog vast amounts of cpu and memory). I've got this far, and 15 minutes after the screensaver activates the killing starts. #!/usr/bin/perl my $cmd = "dbus-monitor --session \"type='signal',interface='org.gnome.ScreenSaver',member='ActiveChanged'\""; open (IN, "$cmd |"); while (<IN>) { if (m/^\s+boolean true/) { print "*** Screensaver is active ***\n"; print "*** Sleeping before megadeath....\n"; sleep(15*60); print "*** killing all jla processes on anvil...\n"; $result = `ssh anvil pkill -u jla`; print "*** should all be dead\n"; print $result; } elsif (m/^\s+boolean false/) { print "*** Screensaver is no longer active ***\n"; } } But what I'd like is to wait 15 minutes while monitoring the keyboard. If say, the 'N' key gets pressed (in the terminal the script is running in), then I want to abort the killing and go back to monitoring the screensaver. This will give me an escape route if the screensaver comes on while I'm getting coffee. Some sort of Bond-style countdown would be nice, too. Actually even better would be to notice when the screensaver get unlocked, and stop the countdown if so, going back into monitoring mode. Then I don't even have to worry about remembering to press N. A: If your perl has thread support, you could do something like this: #!/usr/bin/perl use warnings; use strict; use threads; use threads::shared; use Term::ReadKey; my $DONT_TERMINATE :shared; my $TIMEOUT = 5; threads->new( sub { wait_for_keypress('n', $TIMEOUT) })->detach; threads->new( sub { countdown($TIMEOUT) })->join; sub countdown { my ($timeout) = @_; while ( 1 ) { my $elapsed = time - $^T; last if $elapsed >= $timeout; return if $DONT_TERMINATE; print $timeout - $elapsed, "\n"; sleep 1; } print "Killing some processes\n"; } sub wait_for_keypress { my ($key, $timeout) = @_; my $input = ReadKey( $timeout ); $DONT_TERMINATE = (defined($input) and ($input eq $key)); return; } If you don't have thread support, you can use Coro. Note: I deleted my Coro example because it wasn't working properly. I'll post it again if I figure it out. A: I'd use select (via IO::Select), which lets you check if a filehandle has ready data. However, you can't use "buffered" IO operators like <> with select, so this is more complicated than you might like (You have to use sysread and maintain your own buffer). Here's how to watch the screensaver activity, and do something if it's been on for 15 minutes. use IO::Select; my $s = IO::Select->new(); # ... Start dbus-monitor as above ... $s->add(\*IN); my $buf = ''; my $started = 0; my $waitfor = 15*60; while ( 1 ) { # Read from all ready filehandles (timeout if none ready after 1 sec) foreach my $fh ( @ready = $s->can_read(1) ) { sysread($fh, $buf, 128, length($buf)); } # Handle each complete line of input while ( $buf =~ s/^(.+)\n// ) { my $line = $1 # ... Do something ... if ( $line =~ m/^\s+boolean (true|false)/ ) { if ( $1 eq 'true' ) { $started = time; print "Starting timer\n" } else { $started = 0; print "Canceled timer\n" } } } next unless $started; # Screensaver is on, how long has it been running? my $timeleft = $started+$waitfor-time; if ( $timeleft <= 0 ) { print "The screensaver has been on for at least 15 minutes\n"; # ... Do something ... $started = 0; # Don't do this again until the screensaver is restarted } else { # You can print out an updated countdown print "$timeleft seconds left\n"; } } I haven't tested this at all, but it might be enough for you to make it work. P.S. It won't work on Windows, where select only works on sockets. A: Sinan's and nandhp's solutions will work for this task. threads and select are powerful tools in the Perl programmer's arsenal, but I'd be reluctant to suggest them for somebody's "first ever perl (sic) program". So I'll suggest another approach. To oversimplify the statement of this problem, we want to do something (fire a command to kill processes on a remote sever) when something else happens (the screen saver has been active for 15 minutes). use strict; use warnings; initialize_program(); until (something_happens()) { sleep 60; } do_something(); exit; The do_something part is straightforward: sub do_something { print "*** killing all jla processes on anvil...\n"; $result = `ssh anvil pkill -u jla`; print "*** should all be dead\n"; print $result; } For the something_happens part of the program, I'd suggest sending the dbus-monitor output to a file in a background process, and reading from the file whenever you want to know the state of the screen saver. The dbus-monitor program produces output quite slowly, and reading from a Perl filehandle will tend to block (unless you learn about and use select). I'm going to tweak the dbus-monitor command a little bit. This command will print out a timestamp every time the state of the screen saver changes: my $command = q[dbus-monitor --session "type='signal',interface='org.gnome.ScreenSaver',member='ActiveChanged'" | perl -ne 'print time," $_" if /boolean/']; and we'll start our program by executing: sub initialize_program { # broken into multiple lines for readability my $command = q[dbus-monitor --session ] . q["type='signal',interface='org.gnome.ScreenSaver',member='ActiveChanged'"] . q[ | perl -ne 'print time," $_" if /boolean/']; system("$command > /tmp/screensavermonitor &"); } Now to see whether and for how long the screen saver is active, we parse /tmp/screensavermonitor every once in a while. sub something_happens { open (my $fh, '<', '/tmp/screensavermonitor') or return do { warn $!;0 }; my @output = <$fh>; close $fh; # we only care about the last output my $state = pop @output; if (!defined $state) { # maybe there's no output yet return 0; } if ($state =~ /false/) { # screensaver is not active return 0; # event hasn't happened yet } if ($state =~ /true/) { # screensaver is active -- but for how long? # start time (in seconds since the epoch) is included in output my ($screensaver_start_time) = ($state =~ /(\d+)/); if (time - $screensaver_start_time >= 15 * 60) { return 1; } else { return 0; } } return 0; } A: As mob said, threads and select are overcomplicating this a bit. So here's something nice and simple with Term::ReadKey, which lets you do what you asked for in the first place: Wait for a key to be pressed, but timeout if no key is pressed within 15 minutes. #!/usr/bin/env perl use strict; use warnings; use Term::ReadKey; my $cmd = "dbus-monitor --session \"type='signal', interface='org.gnome.ScreenSaver',member='ActiveChanged'\""; open(IN, "$cmd |"); ReadMode 'cbreak'; # return keypress immediately without waiting for "Enter" while (<IN>) { if (m/^\s+boolean true/) { print "*** Screensaver is active ***\n"; print "*** Sleeping before megadeath....\n"; my $key = ReadKey 900; # timeout after 900 seconds = 15 minutes if (defined $key) { print "*** A key was pressed; megadeath averted\n"; } else { print "*** killing all jla processes on anvil...\n"; my $result = `ssh anvil pkill -u jla`; print "*** should all be dead\n"; print $result; } } elsif (m/^\s+boolean false/) { print "*** Screensaver is no longer active ***\n"; } } ReadMode 'restore'; # back to normal input mode (Code is syntactically correct, but has not been run, so it is not fully tested. You may want to also set the 'noecho' ReadMode in addition to 'cbreak' to prevent the keypress which disables megadeath from appearing on the screen.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7586794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: App Engine Java Unit Test Environment Setup we use the appengine-web.xml file to store global config data as system properties (like the location of various development servers we need to communicate with). These properties are not available when running unit test with the LocalServiceTestHelper class. There seem to be methods to set the desired system properties during setUp of each unit test (cf. e.g. http://code.google.com/appengine/docs/java/tools/localunittesting/javadoc/com/google/appengine/tools/development/testing/LocalServiceTestHelper.html#setEnvAttributes(java.util.Map)) but so far we have failed to implement this. It would be great if somebody could provide a simple example of how to set a system property in a app engine unit test? EDIT: here is a minimal example that demonstrates what I am trying to do import java.util.HashMap; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; public class MyTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()); @Before public void setUp() { Map<String, Object> values = new HashMap<String, Object>(); values.put("de.foo.bar", "baz"); helper.setEnvAttributes(values); helper.setUp(); } @After public void tearDown() { helper.tearDown(); } @Test public void foo() { System.out.println("my env variable: " + System.getenv("de.foo.bar")); } } This prints out "my env variable: null" A: According to the documentation, I think the method setEnvAttributes() does something different than you expect. The environment attributes you're setting are available using Environment.getAttributes() not System.getenv()
{ "language": "en", "url": "https://stackoverflow.com/questions/7586796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: multi vs single instance business application (This topic is so general there has to be an existing thread somewhere, but darned if I can find it. I did find several debates on the best way to enforce single instance apps.) I've got an inhouse business app coded in .Net 3.5. I use ClickOnce to publish and the back end is SQL Server 2008. The app has always been set to single instance just to be on the safe side, but my users are starting to express interest in having multiple instances, mainly so they can view and compare different sets of data simultaneously. I'm trying to think of possible dangers of a multi instance app, but so far nothing critical comes to mind. Obviously the instances will be sharing some resources. Can anyone provide me with specific problems of having a multi instance app? One thing I thought of was that ClickOnce checks for updates upon app startup. Suppose a user opens an instance, then a new version is published, then the user opens a second instance. Does ClickOnce handle the update elegantly? I suppose it would need to close all running instances, then update the version. A: If all your app does is communicate using ADO.NET to a SQL Server, there's not likely to be too many issues as multiple processes on one machine is going to look identical to multiple processes on separate machines as far as SQL Server is concerned. However, if your app uses local files or other shared resources you will have to co-ordinate sensibly between the running instances of your app.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Copy Ant path to WAR's lib directory I think this is probably a common use case. I define a set of paths: <path id="log4j.classpath"> <fileset dir="${log4j.home}"> <include name="log4j-1.2.16.jar"/> </fileset> </path> <path id="junit.classpath"> <fileset dir="${junit.home}"> <include name="junit-4.8.2.jar"/> </fileset> </path> <path id="all.classpath"> <path refid="log4j.classpath"/> <path refid="junit.classpath"/> </path> When I build my web service I have: <target name="compile"> <javac srcdir="${basedir}/src" destdir="${build.classes.dir}" debug="true"> <classpath> <path refid="all.classpath"/> </classpath> </javac> </target> Now, I want to copy all the files in the path with id all.classpath into my war's lib directory. What is the best way to do this? Currently, I have something like this: <copy todir="${war-lib}" verbose="true"> <fileset dir="${log4j.home}"> <include name="log4j-1.2.16.jar" /> </fileset> <fileset dir="${junit.home}"> <include name="junit-4.8.2.jar"/> </fileset> <copy> But I don't want to have to re-define the filesets. That seems to be error-prone, and a bad design. There has got to be a better way. Please enlighten me. EDIT: To make it interesting, I only have access to ANT 1.6 A: Not sure if it will work, but try this (you'll need Ant 1.7 or higher to do this): <copy todir="${war-lib}" verbose="true"> <path><path refid="all.classpath" /></path> </copy>
{ "language": "en", "url": "https://stackoverflow.com/questions/7586803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passing clicked hyperlink text in query string I am using Visual Studio 2005 Professional Edition. I have a Crystal Report on which one column contains hyperlink values coming from a stored procedure. When the user clicks on any of these hyperlink values, a next page [here, ReportAllBlocks.aspx] should open but I want to pass this value as a query string. For example: The user clicked on a hyperlink text: New York, so the URL should become: http://localhost:1031/myProject/ReportAllBlocks.aspx?New York I am not following how to add this hyperlink value to the URL, either in the box shown below, or programatically through C#. A: I would just create a formula field. First create a parameter for the url(or hard code the value if it never changes). In the formula editor: {?URLParameter} + {Table.Field} Then add the formula to your report, open the format editor, and select 'Current Website Field Value' instead of 'A File'. The field will now become a hyperlink. It will still look like text just act different when clicked so you may want to change the font color and underline. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set a ResourceDictionary DataContext from code behind I'm trying to set a ResourceDictionary DataContext, from the code behind of my Resource Dictionary. I have a Data Template that uses its own style (the Resource Dictionary), the style contains a checkbox with its own style : <Style x:Key="CheckBoxStyle" TargetType="CheckBox"> <EventSetter Event="CheckBox.Checked" Handler="CheckBox_Checked"/> <EventSetter Event="CheckBox.Unchecked" Handler="CheckBox_Unchecked"/> </Style> In the CheckBox_Checked event, I want to reference the dictionary's parent (a User Control) View Model, to execute a function, but because Resource Dictionaries do not have a DataContext property setting the DataContext from inside a control event, like this : private void CheckBox_Checked(object sender, RoutedEventArgs e) { MyViewModel viewModel = (MyViewModel)DataContext; } doesn't work (of course). I think I need to get a handle to the Ancestor (the Resource Dictionary User Control), but don't know how to do this - or there may be another way.. Thanks Joe A: As @dowhilefor's comment says, Resource Dictionaries are simply a collection of resources, so do not need a DataContext. You can, however, add a code-behind file to the ResourceDictionary, which may be what you're looking for. Create a new class in the same directory as your ResourceDictionary and name it ResourceDictionaryName.xaml.cs. It will become the code-behind file for your ResourceDictionary. Open the new .cs file, and make sure the following is there (Can't remember if it's added automatically or not): public partial class ResourceDictionaryName { public ResourceDictionaryName() { InitializeComponent(); } } Next, open your XAML file and add the following x:Class attribute to the ResourceDictionary Tag: <ResourceDictionary x:Class="MyNamespace.ResourceDictionaryName" ... /> Now your ResourceDictionary is actually a class, and can have a code-behind file. Edit In response to your edits, I would use the CheckBox itself and get either the CheckBox's DataContext, or traverse up the Visual Tree to find the UserControl I'm looking for and then get it's Data Context Easy way: private void CheckBox_Checked(object sender, RoutedEventArgs e) { var cbx = sender as CheckBox; MyViewModel viewModel = (MyViewModel)cbx.DataContext; } If CheckBox's DataContext is not the ViewModel you're looking for: private void CheckBox_Checked(object sender, RoutedEventArgs e) { var cbx = sender as CheckBox; var userControl = FindAncestor<MyUserControl>(cbx); MyViewModel viewModel = (MyViewModel)myUserControl.DataContext; } public static T FindAncestor<T>(DependencyObject current) where T : DependencyObject { current = VisualTreeHelper.GetParent(current); while (current != null) { if (current is T) { return (T)current; } current = VisualTreeHelper.GetParent(current); }; return null; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7586810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Fake an active record model without db I feel like I've got to me missing something. I'm writing a ruby gem that allows interaction with active record as an add on to its primary function. In writing test cases for it, I need to be able to specify dummy active record models to test this functionality. It would be superb if I could get an instance of an active record model that didn't need any connection to a db, that could have relations, all that stuff, but didn't require me to setup tables in a database. I'm fairly new to testing, and outside of rails testing i'm pretty dang new, but it seems like I should be able to do something like that fairly easily, but I'm not finding anything. Can anyone tell me what I'm missing? I've looked at factories, fabricators, fixtures, all those seem to want to hit the db. How do people test gems where you need AR object only for testing? A: Others have hit this same problem. My usual take is to use a mocking library for unit tests, and write some functional ones using fixtures to complement them for setups too complex to mock (which you should avoid any way). Or use a replacement library for AR which provides the same interface but doesn't require a DB. I haven't used rails in some time, but there used to be some available. This is not completely without the same problems as using a DB in the first place, as these libraries have other requirements usually (like web servies, LDAP, ...), or just need the same single record setup work as mocks do. Or bite it and just use fixtures, but make their cost really small by using an in memory sqlite DB just for tests, and proper migrations. A: Yeah, I wanted to do this awhile back in Rails 2.3 and it was a massive mocking headache. I think it is easier now with ActiveModel, which gives you an explicit interface, if you want to roll your own. Also, haven't used it myself, but Josh Susser has a gem that lets you mix in AR-ish behavior into any class. It seems geared towards using plain ruby objects in forms, but it's probably useful for unit testing too. See informal. He talks about it in a recent Ruby Rogues episode A: It sounds like you need NullDB: NullDB is the Null Object pattern as applied to ActiveRecord database adapters. It is a database backend that translates database interactions into no-ops. Using NullDB enables you to test your model business logic - including after_save hooks - without ever touching a real database. A: Another option is to use a sqlite3 adapter and run the database in memory, and use a DatabaseCleaner to get rid of records after the test. This approach have certain advantages: * *You can see the SQL in the test, that simplifies the query optimisation process *It is close to "real life" examples On the other hand, I should say it is a bit messy, because it is a bit long, but feel free to restructure it ;) Here is a brief description what you need for that: # in Gemfile gem "activerecord" #since you are dealing with activerecord gem "database_cleaner", :group => :test gem "sqlite3", :group => :test I am using the following approach to keep the thing, but you are welcome to have it differently: # in RAILS_ROOT/test/support/active_record.rb require 'logger' ActiveRecord::Base.establish_connection( :adapter => "sqlite3", :database => ':memory:' ) #this line will print the SQL queries right into console ActiveRecord::Base.logger = Logger.new(STDOUT) # in RAILS_ROOT/test/support/database_cleaner.rb require 'database_cleaner' DatabaseCleaner.strategy = :truncation # or DatabaseCleaner.strategy = :trunsaction (it is up to you) module OrmSetup def before_setup DatabaseCleaner.start end def after_teardown DatabaseCleaner.clean end end # in RAILS_ROOT/test/test_helper.rb ... require File.expand_path("support/active_record", File.dirname(__FILE__)) require File.expand_path("support/database_cleaner", File.dirname(__FILE__)) class Test::Unit::TestCase include OrmSetup end And now in your test you can have something like require 'test_helper' class User < ActiveRecord::Base end class MyFancyTest < Test::Unit::TestCase def setup before_setup end def teardown after_teardown end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7586813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to retrieve data from child table using CursorLoader which loads data from main table? My app is using CursorLoader to load data from main table. The data will be displayed in ListView with the help of CursorAdapter. The view displayed in ListView also requires data from child table. The relationship of the tables is one-to-many. * *If I join both tables during the query, the combined records will be as many as child records, thus in ListView, it will display multiple item for one single record in the main table. *If I don't join the table, I am not sure what the best way to retrieve child records after the CursorLoader has delivered the data via the cursor. Anyone able to help me out? A: If the child table data doesn't need to be queried separately then you could put that data into the main table using something like JSON notation and then parse it out inside of the bindView method for the CursorAdapter. This might have performance problems depending on the complexity of the data in the child table. But that would allow you to use a single cursor. Another approach you could take is to make a DAO object that ran the raw query as a join (so you get multiple rows) and then processes the cursor it to a List where Foo is a POJO representing the data. (or run n+1 queries - the main query and then a sub query for each row). Then make a Loader that calls the DAO to return a List and use a ListAdapter from that. Your custom loader could still register for the data change notifications and do the reloading. I've used CursorLoader as a pattern to make my own loaders that reload when I didn't want to mess with the Cursor in the ListView and it works well. A: You should try the join option and set your sort order for your query to make sure that the results are sorted by the results in the main table. Afterwards, you can use an ExpandableListView to show the main item and all the child items underneath to indicate the "one-to-many" relationship in a good way. Of course you need to write your adapter appropriately to handle this case. A: If you want to get the aggregate data from child table ,you should use 'group by' in sql statements.for example,two tables: parent(id,name) child(id,parentId,age) To query all parents with the oldest child: select a.id,a.name,max(b.age) from parent as a inner join child as b on a.id=b.parentId group by a.id,a.name
{ "language": "en", "url": "https://stackoverflow.com/questions/7586816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: moving pointer between vectors in vector causes vector iterators incompatible I have std::vector of cells. Each cell has other std::vector to store some pointers to entities. Now I want to move pointer from one cell to another based on calculation new cell index. But I am getting vector iterators incompatible. I know that is caused by push_back invalid the iterator, but I do not know why, because push_back doesn't manipulate with current existing entityIter. How should I modified the following example to make it work? for(uint32 cellIndex = 0; cellIndex < m_cells.size(); ++cellIndex) { std::vector<entity_type> & entitiesInCurrentCell = m_cells[cellIndex].entities; std::vector<entity_type>::iterator entityIter = entitiesInCurrentCell.begin(); while(entityIter != entitiesInCurrentCell.end()) { entity_type entity = *entityIter; uint32 entityNewIndex = calculateIndex(entity->getPosition()); if(entityNewIndex == cellIndex) { ++entityIter; continue; } m_cells[entityNewIndex].entities.push_back(entity); entitiesInCurrentCell.erase(entityIter++); } } entity_type is a pointer type which point to entity allocated elsewhere, I do not want to delete it, just move the pointer between cells. (I know this approach is not the best way - relocating pointer to higher-index cell causes recalculation it - but this is aim of this question) thank you A: The line that erases from entitiesInCurrentCell has a bug. Correct it by writing entityIter = entitiesInCurrentCell.erase(entityIter); When erasing from a container, the next iterator is returned by the erase function, so you do not need to increment the iterator. A: Erasing from std::vector invalidates iterators. see STL vector::erase Therefore entityIter is invalid after the call to erase. Alas the check "while(entityIter != entitiesInCurrentCell.end())" will never become true. change your code to: if(entityNewIndex == cellIndex) { ++entityIter; } else { m_cells[entityNewIndex].entities.push_back(entity); entityIter = entitiesInCurrentCell.erase(entityIter); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7586817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Datatype/structure to store timezone offset in MySQL Which would be the proper datatype/structure to store timezone offsets in MySQL? I just want to store the numeric value (the city and country are obviously stored in other columns). Examples: * *-5:00 Guayaquil, ECU *-4:30 Caracas, VEN *0:00 Some city *2:00 Bonn, GER A: You should use TIME. It's the right data type for the task: you have formatting and calculations are available. Moreover, according to the docs, TIME is also supposed to be used as a result of differences between two moments, which is what Timezones are in fact. From the docs: MySQL retrieves and displays TIME values in 'HH:MM:SS' format (or 'HHH:MM:SS' format for large hours values). TIME values may range from '-838:59:59' to '838:59:59'. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).
{ "language": "en", "url": "https://stackoverflow.com/questions/7586819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Starting with BDD (using Behat and Symfony2 as background) I'm just starting with BDD and this instructions about Behat but I'm missing an example a bit more complex, Product-Category example is too simple (but necessary at first of course..) when you want to go beyond.. I'm working with models that doesn't have a unique field in order to do this: $product = this->getRepository('AcmeDemoBundle:Product')->findOneByName($productName); In my case I have a relation 1:1: Room hotel_id ... Default configuration room_id name //"single room", "double room"... price ... So, when I want to create the scenario "Scenario: A room has a default configuration" I'd like to start this way: I have a room XXX but I can't because I don't have any field like "name" or any other that is unique, so I just write: I have a room The problem comes when I want to retrieve the room to add a default configuration like in the example Product-Category ($product = $this->getRepository('AcmeDemoBundle:Product')->findOneByName($productName);), I don't know what to do.., how to retrieve the room object I'm using to add a default configuration? or how to retrieve the default configuration object? So, any idea how should I act? EDIT: After the response of everzet I want to add the scenario I'm interested in implement: When I add a default configuration to a room Then I should find a room has a default configuration Maybe this scenario sounds strange, but as I said above, I don't have a unique field in neither in Room nor in Default Configuration. So, what should be the functions in my .feature file? A: All your scenario step definitions run inside single context class instance and every scenario has it's own context instance. It means, that you can set ivars on the current context in one step definition and read it's value in next step definition. It's even described in the Behat documentation ;-) In your case, your I have a room step could save last persisted record id into context ivar and next step could use it's value to find a specific (last added) room in the database. Like that: // Given I have a room // … $room = new Room(); $em->persist($room); $em->flush(); $this->lastRoomId = $room->getId(); // … // Then this room should have ... // … $room = $em->getRepository('AcmeDemoBundle:Room') ->findOneById($this->lastRoomId); // …
{ "language": "en", "url": "https://stackoverflow.com/questions/7586823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I'd like to develop for the Kindle Fire, but it won't be released until November. What should I use for a dev device in the meantime? I haven't developed for Android before, but I hear the emulator is so slow as to be almost unusable, so I want to know which tablet to buy. Getting a device with the same screen resolution (1024 x 600) as the Fire would seem to be the most obvious thing to look for. Anything else? A: I haven't developed for Android before, but I hear the emulator is so slow as to be almost unusable, so I want to know which tablet to buy. For standard Android, emulator speed is only really an issue for Honeycomb (Android 3.x). Earlier versions of Android, such as the Android 2.1(?) that underlies the Fire, run fine in the emulator on reasonable development machines (e.g., 2.5GHz CPUs) for screen resolutions those earlier versions of Android were designed for (e.g., 800x480). A 1024x600 Android 2.1(?) emulator may be somewhat sluggish without a top-end CPU (e.g., Core i7 with Turbo Boost to 3.4GHz). The speed is tied some to screen resolution and some to the increased reliance on hardware graphics acceleration in Honeycomb. Getting a device with the same screen resolution (1024 x 600) as the Fire would seem to be the most obvious thing to look for. You are certainly welcome to purchase such a device, assuming you can find one. While such a device would more closely resemble a Fire than a rutabaga resembles a Fire, please understand that the Fire does not really match any existing Android device. We don't know for certain what Android version it runs. We do not know how much they changed the APIs, since they do not have to be in compliance with any compatibility rules (required for devices that have the Android Market, which the Fire won't have). And so on. You indicate in your question that you want to "develop for the Kindle Fire". If you mean that exclusively, I suggest that you wait until the Fire ships before investing in hardware. With luck, Amazon will publish instructions for an emulator environment, or might even ship their own emulator AVD pre-configured with Fire-style firmware. At the very least, you should download the SDK and try an Android 2.1(?) emulator hacked to the 1024x600 resolution and see if you need to then shell out coin for non-Fire hardware. If, however, you are developing for Android, with one device target being the Fire, then I would worry less about getting hardware that resembles the Fire. Determine what sorts of devices you are going to target (phones, tablets, TVs) and plan out how you are going to test on those profiles. For example, it may make more sense for you to invest in a phone now and also a Fire when it ships. Also, bear in mind that that the Amazon Appstore may not allow you to create apps solely for the Fire. It may be that any app you upload to the Appstore will be available to all devices with the Appstore. Since the Fire was announced less than four hours ago, we simply don't have all these details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: rails2 memcache expires_in problem I have a strange problem with a Rails 2.3.4 application. The expires_in time is set to 10 seconds after each hour. But memcache seems to remember the value even after a cache flush. caches_action :deals, :expires_in => (3600 - Time.now.to_i % 3600) + 10, :cache_path => Proc.new { |controller| "blah" } Memcache output: <8 new client connection <8 get mynamespace:views/show >8 END <8 set mynamespace:views/show 0 1457 20499 >8 STORED <9 new client connection <9 flush_all >9 OK <9 connection closed. <8 get mynamespace:views/show >8 END <8 set mynamespace:views/show 0 1457 20499 >8 STORED A: Try putting your expires_in value inside a proc. edit: I forgot to mention calling the proc with .call at the end. A: Make sure you are actually using memcached, and not the rails default cache mechanism. You should have something like this in your environment.rb : config.cache_store = :mem_cache_store I had a similar problem while trying to get caching working with :expires_in I didn't realise that the above was needed. Without it rails defaults to using a FileStore, or a MemoryStore, both of which will happily sit there caching, but ignoring the :expires_in option. Thanks to this article on memcached basics by Rob Anderton for helping me figure this out in the end
{ "language": "en", "url": "https://stackoverflow.com/questions/7586841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using OpenGL shaders to plot 4D points in 2D in C++ Possible Duplicate: Visualising 4D objects in OpenGL I have a set of 4 dimensional data points (lets call the dimensions X,Y,A, and B) that I'd like to plot in 6 different 2d plots (plot XxY, XxA, XxB, YxA, etc...). In a previous question I asked about the proper way to store and plot this data. The solution was to use a VBO that stored the 4 dimensional vertices. Then using different vertex shaders I could select which dimensions are plotted in each of the 2d plots. I've spent a few weeks looking around for openGL tutorials on how to do this but I haven't yet found something that makes sense. My question is this: In c++, how can I define a shader that would allow me to plot only 2 dimensions of a 4 dimensional point in a VBO, and do I need to define a single shader for all 6 2d plots or do I need a shader for each of 6 different plots? Finally how do I incorporate the shader into the plotting code so it gets used by openGL? A: Since shaders can work with 4 dimensional vectors and 4x4 matrix, we can be smart and use only one vertex shader to do the trick. This shader will take three inputs: * *the point data (a 4 floating vector), *a selection 4x4 matrix, *a projection 4x4 matrix. All the magic is done by the selection matrix, which will map you 4 coordinates vector to planar coordinates. Let's call the point data v, the selection matrix S and P the projection matrix. The output of the vertex shader will be: P * S * v By setting correctly the coefficients of S, you will be able to select which component in v should appear in the result. For example, if you want to display YxB, then S will be: So we have: P is a standard projection matrix, which will help you to place your graph correctly (offsets and scale). Following is an example of vertex shader implementation (not tested, may contain mistakes) for OpenGl3: #version 130 in vec4 vin; uniform mat4 s; uniform mat4 p; out vec4 vout; void main() { vec4 tmp = s * vin; // Depending on your projection matrix, // you may force the 4th component to 1. tmp[3] = 1; vout = p * tmp; } Notes: glUniformMatrix4fv is the function to use to define S and P. A: You have this input: in vec4 Points; You can access to vec4 components by indexing them: Point[0]; // Equals Point.x You can supply the following uniforms to specify which components to use for plotting: uniform int XCoordIndex; uniform int YCoordIndex; gl_Position = vec4(Point[XCoordIndex], Point[YCoordIndex], 0.0, 1.0)
{ "language": "en", "url": "https://stackoverflow.com/questions/7586845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: devise registration confirmation freezes when I click email confirm link I'm getting some strange behavior when testing on my local machine: 1) First of all when I sign-up, I'm redirected to the home page and I see a flash message that says: "You have signed up successfully. However, we could not sign you in because your account is unconfirmed." I find it strange to see a warning type message when the user is merely on the right path to creating an account. I could easily change the message in /locales/devise.en.yml, but I just wanted to confirm this was the default behavior of devise, and not something wrong with my setup? 2) I successfully receive an email with a confirmation link: <p>You can confirm your account through the link below:</p> <p><a href="http://localhost:5000/accounts/confirmation?confirmation_token=MywxHuW3PWHvg6x2nUfG&amp;format=">Confirm my account</a></p> When I click on the email confirmation link, I see a blank web page. the development log shows: Started GET "/accounts/confirmation?confirmation_token=MywxHuW3PWHvg6x2nUfG&format=" for 127.0.0.1 at 2011-09-28 09:41:55 -0700 Processing by Devise::ConfirmationsController#show as Parameters: {"confirmation_token"=>"MywxHuW3PWHvg6x2nUfG"} SQL (0.9ms) SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull FROM pg_attribute a LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum WHERE a.attrelid = '"artists"'::regclass AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum Artist Load (0.4ms) SELECT "artists".* FROM "artists" WHERE "artists"."confirmation_token" = 'MywxHuW3PWHvg6x2nUfG' LIMIT 1 SQL (0.8ms) SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc, a.attnotnull FROM pg_attribute a LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum WHERE a.attrelid = '"artists"'::regclass AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum SQL (0.2ms) BEGIN AREL (0.9ms) UPDATE "artists" SET "confirmation_token" = NULL, "confirmed_at" = '2011-09-28 16:41:55.894603', "updated_at" = '2011-09-28 16:41:55.895467' WHERE "artists"."id" = 85 [paperclip] Saving attachments. SQL (0.8ms) COMMIT SQL (0.1ms) BEGIN AREL (0.5ms) UPDATE "artists" SET "last_sign_in_at" = '2011-09-28 16:41:55.915779', "current_sign_in_at" = '2011-09-28 16:41:55.915779', "last_sign_in_ip" = '127.0.0.1', "current_sign_in_ip" = '127.0.0.1', "sign_in_count" = 1, "updated_at" = '2011-09-28 16:41:55.916532' WHERE "artists"."id" = 85 [paperclip] Saving attachments. SQL (0.5ms) COMMIT Completed 406 Not Acceptable in 231ms "Not Acceptable" it says? What does that mean? Did it go through or not? What happened? A: I figured it out. Apparently the link contained a "&format=" parameter at the end of the link. The devise views for emails were injecting the @resource causing the id of the resource to be put in as the format of the url (in this case it's blank because I'm using params_to and the artist nickname as the id, and there is some other issue I'm having with that not being populated... not related to this problem). I fixed the views and that has fixed the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Placement new breaks consts and references? Following the discussion on my answer to this question, apparently: the following code is allowed struct Foo { int x; }; Foo f; Foo & f_ref = f; (&f) -> ~Foo (); new (&f) Foo (); int x = f_ref .x; but the following code is not allowed struct Foo { const int & x; // difference is const reference Foo (int & i) : x(i) {} }; int i; Foo f (i); Foo & f_ref = f; (&f) -> ~Foo (); new (&f) Foo (i); int x = f_ref .x; Because of $3.8/7 If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if: * *the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type ... I can understand how a reference to f.x could be invalidated when f ceases to exist, but I don't see why f_ref should be invalidated purely because one of its members is const and/or reference and not otherwise: it was a reference to a Foo before and is a reference to a Foo afterwards. Can someone please explain the rationale behind this condition? Edit Thanks for the answers. I don't buy the "guarantee it doesn't change" argument because we don't currently allow optimisers to cache referands, for example: struct Foo { const int & x; Foo (const int & i) : x(i) {} void do_it (); }; int i; Foo f (i); const int & ii = f.x; f .do_it (); // may modify i std :: cout << ii; // May NOT use cached i I don't see how do_it is allowed to invalidate referenced values but operator new isn't -- Sequence points invalidate cached values: why should delete/placement-new be exempt? A: I believe the motivation is to permit the compiler to cache the values of const objects (note that's const objects, not merely referands of pointers-to-const and reference-to-const), and the addresses of referands of references, across calls to unknown code. In your second example, the compiler can "see" firstly that the object has been created and destroyed, and secondly that it was re-created using the same value. But the authors of the standard wanted compilers to be allowed to turn this code: struct Foo { const int & x; Foo (int & i) : x(i) {} }; int i = 1; Foo f(i); some_function_in_another_TU(&f); std::cout << f.x; Into this: struct Foo { const int & x; Foo (int & i) : x(i) {} }; int i = 1; Foo f(i); some_function_in_another_TU(&f); std::cout << i; // this line is optimized because the reference member of f cannot be reseated, and hence must still refer to i. The destruct-and-construct operation violates the non-reaseatable-ness of the reference member x. This optimization should not be particularly controversial: consider the following example, using a const object rather than an object with a const or reference member: const int i = 1; some_function_in_another_TU(&i); std::cout << i; Here i is a compile-time constant, some_function_in_another_TU cannot validly destroy it and create another int in its place with a different value. So the compiler should be allowed to emit code for std::cout << 1; The idea is that the same should be true by analogy for const objects of other types, and for references. If a call to unknown code could reseat a reference member, or alter the value of a const data member, then a useful invariant of the language (references are never reseated and const objects never change their values) would be broken. A: As far as I can tell, it's just a matter of semantic correctness, and the adherent assumptions that the optimizer may make. Consider this: Bar important, relevant; Foo x(important); // binds as const-reference Zoo z(x); // also binds as const reference do_stuff(z); x.~Foo(); ::new (&x) Foo(relevant); // Ouch? The object z may reasonably expect its Foo member reference to be constant and thus refer to important. As the standard says, the destruction plus new construction in the last two lines "automatically updates all references to refer to the (logically) new object", so now the const-reference inside z has changed, despite the promise of being constant. To avoid this backstabbing violation of const-correctness, the entire reconstruction-in-place is forbidden. A: Optimization. Suppose I have: struct Foo { int const x; Foo( int init ) : x( init ) {} }; int main() { Foo a( 42 ); std::cout << a.x << std::endl; new (&a) Foo( 3 ); std::cout << a.x << std::endl; return 0; } The compiler, having seen a const int object, has the right to suppose that the value doesn't change; the optimizer might simply keep the value in a register accross the placement new, and output it again. Note that your example is actually quite different. The data member has type int const&; it is a reference (and references are always const), so the compiler can assume that the reference always refers to the same object. (The value of this object may change, unless the object itself is also const.) The compiler can make no such assumption about the value of the object it refers to, however, since i (in your case) can clearly change. It is the fact that the reference itself (like all references) is immutable that causes the undefined behavior here, not the const that you've written. A: If something is const-qualified, you're not supposed to modify it. Extending its lifetime is a modification with serious consequences. (For example, consider if the destructor has side-effects.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7586848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: JAXB don't generate attribute from java class I have a class like the following: @XmlRootElement(name = "task") class Task{ @XmlElement(name = "id") Integer id; @XmlElement(name = "name") String name; String bzId; } I want to generate an xml like the following: <task> <id>1</id> <name>String</name> </task> I can't seem to find it anywhere. How can i not generate the "bzId" in my example? A: you need to use the @XmlTransient annotation. Same this as the transient keyword, but for xml :D. You can also use the @XmlAccessorType on the class to change the default behaviour and just serialize annotated attributes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do i run a UNIX terminal from Java and send commands to it? Regarding the topic, the code below Process proc = null; try { String[] cmdss= {"gnome-terminal"}; proc = Runtime.getRuntime().exec(cmdss, null, wd); } catch (IOException e) { e.printStackTrace(); } Runs the terminal form Ubuntu. How do I issue commands into the terminal after running the termnal? eg: running the terminal and run command such as "ls" etc. A: You can give gnome-terminal some options on the command line what it shall execute. gnome-terminal -e /my/fortran/program The -x option gives you roughly the same benefit but you can split the commandline into separate words. Both -e and -x run the program with optional arguments while connecting the program`s standard input and output to the terminal. So the user can interact with the terminal properly. Example: gnome-terminal -x bash -c "ls; echo '<enter>'; read" This will open the terminal and run the "program" bash. bash will get two arguments: -c and ls; echo ....; read. The -c option makes bash parsing and executing the next argument. This will call ls, then echo ... then read which waits for the return key. In Java you must split the arguments appropriately into an array like this: String cmd[] = {"gnome-terminal", "-x", "bash", "-c", "ls; echo '<enter>'; read" };
{ "language": "en", "url": "https://stackoverflow.com/questions/7586858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to specify a unicode character using QString? How can I specify a unicode character by code (such as "4FF0") using QString? I tried QString s("\u4FF0"); but it only outputs a question mark. Any idea how to do this? Edit: It works that way, but is there a more direct way? std::wstring str = L"\u4FF07"; QString s = QString::fromStdWString(str)); A: Since C++11 you can use UTF-8 string literal prefix (u8): QString s(u8"\u4FF0"); A: If by direct you mean using a Unicode code point value, then QChar may be it: QString s = QChar(0x4FF0); A: Apparently '\u' only works with UTF-8: QString s = QString::fromUtf8("\u4FF0"); // Or with that at the start of your main function: QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf8")); ... QString s("\u4FF0"); A: As a direct pointer, try QString(QChar(0x4FF0)); You need to ensure you have the correct utf-16 encoding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: $_SERVER not returning query string I'm simply trying to store the current page a user is viewing in a DB. When the page loads, I insert $_SERVER['REQUEST_URI'] . $_SERVER['QUERY_STRING'] into my DB, but only the page (e.g. index.php?) is showing up, without the query string (I have verified that there IS a query string in the URL). I tried $_SERVER['PHP_SELF'] with the same results. EDIT TO ADD: Here is the dump of $_SERVER: Array ( . . . [REQUEST_METHOD] => GET [QUERY_STRING] => view=scores&yr=2010&wk=1 [REQUEST_URI] => /index.php?view=scores&yr=2010&wk=1 . . . ) So the query string is present in the array, even as part of REQUEST_URI. So my query... mysql_query("insert into clickstream (user_id, page) values (" . $_SESSION['user_id'] . ", '" . mysql_real_escape_string($_SERVER['REQUEST_URI']) . mysql_real_escape_string($_SERVER['QUERY_STRING']) . "');") or die('mysql error: ' . mysql_error()); ...should actually insert the query string twice, instead of no times! Thoughts? ADDED THOUGHT: Is it possible the MySQL DB strips everything from the input beyond the ?? The field is varchar. UPDATE W/ PARTIAL SOLUTION: Changing the SQL input to just $_SERVER['QUERY_STRING'] (without REQUEST_URI) successfully input the query string. Thus, it leads me to believe that either PHP or MySQL was stripping everything from the input string after the ?. So the input params were correct; the result just got truncated. Does anyone know why this might be the case? A: Different servers pass different $_SERVER globals to the page. I assume you are using Apache rather than NGINX where you might have to check that QUERY_STRING is defined in FASTCGI_PARAMS. The solution is to to do like @hakre says and just see which $_SERVER key has what you want. <?php print '<pre>'; print_r($_SERVER); print '</pre>'; A: Couldn't you just use $_SERVER['REQUEST_URI'] ? It has the query string as part of the output... A: Thanks for the feedback, particularly @nachito. The problem has been isolated to MySQL, not PHP. The output from PHP is correct, but MySQL is stripping everything from the URL after ? upon insertion into the database. A: Can you show us the definition of the table clickstream ? If the page column were only 10 chars long, then we have spotted the problem :) 'index.php?' (10 chars) To see the table structure you can issue this MySQL command: SHOW CREATE TABLE clickstream;
{ "language": "en", "url": "https://stackoverflow.com/questions/7586863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: phpcassa usual query methods or cql queries? Can you recommend what methods of queries to choose?Cql or usual classes? Phpcassa has both methods.cql is more comfortable than usual.but what will be efficiently? A: So far, the evidence is that CQL is as fast or faster than the older RPC-based API. (See comments on https://issues.apache.org/jira/browse/CASSANDRA-2500, for example.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7586864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java multiplayer game - networking concepts For a school project, we're supposed to create a multiplayer game in Java (it should be client/server) which can be played over the internet (we're programming this at school, so it's not homework). The game is turn-based, but there should be a chat, which ofcourse is real-time. However, none of us has experience with network programming and the more I read about it, the more questions I seem to have. My first thought was to use the socket API to implement the multiplayer part. The server waits for new data from the clients. However, there are multiple kinds of data to receive, like chat messages, movement, etc. Also, once the connection to the server is made, some initial data (like the Player's name) should be sent. The server should be able to see what kind of message it received, but how? I was thinking of creating a class Message with a string field type. But in my server code, I will get code like this: if (message.type.equals("message")) { // code to execute for chat messages } else if (message.type.equals("movement")) { // code to execute for movement } else if () { // ... } else { // ... } // Please ignore syntax errors :P When there are a lot of different kinds of data to send (and there WILL be), this doesn't look like the most efficient way. Also, this would mean both the server and client should have this Message-class/interface (duplicate code). What about other game stuff? For example, player 1 moves his character to a position which defeats another character. The client of player 1 calculates this defeatment and applies the correct actions. But what should be send to the server? Just the new player position or also the defeatment? With the first option, it means all other clients should do the calculations. Couldn't this cause any trouble? As I have no prior network programming experience, I'm a bit confused on how to do all these things. I've also read in another thread here on Stackoverflow that RMI might be a better option. Having read some information about this, I understand what RMI is, but I'm still not able to see whether it is a good option for this project or not. Any tips for this? As you see, I'm a bit confused on how to start with the networking part of this project. I've searched for some game programming books (for Java ofcourse), but none of them are focussed on the networking part. I've also searched for Java networking books, but these seem to be focussed on the technology, not on good code practices. If anyone knows a good book or has some advice in the right diection, it would be greatly appreciated. Thanks A: You're on the right path, but there are few things to clear up. If you're using sockets, you've figured out that you need to define a protocol - a mutual language for communicating moves and the state of the game. Sockets will let you send any sort of data in pretty much any format you want. It looks like you're thinking about serializing a class Message to send this type, this is one of doing things. If you use RMI (which has its own protocol), you will act as if you were calling Java methods, but in essence you're doing something similar, serializing data and passing it over a socket. There's nothing implicitly wrong about sharing code between the client and the server - in fact, most services do this in some form. Your client and server could both use a common library to define the message classes being passed around. RMI uses method stubs to determine the interface. Web services of all sorts define how methods are invoked. The general idea is to only expose the interface, not the implementation. Regarding your code, it might be cleaner to have a different Message subclass for each message type and you could put additional parameters for each message. You could then have a MessageProcessor class like: class MessageProcessor{ void process(Move1Message m) {...} void process(Move2Message m) {...} .... } Regarding what to send - the general principle should be that the client is responsible for sending their move to the server, anything else it does is a bonus, because the server needs to verify the legality of the move. The server should always be the determiner of the state of the game to avoid cheating and erroneous client implementations Unless you're interested in learning how to implement your own protocol or use the Java sockets library, it's going to be easier to use RMI. You could also use SOAP, REST or any other protocol, but I wouldn't bother thinking too hard about which one to use at the moment. I don't have any suggestions beyond the RMI documentation, though I think this book had lots of code examples for networking. A: when going with sockets each client will have it's own connection on which a server thread will wait (don't forget to flush the stream on client side or you'll wait forever) each line will be a separate message and to differentiate the message types you can use a "header" at the start of each message (a specific 3-character sequence at the start) say msg, mov, lgn and use a trie-like selection with switches to quickly decide which one you got when using RMI you can have the server keep a manager object (exported and registered in the registry) on which a client can request a "connection"-object which will be the same as the connection in the socket implementation but you'll be able to have a method for each thing you wanna do though the callbacks will need to be done in some other way (with sockets you have a connection ready for it)
{ "language": "en", "url": "https://stackoverflow.com/questions/7586869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: In JavaScript, what is the advantage of !function(){}() over (function () {})()? Possible Duplicate: What does the exclamation mark do before the function? I've long used the following for self-executing, anonymous functions in JavaScript: (function () { /* magic happens */ })() Lately, I've started seeing more instances of the following pattern (e.g., in Bootstrap): !function () { /* presumably the same magic happens */ }() Anyone know what the advantage is of the second pattern? Or, is it just a stylistic preference? A: These two different techniques have a functional difference as well as a difference in appearance. The potential advantages of one technique over the other will be due to these differences. Concision Javascript is a language where concision can be very important, because Javascript is downloaded when the page loads. That means that the more concise the Javascript, the faster the download time. For this reason, there are Javascript minifiers and obfuscators that compress the Javascript files to optimize the download time. For example, the spaces in alert ( "Hi" ) ; would be optimized to alert("Hi");. Keeping this in mind, compare these two patterns * *Normal closure:   (function(){})() 16 characters *Negated closure: !function(){}() 15 characters This is a micro-optimization at best, so I don't find this a particularly compelling argument unless you are doing a code golf contest. Negating the returned value Compare the result value of a and b. var a = (function(){})() var b = !function(){}() Since the a function does not return anything, a will be undefined. Since the negation of undefined is true, b will evaluate to true. This is an advantage to people who either want to negate the returned value of the function or have an everything-must-return-a-non-null-or-undefined-value fetish. You can see an explanation for how this works on this other Stack Overflow question. I hope that this helps you understand the rationale behind this function declaration that would typically be considered an anti-pattern. A: I always fall back on Ben Alman's IIFE piece for questions like this. It's the definitive as far as I'm concerned. Here's the meat of the article: // Either of the following two patterns can be used to immediately invoke // a function expression, utilizing the function's execution context to // create "privacy." (function(){ /* code */ }()); // Crockford recommends this one (function(){ /* code */ })(); // But this one works just as well // Because the point of the parens or coercing operators is to disambiguate // between function expressions and function declarations, they can be // omitted when the parser already expects an expression (but please see the // "important note" below). var i = function(){ return 10; }(); true && function(){ /* code */ }(); 0, function(){ /* code */ }(); // If you don't care about the return value, or the possibility of making // your code slightly harder to read, you can save a byte by just prefixing // the function with a unary operator. !function(){ /* code */ }(); ~function(){ /* code */ }(); -function(){ /* code */ }(); +function(){ /* code */ }(); // Here's another variation, from @kuvos - I'm not sure of the performance // implications, if any, of using the `new` keyword, but it works. // http://twitter.com/kuvos/status/18209252090847232 new function(){ /* code */ } new function(){ /* code */ }() // Only need parens if passing arguments A: The first "pattern" calls the anonymous function (and has the result of its return value) while the second calls the anonymous function and negates its result. Is that what you're asking? They do not do the same thing. A: It is almost only stylistic preference, except for the fact that ! provides a function return (i.e. returns true, which comes from !undefined). Also, it's one fewer character. A: It seems that the key thing is that you're basically keeping the parser from interpreting the function as a function declaration, and instead it's being interpreted as an anonymous function expression. Using the parens to group the expression or using the ! to negate the return are both just techniques of changing the parsing. It's then immediately invoked by the following parens. Any and all of these forms are having the same net effect in that regard, assuming no explicit return value: (function(){ /* ... */ })(); // Arguably most common form, => undefined (function(){ /* ... */ }()); // Crockford-approved version, => undefined !function(){ /* ... */ }(); // Negates the return, so => true +function(){ /* ... */ }(); // Attempts numeric conversion of undefined, => NaN ~function(){ /* ... */ }(); // Bitwise NOT, => -1 If you're not capturing the returned value, there's no significant difference. One could argue that the ~ might be a faster op since it's just flipping bits, or maybe ! is a faster op since it's a true/false check and returning the negation. At the end of the day though, the way most people are using this pattern is that they're trying to break off a new level of scope to keep things clean. Any and all work. The latter forms are popular because while they do introduce an additional (typically unnecessary) operation, saving every extra byte helps. Ben Alman has a fantastic writeup on the topic: http://benalman.com/news/2010/11/immediately-invoked-function-expression/ A: Well in the first case you are using ( ) to wrap the object you want to execute with the next set of (), and in the next case you are using operator that takes one argument (negation operator !) and you are making it implicitly wrap its argument (funcion) with ( ) so you actually get !(function () { })(), execute the function, and negate the result it returns. This can also work with -, +, ~ in the same principle since all those operators take one argument. !function () { /* presumably the same magic happens */ }() -function () { /* presumably the same magic happens */ }() +function () { /* presumably the same magic happens */ }() ~function () { /* presumably the same magic happens */ }() Why would you want to do this? I guess it is a personal preference or if you have big .JS and want to save 1 char per anonymous function call... :D
{ "language": "en", "url": "https://stackoverflow.com/questions/7586870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "86" }
Q: Why does the Eclipse Java compiler check casts from null? Consider the following Java snippet: public class Test { public static void use(Object[] x) { } public static void main(String[] args) { Object[] x = null; use(x); } } The Java bytecode produced for main() by the Eclipse 3.7 compiler looks like this: public static void main(java.lang.String[]); Code: 0: aconst_null 1: checkcast #20; //class "[Ljava/lang/Object;" 4: astore_1 5: aload_1 6: invokestatic #21; //Method use:([Ljava/lang/Object;)V 9: return On the contrary, this is the bytecode produced by the OpenJDK 1.6.0b22 compiler: public static void main(java.lang.String[]); Code: 0: aconst_null 1: astore_1 2: aload_1 3: invokestatic #2; //Method use:([Ljava/lang/Object;)V 6: return Note that the Eclipse compiler issues an extra checkcast opcode. It also seems to do that only for arrays and not for any other variable type. My questions: * *As far as I know, null is assignable to any class, including arrays. Does it make any sense at all to checkcast a known null value? *Does the extra checkcast affect performance? *Could this be considered a bug in the Eclipse Java compiler? NOTE: I can partially answer (2), at least as far as the OpenJDK 1.6.0b22 JVM is concerned. I performed a simple benchmark with several assignments to null in a timed tight loop. I could not detect any consistent performance difference, one way or the other. That said, my benchmark was simple enough that any half-decent optimizer would have probably made it useless, so it may not be indicative of a real world application. I would expect that the JVM would always optimize out that checkcast opcode, but that may not be the case. A: * *No, it doesn't make sense to check, as null is always castable to any reference type. But it doesn't hurt anything. *Any decent JIT will optimize the check away anyway (it's effectively a no-op), so the biggest cost is the three bytes that the instruction takes up. *I wouldn't consider it a "bug", as the generated bytecode works as intended -- it'll never trigger a ClassCastException, as the value is always known and correct -- and, as you apparently saw, there's not a real performance difference either way. It's an opportunity for improvement, but nothing that will break in any case. A: As for your first question, you are right, the checkcast instruction there is redundant. According to Sun's Java Hotspot wiki null checks and instance checks are cheap. I've opened an issue in Eclipse Bugzilla to get feedback from Eclipse compiler team, but as it been pointed out before, it is redundant, but harmless check. It only affects the bytecode size and Java HotSpot compiler will likely apply type check optimization at the runtime. Update: from Eclipse compiler team it seem like as side effect of another old bug. A: It might be related to a known bug in javac: Unnecessary checkcast in generated code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7586872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }