text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: close button for jquery qtip tooltip plugin I am trying to have a close button on the qTip tooltip - i have the following:
<script type="text/javascript">
$(document).ready(function () {
//****** tooltips **********
$('img.help').hover(function () {
// Destroy currrent tooltip if present
if ($(this).data("qtip")) $(this).qtip("destroy");
$(this) // Set the links HTML to the current opposite corner
.qtip({
content:
{
text: 'this is the tooltip, better to use the alt attribute of the image or use html div content somewhere on the page',
title: {
text: 'This toolip title',
button: true
}
},
position: {
corner: {
tooltip: 'bottomLeft', // Use the corner...
target: 'topRight' // ...and opposite corner
}
},
show: {
solo: true,
when: false, // Don't specify a show event
ready: true // Show the tooltip when ready
},
hide: false, // Don't specify a hide event
style: {
border: {
width: 5,
radius: 10
},
padding: 10,
textAlign: 'left',
tip: true, // Give it a speech bubble tip with automatic corner detection
name: 'blue' // Style it according to the preset 'cream' style
// name: 'light' // Style it according to the preset 'cream' style
}
});
});
however, I do not have a close button. Is there supposed to be an image in my image folder or a style created to do this? All I see in the documentation here is to indicate button: true. I have tried button: 'close' and that creates a 'close' hyperlink as it should - just can't get the close image variation working. Any ideas on what I may be missing here?
A: This is my solution, I wanted a java action to close the qtip when I clicked a button
<input type="button" name="calendar_main_delete" class="calendar_main_delete" id="calendar_main_delete" value="Delete Event" />
<input type="button" onClick="parent.location='#edit'" value="Edit Event" />
<script type="text/javascript">
//click button call from button above
$('.calendar_main_delete').click(function() {
//.qtip is my qtip element from the parent page and then I hide it.
$('.qtip', window.parent.document).qtip("hide");
});
</script>
A: qTip 2 has a close button option. Add the option button close to content and that will add a close button. Positioning can be done using css. The below code snippet will get you started.
$item.qtip({
overwrite: true,
content: {
text: content,
button: 'Close'
}
});
If you need more information on this please refer to this:
http://qtip2.com/options. Look for "content.button" on the page.
A: I am not sure if this is what you are looking for, but from what I can see the close button on the demo page is not an image, but is styled via css like this:
.ui-tooltip-icon .ui-icon {
background: none no-repeat scroll -100em -100em transparent;
color: inherit;
font: bold 10px/13px Tahoma,sans-serif;
height: 14px;
text-align: center;
text-indent: 0;
width: 18px;
border-radius: 3px 3px 3px 3px;
}
And the html is:
<span class="ui-icon ui-icon-close">×</span>
I hope this was helpful!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to correct TypeError: Unicode-objects must be encoded before hashing? I have this error:
Traceback (most recent call last):
File "python_md5_cracker.py", line 27, in <module>
m.update(line)
TypeError: Unicode-objects must be encoded before hashing
when I try to execute this code in Python 3.2.2:
import hashlib, sys
m = hashlib.md5()
hash = ""
hash_file = input("What is the file name in which the hash resides? ")
wordlist = input("What is your wordlist? (Enter the file name) ")
try:
hashdocument = open(hash_file, "r")
except IOError:
print("Invalid file.")
raw_input()
sys.exit()
else:
hash = hashdocument.readline()
hash = hash.replace("\n", "")
try:
wordlistfile = open(wordlist, "r")
except IOError:
print("Invalid file.")
raw_input()
sys.exit()
else:
pass
for line in wordlistfile:
# Flush the buffer (this caused a massive problem when placed
# at the beginning of the script, because the buffer kept getting
# overwritten, thus comparing incorrect hashes)
m = hashlib.md5()
line = line.replace("\n", "")
m.update(line)
word_hash = m.hexdigest()
if word_hash == hash:
print("Collision! The word corresponding to the given hash is", line)
input()
sys.exit()
print("The hash given does not correspond to any supplied word in the wordlist.")
input()
sys.exit()
A: If it's a single line string. wrapt it with b or B. e.g:
variable = b"This is a variable"
or
variable2 = B"This is also a variable"
A: It is probably looking for a character encoding from wordlistfile.
wordlistfile = open(wordlist,"r",encoding='utf-8')
Or, if you're working on a line-by-line basis:
line.encode('utf-8')
EDIT
Per the comment below and this answer.
My answer above assumes that the desired output is a str from the wordlist file. If you are comfortable in working in bytes, then you're better off using open(wordlist, "rb"). But it is important to remember that your hashfile should NOT use rb if you are comparing it to the output of hexdigest. hashlib.md5(value).hashdigest() outputs a str and that cannot be directly compared with a bytes object: 'abc' != b'abc'. (There's a lot more to this topic, but I don't have the time ATM).
It should also be noted that this line:
line.replace("\n", "")
Should probably be
line.strip()
That will work for both bytes and str's. But if you decide to simply convert to bytes, then you can change the line to:
line.replace(b"\n", b"")
A: import hashlib
string_to_hash = '123'
hash_object = hashlib.sha256(str(string_to_hash).encode('utf-8'))
print('Hash', hash_object.hexdigest())
A: The error already says what you have to do. MD5 operates on bytes, so you have to encode Unicode string into bytes, e.g. with line.encode('utf-8').
A: To store the password (PY3):
import hashlib, os
password_salt = os.urandom(32).hex()
password = '12345'
hash = hashlib.sha512()
hash.update(('%s%s' % (password_salt, password)).encode('utf-8'))
password_hash = hash.hexdigest()
A: You must have to define encoding format like utf-8,
Try this easy way,
This example generates a random number using the SHA256 algorithm:
>>> import hashlib
>>> hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
'cd183a211ed2434eac4f31b317c573c50e6c24e3a28b82ddcb0bf8bedf387a9f'
A: encoding this line fixed it for me.
m.update(line.encode('utf-8'))
A: Please take a look first at that answer.
Now, the error message is clear: you can only use bytes, not Python strings (what used to be unicode in Python < 3), so you have to encode the strings with your preferred encoding: utf-32, utf-16, utf-8 or even one of the restricted 8-bit encodings (what some might call codepages).
The bytes in your wordlist file are being automatically decoded to Unicode by Python 3 as you read from the file. I suggest you do:
m.update(line.encode(wordlistfile.encoding))
so that the encoded data pushed to the md5 algorithm are encoded exactly like the underlying file.
A: You could open the file in binary mode:
import hashlib
with open(hash_file) as file:
control_hash = file.readline().rstrip("\n")
wordlistfile = open(wordlist, "rb")
# ...
for line in wordlistfile:
if hashlib.md5(line.rstrip(b'\n\r')).hexdigest() == control_hash:
# collision
A: This program is the bug free and enhanced version of the above MD5 cracker that reads the file containing list of hashed passwords and checks it against hashed word from the English dictionary word list. Hope it is helpful.
I downloaded the English dictionary from the following link
https://github.com/dwyl/english-words
# md5cracker.py
# English Dictionary https://github.com/dwyl/english-words
import hashlib, sys
hash_file = 'exercise\hashed.txt'
wordlist = 'data_sets\english_dictionary\words.txt'
try:
hashdocument = open(hash_file,'r')
except IOError:
print('Invalid file.')
sys.exit()
else:
count = 0
for hash in hashdocument:
hash = hash.rstrip('\n')
print(hash)
i = 0
with open(wordlist,'r') as wordlistfile:
for word in wordlistfile:
m = hashlib.md5()
word = word.rstrip('\n')
m.update(word.encode('utf-8'))
word_hash = m.hexdigest()
if word_hash==hash:
print('The word, hash combination is ' + word + ',' + hash)
count += 1
break
i += 1
print('Itiration is ' + str(i))
if count == 0:
print('The hash given does not correspond to any supplied word in the wordlist.')
else:
print('Total passwords identified is: ' + str(count))
sys.exit()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "450"
}
|
Q: tokenizer null character inputValue = "111,GOOG,20,475.0"
StringTokenizer tempToken = new StringTokenizer(inputValue, ",");
while(tempToken.hasMoreTokens() == true)
{
test = token.nextToken();
counterTest++;
}
It's giving me some invalid correct NULL character
I started to learn stringtokenizer and I'm not sure at this point what wen't wrong logicly I think it works out but am I forgetting something?
A: Your code snippet is working with some minor adjustments, maybe your missing something simple, so check the rewritten full example below:
public static void main(String[] args) throws Exception {
String inputValue = "111,GOOG,20,475.0";
StringTokenizer tempToken = new StringTokenizer(inputValue, ",");
int counterTest = 0;
while (tempToken.hasMoreTokens()) {
String test = tempToken.nextToken();
System.out.println(test);
counterTest++;
}
System.out.println("-------------------");
System.out.println("counterTest = " + counterTest);
}
Output:
111
GOOG
20
475.0
-------------------
counterTest = 4
A: I see some typo in your code.
However,using StringTokenizer is discouraged in new code. From the javadocs:
StringTokenizer is a legacy class that is retained for compatibility
reasons although its use is discouraged in new code. It is recommended
that anyone seeking this functionality use the split method of String
or the java.util.regex package instead.
The recommended way is to use String#split.
Something like:
private void customSplit(String source) {
String[] tokens = source.split(";");
for (int i = 0; i < tokens; i++) {
System.out.println("Token" + i + "is: " + token[i]);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Identical data frames with different digests in R? I have two large data frames, a and b for which identical(a,b) is TRUE, as is all.equal(a,b), but identical(digest(a),digest(b)) is FALSE. What could cause this?
What's more, I tried to dig in deeper, by applying digest to bunches of rows. Incredibly, at least to me, there is agreement in the digest values on sub-frames all the way to the last row of the data frames.
Here is a sequence of comparisons:
> identical(a, b)
[1] TRUE
> all.equal(a, b)
[1] TRUE
> digest(a)
[1] "cac56b06078733b6fb520442e5482684"
> digest(b)
[1] "fdd5ab78ca961982d195f800e3cf60af"
> digest(a[1:nrow(a),])
[1] "e44f906723405756509a6b17b5949d1a"
> digest(b[1:nrow(b),])
[1] "e44f906723405756509a6b17b5949d1a"
Every method I can think of indicates these two objects are identical, but their digest values are different. Is there something else about data frames that can produce such discrepancies?
For further details: the objects are about 10M rows x 12 columns. Here's the output of str():
'data.frame': 10056987 obs. of 12 variables:
$ V1 : num 1 11 21 31 41 61 71 81 91 101 ...
$ V2 : num 1 1 1 1 1 1 1 1 1 1 ...
$ V3 : num 2 3 2 3 4 5 2 4 2 4 ...
$ V4 : num 1 1 1 1 1 1 1 1 1 1 ...
$ V5 : num 1.8 2.29 1.94 2.81 3.06 ...
$ V6 : num 0.0653 0.0476 0.0324 0.034 0.0257 ...
$ V7 : num 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 ...
$ V8 : num 0.00653 0.00476 0.00324 0.0034 0.00257 ...
$ V9 : num 1.8 2.3 1.94 2.81 3.06 ...
$ V10: num 0.1957 0.7021 0.0604 0.1866 0.9371 ...
$ V11: num 1704 1554 1409 1059 1003 ...
$ V12: num 23309 23309 23309 23309 23309 ...
> print(object.size(a), units = "Mb")
920.7 Mb
Update 1: On a whim, I converted these to matrices. The digests are the same.
> aM = as.matrix(a)
> bM= as.matrix(b)
> identical(aM,bM)
[1] TRUE
> digest(aM)
[1] "c5147d459ba385ca8f30dcd43760fc90"
> digest(bM)
[1] "c5147d459ba385ca8f30dcd43760fc90"
I then tried converting back to a data frame, and the digest values are equal (and equal to the previous value for a).
> aMF = as.data.frame(aM)
> bMF = as.data.frame(bM)
> digest(aMF)
[1] "cac56b06078733b6fb520442e5482684"
> digest(bMF)
[1] "cac56b06078733b6fb520442e5482684"
So, b looks like the bad boy, and it has a colorful past. b came from a much bigger data frame, say B. I took only the columns of B that appeared in a and checked to see if they were equal. Well, they were equal, but had different digests. I converted the column names (from "InformativeColumnName1" to "V1", etc.), just to avoid any issues that might arise - though all.equal and identical tend to point out when column names differ.
Since I am working on two different programs and don't have simultaneous access to a and b, it is easiest for me to use the digest values to check the calculations. However, something seems to be odd in how I extract columns from a data frame and then apply digest() to it.
ANSWER:
It turns out, to my astonishment (dismay, horror, embarrassment, you name it), identical is very forgiving about attributes. I had assumed that only all.equal was forgiving about attributes.
This was discovered via Tommy's suggestion identical(d1, d2, attrib.as.set=FALSE). Running attributes(a) is a bad, bad idea: the deluge of row names took awhile before Ctrl-C could interrupt it. Here is the output of names(attributes()):
> names(attributes(a))
[1] "names" "row.names" "class"
> names(attributes(b))
[1] "names" "class" "row.names"
They're in different orders! Kudos to digest() for being straight with me.
UPDATE
To aid others with this problem, it seems that simply rearranging the attributes will be adequate to get identical hash values. Since tinkering with attribute orders is new to me, this may break something, but it works in my case. Note that it is a little time consuming if the objects are big; I'm not aware of a faster method for doing this. (I'm also looking to move to using matrices or data tables instead of data frames, and this may be another incentive to avoid data frames.)
tmpA0 = attributes(a)
tmpA1 = tmpA0[sort(names(tmpA0))]
a2 = a
attributes(a2) = tmpA1
tmpB0 = attributes(b)
tmpB1 = tmpB0[sort(names(tmpB0))]
b2 = b
attributes(b2) = tmpB1
digest(a2) # e04e624692d82353479efbd713ec03f6
digest(b2) # e04e624692d82353479efbd713ec03f6
identical(b,b2, attrib.as.set = FALSE) # FALSE
identical(b,b2, attrib.as.set = TRUE) # TRUE
identical(a2,b2, attrib.as.set = FALSE) # TRUE
A: Without having the actual data.frames it is of course hard to know, but one difference could be the order of the attributes. identical ignores that by default, but setting attrib.as.set=FALSE can change that:
d1 <- structure(1, foo=1, bar=2)
d2 <- structure(1, bar=2, foo=1)
identical(d1, d2) # TRUE
identical(d1, d2, attrib.as.set=FALSE) # FALSE
A: Our digest package uses the internal R function serialize() to get what we feed to the hash-generating functions (md5, sha1, ...).
So I strongly suspect that may have something like an attribute differ. Until you can construct something reproducible that does not depend on your 1e7 x 12 data set, there is little we can do.
Also, the digest() function can output intermediate results and (as of the recent 0.5.1 version) even raw vectors. That may help.
Lastly, you can always contact us (as the package maintainers / authors) off-line which happens to be the recommended way within R land, the popularity of StackOverflow not withstanding.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Determining most register hungry part of kernel when I get a kernel using too many registers there are basically 3 options I can do:
*
*leave the kernel as it is, which results in low occupancy
*set compiler to use lower number of registers, spilling them, causing worse performance
*rewrite the kernel
For option 3, I'd like to know which part of the kernel needs the maximum number of registers. Is there any tool or technique allowing me to identify this part? Reading through the PTX code (I develop on NVidia) is not helpful, the registers have various high numbers and to be honest, the best I can do is to identify which part of the assembly code maps to which part of the C code.
Just commenting out some code is not much a way to go - for example, I noticed that if I just put the code into loop, the number of registers raises dramatically, not only by one for the loop control variable. I personally suspect the NVidia compiler from imperfect variable liveness analysis, but of course I cannot do much with that :-)
A: If you're running on NVidia hardware, you can pass -cl-nv-verbose compile option to clBuildProgram then clGetProgramInfo CL_PROGRAM_BINARIES to get human readable text about the compile. In there it will say the number of registers it uses. Note that NVidia caches compiles and it only produces that register info when the kernel source actually changes, so you may want to inject some superfluous change in the source code to force it to do the full analysis.
If you're running on AMD hardware, just set the environment variable GPU_DUMP_DEVICE_KERNEL=1. It will produce a text file of the IL during the compile. Not sure it explicitly says the number of registers used, but it's what is equivalent to the NVidia technique above.
When looking at that output (at least on nvidia), you'll find that it seems to use an infinite number of registers (if you go by the register numbers). In reality, it does a flow analysis and actually reuses registers in a way that is not at all obvious when looking at the IL.
A: This is a tough question in any language, and there's probably not one correct answer. But here are some things to think about:
*
*Look for the code in the "deepest" scope you can find, keeping in mind that most functions are probably inlined by your OpenCL compiler. Count the variables used in this scope, and walk up the containing scopes. In each containing scope, count variables that are used both before and after the inner scope. These are potentially live while the inner scope executes. This process could help you account for the live registers at a particular part of the program.
*Try to take variables that "span" deep scopes and make them not span the scope if possible. For example, if you have something like this:
int i = func1();
int j = func2(); // perhaps lots of live registers here
int k = func3(i,j);
you could try to reorder the first two lines if func2 has lots of live registers. That would remove i from the set of live registers while func2 is running. This is a trivial pattern, of course, but hopefully it's illustrative.
*Think about getting rid of variables that just keep around the results of simple computations. You might be able to recompute these when you need them. For example, if you have something like int i = get_local_id(0) you might be able to just use get_local_id(0) wherever you would have used i.
*Think about getting rid of variables that are keeping around values stored in memory.
Without good tools for this kind of thing, it ends up being more art than science. But hopefully some of this is helpful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Schedule a task after a specific interval in Java I've got a class
class A {
int a=0;
public int getVal() {
return a;
}
}
and I've to execute the function getVal periodically. How do I do it from another class b? Thanks.
A: Old Way
java.util.Timer
New (and preferred) Way
java.util.concurrent.Executors
Implementation
More specifically, use the ScheduledExecutorService class.
A: Various potential problems with java.util.Timer are listed in section 6.2.5 of "Java Concurrency in Practice." For example:
*
*Timer behaves poorly if a TimerTask takes too long to run.
*Timer behaves poorly if a TimerTask throws an unchecked exception.
The authors of that book concluded that "there is little reason to use Timer in Java 5.0 or later."
Instead, they recommend using a ScheduledExecutorService. You can construct one either via the ScheduledThreadPoolExecutor constructor or via the newScheduledThreadPool factory methods in Executors. The later option is better.
A: Check out the Timer class.
http://download.oracle.com/javase/1.4.2/docs/api/java/util/Timer.html
A: Simply just give a look on Threads in java. you can make this class runnable, and execute the function periodically, and the delay can be generated using the sleep() function. Otherwise you can make the calling function runnable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MS Word Macros 2003 - 2007 I work in a remote region with limited resources and technical expertise as a Project Manager and a new project I just got handed was the testing of MS Word 2003 macros on a MS Word 2007 platform. The Macros were initially developed by Corel a few years ago when we migrated they migrated that specific division from WordPerfect to MS Office 2003.
I have a test workstation with Office 2007 installed and followed the steps required to get the Macros work to no avail. Any tips and recommendations would be appreciated. I do have experience in VBA and XML coding but the VBA was about 10 years ago and I haven't looked at XML code in at least 4 years.
If I can sollicit some high level suggestions, if coding needs to changed or updated, I can try to figure it out or contract it out but just want to make sure that I have exhausted all other options prior opting for that route.
Thanks
A: I doubt you will get any useful answers in this forum, which concerns itself with programming questions. But you might want to try this discussion group, which seems to be just what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: The type or namespace name 'DinnerForm' does not exist in the namespace 'NerdDinner.Models' when trying to implement partial form Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0234: The type or namespace name 'DinnerForm' does not exist in the namespace 'NerdDinner.Models' (are you missing an assembly reference?)
Source Error:
Line 170:
Line 171: [System.Runtime.CompilerServices.CompilerGlobalScopeAttribute()]
Line 172: public class views_dinners_create_aspx : System.Web.Mvc.ViewPage, System.Web.SessionState.IRequiresSessionState, System.Web.IHttpHandler {
Line 173:
Line 174: private static bool @__initialized;
DinnerFormViewModel.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NerdDinner.Controllers;
namespace NerdDinner.Models
{
public class DinnerFormViewModel
{
// Properties
public Dinner Dinner { get; private set; }
public SelectList Countries { get; private set; }
// Constructor
public DinnerFormViewModel(Dinner dinner)
{
Dinner = dinner;
Countries = new SelectList(PhoneValidator.Countries, dinner.Country);
}
}
}
DinnerForm.ascx:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<NerdDinner.Controllers.DinnerFormViewModel>" %>
<%= Html.ValidationSummary("Please correct the errors and try again.") %>
<% using (Html.BeginForm()) { %>
<fieldset>
<p>
<label for="Title">Dinner Title:</label>
<%= Html.TextBox("Title", Model.Dinner.Title) %>
<%=Html.ValidationMessage("Title", "*") %>
</p>
<p>
<label for="EventDate">Event Date:</label>
<%= Html.TextBox("EventDate", Model.Dinner.EventDate) %>
<%= Html.ValidationMessage("EventDate", "*") %>
</p>
<p>
<label for="Description">Description:</label>
<%= Html.TextArea("Description", Model.Dinner.Description) %>
<%= Html.ValidationMessage("Description", "*") %>
</p>
<p>
<label for="Address">Address:</label>
<%= Html.TextBox("Address", Model.Dinner.Address) %>
<%= Html.ValidationMessage("Address", "*") %>
</p>
<p>
<label for="Country">Country:</label>
<%= Html.DropDownList("Country", Model.Countries) %>
<%= Html.ValidationMessage("Country", "*") %>
</p>
<p>
<label for="ContactPhone">Contact Phone #:</label>
<%= Html.TextBox("ContactPhone", Model.Dinner.ContactPhone) %>
<%= Html.ValidationMessage("ContactPhone", "*") %>
</p>
<p>
<input type="submit" value="Save"/>
</p>
</fieldset>
<% } %>
DinnersControllers.cs (create methods)
//
// GET: /Dinners/Create
public ActionResult Create()
{
Dinner dinner = new Dinner()
{
EventDate = DateTime.Now.AddDays(7)
};
return View(new DinnerFormViewModel(dinner));
}
//
// POST: /Dinners/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Dinner dinner)
{
if (ModelState.IsValid)
{
try
{
dinner.HostedBy = "SomeUser";
dinnerRepository.Add(dinner);
dinnerRepository.Save();
return RedirectToAction("Details", new { id = dinner.DinnerID });
}
catch
{
foreach (var issue in dinner.GetRuleViolations())
{
ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
}
return View(new DinnerFormViewModel(dinner));
}
}
return View(new DinnerFormViewModel(dinner));
}
Create.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Models.DinnerForm>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Host A Dinner
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Host a Dinner</h2>
<% Html.RenderPartial("DinnerForm"); %>
</asp:Content>
A: DinnerForm.ascx:
Inherits="System.Web.Mvc.ViewUserControl<NerdDinner.Models.DinnerFormViewModel>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get jQuery Mobile to use Javascript Array I have jQuery mobile app. I get new data from the server and hold it in javascript Arrays.
When I go to a page in the jQuery mobile app I want it to populate with the data from the Javascript Arrays.
The reason for this is I update the data in the web app
Question is how do you put the Arrays on to the page and how do you call that function when the page is displayed.
I have tried jQuery.each but do not know when or how the function this is in is called.
A: I use arrays in my jquery mobile app like this:
For putting JSON data in an array:
var g_RunCard = new Array();
function fLoadRunCard() {
$.getJSON("runCards.json", function (json) {
g_RunCard = json;
});
}
I have code that uses the g_RunCard as needed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Handling exceptions in a class library enveloping a device driver I am writing a class library that envelopes an USB device driver.
This device has its own class library, provided by the hardware vendor.
Very often, especially if you handle with old DLL or COM assemblies, there are methods (functions to be correct) that return TRUE if all was OK, or FALSE if any error happen.
Often these methods return information about the error in one of their parameters or separately in a GetLastError method or even if in an OnError event.
Now, normally I handle all native .NET exceptions in my class libray handling locally or re-throwing to the client if the error is useful to know. But what to do with all other errors that are hidden in the vendor's methods? (in the true I have no exceptions, but only returned TRUE or FALSE values).
Let's make an example with the method "CONNECT" that connect the client to the USB device.
I envelope the method in this way:
Public Sub Connect()
oVendorDevice.connect()
End Sub
now if any connection error happen, the vendor's connect method return FALSE.
But I do not know why the connection failed. To know why the connection failed I have to call (for example) the method GetLastError that gives me information about the error.
(but do not forget that other vendors use other strategies like returning the error in a method's parameter or in a OnError events.
Now, in order to follow a good .NET exception handling strategy I could write something like this:
Public Sub Connect()
Dim res As Boolean = oVendorDevice.connect()
If res = False Then
Dim sError As String = oVendorDevice.GetLastError
Throw New Exception(sError) 'or a my own exception class
End If
End Sub
But I could also preserve the vendor strategy with something like
Public Function Connect2(ByRef Err As String) As Boolean
Connect2 = oVendorDevice.connect()
Err = oVendorDevice.GetLastError
End Function
or like this
Public Function Connect3() As Boolean
Connect3 = oVendorDevice.connect()
MyGetLastError = oVendorDevice.GetLastError
End Function
What is the best .NET-way to "envelope the errors" of the vendor class library?
A: The way I would approach this would be "as a consumer of the API, do I want to get an exception here or should this be some sort of less exceptional error case?"
In case of connection, I would generally say that probably should throw an exception -- preferably a strongly, distinctly typed one that includes the vendors error information.
Now, for a counter-example, let's say the device had an error when reading from an empty buffer. But in your program, you think it makes more sense to just return an empty buffer. This sort of case is where you probably don't need to throw an exception in your client.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jQuery fadeIn fadeOut makes page scroll I have wordpress enabled website where I want to create a featured block. This featured block will have featured articles fading one after another. I got it working by using the fadeIn and fadeOut APIs of jQuery, but there is a problem with the implementation.
Here is the code I have -
var count=0;
var sticky_count=<?php echo count($sticky);?>;
jQuery(document).ready(featured_block);
function featured_block() {
jQuery(".featured" + count % sticky_count).delay(5000).fadeOut(callback);
}
function callback() {
count++;
jQuery(".featured" + count % sticky_count).fadeIn().delay(5000);
jQuery(".featured" + count % sticky_count).fadeOut(callback);
}
The fadeIn - fadeOut effect is working fine till the user navigates to the bottom of the page. When the user is at the bottom of the page, the entire page scrolls up when the fade switch happens.
You can see this in action at http://www.ronakg.com
Please advice how can I avoid the page scroll.
EDIT: Here's how the HTML code looks like -
<div class="featured0">
...
</div>
<div class="featured1" style="display:none">
...
</div>
...
A: Try giving the containing element of the blocks that fade in and fadeout a static height: attribute with CSS.
Wrap <div id="featured"> block with another div.
<div id="rotator" style="height: 340px;">
<div id="featured">
...
</div>
</div>
A: If you are using <a> with href iqual to "#", just put return false; in the end of your featured_block function that should solve the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Cycles in chained exceptions I'll first quickly motivate the question with my use case.
My library needs to expose a Java exception classifier to a framework which it plugs in to. For example:
enum Classification { FATAL, TRANSIENT, UNKNOWN }
Classification classify(Throwable t) {
if (t instanceof MyTransientException)
return Classification.TRANSIENT;
else if (t instanceof MyFatalException)
return Classification.FATAL;
else
return Classification.UNKNOWN;
}
Sometimes, and for reasons out of my control, the passed exception is a wrapper around the one I'm interested in so I want to search the cause chain for it. My initial idea was:
Classification classify(Throwable t) {
if (t == null)
return Classification.UNKNOWN;
if (t instanceof MyTransientException)
return Classification.TRANSIENT;
else if (t instanceof MyFatalException)
return Classification.FATAL;
else
return classify(t.getCause());
}
Unfortunately, this could result in infinite recursion if the passed exception has a cycle in its causal chain. It's highly unlikely that such an exception will be passed, and an argument could be made that it's an error elsewhere in the system if such an exception is created, but I'm very uncomfortable with having the possibility of my library being responsible for a production outage if it happens. Throwable's API and javadoc do not explicitly forbid this possibility beyond the idea that cycles are inherently nonsensical in a causal chain.
I noticed that Guava has a @Beta method to extract the causal chain, Throwables.getCausalChain, but its implementation is susceptible to the same issue -- it will wind up throwing an OOME.
I'm planning to use an identity hash set to detect the cycle and mitigate the risk, but I wanted to hear how others view this issue. Do you think I'm being overly defensive? What would you do?
A: It's great that you are being so conscientious. But you don't want to get into the business of manufacturing kevlar boots.
If a user does something that would make even Throwable.printStackTrace go into infinite recursion, that user is beyond help. Don't even worry about this.
A: I think it is on the defensive side to do in your own code, but because these days we use many libraries, you never know which will actually do something as unexpected as create a causechain loop.
Apache Commons does handle this in it's ExceptionUtils. For instance in ExceptionUtils.getThrowableList. It does this in a fairly simple way:
public static List<Throwable> getThrowableList(Throwable throwable) {
final List<Throwable> list = new ArrayList<>();
while (throwable != null && !list.contains(throwable)) {
list.add(throwable);
throwable = throwable.getCause();
}
return list;
}
By using helper libraries instead of building your own you can prevent mistakes on things you would never think of yourself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Testing for console.log statements in IE
Possible Duplicate:
'console' is undefined error for internet explorer
If you have console.log statements in your code, Internet Explorer will throw a JavaScript error (at least in IE7 which is what our intranet users have installed).
I am using Firefox for most of my development testing primarily because of the functionality provided by Firebug (where I use a lot of console statements) but I also need to test in IE.
if I add the following to my JavaScript, the error does not get thrown.
var debugging = false;
if (typeof console == "undefined")
var console = { log: function() {} };
The problem is that I would like to trigger an event if debugging mode is false. If I create a function to test whether debugging is false and do an action (at this point just an alert) but when I try do the following I receive an IE error saying Console is not defined.
var debugging = false; // or true
if (typeof console == "undefined")
var console = { log: function() {consoleMsg()} };
function consoleMsg() {
if(!debugging) {
alert('Console.log event in Production Code');
}
If someone could help me to fix my code, provide a better way to help me achieve my goal, or direct me to a resource to edumacate myself I would be very appreciative.
A: 'console' itself needs to be a function, as well as 'log'. So:
if(typeof(console) === 'undefined') {
console = function(){};
console.log = function(){consoleMsg()};
}
A: Did you try try-catch:
var debugging = false; // or true
try {
console.log();
} catch(ex) {
/*var*/ console = { log: function() {consoleMsg()} };
}
A: You don't have to jump through all these hoops. Simply check if the console exists before using it.
So, instead of:
console.log('foo');
Use:
window.console && console.log('foo');
...and you won't get any errors.
Alternatively, you could just check for it at the top of your script, and if it's undefined, just fill it with an empty function:
// At the top of your script:
if ( ! window.console ) console = { log: function(){} };
// If you use other console methods, add them to the object literal above
// Then, anywhere in your script:
console.log('This message will be logged, but will not cause an error in IE7');
For a more robust solution, use this piece of code (taken from twitter's source code):
// Avoid `console` errors in browsers that lack a console.
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
A: (function(debug) {
var console;
function wrapConsoleMethod(fnName) {
if(fnName in console)
console[ fnName ] = function(fn) {
return function() {
if(debug)
return fn.apply(console, arguments);
else
alert('Console event in Production Code');
};
}(console[ fnName ]);
else
; // fn not in console
};
if(!('console' in window))
window.console = {
log : function() {}
// ...
};
console = window.console;
wrapConsoleMethod('log');
// ...
})(true /* debug */);
console.log('test');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "48"
}
|
Q: Zend Quickstart Tutorial Conceptual Problem I am trying to learn zend framework, and managed to get through the whole quickstart tutorial they have. However, there is something that I simply can not understand, and was hoping somebody can help me with.
In the tutorial, you create a db-table class, a mapper, and a model. I read the documentation, and understand the purpose of the db-table class (define table, relations, create/fetch rows). When you query the db-table class, you'll get an object of class db-table-row, which you can use to manipulate a specific record in the db.
However, I can not understand why the tutorial would have me create a mapper and a model, nor the reason for defining getter/setter methods in the model (shouldn't those be provided by db-table-row?)
Even in the controller, they created an object from the model class and the mapper class, then they completely ignored the model object, and just used the mapper object.
Is there any need at all to have those 3 classes? what different purpose does each fulfill? As far as I can see, all I need is the db-table class, am I right?
A:
When you query the db-table class, you'll get an object of class
db-table-row
No you get db-table-rowset instead which is collection of row .
secondly
you don't even need db-table class
$dbTable = new Zend_Db_Table('tableName');
But since db-table class allow you to define relationship between other tables inside it (business logic) hence became important .
db-table-row became important when the entity is important for e.g User Table . Inside your custom db-table-row for user you can add method getTopics(); which return rowset for all the topics created by theat user hence fruther helping with business logic.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to handle i18n in Go? I searched on web but I didn't find anything related to i18n and Go.
I wish to use Go for develop web sites. What is the best way to handle internationalization?
A:
Packages roadmap
Comprehensive support for international text.
Support for international dates, times, etc.
Support for multilingual messages.
As you can see from the Go Roadmap, Go doesn't provide full i18n support yet.
A: The new template package allows you to at add a function to template's function map, that would transform the given string to a localized version. What's going on underneath would be up to you for now, as the language choice could be based on headers sent by the browser.
That's a very basic use case for adding localized messages in a web app, for one.
Can't wait for the proper support for internationalization, local date and time formats.
A: go-i18n has some nice features:
*
*Implements CLDR plural rules.
*Uses text/template for strings with variables.
*Translation files are simple JSON.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: Why does my WCF service give the message 'does not have a Binding with the None MessageVersion'? I have created a working WCF service. I now want to add some security to it to filter Ip Addresses. I have followed the example that microsoft publish in the samples to try and add a IDispatchMessageInspector that will raise a call AfterReceiveRequest and then throw an error if the ip address is not from the allowed list.
After looking at the code; they have configured it using 'wsHttpBinding', however I want to use 'webHttpBinding' or 'basicHttpBinding'. But when I set it up I get the error:
The endpoint at 'http://upload/api/Api.svc/soap' does not have a
Binding with the None MessageVersion.
'System.ServiceModel.Description.WebHttpBehavior' is only intended for
use with WebHttpBinding or similar bindings.
My configuration is:
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true">
</serviceHostingEnvironment>
<!--Set up the service-->
<services>
<service behaviorConfiguration="SOAPRESTDemoBehavior" name="HmlApi">
<endpoint address="rest" binding="webHttpBinding" contract="VLSCore2.Interfaces.IHmlApi" behaviorConfiguration="SOAPRESTDemoEndpointBehavior" />
<endpoint address="soap" binding="basicHttpBinding" contract="VLSCore2.Interfaces.IHmlApi" behaviorConfiguration="SOAPRESTDemoEndpointBehavior" />
</service>
</services>
<!--Define the behaviours-->
<behaviors>
<serviceBehaviors>
<behavior name="SOAPRESTDemoBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<!---Endpoint -->
<endpointBehaviors>
<behavior name="SOAPRESTDemoEndpointBehavior">
<ipFilter/>
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<extensions>
<behaviorExtensions>
<add name="ipFilter" type="VLSCore2.Api.IpFilterBehaviourExtensionElement, VLSCore2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</behaviorExtensions>
</extensions>
</system.serviceModel>
So what im wondering is how I can set up my message inspector without using WebHttpBinding. Is this even possible?
I want to use SOAP 'basicHttpBinding' not wsHttpBinding (and all of the WS*) associated overheads....
A: This is simply happening because you have configured a single endpointBehavior for both the SOAP and REST endpoints but the SOAP endpoint can't have the webHttp behavior. You need to split these apart so that they are:
<endpointBehaviors>
<behavior name="SOAPDemoEndpointBehavior">
<ipFilter/>
</behavior>
<behavior name="RESTDemoEndpointBehavior">
<ipFilter/>
<webHttp />
</behavior>
</endpointBehaviors>
and then your endpoints should be:
<endpoint address="rest" binding="webHttpBinding" contract="VLSCore2.Interfaces.IHmlApi" behaviorConfiguration="RESTDemoEndpointBehavior" />
<endpoint address="soap" binding="basicHttpBinding" contract="VLSCore2.Interfaces.IHmlApi" behaviorConfiguration="SOAPDemoEndpointBehavior" />
A: For me, this was because I had a 'webHttp' defined as a behaviour for a SOAP config. Only its absence resolved it..
A: For 4 days, I have been up and down through MS documentation, Stack overflow and everything else. trying to get the configuration file working correctly after I started using HTTPS / SSL for requests from my service. The setup of this configuration file is so critical.
I did not have to modify any of the code switching from HTTP to HTTPS is was all in the web.config file system.serviceModel section.
This config works for using javascript to access JSON data from the ASP.NET c# WCF. I am so happy!
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="false">
</serviceHostingEnvironment>
<behaviors>
<endpointBehaviors>
<behavior name="webBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpsGetEnabled="false"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<webHttpBinding>
<binding name="sfbSecureBinding">
<security mode="Transport">
<transport clientCredentialType="None"/>
</security>
</binding>
</webHttpBinding>
</bindings>
<services>
<service name="buildingsWebService.Service1">
<endpoint address="https://www.azsfb.gov/Service/Service1.svc"
binding="webHttpBinding"
bindingConfiguration="sfbSecureBinding"
contract="buildingsWebService.IService1"
behaviorConfiguration="webBehavior">
</endpoint>
<host>
<baseAddresses>
<add baseAddress="https://www.azsfb.gov/"/>
</baseAddresses>
</host>
</service>
</services>
<protocolMapping>
<add binding="basicHttpBinding" scheme="https"/>
</protocolMapping>
</system.serviceModel>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
}
|
Q: how to get Roundhouse to create db on second hard drive I want Roundhouse to create the db on a second hd (not the C drive which it does right now). Is there any way in Roundhouse to do this ? Iam using sql server 2008 r2 express. I tried the -cds option for custom db creation but it gives an error saying does not provide facility at this time.
thank you
A: First you must know how you would create it in T-SQL outside of RoundhousE. If you verify that it works with SQL Express, then you can provide the script to rh as text or (with the newest in trunk and soon to be released 0.8.5) you can point it to a script file that it will read.
If you are using an older version of RH, you MUST give the actual text to /cds and not a path to a file. That text cannot contain the word GO in it at all either. Both of these things will be fixed when 0.8.5 is released.
HTH
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to setup a Windows Phone App without a tile title How can I set no title to my app, like the Facebook app, since my app also have its name displayed in the logo ? I tried in the app properties in Visual Studio but it displays an error saying that the title should not be empty.
To clarify : I want the app tile not to display the app title.
A: Open the WMManifest.xml in the Properties folder.
Find this:
<Tokens>
<PrimaryToken TokenID="AppToken" TaskName="_default">
<TemplateType5>
<BackgroundImageURI IsRelative="true" IsResource="false">Background.png</BackgroundImageURI>
<Count>0</Count>
<Title>YOUR APP TITLE HERE</Title>
</TemplateType5>
</PrimaryToken>
</Tokens>
And change the Title element to
<Title></Title>
Done. No more title displayed on the tile when pinning your app.
Example to prove it's possible (This is a app that's available on the marketplace)
A: You cannot have your primary application title without a title, though I believe that through Push Notification services it has been possible to remove the title.
If you are creating a Windows Phone 7.1 (Mango) application, you could try using the ShellTile API to set the title to an empty string. The primary tile is the first value returned by the ActiveTiles property if the application is pinned to the Start screen.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Anchor button label not aligned I can't seem to align the label of an anchor tag that's been made to look like a button.
Cancel label is clearly off. I would like it to be aligned with the Next button's label. We need the Cancel button to be an anchor tag because this site needs to work without Javascript.
Anyone have any ideas?
<div class="submit-voucher footer">
<a href="@Model.ReturnUrl.ToString()" class="cancelLinkButton button cancel">Cancel</a>
<input class="button default" type="submit" name="submit" value="Next" />
</div>
Here's the CSS from Firebug for the Cancel link/button:
a, a:active, a:visited {
color: #0066DD;
text-decoration: none;
}
.cancelLinkButton {
height: 22px;
vertical-align: middle;
}
.button, input[type="submit"], input[type="button"], button {
background: -moz-linear-gradient(center top , #FDFDFD 0%, #EBEBEB 60%) repeat scroll 0 0 transparent;
border: 1px solid #BBBBAF;
display: inline-block;
padding: 0 20px;
width: auto;
}
Here's the CSS for the DIV:
.submit-voucher.footer {
text-align: right;
vertical-align: middle;
border: 0 none;
font: inherit;
margin: 0;
padding: 0;
}
Thanks for the help.
EDIT: Added closing curly brackets to code in post.
A: Try using with line-height
.cancelLinkButton {
height: 22px;
vertical-align: middle;
line-height:22px;
}
A: Very simple. Just add some padding-top to .cancelLinkButton. From the looks of it, you probably need about 5px or so.
And depending on the border-box value on the element, you may need to decrease the height of the .cancelLinkButton the same amount of padding that you add. If you don't know what border-box is, then you almost definitely will need to decrease the height.
A: You are setting the CancelLinbutton property somewhere esle that is overriding the one you are setting below. Find out all the CSS references to cancelbutton and see what properties is actually use. You can use F12 and see which properties have been applied and which have been overridden.
.cancelLinkButton {
height: 22px;
vertical-align: middle;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ASP.net/C# newbie looking for help editing column width dynamically when data is retrieved I've been messing around with this and have yet to find a clean solution. At the moment, I have a asp:DataGrid control on the aspx page (I am open to changing this). When I click a button, I retrieve a DataSet from a database and use a DataTable from the DataSet to fill up my DataGrid.
If my asp:DataGrid is named "tableData" and my DataSet is named data the following implementation will fill my grid successfully:
protected void renderData(object sender, EventArgs e)
{
DataSet data = hc.getDataSet();
tableData.DataSource = data.Tables[0];
tableData.DataBind();
}
But my column widths are not as wide as desired. I would like to look at all the data in each column of data.Tables[0] and choose my tableData column's widths accordingly.
I have tried many ways of accomplishing this and failed but here are my two main ideas and the problems I've encountered:
Solution 1: Alter column width after the DataBind(). I would use some type of code along the lines of
tableData.Columns[i].ItemStyle.Width = longestField;
The problem with this solution is the DataBind() seems to not have taken place yet and I get some null pointer like exceptions. I could do it after, but how would I know when it is done? Even if there was some event like AfterDataBind I would prefer not to use it because if I would have to determine what table I was dealing with in that particular function.
Solution 2: Create my own databind method and use that instead
The problem with this solution is I can't seem to add rows to tableData myself (I would expect something like a tableData.NewRow() function but I can't seem to find one fitting my needs.
I have also tried using OnDataItemBound function, but I realized I have know idea how to relate the DataGridItemEventArgs e back to datagrid's column collection.
I would appreciate some insight. Thanks in advance guys.
A: Calculating column widths is a tricky business, and is prone to glitches. I would suggest setting fixed widths for columns with a limited amount of data, and let the grid use percentage widths for the other columns.
For example, let's say you have a list of addresses.
*
*Zip code should be less than 10 digits, so around 80px should be sufficient
*City is not as limited, but 200px will probably do the trick
*Street address could be really short or really long, so use a percentage width
If you're dead-set on calculating the column widths, take a look at this article:
http://www.syncfusion.com/FAQ/WindowsForms/FAQ_c44c.aspx#q877q
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Reusing LINQ query results in another LINQ query without re-querying the database I have a situation where my application constructs a dynamic LINQ query using PredicateBuilder based on user-specified filter criteria (aside: check out this link for the best EF PredicateBuilder implementation). The problem is that this query usually takes a long time to run and I need the results of this query to perform other queries (i.e., joining the results with other tables). If I were writing T-SQL, I'd put the results of the first query into a temporary table or a table variable and then write my other queries around that. I thought of getting a list of IDs (e.g., List<Int32> query1IDs) from the first query and then doing something like this:
var query2 = DbContext.TableName.Where(x => query1IDs.Contains(x.ID))
This will work in theory; however, the number of IDs in query1IDs can be in the hundreds or thousands (and the LINQ expression x => query1IDs.Contains(x.ID) gets translated into a T-SQL "IN" statement, which is bad for obvious reasons) and the number of rows in TableName is in the millions. Does anyone have any suggestions as to the best way to deal with this kind of situation?
Edit 1: Additional clarification as to what I'm doing.
Okay, I'm constructing my first query (query1) which just contains the IDs that I'm interested in. Basically, I'm going to use query1 to "filter" other tables. Note: I am not using a ToList() at the end of the LINQ statement---the query is not executed at this time and no results are sent to the client:
var query1 = DbContext.TableName1.Where(ComplexFilterLogic).Select(x => x.ID)
Then I take query1 and use it to filter another table (TableName2). I now put ToList() at the end of this statement because I want to execute it and bring the results to the client:
var query2 = (from a in DbContext.TableName2 join b in query1 on a.ID equals b.ID select new { b.Column1, b.column2, b.column3,...,b.columnM }).ToList();
Then I take query1 and re-use it to filter yet another table (TableName3), execute it and bring the results to the client:
var query3 = (from a in DbContext.TableName3 join b in query1 on a.ID equals b.ID select new { b.Column1, b.column2, b.column3,...,b.columnM }).ToList();
I can keep doing this for as many queries as I like:
var queryN = (from a in DbContext.TableNameN join b in query1 on a.ID equals b.ID select new { b.Column1, b.column2, b.column3,...,b.columnM }).ToList();
The Problem: query1 is takes a long time to execute. When I execute query2, query3...queryN, query1 is being executed (N-1) times...this is not a very efficient way of doing things (especially since query1 isn't changing). As I said before, if I were writing T-SQL, I would put the result of query1 into a temporary table and then use that table in the subsequent queries.
Edit 2:
I'm going to give the credit for answering this question to Albin Sunnanbo for his comment:
When I had similar problems with a heavy query that I wanted to reuse in several other queries I always went back to the solution of creating a join in each query and put more effort in optimizing the query execution (mostly by tweaking my indexes).
I think that's really the best that one can do with Entity Framework. In the end, if the performance gets really bad, I'll probably go with John Wooley's suggestion:
This may be a situation where dropping to native ADO against a stored proc returning multiple results and using an internal temp table might be your best option for this operation. Use EF for the other 90% of your app.
Thanks to everyone who commented on this post...I appreciate everyone's input!
A: If the size of TableName is not too big to load the whole table you use
var tableNameById = DbContext.TableName.ToDictionary(x => x.ID);
to fetch the whole table and automatically put it in a local Dictionary with ID as key.
Another way is to just "force" the LINQ evaluation with .ToList(), in the case fetch the whole table and do the Where part locally with Linq2Objects.
var query1Lookup = new Hashset<int>(query1IDs);
var query2 = DbContext.TableName.ToList().Where(x => query1IDs.Contains(x.ID));
Edit:
Storing a list of ID:s from one query in a list and use that list as filter in another query can usually be rewritten as a join.
When I had similar problems with a heavy query that I wanted to reuse in several other queries I always went back to the solution of creating a join in each query and put more effort in optimizing the query execution (mostly by tweaking my indexes).
A: Since you are running a subsequent query off the results, take your first query and use it as a View on your SQL Server, add the view to your context, and build your LINQ queries against the view.
A: Have you considered composing your query as per this article (using the decorator design pattern):
Composed LINQ Queries using the Decorator Pattern
The premise is that, instead of enumerating your first (very constly) query, you basically use the decorator pattern to produce a chain of IQueryable that is a result of query 1 and query N. This way you always execute the filtered form of the query.
Hope this might help
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Setting IGMP Version on Windows 7 I have a piece of software written "out there" (e.g. no source code available) that allows me to use it in multicast mode. I'm trying to use this software on a network that, for technical reasons, can only use IGMP Version 2.
My OS is Windows 7 (64-bit, though I doubt that makes a difference). So far my searches have only given me Windows XP & Windows Server solutions, all of which involve editing the registry. In addition to the usual reasons (aka "registry paranoia"), I hesitate to edit the registry in this case because this particular network is not the only one that I will be using; I have not problems at all in all the other networks I try using multicast on.
Is there a straightforward way to force this software onto IGMP V2?
Thanks!
John Price
A: As far as I remember, adding IGMPVersion=3 to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters is the only way to solve your problem.
Anyway, there is another creepy solution - just write a little daemon, that will sniff for IGMPv3, parse data from it and send IGMPv2 packets =)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can automate the input to a program with Perl? The program has these prompts:
Enter Username:
Enter Code:
How can I get Perl to input the proper text for each prompt?
A: You can use expect. There's a CPAN module for it.
A: Expect is the usual solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Write object to XML file (specify my own file name) So there's the basic function like this ....
def show
@position = Position.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @position }
end
end
and if you go to, say, http://localhost/(position_id).xml then you will see the xml... But I wish to have a standard xml filename that I can write the object details to because I want to access it from outside rails. I am very new to rails and have not programmed in a while...seems like this should be easy, right ? So I just want to have a file created with a name like my_xml.xml for all the objects, rather than 1.xml, 2.xml, (id).xml, etc.
Thanks for the help !
A: I met similar questions, here is my solution(I am a newbie):
I added below in routes.rb:
resources do
collection do
get 'my_xml'
end
end
Then added the my_xml action in controller. In my_xml action, assemble all data, and format it to xml via to_xml method.
No sure whether above is useful for you. Hope it helpful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to install or integrate bundles in Symfony2 i have downloaded a sonata admin bundle, and have placed in /var/www/Symfony/vendor/symfony/src/Symfony/Bundle, and have made an entry in AppKernel.php as $bundles = array( ... new Symfony\Bundle\SonataAdminBundle\SonataAdminBundle(),), but throwing an error as
Fatal error: Class
'Symfony\Bundle\SonataAdminBundle\SonataAdminBundle' not found in
/var/www/Symfony/app/AppKernel.php on line 21 Call Stack: 0.0001
326332 1. {main}() /var/www/Symfony/web/app_dev.php:0 0.0122 1121592
2. Symfony\Component\HttpKernel\Kernel->handle()
please help me as i am very new to symfony 2. As a whole please give a link or detail like how to install/configure any bundle that is downloaded.
Thanks
Ravi.M
A: First off, SonataAdminBundle lives in Sonata namespace, not Symfony. So you'll have to rewrite the instantiation in app/AppKernel.php to:
new Sonata\AdminBundle\SonataAdminBundle()
You also have to register namespace in app/autoload.php:
$loader->registerNamespaces(array(
...
'Sonata' => __DIR__.'/path/to/parent/of/Sonata/folder'
...
));
A: You need to move the bundle to
/var/www/Symfony/vendor/bundles
Then in AppKernel.php add
new Sonata\AdminBundle\SonataAdminBundle(),
in your $bundles array.
In autoload.php add
'Sonata' => __DIR__.'/../vendor/bundles',
to the $loader->registerNamespaces array
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Have only one tooltip active on the screen when using the qtip jquery tooltip plugin I am using the jquery qtip tooltip on multiple elements (images) on a page. I am trying to have only one tooltip appear on the page at a particular time. If a tooltip is shown and another tooltip has been triggered to open, the currently open instance should close. I have found this in the documentation and have set solo: true however multiple instances of the tooltip are still appearing ont the page. Here is my jquery:
<script type="text/javascript">
$(document).ready(function () {
//****** tooltips **********
$('img.help').hover(function () {
// Destroy currrent tooltip if present
//if ($(this).data("qtip")) $(this).qtip("destroy");
$(this) // Set the links HTML to the current opposite corner
.qtip({
content:
{
text: 'this is the tooltip, better to use the alt attribute of the image or use html div content somewhere on the page',
title: {
text: 'This toolip title',
button: 'Close'
}
},
position: {
corner: {
tooltip: 'bottomLeft', // Use the corner...
target: 'topRight' // ...and opposite corner
}
},
show: {
solo: true,
when: false, // Don't specify a show event
ready: true // Show the tooltip when ready
},
hide: false, // Don't specify a hide event
style: {
border: {
width: 5,
radius: 10
},
padding: 10,
textAlign: 'left',
tip: true, // Give it a speech bubble tip with automatic corner detection
name: 'blue' // Style it according to the preset 'cream' style
// name: 'light' // Style it according to the preset 'cream' style
}
});
});
});
html:
<div>
<div class="left sublabel">
Parameds</div>
<div class="left help">
<img src="images/help.png" class="help" /></div>
<div class="clear">
</div>
</div>
<div>
<div class="left sublabel">
Vision</div>
<div class="left help">
<img src="images/help.png" class="help" /></div>
<div class="clear">
</div>
</div>
A: My guess as to why they are still showing even though you have solo set to true is because all the instances of the qtip have the same class. I have always had different class names on my qtips instances when dealing with multiple tooltips on the same page and that way has worked for me.
If that doesn't work for some reason you could try hiding all the tooltips in the beforeShow api method.
$('#tooltip').qtip({
...
api: {
beforeShow: function() {
$('img.help').qtip("hide");
}
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to show MBProgressHUD on iPhone without spawning new threads? I want to show an MBProgressHUD in my iPhone app without spawning new threads.
I have a very complicated set of business logic which sometimes (but not always) needs to wait for user input, and running on multiple threads ends up asking for user input multiple times at once, leading to crazy errors. Thus I would prefer to avoid running anything off of the main thread. However, due to this constraint, MBProgressHUD is not showing because the main thread is being blocked! Normally I would create my MBProgressHUD with the following code:
[HUD showWhileExecuting:@selector(myWorkerMethod) onTarget:self withObject:nil animated:YES];
But I would like to use the following code without blocking the main thread:
HUD = [[MBProgressHUD alloc] initWithView:self.view];
[self.view addSubview:HUD];
HUD.delegate = self;
HUD.minShowTime = 0.0;
HUD.labelText = @"some text";
[HUD show:YES];
Any thoughts?
A: How about this?
MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
HUD.labelText = @"Foo";
// code to execute synchronously
[MBProgressHUD hideHUDForView:self.view animated:YES];
A: Better late than never. You can do this with some run loop tickery. See this answer for details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: I want to be able to convert numbers into text according to the ASCII decimal table I am trying to make it so that I can take individual three-character substrings and convert them to integers under the conditions tht the length of the String is a multiple of three. The integers into which the partioned substrings are converted are supposed to function as relative positions in an array that contains all the printing characters of the ASCII table.
String IntMessage = result.toString();
if
{
(IntMessage.substring(0,1)=="1" && IntMessage.length()%3==0)
for(j=0;j < IntMessage.length()-2;j += 3)
n = Integer.parseInt(IntMessage.substring(j,j+3));
mess += ASCII[n-32];
return mess;
Under otherwise conditions, the method should take the first two characters of the String and initialize them to a variable i. In this case, the variable mess is initialized to the character in the ASCII array with an index of i-32. Then there is a for loop that takes the remaining characters and partitions them into three-digit substrings and they are taken and changed into strings according to their corresponding positions in the ASCII array. The String variables in this array are continuously added on to the the variable mess in order to get the BigInteger to String conversion of the IntMessage String.
int i = Integer.parseInt(IntMessage.substring(0,2));
mess=ASCII[i-32];
for(l=2; l< IntMessage.length() - 2; l+=3)
r = Integer.parseInt(IntMessage.substring(l,l+3));
mess+=ASCII[r-32];
return mess;
For some reason the method isn't working and I was wondering whether I was doing something wrong. I know how to take an input String and convert it into a series of numbers but I want to do the opposite also. Is there anyway you could help?
A: Based on your description you can use the following methods:
String fromIntMessage(String msg) {
StringBuilder result = new StringBuilder();
for (int x = (msg.length() % 3 - 3) % 3; x < msg.length(); x += 3) {
int chr = Integer.parseInt(msg.substring(Math.max(x, 0), x + 3));
result.append(Character.toString((char) (chr - 32)));
}
return result.toString();
}
String toIntMessage(String string) {
StringBuilder result = new StringBuilder();
for (char c : string.toCharArray()) {
result.append(String.format("%03d", c + 32));
}
return result.charAt(0) == '0' ? result.substring(1) : result.toString();
}
which will give you
toIntMessage("DAA") // => "100097097"
fromIntMessage("100097097") // => "DAA"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Drupal path pattern token if/then I would like to do something like
if [node:subtitle] is available make the path pattern
[node:title]-[node:subtitle]
else
[node:title]
What is the best way to do something like this?
A: You can't do it with the pathauto module I'm afraid, it simply doesn't have this functionality. You'd have to implement hook_node_presave() and change the path manually for each node you want to do this for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get a person assigned to the task in Alfresco? There are many elements in repo and I start workflows specifying a document attached to the workflow:
var workflow = actions.create("start-workflow");
// ...
var node = search.findNode("workspace://SpacesStore/" + uuid);
workflow.execute(node);
Workflow starts so I can see it in my-tasks page.
Then I want to receive an active task from the workflow and a list of people who works due to this task. Is it possible? Moreover I want to get a list of people assigned to the workflow at all.
But this is not all! I want to receive custom properties defined in the workflow model, but I don't see anything like properties field or methods to get property in the WorkflowInstance.
I'm sure that I just don't undestand something, so explain me please: how can I do everything I asked?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dialog manipulation I want to create a dialog window, where the user can perform various tasks, and would like him to return from the dialog by clicking on the Cancel button with the mouse (i.e. not by hitting Enter). Therefore I do not want to use CreateDialog. However, by creating a less-specific dialog window via CreateWindow, all strings appear unformatted.
expr = Column[{
Row@{"set variable to: ", InputField["value", String]},
"Try to hit Enter in any of the dialogs: it closes #2 but not #1.",
CancelButton[]
}];
CreateWindow[DialogNotebook[expr], WindowSize -> All, WindowMargins -> {{100, Automatic}, {Automatic, Automatic}}, WindowTitle -> "1. CreateWindow & DialogNotebook"];
CreateDialog[expr, WindowTitle -> "2. CreateDialog"];
Is there any clever way to have the looks of the second dialog window, but the button-behaviour of the first one? Of course, expr here is a simple example, but it can be quite complex in reality, thus it is no option to wrap every string into Cell[string, "Text"], and every other expression into some obscure boxform.
A: This will stop your dialog window closing when Enter is pressed:
CreateDialog[expr, WindowTitle -> "2. CreateDialog", NotebookEventActions -> {}];
It overwrites the default dialog NotebookEventActions.
A: Perhaps using TextCell:
expr = Column[{Row@{TextCell@"set variable to: ",
InputField["value", String]},
TextCell@"Try to hit Enter in any of the dialogs: \
it closes #2 but not #1.",
CancelButton[]}];
CreateWindow[
DialogNotebook[expr], WindowSize -> All,
WindowMargins -> {{100, Automatic}, {Automatic, Automatic}},
WindowTitle -> "1. CreateWindow & DialogNotebook"]
Edit
Use
TextCell@Style[" ... blah blah ...", style_opt ]
for formatting.
A: Another option:
expr = Style[
Column[{Row@{"set variable to: ", InputField["value", String]},
"Try to hit Enter in any of the dialogs: it closes #2 but not \
#1.", CancelButton[]}], ShowStringCharacters -> False];
A: There are a number of ways to do this, and other folks have posted two good ones, but in my opinion the easiest approach is to set the BaseStyle of the Column expression to match the base style of the dialog, and then use CreateWindow. The style in question is "Panel", so this gets you the result you want:
expr = Column[{Row@{"set variable to: ", InputField["value", String]},
"Try to hit Enter in any of the dialogs: it closes #2 but not #1.",
CancelButton[]}, BaseStyle -> "Panel"];
CreateWindow[DialogNotebook[expr], WindowSize -> All,
WindowMargins -> {{100, Automatic}, {Automatic, Automatic}},
WindowTitle -> "1. CreateWindow & DialogNotebook"];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to draw a arbitrary path with touch move on a UIView I know that you can draw a line easy by Core Graphic on UIView in a drawrect function. However, I only can draw a straight line。 If I want to draw a arbitrary path with the touch move, what should I do? Can someone give a hint?
Best Regards,
A: You could use the CGPoints that are being passed to touchesMoved: and draw a line in between each on of those CGPoints in order to draw your arbitrary path. You would only need to draw a new line once, unless you are redrawing your screen, which means you would have to store all the points in an NSMutableArray, and redraw them every time. Hope that Helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adapting Library for Android The library given consists of several parts:
*
*a network module
*a storage module
*a 'controller' module
They all rely on the former module (storage relies on network, controller relies on storage). Most of the functionality is exposed in controller module.
My first plan was to wrap the whole library in a Service that serves as a Adapter for the Android world. But I found out that Services do not have a way to get a result back. So there is no (reasonable) way to call some of the 'getStuff'-Methods in the Controller Module.
What is the 'Android Way' of doing this?
Edit
The network module has to run continuously in the background cause it handles some ongoing network stuff. (so this should be a service, right?) The storage module listens for events from the network and updates itself. As these are POJOs the storage module is registered at the network module.
In the Android Part of the Application i have several Activities. All of these need to access the storage module. But there is no way to get a reference to it cause it is in the Service part of the application.
I would wrap all required methods in Intent responses, but afaik Service Intents can not be called with a result.
So ... how do i get my data from the service into activities?
A: Android build tools (well, Eclipse) support the notion of libraries. Just like any other Java library, a library might have a bunch of classes, some of them public, that consumers are free to instantiate and call. Other projects in the workspace refer to it and instantiate away. What's wrong with that approach?
EDIT: if the activities are within one app, the library code will be shared by default. Activities within one app all run in the same process (unless explicitly configured otherwise), so whatever underlying code is there, it's all shared.
If the activities are different apps, that's another question. Do you need to share the code, or the data? If just the code, then Android build-time libraries still work, as long as all said apps reside within the same workspace. Only if you need to run a set of apps on top of some shared data you have to employ IPC mechanisms - services, content providers. Another answer is the cloud. Another is shared memory (Android supports it). Yet another is a shared data storage somewhere on the SD card (so that app sandboxing does not get in the way).
A: Hmm... maybe I should have investigated more into bound services. They seem to do exactly what i want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP script unexpectedly not continuing I have a PHP script (let's call it execute.php) that draws the whole page (HTML tags and body tags etc.) at the beginning and, afer that, executes some commands (C++ programs) in the background. It then waits for these programs to terminate (some depend on the results of others, so they may be executed sequentially) and then has a JavaScript that auto-submits a form to another PHP script (which we will call results.php) because results.php needs the POST-information from the previous script.
execute.php:
<?php
print"
<html>
<body>
Some HTML code here
</body>
</html>
";
// Here come some C++-program calls
$pid_program1 = run_in_background($program1)
$pid_program2 = run_in_background($program2)
while (is_running($pid_program1) or is_running($pid_program2) )
{
//echo(".");
sleep(1);
}
// Here come some later C++-program calls that execute quickly
$pid_program3 = run_in_background($program3)
$pid_program4 = run_in_background($program4)
while (is_running($pid_program3) or is_running($pid_program4) )
{
sleep(1);
}
...
// We are now finished
print "
<form action=\"results.php\" id=\"go_to_results\" method=\"POST\">
<input type='hidden' name=\"session_id\" value=\"XYZ\">
</form>
<script type=\"text/javascript\">
AutoSubmitForm( 'go_to_results' );
</script>
";
This works nicely if the C++ programs 1 and 2 execute quickly. However, when they take their time (around 25 minutes in total), the PHP script seems to fail to continue. Interestingly the C++ programs 3 and 4 are nevertheless executed and produce the expected outputs etc.
However, when I put a echo("."); in the first while-loop before the sleep(), it works and continues until the JavaScript autosubmit.
So it seems to me that the remaining PHP code (including the autosubmit) is, for whatever reason, not send when there is no output in the first while loop.
I have also tried using set_time_limit(0) and ignore_user_abort(true) and different other things like writing to an outputbuffer (don't want to clutter the already finally displayed webpage) instead of the echo, but none of these work.
When I run the same scripts on a machine with multiple cores, so that program1 and 2 can be executed in parallel, it also works, without the echo(".").
So I am currently very confused and can't find any error messages in the apache log or PHP log and thus would really appreciate your thoughts on this one.
EDIT
Thanks again for your suggestions so far.
I have now adopted a solution involving (really simple) AJAX and it's definitely nicer this way.
However, if the C++-programs executions take "longer" it is not autosubmitting to the results-page, which is actually created this time (failed to do so before).
Basically what I have done is:
process.php:
<?php
$params = "someparam=1";
?>
<html>
<body>
<script type="text/javascript">
function run_analyses(params){
// Use AJAX to execute the programs independenantly in the background
// Allows for the user to close the process-page and come back at a later point to the results-link, w/o need to wait.
if (window.XMLHttpRequest)
{
http_request = new XMLHttpRequest();
}
else
{
//Fallback for IE5 and IE6, as these don't support the above writing/code
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
//Is http_request still false
if (!http_request)
{
alert('Ende :( Kann keine XMLHTTP-Instanz erzeugen');
}
http_request.onreadystatechange=function(){
if (http_request.readyState==4 && http_request.status==200){
// Maybe used to display the progress of the execution
//document.getElementById("output").innerHTML=http_request.responseText;
// Call of programs is finished -> Go to the results-page
document.getElementById( "go_to_results" ).submit();
}
};
http_request.open("POST","execute.php",true);
//Send the proper header information along with the request
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", params.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(params);
};
</script>
<?php
// Do some HTML-markup
...
// Start the programs!
print "
<script type=\"text/javascript\">
run_analyses('".$params."');
</script>
<form action=\"results.html" id=\"go_to_results\" method=\"POST\">
<input type='hidden' name=\"session_id\" value=\"XYZ\">
</form>
?>
</html>
</body>
and execute.php contains the C++-program calls, waiting-routines and finally, via "include("results.php")" the creation of the results-page.
Again, for "not so long" program executions, the autosubmission works as expected, but not if it takes "longer". By "longer" I mean around 25 minutes.
I have absolutely no idea what could cause this as again, there are no error-messages to be found.
Am I missing a crucial configuration option there (apache, php, etc.)?
EDIT
As it turned out, letting the requested PHP-script "echo" something repeatedly prevents the timeout. So it is basically the same as for the PHP-solution without AJAX, but this time, since the responseText of the AJAX-request is not necessarily needed, the progress-page is not cluttered and it may be used as a workaround. Specifically, I would not necessarily recommend it a as a general solution or good-practice.
A: It occurs to me that a better approach would be to:
*
*Output the complete HTML page
*Show a loading message to the user
*Send an AJAX request to start the external program
*Wait for callback (waiting for external program to finish)
*Repeat steps 3 and 4 until all program have been executed
*Update the page to tell the user what is going on
*Submit the form
This way, you get the HTML to the user as quickly as possible, then you execute the programs sequentially in an orderly and controlled fashion without worrying about hitting the max_execution_time threshold. This also enables you to keep your user informed - after each AJAX callback, you can tell the user that "program ABC has completed, starting DEF..." and so on.
EDIT
Per request, I'll add an outline of how this could be implemented. A caveat, too: If you are going to be adding more javascript-derived functionality to your page, you'll want to consider using a library like jQuery or mootools (my personal favorite). This is a decision you should make right away - if you aren't going to be doing a lot of javascript except this, then a library will only bloat your project, but if you are going to be adding a lot of javascript, you don't want to have to come back later and re-write your code because you add a library 3/4 of the way through the project.
I've used mootools to create this demonstration, but it isn't necessary or even advisable to add mootools if this is the only thing you're going to use it for. It is simply easier for me to write an example really quick without having to stop and think :)
First, the main page. We'll call this page view.php. This should contain your initial HTML as well as the javascript that will fire off the AJAX requests. Basically, this entire jsFiddle would be view.php: http://jsfiddle.net/WPnEy/1/
Now, execute.php looks like this:
$program_name = isset($_POST['program_name']) ? $_POST['program_name'] : false;
switch ($program_name) {
case 'program1':
$program_path = '/path/to/executable/';
$friendly_name = 'Some program 1';
break;
case 'program2':
$program_path = '/path/to/executable/';
$friendly_name = 'Some program 2';
break;
case 'program3':
$program_path = '/path/to/executable/';
$friendly_name = 'Some program 3';
break;
case 'program4':
$program_path = '/path/to/executable/';
$friendly_name = 'Some program 4';
break;
default:
die(json_encode(array(
'program_name'=>'Invalid',
'status'=>'FAILED',
'error'->true,
'error_msg'=>'Invalid program'
)));
break;
}
$pid = run_in_background($program_path)
while (is_running(pid)) {
sleep(1);
}
// check here for errors, get any error messages you might have
$error = false;
$error_msg = '';
// use this for failures that are not necessarily errors...
$status = 'OK';
die(json_encode(array(
'program_name'=>$friendly_name,
'status'=>$status,
'error'->$error,
'error_msg'=>$error_msg
)));
execute.php would then be called once for each program. The $friendly_program variable gives you a way to send back something for the user to see. The switch statement there makes sure that the script isn't being asked to execute anything you aren't expecting. The program is executed, and when it is done you send along a little package of information with the status, the friendly name, any errors, etc. This comes into the javascript on view.php, which then decides if there are more programs to run. If so, it will call execute.php again... if not, it will submit the form.
A: This seems rather convoluted... And very risky. Any network glitches, the user's browser closing for whatever reason, and even a firewall timing out, and this script is aborted.
Why not run the whole thing in the background?
<?php
session_start();
$_SESSION['background_run_is_done'] = false;
session_write_close(); // release session file lock
set_time_limit(0);
ignore_user_abort(true); // allow job to keep running even if client disconnects.
.... your external stuff here ...
if ($successfully_completed) {
session_start(); // re-open session file to update value
$_SESSION['background_run_is_done'] = TRUE;
}
... use curl to submit job completion post here ...
?>
This disconnects the state of the user's browser from the processing of the jobs. You then just have your client-side code ping the server occasionally to monitor the job's progress.
A: Launching and managing multiple and long-running processes from a webserver PHP process is fraught with complications and complexity. It's also very different on different platforms (you didn't say which you are using).
Handling the invocation of these processes synchronously from the execution of your PHP is not the way to address this. You really need to run the programs in a seperate session group - and use (e.g.) Ajax or Comet to poll the status of them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Horizontal Scroll View and a gap with overlapping content After some issues, I now have a working horizontal scroller, it uses a linear layout, with various image views inside, the problem is, I want some of the image views to overlap each other, I achieve this by using
myImageView.setX(-100);
The problem is, there is a big blank space at the end of the scroller, as if all of the image views widths have been taken into account but as they have been moved back a bit, an empty space has been left.
Is there a way to use a relative layout with a scroller? Or a way to manually decrease the width of the scroller so my overlapping content fits?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android: Identify what code an AsyncTask is running In Eclipse in the Debug window I see a thread that shows:
Thread <16> AsyncTask #11
Is there a way to determine what actual section of code the AsyncTask is referring to? Is there something I have to add in code to identify that running thread?
A: You can name the AsyncTask thread at the beginning of your doInBackground function:
public void doInBackground(Params... params) {
Thread.currentThread().setName("Foo (AsyncTask)");
// ... rest of your AsyncTask processing ...
}
The specified name will be shown in the Eclipse Debug window, as well as thread list in DDMS perspective.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: MySQL Query Pegs Server at 100% - Sometimes I've got a MySQL query that runs very, very slowly and pegs the server usage at 100% as soon as it's executed....sometimes.
Here's the query:
SELECT DISTINCT r1.recordID,
(SELECT MAX(r2.date)
FROM reminders as r2
WHERE r2.owner = '$owner'
AND r2.recordID = r1.recordID
AND r2.status = 'Active'
AND r2.followUp != 'true'
ORDER BY r2.date DESC LIMIT 1) as maxDate
FROM reminders as r1
WHERE r1.owner = '$owner'
AND (SELECT MAX(r2.date)
FROM reminders as r2
WHERE r2.recordID = r1.recordID
AND r2.status = 'Active'
AND r2.followUp != 'true'
ORDER BY r2.date DESC LIMIT 1) <= '$date'
AND (SELECT do_not_call
FROM marketingDatabase
WHERE id = r1.recordID) != 'true'
AND r1.status = 'Active'
ORDER BY maxDate DESC
I'm not sure if it's a poorly written query (might be...I'm new at this) or something else. Sometimes it works fine and results are returned almost instantly but other times it takes a long time (15+ minutes) and 100% server resources to return the results.
Any idea why this could be happening? Anything I can do to the query to prevent this?
Thanks in advance!
[EDIT]
Here's the EXPLAIN.
Array
(
[0] => Array
(
[id] => 1
[select_type] => PRIMARY
[table] => r1
[type] => ALL
[possible_keys] =>
[key] =>
[key_len] =>
[ref] =>
[rows] => 2073
[Extra] => Using where; Using temporary; Using filesort
)
[1] => Array
(
[id] => 4
[select_type] => DEPENDENT SUBQUERY
[table] => marketingDatabase
[type] => eq_ref
[possible_keys] => PRIMARY
[key] => PRIMARY
[key_len] => 4
[ref] => teleforce.r1.recordID
[rows] => 1
[Extra] =>
)
[2] => Array
(
[id] => 3
[select_type] => DEPENDENT SUBQUERY
[table] => r2
[type] => ALL
[possible_keys] =>
[key] =>
[key_len] =>
[ref] =>
[rows] => 2073
[Extra] => Using where
)
[3] => Array
(
[id] => 2
[select_type] => DEPENDENT SUBQUERY
[table] => r2
[type] => ALL
[possible_keys] =>
[key] =>
[key_len] =>
[ref] =>
[rows] => 2073
[Extra] => Using where
)
)
A: Several things could make this query slow.
One: In general, the first thing to check is indexes. You have three embedded queries that have to be executed for each record in r1. If any of these are not able to effectively use an index and have to process a large number of records, this query will be very slow. Review your indexes, and use "explain" to see what's being used.
Two: Embedded queries tend to be slower than joins. See if you can't transform some of your embedded queries to joins.
Three: In this particular query, you're joining "remainders" back on itself, as far as I can figure out, just to find max(date). Why not just use a GROUP BY? My step 1 to improving this query would be:
select r1.recordID, max(r1.date) as maxdate
from reminders as r1
where r1.owner=$owner and r1.status='Active' and r1.followUp!='true'
and (SELECT do_not_call FROM marketingDatabase WHERE id = r1.recordID) != 'true'
group by r1.recordID
having max(r1.date)<=$date
order by maxdate desc
I don't have your database to test this, but I think it would give the same results.
Four: I'd turn the other embedded query into a join. Like:
select r1.recordID, max(r1.date) as maxdate
from reminders as r1
join marketingDatabase as m on m.id=r1.recordID
where r1.owner=$owner and r1.status='Active' and r1.followUp!='true'
and m.do_not_call != 'true'
group by r1.recordID, r1.owner
having max(r1.date)<=$date
order by maxdate desc
(I'm not sure what a recordID identifies. It appears from your query that you can have multiple records in reminders with the same recordid.)
Five: You'll probably get best performance if you have indexes on reminders(owner, date) and marketingDatabase(id).
Six: Just by the way, if "do_not_call" and followUp are true/false, they should be booleans and not varchars. You're just wasting disk space and execution time processing "true" instead of a boolean TRUE. And you create the problem of mis-spellings, like "ture" or "True". At the absolute worst, make them a char(1), T or F.
There are times when you need embedded queries, but they should be a last resort.
A: Try to create an index on reminders.owner with the command
CREATE INDEX someNameYouChoose ON reminders(owner);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jstack gives java.lang.reflect.InvocationTargetException Til yesterday, jstack was working fine.
Today, all out of sudden it gives me the exception below and I don't know why:
$ sudo -u tomcat6 jstack -J-d64 -m 26385
Attaching to process ID 26385, please wait...
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at sun.tools.jstack.JStack.runJStackTool(JStack.java:118)
at sun.tools.jstack.JStack.main(JStack.java:84)
Caused by: sun.jvm.hotspot.runtime.VMVersionMismatchException: Supported versions are 20.1-b02. Target VM is 19.0-b09
at sun.jvm.hotspot.runtime.VM.checkVMVersion(VM.java:224)
at sun.jvm.hotspot.runtime.VM.<init>(VM.java:287)
at sun.jvm.hotspot.runtime.VM.initialize(VM.java:357)
at sun.jvm.hotspot.bugspot.BugSpotAgent.setupVM(BugSpotAgent.java:594)
at sun.jvm.hotspot.bugspot.BugSpotAgent.go(BugSpotAgent.java:494)
at sun.jvm.hotspot.bugspot.BugSpotAgent.attach(BugSpotAgent.java:332)
at sun.jvm.hotspot.tools.Tool.start(Tool.java:163)
at sun.jvm.hotspot.tools.JStack.main(JStack.java:86)
... 6 more
Does anyone know what's causing this?
I'm running Tomcat6 on Ubuntu server edition.
A: Nevermind. It was an issue with OpenJDK.
Replacing it with Sun/Oracle's original JRE and JDK fixed the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is ObjectContext.SaveChanges ACIDIC? As the title suggests, Is the following code acidic, e.g. if I call SaveChanges, will all the Product.Add INSERT statements be executed (or rolled back if there is an error).
using(DBEntities ctx = new DBEntities())
{
for(int i = 0; i < 10; i++)
{
ctx.Products.Add(new Product("Product " + (i + 1)));
}
ctx.SaveChanges();
}
MSDN states:
SaveChanges operates within a transaction. SaveChanges will roll back
that transaction and throw an exception if any of the dirty
ObjectStateEntry objects cannot be persisted.
However looking at the profiler, this doesn't seem to be the case. Am I required to wrap the block with TransactionScope?
A: using(DBEntities ctx = new DBEntities())
{
for(int i = 0; i < 10; i++)
{
ctx.Products.Add(new Product("Product " + (i + 1)));
}
ctx.SaveChanges();
}
This SaveChanges() call will be in a transaction automatically. You won't have to wrap it under a new transactionscope.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Testing Exceptions using SenTestingKit/OCUnit The only solution I seem to be able to find for testing for exceptions is using SenTestingKit's STAssertThrows and STAssertThrowsSpecific, however in both cases when the exception is thrown the application under test hangs until I manually ask it to continue. Surely the exceptions should be swallowed by the testing framework? And if not, does anyone have a beter suggestion for testing exceptions?
A: I was going to delete this question, but here is the solution for anyone else who finds themselves in a the same situation:
The reason that the application was breaking was that I had an Exception Breakpoint set up. This breaks as soon as an exception is raised, not when it bubbles up, so it was actually being halted before it had even got as far as my assertion. I just need to toggle off breakpoints (or just the exception breakpoint) when I am running tests.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: problem reading hex values from file with NSString or NSData I have a file which I need to grab some data from but I am only getting nil when i read it.
the file contains
K vU™"3Dô
U0?*
the hex values are
1B 1B 01 1B 4B 07 20 1B 76 02 06 55 AA 11 22 33 44 99 20 0A 1B 55 30 1B 1B 3F 0C 1B 2A 01 0C 0C
I have tried reading the file a few ways but always get nil when i turn it into a string.
NSData *textData = [[NSData alloc] initWithContentsOfFile:filename];
NSLog(@"%@",[textData description]);
//prints out <1b1b011b 4b07201b 76020655 aa112233 4499200a 1b55301b 1b3f0c1b 2a010c0c>
text = [[NSString alloc] initWithData:textData encoding:NSUTF8StringEncoding];
//at this point text is nil
text = [[NSString alloc] initWithContentsOfFile:filename encoding:NSUTF8StringEncoding error:err];
//at this point text is still nil
text = [NSString stringWithContentsOfFile:filename encoding:NSUTF8StringEncoding error:err];
//at this point text is still nil
I know its reading the file. I can print out the attributes and see it says the size is 30. what did i miss/what am i doing wrong?
A: Your file is probably simply not encoded in UTF8. That's why trying to interpret the data into some UTF8 string fails.
Are you sure it is not UTF-16 (LE or BE) or any other encoding? (or maybe simply ASCII -- with some non-printable characters)
A: How about text = [[NSString alloc] initWithString:[textData description]];? :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CoreData: How to handle inheritance dynamically? e.g., I've got three classes in my CoreData-project: Person, Pupil and Teacher. Pupil and Teacher have Person as parent class.
Now, I'd like to do something like:
Person *person;
if (createPupil) {
person = [[Pupil alloc] init];
...
} else {
person = [[Teacher alloc] init];
...
}
[self.managedObjectContext save:&error];
But it seems like its always saving to the Person-table. When I try to fetch pupils or teachers, they are empty. Is there a possiblity to make this dynamic?
Thanks a lot,
Stefan
A: Your if statements already introduce the dynamic element. This is how I would do it:
if (createPupil) {
Pupil *person = [NSEntityDescription
insertNewObjectForEntityForName:"Pupil"
inManagedObjectContext:self.managedObjectContext];
// ... configure
}
else {
Teacher *person = [NSEntityDescription
insertNewObjectForEntityForName:"Teacher"
inManagedObjectContext:self.managedObjectContext];
// ... configure
}
[self.managedObjectContext save:&error];
Also check out Apple's comment in the insertNewObjectForEntityForName: inManagedObjectContext: documentation.
The method is particularly useful on Mac OS X v10.4, as you can use it
to create a new managed object without having to know the class used
to represent the entity. This is especially beneficial early in the
development life-cycle when classes and class names are volatile.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Best way to convert string to bytes in Python 3? TypeError: 'str' does not support the buffer interface suggests two possible methods to convert a string to bytes:
b = bytes(mystring, 'utf-8')
b = mystring.encode('utf-8')
Which method is more Pythonic?
A: If you look at the docs for bytes, it points you to bytearray:
bytearray([source[, encoding[, errors]]])
Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.
The optional source parameter can be used to initialize the array in a few different ways:
If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
If it is an integer, the array will have that size and will be initialized with null bytes.
If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.
Without an argument, an array of size 0 is created.
So bytes can do much more than just encode a string. It's Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense.
For encoding a string, I think that some_string.encode(encoding) is more Pythonic than using the constructor, because it is the most self documenting -- "take this string and encode it with this encoding" is clearer than bytes(some_string, encoding) -- there is no explicit verb when you use the constructor.
I checked the Python source. If you pass a unicode string to bytes using CPython, it calls PyUnicode_AsEncodedString, which is the implementation of encode; so you're just skipping a level of indirection if you call encode yourself.
Also, see Serdalis' comment -- unicode_string.encode(encoding) is also more Pythonic because its inverse is byte_string.decode(encoding) and symmetry is nice.
A: It's easier than it is thought:
my_str = "hello world"
my_str_as_bytes = str.encode(my_str)
print(type(my_str_as_bytes)) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
print(type(my_decoded_str)) # ensure it is string representation
you can verify by printing the types. Refer to output below.
<class 'bytes'>
<class 'str'>
A: Answer for a slightly different problem:
You have a sequence of raw unicode that was saved into a str variable:
s_str: str = "\x00\x01\x00\xc0\x01\x00\x00\x00\x04"
You need to be able to get the byte literal of that unicode (for struct.unpack(), etc.)
s_bytes: bytes = b'\x00\x01\x00\xc0\x01\x00\x00\x00\x04'
Solution:
s_new: bytes = bytes(s, encoding="raw_unicode_escape")
Reference (scroll up for standard encodings):
Python Specific Encodings
A: The absolutely best way is neither of the 2, but the 3rd. The first parameter to encode defaults to 'utf-8' ever since Python 3.0. Thus the best way is
b = mystring.encode()
This will also be faster, because the default argument results not in the string "utf-8" in the C code, but NULL, which is much faster to check!
Here be some timings:
In [1]: %timeit -r 10 'abc'.encode('utf-8')
The slowest run took 38.07 times longer than the fastest.
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 183 ns per loop
In [2]: %timeit -r 10 'abc'.encode()
The slowest run took 27.34 times longer than the fastest.
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 137 ns per loop
Despite the warning the times were very stable after repeated runs - the deviation was just ~2 per cent.
Using encode() without an argument is not Python 2 compatible, as in Python 2 the default character encoding is ASCII.
>>> 'äöä'.encode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
A: How about the Python 3 'memoryview' way.
Memoryview is a sort of mishmash of the byte/bytearray and struct modules, with several benefits.
*
*Not limited to just text and bytes, handles 16 and 32 bit words too
*Copes with endianness
*Provides a very low overhead interface to linked C/C++ functions and data
Simplest example, for a byte array:
memoryview(b"some bytes").tolist()
[115, 111, 109, 101, 32, 98, 121, 116, 101, 115]
Or for a unicode string, (which is converted to a byte array)
memoryview(bytes("\u0075\u006e\u0069\u0063\u006f\u0064\u0065\u0020", "UTF-16")).tolist()
[255, 254, 117, 0, 110, 0, 105, 0, 99, 0, 111, 0, 100, 0, 101, 0, 32, 0]
#Another way to do the same
memoryview("\u0075\u006e\u0069\u0063\u006f\u0064\u0065\u0020".encode("UTF-16")).tolist()
[255, 254, 117, 0, 110, 0, 105, 0, 99, 0, 111, 0, 100, 0, 101, 0, 32, 0]
Perhaps you need words rather than bytes?
memoryview(bytes("\u0075\u006e\u0069\u0063\u006f\u0064\u0065\u0020", "UTF-16")).cast("H").tolist()
[65279, 117, 110, 105, 99, 111, 100, 101, 32]
memoryview(b"some more data").cast("L").tolist()
[1701670771, 1869422624, 538994034, 1635017060]
Word of caution. Be careful of multiple interpretations of byte order with data of more than one byte:
txt = "\u0075\u006e\u0069\u0063\u006f\u0064\u0065\u0020"
for order in ("", "BE", "LE"):
mv = memoryview(bytes(txt, f"UTF-16{order}"))
print(mv.cast("H").tolist())
[65279, 117, 110, 105, 99, 111, 100, 101, 32]
[29952, 28160, 26880, 25344, 28416, 25600, 25856, 8192]
[117, 110, 105, 99, 111, 100, 101, 32]
Not sure if that's intentional or a bug but it caught me out!!
The example used UTF-16, for a full list of codecs see Codec registry in Python 3.10
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1399"
}
|
Q: java string optimizations - load-in-place algorithm I need to optimize the actual loading/parsing of a csv file (strings). The best way I know is the load-in-place algorithms and I successfully used it using JNI and a C++ dll that loads the data directly from a file made out of the parsed csv data.
It would have been fine if it stopped there but using that scheme only made it 15% faster (no more parsing of the data). One of the reason it is not as fast as I first thought it would be is because the java client uses jstring so I need to convert the actual data again from char* to jstring.
The best would be to ignore that conversion step and load-in-place the data directly into the jstring objects (no more conversion). So instead of duplicating the data based on the loaded-in-place data, the jstring would be pointing directly into the chunk of memory (note that the data would be made of jchars instead of chars). The real bad thing is that we would need to make sure the garbage collector doesn't collect that data (by keeping a reference to it maybe?) but it should be feasible.. no?
I think I have two options to do that:
1- Load the data in java (no more jni) and use chars that are pointing to the loaded data to create the strings.. but I need to find a way to prevent the duplicating of the data when creating a String.
2- Continue using jni to "manually" create and set the jstring variable and make sure that the garbage collector options are set properly to prevent it from doing anything to it. For instance:
jstring str;
str.data = loadedinplacedata; // assign data pointer
return str;
Not sure if that's possible but I wouldn't mind just save the jstring directly into the file and reload it like that:
jstring * str = (jstring *)&loadedinplacedata[someoffset];
return * str;
I'm aware that this is not the usual Java thing, but I'm pretty sure Java is extensible enough to be able to do that. And it's not like I really have a choice in the matter... the project is already 3 years old and it needs to work. =S
This is the JNI code (C++):
const jchar * data = GetData(id, row, col); // get pointer of the string ends w/ \0
unsigned int len = wcslen( (wchar_t*)data );
// The best would be to prevent this function to duplicate the data.
jstring str = env->NewString( data, len );
return str;
Note: The code above made it 20% faster (instead of 15) by using unicode data instead of UTF8 (NewString instead of NewStringUTF). This shows that if I can remove that step or optimize it, I'd get quite the good performance increase.
A: I've never worked with JNI, but... does it make any sense to have it return a custom class implementing CharSequence, and maybe a few other interfaces like Comparable< CharSequence >, instead of a String? It seems like you'd be less likely to have data corruption problems that way.
A: I think first you have to understand why the C++ version runs 15% faster, and why that performance improvement is not directly translatable into Java. Why can't you write the code 15% faster in Java?
Lets look at your problem. You've eliminated the parsing by using a C++ dll. (Why could this not have been done in Java?). And then as I understand it:
*
*You're proposing to manipulate the contents of the jstrings directly
*You want to prevent the garbage collector from touching these modified jstrings (by keeping a reference to them), and therefore potentially modifying the behaviour of the JVM and screwing with the garbage collector when it does eventually garbage collect.
Will you 'fix' these references before you allow them to be garbage collected?
If you propose doing your own memory management, why are you using java at all? Why not just do it in pure C++?
Assuming that you wish to continue in Java, when you create a String, it the String itself is a new Object, but the data that it's pointing to is not necessarily. You can test this by calling String.intern(). Using the following code:
public static void main(String[] args) {
String s3 = "foofoo";
String s1 = call("foo");
String s2 = call("foo");
System.out.println("s1 == s2=" + (s1 == s2));
System.out.println("s1.intern() == s2.intern()=" + (s1.intern() == s2.intern()));
System.out.println("s1.intern() == s3.intern()=" + (s1.intern() == s3.intern()));
System.out.println("s1.substring(3) == s2.substring(3)=" + (s1.substring(3) == s2.substring(3)));
System.out.println("s1.substring(3).intern() == s2.substring(3).intern()=" + (s1.substring(3).intern() == s2.substring(3).intern()));
}
public static String call(String s) {
return s + "foo";
}
This produces:
s1 == s2=false
s1.intern() == s2.intern()=true
s1.intern() == s3.intern()=true
s1.substring(3) == s2.substring(3)=false
s1.substring(3).intern() == s2.substring(3).intern()=true
So you can see that although the String objects are different, the data, the actual bytes aren't. So your modifications may not actually be that relevant, the JVM may already be doing it for you. And it's worth saying that if you start modifying the internals of jstrings, this may well screw this up.
My suggestion would be to find out what you can do in terms of algorithms. Development with pure java is always quicker that Java & JNI combined. You've got a much better chance of finding a better solution with pure Java.
A: Well... seems like what I wanted to do is not "supported" by Java unless I hack it.. I believe it would be possible to do so by using GetStringCritical to get the actual char array address and then find out the number of characters and such but this is way beyond "safe" programming.
The best work around I found was to create a hash table in java and use an unique identifier processed while creating my data file (acting similar to .intern()). if the string was not in the hash table, it would query it through the dll and save it in the hash table.
data file:
numrow,numcols,
for each cell, add a integer value (in my case the offset in memory pointing to the string)
for each cell, add string ending with \0
By using the offset value, I can somewhat minimize the number of strings creation and string queries. I tried using globalref to keep the string inside the dll but that made it 4 times slower.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Defining jquery plugins I have a problem with defining jquery plugins. In asp.net page located RadAjaxPanels, in which are loaded widgets (asp.net controls). In the widget I define jquery plugins:
<script src="../../JS/jquery-1.5.1.js" type="text/javascript"></script>
<script src='../../JS/jquery-ui-1.8.16.custom.min.js' type="text/javascript"></script>
<script src="../../JS/ui.spinner.min.js" type="text/javascript"></script>
<script src="../../JS/jquery.blockUI.js" type="text/javascript"></script>
<script src="../../JS/jquery.json-2.2.min.js" type="text/javascript"></script>
But at the first applying to the plug-in (eg $('#tReports').unblock()) an error occurs: "Object doesn't support property or method 'unblock'".
Maybe it's because conflicts with jquery defined in Telerik control. Jquery object works properly. Please help :)
A: It sounds like you're including jQuery more than once, and the instance of jQuery that you're using to call unblock() is not the one the plug-in has extended. Possibly from telerik, but also possibly from having multiple user controls with jQuery script blocks.
You need to put a system in-place to ensure proper composition of script includes (like ScriptManager or RadScriptManager in WebForms) .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: TSQL DISTINCT RECORD COUNT
I am using SSMS 2008 and am trying to get a distinct count of Event_names from my table. But instead, it is returning count = 1 when there are actually 2 records and other invalid values. What I want is the total count / consumer for their number of distinct event_names they are part of. Also, some of the Event Counts for the same consumer are different. But I want one distinct count / consumer. Here is a portion of the data returned by my invalid query:
consumer Program Enrollment Date event_name Event_Ct
B, Tiffany 2010-09-27 12:00:00.000 Comprehensive Clinical Assessment 1
B, Tiffany 2010-09-27 00:00:00.000 Telemedicine Comprehensive Clinical Assessment 1
B, Nickolas Tyan 2010-12-07 15:00:00.000 Comprehensive Clinical Assessment 1
B, Nickolas Tyan 2010-12-07 00:00:00.000 Telemedicine Comprehensive Clinical Assessment 1
B, Jack 2011-06-13 08:30:00.000 Comprehensive Clinical Assessment 1
B, Jack 2011-01-03 00:00:00.000 Medication Management 1
B, Victoria Lynn 2010-11-10 00:00:00.000 Telemedicine Comprehensive Clinical Assessment 3
B, Victoria Lynn 2010-12-28 00:00:00.000 Telemedicine Psychiatric Assessment 3
B, Victoria Lynn 2011-01-07 00:00:00.000 Telemedicine Psychiatric Progress Note 2
B, Victoria Lynn 2011-02-08 00:00:00.000 Telemedicine Psychiatric Progress Note 2
And here is the T-SQL I used for the above:
SELECT consumer, [Program Enrollment Date], event_name, [Program Quarter]
INTO #INITIATIONS
FROM #consumer_initiations
WHERE consumer IN
(SELECT DISTINCT Consumer
FROM #consumer_initiations
GROUP BY Consumer
HAVING Count(DISTINCT event_name) > 1)
ORDER BY consumer, event_name
SELECT A.consumer, A.[Program Enrollment Date], A.event_name, count(A.event_name)
FROM #INITIATIONS A
JOIN #INITIATIONS B ON A.consumer = B.consumer AND A.event_name <> B.event_name AND A.[Program Enrollment Date] <> B.[Program Enrollment Date]
GROUP BY A.consumer, A.event_name, a.[Program Enrollment Date]
I also tried this query, which returned correct counts for consumers with only 2 records, but for those with > 2 records, it returned too high of counts:
SELECT A.consumer, count(A.event_name)
FROM #INITIATIONS A
JOIN #INITIATIONS B ON A.consumer = B.consumer AND A.event_name <> B.event_name AND A.[Program Enrollment Date] <> B.[Program Enrollment Date]
GROUP BY A.consumer
Thanks to Chris, here is the solution that worked:
Select I.consumer, [Program Enrollment Date], event_name, countPerConsumer.[Number of Events]
From #INITIATIONS i
Join (Select Consumer, count(distinct event_name) as [Number of Events] From #INITIATIONS GROUP BY Consumer) countPerConsumer
on countPerConsumer.Consumer
= i.consumer
A: I think I've grasped what your trying to do. If not I appolgize. something like this should help you:
Select consumer, [Program Enrollment Date], event_name, countPerConsumer.[Number of Events]
From #INITIATIONS i
Join (Select Consumer, count(distinct event_name) as [Number of Events]
group by Consumer)countPerConsumer
on countPerConsumber.consumer = i.consumer
the idea is your joining a table built on the fly of a count of distinct events for each consumer. you should be able to keep the piece where you build #INITIATIONS and just replace the last query with the above. hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to draw a pixel on the screen directly? I'm wanting to do something like the following:
...
pixel[0,0] = [ 254, 0, 0 ] # Draw R at pixel x0y0
pixel[2,1] = [ 0, 254, 0 ] # Draw G at pixel x2y1
pixel[4,2] = [ 0, 0, 254 ] # Draw B at pixel x4y2
...
I hope to display many different configurations of pixels and colours in a short space of time -- writing to an intermediary file would be too expensive.
How should I best go about achieving this goal in Python?
A: Although it does not exactely what you say (paint "by pixel"), I like to use Python, GTK and Cairo.
In this case, you create a GTK Window, add a DrawingArea, create a Cairo context, and do paint operations.
The difference is that you have a continuous canvas with floating-point coordinates, and instead of pixels you draw geometric shapes with strokes and fills. You could even draw rectangles one-pixel-sized, and fill them, but that would not be so fast.
Also, you can take any raster object (image, pixbuffer) and render it at once. Then you could generate images in a fast sequence, and render its pixels all at once, similar to a movie.
A working example can be seen in a previous answer here (second snippet):
quickest way to get started with cairo
A: Im not sure if I get your question right, but I believe you should investigate some framework or middleware that give you an access to screen. I would say PyGame or Pyglet or maybe even Panda. It may be overkill a bit because Pygame and Panda is a framework that let you develop game while Pyglet is wrapper to Opengl in python, but it will let you control pixels, windows and similar with easy.
A: Direct answer:
This can only be done with OS-specific APIs. Some OSes do not allow changing pixels on the screen directly.
On Windows, you can use pywin32 libraries to get screen's device context with dc = GetDC(0) call, then paint pixels with SetPixel(dc, x, y, color).
import win32gui
import win32api
dc = win32gui.GetDC(0)
red = win32api.RGB(255, 0, 0)
win32gui.SetPixel(dc, 0, 0, red) # draw red at 0,0
Of course, what you paint this way can be erased at any moment.
Right answer:
Painting pixel by pixel is the slowest way to paint something. For example, on Windows, creating an image in memory then painting it in one operation is order of magnitude faster than painting with SetPixel.
If you need speed, use some user interface library for python, for example, Tkinter module or PyQt. Create a window and image in memory, then paint the image on the window. If you need to manipulate pixels, manipulate them in the image and repaint every time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: org.postgresql.util.PSQLException: Large Objects may not be used in auto-commit mode I am using Spring , JPA, Hibernate, Postgresql. I can upload/insert a file to the database. But I got the error when tried to access the file.
EVERE: Servlet.service() for servlet default threw exception
org.postgresql.util.PSQLException: Large Objects may not be used in auto-commit mode.
at org.postgresql.largeobject.LargeObjectManager.open(LargeObjectManager.java:200)
at org.postgresql.largeobject.LargeObjectManager.open(LargeObjectManager.java:172)
at org.postgresql.jdbc2.AbstractJdbc2BlobClob.<init>(AbstractJdbc2BlobClob.java:47)
at org.postgresql.jdbc2.AbstractJdbc2Blob.<init>(AbstractJdbc2Blob.java:21)
at org.postgresql.jdbc3.AbstractJdbc3Blob.<init>(AbstractJdbc3Blob.java:19)
at org.postgresql.jdbc4.AbstractJdbc4Blob.<init>(AbstractJdbc4Blob.java:20)
at org.postgresql.jdbc4.Jdbc4Blob.<init>(Jdbc4Blob.java:20)
at org.postgresql.jdbc4.Jdbc4ResultSet.getBlob(Jdbc4ResultSet.java:52)
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.getBlob(AbstractJdbc2ResultSet.java:335)
at org.apache.tomcat.dbcp.dbcp.DelegatingResultSet.getBlob(DelegatingResultSet.java:527)
at org.hibernate.type.ByteArrayBlobType.get(ByteArrayBlobType.java:112)
at org.hibernate.type.AbstractLobType.nullSafeGet(AbstractLobType.java:68)
at org.hibernate.type.AbstractType.hydrate(AbstractType.java:105)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2267)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1423)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1351)
at org.hibernate.loader.Loader.getRow(Loader.java:1251)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:619)
at org.hibernate.loader.Loader.doQuery(Loader.java:745)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:270)
at org.hibernate.loader.Loader.loadCollection(Loader.java:2062)
at org.hibernate.loader.collection.CollectionLoader.initialize(CollectionLoader.java:62)
at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:628)
at org.hibernate.event.def.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:83)
at org.hibernate.impl.SessionImpl.initializeCollection(SessionImpl.java:1853)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:366)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:108)
at org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:272)
at org.apache.taglibs.standard.tag.common.core.ForEachSupport.toForEachIterator(ForEachSupport.java:382)
at org.apache.taglibs.standard.tag.common.core.ForEachSupport.supportedTypeForEachIterator(ForEachSupport.java:258)
at org.apache.taglibs.standard.tag.common.core.ForEachSupport.prepare(ForEachSupport.java:189)
at javax.servlet.jsp.jstl.core.LoopTagSupport.doStartTag(LoopTagSupport.java:287)
at org.apache.jsp.WEB_002dINF.jsp.purchaseOrder.editForm_jsp._jspx_meth_c_005fforEach_005f4(editForm_jsp.java:1884)
at org.apache.jsp.WEB_002dINF.jsp.purchaseOrder.editForm_jsp._jspService(editForm_jsp.java:131)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:377)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:551)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:488)
at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:968)
at org.apache.jasper.runtime.PageContextImpl.doInclude(PageContextImpl.java:650)
at org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:644)
at org.apache.tiles.jsp.context.JspTilesRequestContext.include(JspTilesRequestContext.java:103)
at org.apache.tiles.jsp.context.JspTilesRequestContext.dispatch(JspTilesRequestContext.java:96)
at org.apache.tiles.renderer.impl.TemplateAttributeRenderer.write(TemplateAttributeRenderer.java:44)
at org.apache.tiles.renderer.impl.AbstractBaseAttributeRenderer.render(AbstractBaseAttributeRenderer.java:106)
at org.apache.tiles.renderer.impl.ChainedDelegateAttributeRenderer.write(ChainedDelegateAttributeRenderer.java:76)
at org.apache.tiles.renderer.impl.AbstractBaseAttributeRenderer.render(AbstractBaseAttributeRenderer.java:106)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:670)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:336)
at org.apache.tiles.template.InsertAttributeModel.renderAttribute(InsertAttributeModel.java:210)
at org.apache.tiles.template.InsertAttributeModel.end(InsertAttributeModel.java:126)
at org.apache.tiles.jsp.taglib.InsertAttributeTag.doTag(InsertAttributeTag.java:311)
at org.apache.jsp.WEB_002dINF.templates.main_jsp._jspx_meth_tiles_005finsertAttribute_005f2(main_jsp.java:619)
at org.apache.jsp.WEB_002dINF.templates.main_jsp._jspService(main_jsp.java:178)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:377)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
at org.apache.tiles.servlet.context.ServletTilesRequestContext.forward(ServletTilesRequestContext.java:241)
at org.apache.tiles.servlet.context.ServletTilesRequestContext.dispatch(ServletTilesRequestContext.java:222)
at org.apache.tiles.renderer.impl.TemplateAttributeRenderer.write(TemplateAttributeRenderer.java:44)
at org.apache.tiles.renderer.impl.AbstractBaseAttributeRenderer.render(AbstractBaseAttributeRenderer.java:106)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:670)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:690)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:644)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:627)
at org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:321)
at org.springbyexample.web.servlet.view.tiles2.DynamicTilesViewProcessor.renderMergedOutputModel(DynamicTilesViewProcessor.java:106)
at org.springbyexample.web.servlet.view.tiles2.DynamicTilesView.renderMergedOutputModel(DynamicTilesView.java:104)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
at org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:213)
at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:171)
at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:96)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:113)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
When I remove the piece code from the JSP file, it is fine.
<c:forEach items="${purchaseOrder.purchaseOrderQuotes}" var="document">
<tr>
<td>
${document.name}
</td>
<td>
${document.description}
</td>
<td align="left">
${document.filename}
</td>
<td>
${document.created}
</td>
</td>
</tr>
</c:forEach>
the method that I retrieve the purchaseOrder:
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public PurchaseOrder findById(Integer id)
{
log.debug((new StringBuilder("getting PurchaseOrder instance with id: ")).append(id).toString());
try
{
PurchaseOrder instance = entityManager.find(PurchaseOrder.class, id);
// if(instance.getProjectFundingYears() != null)
// log.debug("get successful");
// log.debug("get successful");
return instance;
}
catch(RuntimeException re)
{
log.error("get failed", re);
throw re;
}
}
Here is the relationship of two Entities:
PurchaseOrder
@Entity
@Table(name = "purchase_order", schema = "pta")
public class PurchaseOrder implements java.io.Serializable {
............
private List<PurchaseOrderQuotes> purchaseOrderQuotes = ShrinkableLazyList
.decorate(new ArrayList(), FactoryUtils
.instantiateFactory(PurchaseOrderQuotes.class));
.............................................................
public PurchaseOrder() {
}
....................................................................
@OneToMany(cascade = CascadeType.REFRESH,fetch=FetchType.LAZY, mappedBy="purchaseOrder")
public List<PurchaseOrderQuotes> getPurchaseOrderQuotes() {
return purchaseOrderQuotes;
}
public void setPurchaseOrderQuotes(List<PurchaseOrderQuotes> purchaseOrderQuotes) {
this.purchaseOrderQuotes = purchaseOrderQuotes;
}
............................................................................
}
PurchaseOrderQuotes
@Entity
@Table(name = "purchase_order_quotes", schema = "pta")
public class PurchaseOrderQuotes implements java.io.Serializable {
private Integer id;
private String name;
private String description;
private String filename;
private byte[] content;
private String contentType;
private Date created;
private PurchaseOrder purchaseOrder;
public PurchaseOrderQuotes() {
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "purchase_order_quotes_id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name="filename")
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
@Lob
@Type(type="org.hibernate.type.PrimitiveByteArrayBlobType")
@Basic(fetch = FetchType.LAZY)
@Column(name="content")
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
@Column(name="content_type")
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name="created")
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
@ManyToOne
@JoinColumn(name = "purchase_order_id", referencedColumnName = "purchase_order_id")
public PurchaseOrder getPurchaseOrder() {
return purchaseOrder;
}
public void setPurchaseOrder(PurchaseOrder purchaseOrder) {
this.purchaseOrder = purchaseOrder;
}
I am not clear . Sorry.
Here I dont access the BLOB file directly, I get its parent object.
I was able to upload the file and retrieve one purchaseOrder without any problem.
It only reports error when I add this piece code in the JSP file. But it should not try to access the BLOB field since I set FetchType.LAZY. I get confused.
<c:forEach items="${purchaseOrder.purchaseOrderQuotes}" var="document">
<tr>
<td>
${document.name}
</td>
<td>
${document.description}
</td>
<td align="left">
${document.filename}
</td>
<td>
${document.created}
</td>
</td>
</tr>
</c:forEach>
A: Since you have defined your Spring transactions via @Transactional, you are by default running inside of an auto-commit transaction. As per this other thread, you need to create a second session factory which runs in autocommit = false to retrieve the file.
Additionally, the DAO for the retrieval should be annotated with @Qualifier so that it knows which session factory to use. Example:
@Autowired
public MyDAOImpl(@Qualifier("someSessionFactory") SessionFactory sessionFactory) {
setSessionFactory(sessionFactory);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can't call my service method I'm getting this error:
The communication object,
System.ServiceModel.ChannelFactory`1[FxCurveService.IFxCurveService],
cannot be used for communication because it is in the Faulted state.
When I call this code:
using (var client = new WCFServiceChannelFactory<IFxCurveService>(new Uri("http://ksqcoreapp64int:5025/")))
{
guid = client.Call(svc => svc.ReserveSnapshot(fxCurveKey));
DiscountFactorNew[] dfs = client.Call(svc => svc.GetDiscountFactors(guid, dates, from));
Assert.IsTrue(guid != null);
}
It errors here - client.Call(svc => svc.ReserveSnapshot(fxCurveKey));
I have no idea why it is doing this. I am passing the right parameters, inputting the correct address for the service, what else should I be checking here?
Btw, WCFServiceChannelFactory is our own class we use to take care of making service calls. Outline here:
public class WCFServiceChannelFactory<T> : IDisposable
{
public WCFServiceChannelFactory();
public WCFServiceChannelFactory(Uri uri);
public T Channel { get; }
public System.ServiceModel.ChannelFactory<T> ChannelFactory { get; }
public Type ChannelType { get; }
public void Call(Action<T> f);
public R Call<R>(Func<T, R> f);
public void Dispose();
}
The thing is, the problem is not with this, as this is working in the same exact fashion in every other project but this one. Basically, I have to pass the Uri directly in mine, where as others derive it from a .config file in the project, which I was unable to do here. That's the only difference.
Thanks.
A: You can't access details of the exception if the channel is disposed. So the lovely using pattern construction is not recommended when accessing a WCF service. In fact, the Exception properties requires to have access to the channel to extract some information about the exception (don't know if MS missed that point, or if there are technical reasons behind).
I've written a small class to simplify the call to WCF proxies (this site helps me to understand the problem and to write the class) :
using System;
using System.ServiceModel;
namespace Utility
{
public class ServiceHelper
{
/// <summary>
/// WCF proxys do not clean up properly if they throw an exception. This method ensures that the service
/// proxy is handeled correctly. Do not call TService.Close() or TService.Abort() within the action lambda.
/// </summary>
/// <typeparam name="TService">The type of the service to use</typeparam>
/// <param name="action">Lambda of the action to performwith the service</param>
[System.Diagnostics.DebuggerStepThrough]
public static void UsingProxy<TService>(Action<TService> action)
where TService : ICommunicationObject, IDisposable, new()
{
var service = new TService();
bool success = false;
try
{
action(service);
if (service.State != CommunicationState.Faulted)
{
service.Close();
success = true;
}
}
finally
{
if (!success)
{
service.Abort();
}
}
}
/// <summary>
/// WCF proxys do not clean up properly if they throw an exception. This method ensures that the service
/// proxy is handeled correctly. Do not call TService.Close() or TService.Abort() within the action lambda.
/// </summary>
/// <typeparam name="TIServiceContract">The type of the service contract to use</typeparam>
/// <param name="action">Action to perform with the client instance.</param>
/// <remarks>In the configuration, an endpoint with names that maches the <typeparamref name="TIServiceContract"/> name
/// must exists. Otherwise, use <see cref="UsingContract<TIServiceContract>(string endpointName, Action<TIServiceContract> action)"/>. </remarks>
[System.Diagnostics.DebuggerStepThrough]
public static void UsingContract<TIServiceContract>(Action<TIServiceContract> action)
{
UsingContract<TIServiceContract>(
typeof(TIServiceContract).Name,
action
);
}
/// <summary>
/// WCF proxys do not clean up properly if they throw an exception. This method ensures that the service
/// proxy is handeled correctly. Do not call TService.Close() or TService.Abort() within the action lambda.
/// </summary>
/// <typeparam name="TIServiceContract">The type of the service contract to use</typeparam>
/// <param name="action">Action to perform with the client instance.</param>
/// <param name="endpointName">Name of the endpoint to use</param>
[System.Diagnostics.DebuggerStepThrough]
public static void UsingContract<TIServiceContract>(
string endpointName,
Action<TIServiceContract> action)
{
var cf = new ChannelFactory<TIServiceContract>(endpointName);
var channel = cf.CreateChannel();
var clientChannel = (IClientChannel)channel;
bool success = false;
try
{
action(channel);
if (clientChannel.State != CommunicationState.Faulted)
{
clientChannel.Close();
success = true;
}
}
finally
{
if (!success) clientChannel.Abort();
}
}
}
}
Then you can simply do something like this (depending if you have a service reference or the contracts :
ServiceHelper.UsingContract<IFxCurveService>(svc=>
{
guid = svc.ReserveSnapshot(fxCurveKey);
DiscountFactorNew[] dfs = svc.GetDiscountFactors(guid, dates, from));
Assert.IsTrue(guid != null);
}),
This helpers ensure the correct closing of channels, whithout disposing it. You will be able to see the actual exception then. Edit your post when you'll find the actual exception.
(Maybe your service factory is already using this technique. If not, do not hesitate to update it like my class).
[edit] You still have to play with config. here is a probably working config for you :
contract="The.Correct.Namespace.IFxCurveService"
name="IFxCurveService" />
A: I am using 4.0 and i have configured it like as follow:
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="defaultBasicHttpBinding">
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"/>
<!--<message clientCredentialType="Certificate" algorithmSuite="Default" />-->
</security>
</binding>
</webHttpBinding>
</bindings>
<client>
<endpoint address="https://abc1234.abc.nsroot.net/MyService/MyService.svc"
binding="webHttpBinding"
bindingConfiguration="defaultBasicHttpBinding"
contract="IMyService"
name="TestJeph"/>
</client>
</system.serviceModel>
FYI: I am calling the WCF Rest service, does it matter?
the following is my service interface that i have created in the web app solution:
namespace anothertest
{
using System;
using System.ServiceModel;
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName = "IMyService")]
public interface IMyService
{
[OperationContract]
test.WebService.Entity.BusinessEntity[] GetAllActiveBusiness();
}
public class ProductClient : ClientBase<IMyService>, IMyService
{
#region Members
public test.WebService.Entity.BusinessEntity[] GetAllActiveBusiness()
{
return Channel.GetAllActiveBusiness();
}
#endregion
}
}
the following is the code to call the service:
anothertest.Utility.ServiceHelper.UsingContract<anothertest.IMyService>
("TestJeph",
svc=>
{
string test = svc.UpdateCMPStatus("test", "me");
});
A: Are you targeting .Net 3.5 or .Net 4.0 ? In .Net 4.0 you get lots of defaults for the configuration of the service. In .Net 3.5 you are going to have to configure the endpoint completely in either in the App.config or programatically. For example what binding is the enpoint using ? If you are using .Net 4.0 then you are going to get a BasicHttpBinding by default since you specified an http uri. In .Net 3.5 you are going to fault as there will be no binding configured.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jsp scriptlet function called from button click I am looking for a quick and dirty way to allow a user to enter something in a text field, click a button, and have some results be displayed based on what is entered. How do I accomplish this with scriptlets in a jsp? Thanks.
A: You can't make scriptlets (java code snippets in <% %>) execute in any other moment than the moment when the server is preparing the jsp to be rendered.
In case you want to get the results server-side, you could, for instance:
*
*Put that textfield inside a form, with an action attribute: <form action="myServlet">
*Put a <input type='submit'> button in the form.
*In the myServlet servlet, retrieve the textfield's value (request.getParameter()) and perform the search. Make a request to another/the same jsp and put the results in a request attribute
*Display the results in that jsp. You can get them with <% request.getAttribute(); %>
UDPATE : Take into account that scriptlets are considered poor practice, use JSTL tags and Unified Expression Language instead.
A: There may be some other way to achive you goal. But it is good if you can use AJAX to get dynamic data from the serve side.
If the result data is static you can go with javascript.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Accessing Files Relative to Bundle in Symfony2 In a Symfony2 app's routing configuration, I can refer to a file like this:
somepage:
prefix: someprefix
resource: "@SomeBundle/Resources/config/config.yml"
Is there any way to access a file relative to the bundle within a controller or other PHP code? In particular, I'm trying to use a Symfony\Component\Yaml\Parser object to parse a file, and I don't want to refer to that file absolutely. Essentially, I want to do this:
$parser = new Parser();
$config = $parser->parse( file_get_contents("@SomeBundle/Resources/config/config.yml") );
I've checked out the Symfony\Component\Finder\Finder class, but I don't think that's what I'm looking for. Any ideas? Or maybe I'm completely overlooking a better way of doing this?
A: Thomas Kelley's answer is good (and works!) but if you are using dependency injection and/or don't want to tie your code directly to the kernel, you're better off using the FileLocator class/service:
$fileLocator = $container->get('file_locator');
$path = $fileLocator->locate('@MyBundle/path/to/file.txt')
$fileLocator will be an instance of \Symfony\Component\HttpKernel\Config\FileLocator. $path will be the full, absolute path to the file.
Even though the file_locator service itself uses the kernel, it's a much smaller dependency (easier to substitute for your own implementation, use test doubles, etc.)
To use it with dependency injection:
# services.yml
services:
my_bundle.my_class:
class: MyNamespace\MyClass
arguments:
- @file_locator
# MyClass.php
use Symfony\Component\Config\FileLocatorInterface as FileLocator;
class MyClass
{
private $fileLocator;
public function __construct(FileLocator $fileLocator)
{
$this->fileLocator = $fileLocator;
}
public function myMethod()
{
$path = $this->fileLocator->locate('@MyBundle/path/to/file.txt')
}
}
A: You can use $container->getParameter('kernel.root_dir') to get the app folder of your application, and browse your directories to the file you want.
A: If you want to do that in a file located in src/.../SomeBundle/... you can use __DIR__ to get the full path of the current file. Then append your Resources/... path to that like
$foo = __DIR__.'/Resources/config/config.yml';
A: As a matter of fact, there is a service you could use for this, the kernel ($this->get('kernel')). It has a method called locateResource().
For example:
$kernel = $container->getService('kernel');
$path = $kernel->locateResource('@AdmeDemoBundle/path/to/file/Foo.txt');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "84"
}
|
Q: @HTML.CheckBoxFor() MVC 3.0 Issue? I have a loop that generates List of items with Check box to select
foreach(var i in item)
{
@Html.CheckBoxFor(x=>i.Checked)
@Html.labelfor(x=>i.price)
}
I have 3 items. so this is Producing below code three times
<input id="paid" name="paid" value="true" type="checkbox">
<input name="paid" value="false" type="hidden">
Now when i try to access the checked prices in my controller
string[] paid = Request.Form["paid"].split(',');
I should receive 3 values of true/false, irrespective of how many prices were check by the user
Instead, it returns 3+ as many as user checked. Lets say if user check one price then in my controller. I will receive 3+1= 4 true/false values.
How can i get rid of this issue?
A: I think what you are looking for is this post. http://forums.asp.net/t/1314753.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Tomcat auto unpack WAR file changed the last modified time of files I experienced an issue when I tried to deploy a WAR file to tomcat.
While the auto unpack process from tomcat, the last modified date of unpack files were being modified.
The date of unpack web app. files became 12 hours faster, and this results several miscellaneous errors.
I tried to unpack manually via jar -xvf, the last modified date of files remain unchanged.
I also tested in a local tomcat (same timezone with dev. env.), nothing changed in last modified date.
It seems the tomcat timezone issue, does setup on tomcat I can do to solve out this issue?
Great thanks for any help.
Environment:
Tomcat 6 on linux, with GMT-4 timezone both set in server and tomcat
the WAR file created by machine with GMT+8 timezone set
A: In my case, the application was setting the default timezone from within Tomcat as the application was being initialized. The difference introduced by the change in timezones matched the offset in the file modification times.
I was surprised that any code within the app could run before being unpacked, but the Tomcat container does give the application an opportunity to run initialization code prior to all files being unpacked.
Look for an occurrence of TimeZone.setDefault() and try removing the call or moving the call later in the initialization sequence.
Helpful clues:
This JSP told me that the application was always running with a specific timezone regardless of the environment settings:
<html>
<body>
<h2>Current Timezone</h2>
<% java.util.Date date = new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("zzz"); %>
<%=sdf.format(date)%>
</body>
</html>
In the log files, I could see the instant the timezone was changing (four hour jump). It happens at the time the app is loaded.
Note: Once set, the timezone will stay set until Tomcat is restarted.
Sep 18, 2015 2:34:26 PM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8443
Sep 18, 2015 2:34:26 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 285 ms
Sep 18, 2015 2:34:26 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Sep 18, 2015 2:34:26 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.24
Sep 18, 2015 2:34:26 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive myWebapp.war
Sep 18, 2015 6:34:30 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Sep 18, 2015 6:34:34 PM org.apache.catalina.core.ApplicationContext log
INFO: org.tuckey.web.filters.urlrewrite.UrlRewriteFilter INFO: loaded (conf ok)
Sep 18, 2015 6:34:34 PM org.apache.catalina.core.ApplicationContext log
INFO: struts: []: Verifying ModuleConfig for this module
Sep 18, 2015 6:34:34 PM org.apache.catalina.core.ApplicationContext log
INFO: struts: []: Verification of ModuleConfig has been completed
Sep 18, 2015 6:34:34 PM org.apache.catalina.core.ApplicationContext log
INFO: struts: []: Verifying ModuleConfig for this module
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Chrome brings the integer value for $('.abc').css("top"); The following javascript code returns two different values for Chrome and Firefox for the same page element.
$('.abc').css("top");
Chrome returns: 114px
while Firefox returns 114.1230px
I've tried this several times on the same page and Chrome consistently chops off the decimal point and the following digits.
Any suggestions on how I can get the full value within Chrome as well?
A: Firefox is a little special in this case... it supports decimal pixels. This means that if you set a height OR width on f.e. an image, it will resize the picture and this calculation will contain (most likely) decimal pixels. This is the same with divs, it gets calculated and decimals are used in firefox.
As far as I know, firefox is the only major browser that support decimals...
If you need full pixels, try a regex expression or something to remove the decimals if you have a string or floor() if you have a number.
A: Try: $('.abc').offset().top or $('.abc').position().top.
(Although what 0.123 of a pixel looks like is beyond me).
A: Best answer might be to simply floor() the value so you end up with 114px in both cases. (Chrome rounds down the sub-pixel amount)
A: As long as you keep the width a decimal, Chrome will truncate it. If you make it a percentage, though, (might not be an option for you), Chrome will keep it the way it is.
This might not be what you're looking for, but you can store the pixel value in the jQuery object:
$('#foo').data('actualTop', 114.123);
But why do those decimal places bother you?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Javascript Variables - A variable variable is required The following code requires that the name of 2 variables are combined.
var myScroll;
var orderit;
var id;
$('.scrollable').each(function(){
orderit += 1;
$(this).attr('id', 'scrollp' + orderit);
id = $(this).attr('id');
myscroll = new iScroll( id );
});
So the problem is that the variable my scroll must be unique each time, so its name needs to be myscroll+orderit but I cannot name a variable like that.
Any ideas how to do this.
Marvellous
A: Make myScroll an array, and push() onto it:
var myScroll = [];
var orderit;
var id;
$('.scrollable').each(function(){
orderit += 1;
$(this).attr('id', 'scrollp' + orderit);
id = $(this).attr('id');
// push another iScroll() onto myScroll
myScroll.push(new iScroll( id ));
});
Note: In your code, you declared myScroll but later use myscroll. Check the case difference - I fixed it in my example.
A: Trying to dynamically generate variables is the wrong approach. It can be done (though not in "strict mode"), but it isn't advised.
Instead, you should be creating a collection. You could either use an Array or an Object.
With an Array, you can use .map() to build a collection. Then use .toArray() to generate an Array.
var orderit = 0;
var myScroll = $('.scrollable').map(function(){
this.id = 'scrollp' + (++orderit);
return new iScroll( this.id );
}).toArray();
...and access them like:
myScroll[0];
myScroll[1];
// ...and so on
If you instead want the myScroll1, myScroll2 names, then use an Object.
var orderit = 0;
var scrolls = {};
$('.scrollable').each(function(){
this.id = 'scrollp' + (++orderit);
scrolls[ 'myScroll' + orderit ] = new iScroll( this.id );
});
...and access them like:
scrolls.myScroll1;
scrolls.myScroll2;
// ...and so on
FYI: There's no need for .attr() to get and set the ID of an element. Just access it directly with this.id as I did in my answer.
EDIT: I used the wrong value to build the object properties. Fixed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: python oauth 2.0 new fbsr facebook cookie, error validating verification code I'm trying to use the new fbsr_{{appID}} cookie.
I'm using the following functions to parse it, but when I try to get the access_token afterwards, I get 'error validating verification code' message. Is something wrong with these parsing functions? If not, what could be the problem?
more info:
I managed to log users in without cookies using the oauth link which redirects back into my site with the code as a parameter, so it can't be the app id, app secret or the redirect_uri. Another reason is that these have different error messages.
def base64_url_decode(inp):
padding_factor = (4 - len(inp) % 4) % 4
inp += "="*padding_factor
return base64.b64decode(unicode(inp).translate(dict(zip(map(ord, u'-_'), u'+/'))))
def parse_signed_request(signed_request, secret):
l = signed_request.split('.', 2)
encoded_sig = l[0]
payload = l[1]
sig = base64_url_decode(encoded_sig)
data = json.loads(base64_url_decode(payload))
if data.get('algorithm').upper() != 'HMAC-SHA256':
logging.error('Unknown algorithm')
return None
else:
expected_sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest()
if sig != expected_sig:
return None
else:
logging.debug('valid signed request received..')
return data
args = {}
args['client_id'] = fbapp_id
args['redirect_uri'] = site_url
args['client_secret'] = fbapp_secret
args['code'] = code
response = urllib.urlopen('https://graph.facebook.com/oauth/access_token?'+urllib.urlencode(args))
# ... here i'm getting the error back from the server: error validating verification code...
A: There is a modified version of the facebook python SDK which supports OAuth 2.0 and parsing of the fbsr_ cookie on github here:
https://gist.github.com/1190267
You can look into the code to see how to parse the cookie or just let that file do the work for you.
A: I had to programetically expire the cookie for my logout to work. The link from facebook does not work but the serverside oauth can do logout without javascript:
class LogoutHandler(webapp2.RequestHandler):
def get(self):
self.set_cookie("fbsr_" + facebookconf.FACEBOOK_APP_ID, None, expires=time.time() - 86400)
self.redirect("/")
def set_cookie(self, name, value, expires=None):
if value is None:
value = 'deleted'
expires = datetime.timedelta(minutes=-50000)
jar = Cookie.SimpleCookie()
jar[name] = value
jar[name]['path'] = '/'
if expires:
if isinstance(expires, datetime.timedelta):
expires = datetime.datetime.now() + expires
if isinstance(expires, datetime.datetime):
expires = expires.strftime('%a, %d %b %Y %H:%M:%S')
jar[name]['expires'] = expires
self.response.headers.add_header(*jar.output().split(': ', 1))
Could you update your question to tell us how it went and how we handle the cookies. For facebook-oath, did you get logout to work? I had to add a cookie handling and a logout handler for this to work for me but now after much troubleshooting it works. I login like this:
class OAuthHandler(I18NHandler):
def get(self):
args = dict(
code = self.request.get('code'),
client_id = facebookconf.FACEBOOK_APP_ID,
client_secret = facebookconf.FACEBOOK_APP_SECRET,
redirect_uri = 'http://www.koolbusiness.com/oauth',
)
file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args))
try:
token_response = file.read()
finally:
file.close()
access_token = cgi.parse_qs(token_response)["access_token"][-1]
graph = main.GraphAPI(access_token)
user = graph.get_object("me")
self.response.out.write(user["id"])
self.response.out.write(user["name"])
def get(self):
fbuser=None
profile = None
access_token = None
accessed_token = None
if self.request.get('code'):
args = dict(
code = self.request.get('code'),
client_id = facebookconf.FACEBOOK_APP_ID,
client_secret = facebookconf.FACEBOOK_APP_SECRET,
redirect_uri = 'http://'+self.get_host()+'/',
)
logging.debug("client_id"+str(args))
file = urllib.urlopen("https://graph.facebook.com/oauth/access_token?" + urllib.urlencode(args))
try:
logging.debug("reading file")
token_response = file.read()
logging.debug("read file"+str(token_response))
finally:
file.close()
access_token = cgi.parse_qs(token_response)["access_token"][-1]
graph = main.GraphAPI(access_token)
user = graph.get_object("me") #write the access_token to the datastore
fbuser = main.FBUser.get_by_key_name(user["id"])
logging.debug("fbuser "+fbuser.name)
if not fbuser:
fbuser = main.FBUser(key_name=str(user["id"]),
id=str(user["id"]),
name=user["name"],
profile_url=user["link"],
access_token=access_token)
fbuser.put()
elif fbuser.access_token != access_token:
fbuser.access_token = access_token
fbuser.put()
current_user = main.get_user_from_cookie(self.request.cookies, facebookconf.FACEBOOK_APP_ID, facebookconf.FACEBOOK_APP_SECRET)
if current_user:
graph = main.GraphAPI(current_user["access_token"])
profile = graph.get_object("me")
accessed_token = current_user["access_token"]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: after reloading the asp page why textbox text will goes to blank? After reloading the page how can i get the previous values in that textbox again.
Because when that page reload then textbox value goes blank?
How can I do this using javascript and jquery?
A: You don't typically save POST values with javascript or jquery (though it is probably possible)
You need to do something like <input type="text" value=" <? printf(POST['field']); ?>">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Google OCR Api with OAuth 2 I try to upload image to google docs using code
I setup access_token and access_token_secret
$uri = 'https://docs.google.com/feeds/documents/private/full?ocr=true';
$newDocumentEntry = $client->uploadFile($fileLocation, $fileName, $mimeType, $uri);
but i receive exception
"The field ocr is not supported in this request version"
without "?ocr=true"
upload is correct
is there any way to upload image with ocr ?
A: OCR only works with version 3 of the API. Have you tried POSTing to .../full?v=3&ocr=true?
http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#Versioning
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Null parameter checking in C# In C#, are there any good reasons (other than a better error message) for adding parameter null checks to every function where null is not a valid value? Obviously, the code that uses s will throw an exception anyway. And such checks make code slower and harder to maintain.
void f(SomeType s)
{
if (s == null)
{
throw new ArgumentNullException("s cannot be null.");
}
// Use s
}
A: Without an explicit if check, it can be very difficult to figure out what was null if you don't own the code.
If you get a NullReferenceException from deep inside a library without source code, you're likely to have a lot of trouble figuring out what you did wrong.
These if checks will not make your code noticeably slower.
Note that the parameter to the ArgumentNullException constructor is a parameter name, not a message.
Your code should be
if (s == null) throw new ArgumentNullException("s");
I wrote a code snippet to make this easier:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>Check for null arguments</Title>
<Shortcut>tna</Shortcut>
<Description>Code snippet for throw new ArgumentNullException</Description>
<Author>SLaks</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
<ID>Parameter</ID>
<ToolTip>Paremeter to check for null</ToolTip>
<Default>value</Default>
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[if ($Parameter$ == null) throw new ArgumentNullException("$Parameter$");
$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
A: I agree with Jon, but I would add one thing to that.
My attitude about when to add explicit null checks is based on these premises:
*
*There should be a way for your unit tests to exercise every statement in a program.
*throw statements are statements.
*The consequence of an if is a statement.
*Therefore, there should be a way to exercise the throw in if (x == null) throw whatever;
If there is no possible way for that statement to be executed then it cannot be tested and should be replaced with Debug.Assert(x != null);.
If there is a possible way for that statement to be executed then write the statement, and then write a unit test that exercises it.
It is particularly important that public methods of public types check their arguments in this way; you have no idea what crazy thing your users are going to do. Give them the "hey you bonehead, you're doing it wrong!" exception as soon as possible.
Private methods of private types, by contrast, are much more likely to be in the situation where you control the arguments and can have a strong guarantee that the argument is never null; use an assertion to document that invariant.
A: You might want to take a look at Code Contracts if you need a nicer way to make sure you do not get any null objects as a parameter.
A: I've been using this for a year now:
_ = s ?? throw new ArgumentNullException(nameof(s));
It's a oneliner, and the discard (_) means there's no unnecessary allocation.
A: It saves some debugging, when you hit that exception.
The ArgumentNullException states explicitly that it was "s" that was null.
If you don't have that check and let the code blow up, you get a NullReferenceException from some unidentified line in that method. In a release build you don't get line numbers!
A: In C# 11 preview it is super cool!!
You just need to add two exclamation marks !! at the end of the parameter name. This will do the null parameter checking.
void f(SomeType s!!)
{
// Use s
}
This is equivalent to:
void f(SomeType s)
{
if (s is null)
{
throw new ArgumentNullException(nameof(s));
}
// Use s
}
A good explanation article about it can be found here.
A: The main benefit is that you're being explicit with the requirements of your method right from the start. This makes it clear to other developers working on the code that it is truly an error for a caller to send a null value to your method.
The check will also halt the execution of the method before any other code executes. That means you won't have to worry about modifications being made by the method that are left unfinished.
A: Yes, there are good reasons:
*
*It identifies exactly what is null, which may not be obvious from a NullReferenceException
*It makes the code fail on invalid input even if some other condition means that the value isn't dereferenced
*It makes the exception occur before the method could have any other side-effects you might reach before the first dereference
*It means you can be confident that if you pass the parameter into something else, you're not violating their contract
*It documents your method's requirements (using Code Contracts is even better for that of course)
Now as for your objections:
*
*It's slower: Have you found this to actually be the bottleneck in your code, or are you guessing? Nullity checks are very quick, and in the vast majority of cases they're not going to be the bottleneck
*It makes the code harder to maintain: I think the opposite. I think it's easier to use code where it's made crystal clear whether or not a parameter can be null, and where you're confident that that condition is enforced.
And for your assertion:
Obviously, the code that uses s will throw an exception anyway.
Really? Consider:
void f(SomeType s)
{
// Use s
Console.WriteLine("I've got a message of {0}", s);
}
That uses s, but it doesn't throw an exception. If it's invalid for s to be null, and that indicates that something's wrong, an exception is the most appropriate behaviour here.
Now where you put those argument validation checks is a different matter. You may decide to trust all the code within your own class, so not bother on private methods. You may decide to trust the rest of your assembly, so not bother on internal methods. You should almost certainly validate the arguments for public methods.
A side note: the single-parameter constructor overload of ArgumentNullException should just be the parameter name, so your test should be:
if (s == null)
{
throw new ArgumentNullException("s");
}
Alternatively you can create an extension method, allowing the somewhat terser:
s.ThrowIfNull("s");
In my version of the (generic) extension method, I make it return the original value if it's non null, allowing you to write things like:
this.name = name.ThrowIfNull("name");
You can also have an overload which doesn't take the parameter name, if you're not too bothered about that.
Update .NET 6
There is a new method in .NET API which simplifies null check syntax.
ArgumentNullException.ThrowIfNull(someParameter);
A: Original code:
void f(SomeType s)
{
if (s == null)
{
throw new ArgumentNullException("s cannot be null.");
}
// Use s
}
Rewrite it as:
void f(SomeType s)
{
if (s == null) throw new ArgumentNullException(nameof(s));
}
The reason to rewrite using nameof is that it allows for easier refactoring. If the name of your variable s ever changes, then the debugging messages will be updated as well, whereas if you just hardcode the name of the variable, then it will eventually be outdated when updates are made over time. It's a good practice used in the industry.
A: int i = Age ?? 0;
So for your example:
if (age == null || age == 0)
Or:
if (age.GetValueOrDefault(0) == 0)
Or:
if ((age ?? 0) == 0)
Or ternary:
int i = age.HasValue ? age.Value : 0;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "90"
}
|
Q: android layout issue - separating the screen into two layouts (inside a tab) I have tabhost and in 1 tab I want to do the following:
1. At the top - a search edittext.
2. Below it some textbox. When user press the search button - I need this textbox to be changed into a list, on the rest of the screen (below the search).
Actually I need to separate the screen into 2 part.
A: There is more than one way, but something like this is fairly basic and should work. If you use a ListActivity just specify the image as the id/empty and the listview as the id/list. Then when your list is empty, users see the ImageView. When you populate it, it'll switch automatically.
<LinearLayout ...
android:orientation="vertical">
<LinearLayout ...>
<EditText .../>
<ImageButton .../>
</LinearLayout>
<ImageView ...
android:id="@android:id/empty"/>
<ListView ...
android:id="@android:id/list"/>
</LinearLayout>
If you can't use ListActivity, just do it yourself (e.g. in the click listener for the button):
ImageView image = findViewById(R.id.YOUR-IMAGEVIEW);
image.setVisibility(View.GONE);
ListView list = findViewById(R.id.YOUR-LISTVIEW);
list.setVisibility(View.VISIBLE);
And be sure to set android:visibility="gone" on your list in the XML to make it be initially hidden.
A: Add a common layout in tab host as parent layout and add or remove the view as u like.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to exclude code from the Clover coverage report? Is there any way to hide classes or methods from being included in the Clover code coverage report? We have some proof of concept code along side production quality code in the same directories. This concept code is being included in the code coverage reports which is skewing our numbers. We were wondering if we could annotate or mark them in such a way that Clover will ignore them when generating the report.
-- Update --
What about using a methodContext against a custom annotation?
A: I you are using Clover as a Maven plugin, you can configure excluded classes.
<configuration>
<excludes>
<exclude>**/*Dull.java</exclude>
</excludes>
</configuration>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: search and print specific date in a log file I'm working with a log file and I want to print from a specific day till the end of it . that specific date is ($sd=27/Dec/2002) for example. now I want to search for this day and print from it till the end of log file ! but what if 27/Dec is not among items in log file ? it should search for items >= $sd (27/Dec) , how could I do this?
this code just search for $Sd which is 27/Dec/2002 , I want to search for items >= $sd
sed -n "$(awk '/'$sd'/ {print NR}' serverlog.log.log | head -1),$ p" serveerlog.log|cut -d: -f1
example of log file :
213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.132.36.66 - - [28/Dec/2002:19:33:29 +0100]
and the log file is sorted !
A: it would be very easy with awk. see the example below:
kent$ cat log.txt
213.64.237.213 - - [20/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [20/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [20/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [20/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [20/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.132.36.66 - - [28/Dec/2002:19:33:29 +0100]
kent$ sd=21/Dec/2002
kent$ awk -F'[:[]' -v d=$sd '$2>d' log.txt
output
213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.132.36.66 - - [28/Dec/2002:19:33:29 +0100]
update
try this awk line: $sd is the variable. hope that it would work for you.
kent$ awk -F'[:[]' -v vd=$sd 'BEGIN{ gsub(/\//," ",vd);"date +%s -d \""vd"\""|getline d} {p=$0; gsub(/\//," ",$2); "date +%s -d \""$2"\""|getline o;if(o>d) print p}' log.txt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: .NET SmtpClient sending EHLO vs HELO Running into a peculiar issue. I have an SMTP server that I need to authenticate to in order to send mail. We have a C# service that is designed to automatically do this, however the server host has configured the SMTP server to not allow relaying when a client initiates with HELO vs. EHLO. When a client uses EHLO, relay is allowed.
Is there anyway to maintain SmtpClient use and send EHLO vs HELO?
Email response to HELO/EHLO relaying question from SMTP host provider:
"By default our server is setup to authenticate to ehlo commands and
not helo. It will answer helo from hosts and delivery mail locally but
not relay."
Error from the application sent by the developer:
2011-09-14 14:32:17,764 ERROR ISearchService - An unhandled exception
was thrown while invoking
[AptitudeSolutions.OnCore.Services.ServiceAdapter.Search.SearchServiceAdapter].
System.Net.Mail.SmtpException: The SMTP server requires a secure
connection or the client was not authenticated. The server response
was: Relaying not allowed (enable smtp authentication on your email
client) at
System.Net.Mail.RecipientCommand.CheckResponse(SmtpStatusCode
statusCode, String response) at
System.Net.Mail.SmtpTransport.SendMail(MailAddress sender,
MailAddressCollection recipients, String deliveryNotify,
SmtpFailedRecipientException& exception) at
System.Net.Mail.SmtpClient.Send(MailMessage message) at
AptitudeSolutions.OnCore.BusinessProcesses.Scenario.PublicRecordsNotification.AppServices.PublicRecordsNotificationEmailService.SendEmail(String
email, String subject, String body) at
AptitudeSolutions.OnCore.BusinessProcesses.Scenario.PublicRecordsNotification.AppServices.PublicRecordsNotificationEmailService.SendNewAccountActivationEmailTo(String
email) at
AptitudeSolutions.OnCore.BusinessProcesses.Scenario.PublicRecordsNotification.ServiceLayer.PublicRecordsNotificationServiceLayer.RequestNewAccount(NewAccountRequest
request) at
AptitudeSolutions.OnCore.Services.ServiceAdapter.Search.SearchServiceAdapter.RequestNewNotificationAccount(NewAccountRequest
request) at SyncInvokeRequestNewNotificationAccount(Object ,
Object[] , Object[] ) at
System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object
instance, Object[] inputs, Object[]& outputs) at
AptitudeSolutions.Framework.DataAccessBase.Utility.Wcf.ServiceAttributes.ExceptionLoggingOperationInvoker.Invoke(Object
instance, Object[] inputs, Object[]& outputs)
Relevant part of config file:
<system.net>
<mailSettings>
<smtp from="email@host.com">
<network host="mail.smtphost.com" port="25" userName="username" password="password" defaultCredentials="false" />
</smtp>
</mailSettings>
</system.net>
Some information has been edited for security purposes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do you set the required property when adding a column in Access using ADOX? I have the following script that adds columns to and table in an Access database. I don't know how to set the "required" property of that column to "NO", the default is yes. Here is my script:
Option Compare Database
Function AddColumns()
'Purpose: Show how to add fields to a table, and delete them using ADOX.
Dim cat As New ADOX.Catalog
Dim tbl As ADOX.Table
Dim col As New ADOX.Column
Set cnn = CreateObject("ADODB.Connection")
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Data Source=\\network\drive\TestDB.accdb; Jet OLEDB:Database Password=testing; "
'Initialize
cat.ActiveConnection = cnn
Set tbl = cat.Tables("Test_Table")
'Add a new column
With col
.Name = "Test_Column"
.Type = adVarWChar 'Decimal type.
'.Precision = 28 '28 digits.
'.NumericScale = 8 '8 decimal places.
End With
tbl.Columns.Append col
MsgBox col.Name & " successfully added"
Set col = Nothing
'Debug.Print "Column added."
'Clean up
Set col = Nothing
Set tbl = Nothing
Set cat = Nothing
End Function
A: You need to use the Attributes Property (ADOX)
e.g
With col
...
.Attributes = adColNullable
...
End With
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Google map with highlighted locations I want google map with highlighted locations using html or classic asp. How can i do it? Please check the link.
This is sample link.
A: They've created separate overlays, in which they're layering transparent PNG images over the top of a map,
e.g.
http://www.shelbybb.com/gunnel.png
And the code to add it to the map:
var gunnelBounds = new google.maps.LatLngBounds(new google.maps.LatLng(38.01051, -85.00043), new google.maps.LatLng(38.54504, -83.97889));
var gunnelmap = new google.maps.GroundOverlay("gunnel.png", gunnelBounds);
gunnelmap.setMap(map);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Drop-down width -- IE labels crop I know it is possible to set a CSS width for a drop-down menu. In FF the top window is affected by it, while the option items scale as far as the content in them, however in IE the options are also as wide as the window, thus cutting the options' labels.
Is there a better way to control the width of SELECT element?
<select style="width:100px">
<option>Very long label 1 is gpoing to be here</option>
<option>Very long label 2 is gpoing to be here</option>
</select>
A: *
*When talking to developers, please refer to select elements as
select elements, because a "drop-down" can infer something else
entirely.
*There is a fix here.
A: You could use the width: auto rule. This automatically sets the width according to the length of the options.
If that doesn't work for you, you could use Javascript to dynamically change the width of the select when it is moused over, but nothing simple will make IE8 and below act like it is supposed to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can one scale a SharePoint Excel Web Services Web Part chart? I'm please with my the Excel chart being displayed as a web part in our SharePoint 2010 site... however, it's coming out too large, taking up most of the screen.
I had hoped I could change the width/height of the web part, but that just creates me scrollbars without scaling the chart.
This must be possible somehow, surely? Anyone know how?
Thanks!
A: You can change the height and width of chart web part otherwise you can follow scrolling like below.
<div style="height:100px;overflow:auto;padding:3px; border: solid 1px black;"></div>
A: Yes... you can :)
So, it doesn't seem to work when the chart is on a dedicated sheet (although this is often nicer inside Excel).
However, to scale the chart for the web part, it needs inserted into a standard sheet and then it can be resized.
Simples, no?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Polygon based pathfinding I have implemented a basic grid based A* pathfindinder in Java. I would like to make a navigational mesh/polygon based pathfinder, but the problem I have is this:
If I found the orange route then I could use something like a funnel algorithm to straighten it to get the desired route (blue). However, if the program calculates the cost of each of the routes, red and orange, then it will say the red one is the cheaper one. How do I program my A* algorithm and/or create my meshes so that this doesn't happen.
A: Chapter 15 in Computational Geometry: Algorithms and Applications describes and solves exactly this problem: the free space can be described by a trapezoidal map, but paths found using the map aren't necessarily the shortest. The recommended representation (also discussed in LaValle's Planning Algorithms (Section 6.2.4)) is a so-called visibility graph, which has edges that connect vertices of the obstacles.
Pseudo-code and figures are available from the book homepage and the Google preview also contains parts of the chapter.
A: Sorry I can't help with your question directly, but we ported a polygon based pathfinder to haxe and it can compile to java ( only tried with swing so far but might try slick2d soon ) and could be integrated into a Java project given some research. It's called hxDaedalus and is on github and might be an interesting point of reference.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: CUDA: can different threads read from the same memory location simultaenously? I am writing a CUDA program for the NVIDIA Tesla C2050 where each thread has to read a string of characters in an ordered fashion from position 0 to n-1. The string size is small so it can easily fit in constant, shared, or texture memory.
My question is: would different threads access the string simultaneously at the same time or serially? It seems this would affect the running time of my program.
A: The answer would be 'Yes and No'. It depends on the type of memory.
As @Jawad commented, the texture memory is cached but I'm not totally sure if the read is full simultaneously or it's serialized and read from the cache memory.
On the other hand, constant Memory is broadcast when threads in a half-warp read from the same location but It's serialized when reading from multiple location. This type of memory is also cached.
Finally, shared memory is serialized if some threads try to read the same bank of memory, a.k.a. bank conflict but *can broadcast to several threads simultaneously when servicing one memory read request*.
And It's also depend on the compute capability of your graphic card. I recommend you take a look at NVIDIA CUDA C Programming Guide (v.3.2 - chapter Appendix G., sections G.3 Compute Capability 1.x and G.4 Compute Capability 2.x).
Hope this help.
A: Map the memory as texture and the driver will automatically cache the reads i.e. if more than one threads try to read from a single global position there will be only one call to global memory.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is it possible to set product version at build time in a Basic MSI project? I have an InstallScript project that I'm looking at manually recreating as a Basic MSI project. For the InstallScript project, we obtain the product version at build time through the following mechanism:
*
*Ant does all the compiling, testing, etc. and during this process obtains a build version number.
*Ant calls IsCmdBld.exe, passing the build version as an environment variable.
*Installshield has an "Environment"-type path variable configured, which picks up the build version.
*This path variable is specified in the General Information -> Product Version field.
Unfortunately, it looks like the Basic MSI project does not allow path variables in the Product Version field.
Does this mean the product version has to always be manually modified before each build with a Basic MSI project? Or is there a different way to pass the version to InstallShield?
A: You can use the following command for Basic MSI and InstallScript MSI:
ISCmdBld.exe -y "1.0.5"
A: Another way:
IsCmdBld.exe -z "ProductVersion=1.0.0002"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585522",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Generate SOAP Envelope and digital signature So currently we have a model of just writing a SOAP Body and then manually wrapping that into a SOAP Envelope that is done in a script. That then gets passed to an app that makes a request to a webservice. Also, the language the app that would generate the soap would be C++ not C#.
I am looking into building a SOAP Generator that could also generate digital signatures and looking something small and easy to implement as I do not need it to actually make the request as it just hands off the xml to pass another service that sends the request.
I was looking at gSoap http://www.cs.fsu.edu/~engelen/soap.html
But it may be alot of extra stuff just for generating XML, any tips or other libraries that can do this?
Thanks
A: For the XML signature part you could use Apache Santuario.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Extjs form not submitting its values I have this function that creates a form and the form not submitti its values, what is wrong?
It submits empty ajax, If I change the third line to applyTo:document.body it works fine.
(the tab variable is a tab panel that the form needs to be on it)
function myFunction(tab) {
var frm = new Ext.form.FormPanel({
applyTo: tab.id,
height: 250,
id: 'frm',
name: 'frm',
layout: 'form',
width: 520,
url: 'operation/DataManipulator/',
method: "post",
labelWidth: 200,
items: [{
xtype: 'textfield',
name: 'users',
id: "users",
fieldLabel: 'How many users to create?'
}],
buttons: [{
text: 'Submit',
handler: function (btn, evt) {
frm.getForm().submit();
}
}]
});
A: Try setting "scope: this" after "text:'Submit'" or try inside your handler function:
function(btn, evt) {
Ext.getCmp('frm').getForm().submit();
}
A: Your method config should be method : 'POST'. The POST is case sensitive.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery and MooTools conflict with jQuery plugin I have to use both MooTools and jQuery in a single page. I am using the featureCarousel jQuery slider plugin. There is a conflict between jQuery and MooTools. But the animation is not working perfectly even with jQuery.noConflict() function.
You can see the live demo of the issue here.
Please let me know how can I fix this issue.
A: Try loading JQuery and call noConflict() before loading the MooTools. Otherwise MooTools will use the $ namespace before you can call noConflict().
It doesn't look like you're using MooTools at all in the example. Also the animation seems to be working fine for me on Chrome.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Fill template of one class from another template class If I have two classes:
template <typename T>
struct Node
{
...
};
tempalte <typename T_Node, typename T>
struct NodeIterator
{
T m_value;
};
NodeIterator<Node<int>, int>
can I deduce the template argument T from T_Node without the class Node explicitly creating a typedef like this:
// To make it clear, yes I know this works, but I had to typedef the type
template <typename T>
struct Node
{
typedef T node_type;
...
};
template <typename T_Node>
struct NoteIterator
{
typedef typename T_Node::node_type node_type;
node_type m_value;
};
NodeIterator<Node<int> >
If not, is there a reason why I cannot do that (the compiler already knows about T_Node and the type T it took in) apart from "the feature is just not there in C++"? I ask this as usually there is a good reason for something simple (at least on the surface) like this missing from the language.
A: Why dont't you change the NodeIterator to something like that:
template <typename T>
struct NodeIterator
{
typedef Node<T> node_type;
node_type m_value;
};
this should allow you to create objects of the type NodeIterator<int>. I think this would be an elegant solution.
`
A: Without the typedef, that's not possible. The point is that the compiler has no idea that T_Node is itself an instantiation of a template. Node<T> is just a type, nothing more.
C++ knows three tiers of entities: values, types, and templates. Node is a template, and Node<T> is a type. When your class template accepts a type parameter, then you have no further way to inspect the nature of that type.
Pattern matching through partial specialization is the only way to extract such information, and you don't get around a bit of functional metaprogramming. Any sort of type inspection is usually referred to as a "type trait". It'll all boil down to the same thing, very similar to what you already suggested, but perhaps here's another, more generic way:
template <typename> struct ClassWithOneArg;
template <template <typename> class C, typename T>
struct ClassWithOneArg<C<T>>
{
typedef T value_type;
};
Now you can say: typedef typename ClassWithOneArg<T_Node>::value_type type;.
A: Yes. What you've tried is almost correct, except that you forgot typename:
typedef typename T_Node::node_type node_type;
//^^^^^^^ note this!
You need to write the keyword typename because the nested type node_type is a dependent type.
A: No, you can't. You need the typedef. C++ does not have any compile time reflection support, where this feature would fit in.
The reason why it is not in the language is simple: No one came up with a good proposal for such a feature in the standardization process. This is probably becasue such a feature is not trivial. Why you might be just happy with getting hands on the template parameters, there are lots of other places that would need to be considered to make the feature as a whole look "round".
You could work out such a proposal when intrested ;)
A: I don't think you can, but I don't think you should need to either. Using typedefs for this is a well-established practice; look at the standard containers and their value_type, etc. typedefs.
You mentioned in a comment on another answer that you don't want NodeIterator to know about Node. It doesn't have to know about Node specifically; it just requires that its template argument be some type that contains a node_type type within it. That could be Node or it could be something else, and NodeIterator doesn't have to know or care.
A: The answer is no, you cannot do that in C++. This is why STL iterator types contain those nested typedefs that you're trying to avoid. Also, relying on those nested types is going to get you in trouble if you want to allow pointers to Nodes (which fit all the requirements for RandomAccessIterators). You'll need to use traits classes if you want to include raw pointers to Nodes as node iterator types, since they cannot have nested types.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Simplest Way of drawing line, point, pixel? I'm using SlimDX and C#.
Can you tell me how to draw a simple line and pixel using directx9?
I don't want this line to be textured, 3d or shaded or affect by lighting.
I just want to draw simple 2d solid colored line and pixel.
A: Just using dx9 makes these trivial tasks difficult. It was not built to do these kind of 2D operations. Of course there are ways to do it. Like creating a VertexBuffer with your point or line data, and rendering it as LineList or PointList. But the overhead just for doing this is a lot.
Microsoft understood these kind of limitation so they brought back the idea of DirectDraw (which wasn't easy to use for these task aswell)in the form of Direct2D it is exactly for these kind of things BUT, and this maybe makes it useless for you, it only works on Vista and Windows7. If not, i would definitly use Direct2D for that, which is also wrapped in SlimDX.
If this is not an option, you have to decide if you need DX9 after all and maybe switch to GDI or bite the bullet and take the hard way of using D3D9 for that.
One hint i know is, that SlimDX has a Line class in SlimDX.Direct3D9.Line which might help you a bit.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Large negative hex value conversion to long in java the result should have a negative value, but its positive.
How can I fix this?
Thanks!!
BigInteger b = new BigInteger("80000000000000004308000000000000", 16);
System.out.println("long value: "+b.longValue());
-->
long value: 4830110600354856960
A: http://download.oracle.com/javase/1,5,0/docs/api/java/math/BigInteger.html#longValue%28%29
See the above page to understand why it won't be negative. It returns the low 64bits, so your last 64 bits must be higher than Long.MAX_VALUE to cause a negative value.
A: Your string representation is a signed long but is being presented to BigInteger as an unsigned string (sign is denoted by using a "-" at the start of your string).
The String representation consists of an optional minus sign followed by a sequence of one or more digits in the specified radix.
Bit shifting or correcting your string is needed to make this work from a string instantiation.
I think the best answer is to convert your string to a byte array and use the BigInteger(byte[] val) instantiation which will recognize a negative or positive number based on two's complement. Many options exist for that string to byte array conversion. Take your pick.
... oh, and your number is too large to fit into a long, so that's going to be an issue too; you get the least significant bits.
A: If you always have 128-bit numbers and assume the highest bit is your sign then you can use the following lines:
BigInteger neg = BigInteger.ONE.shiftLeft(127);
BigInteger b = new BigInteger("80000000000000004308000000000000", 16);
if(b.compareTo(neg) >= 0) {
b = neg.subtract(b);
}
Note: b.longValue() will only be appropriate if the number of bits fits into a long which may not be the case for such large numbers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I re-authenticate a user in an ASP.NET MVC 3 Intranet application? The application is already using Windows integrated security, not Forms. What I am trying to accomplish is a so called "step-up" authentication, or "force re-authentication" for the following scenario:
*
*the user is browsing the site doing common, trivial stuff
*suddenly, the user has to do a sensitive action such as authorizing
a resource allocation or confirming a car loan or something similar
*the user is prompted for the credential before (s)he's redirected to
the sensitive page, in a manner similar to SharePoint's "Sign In as
a Different User"
*if, and only if, the credentials entered are
the same as for the currently logged-in user the application
proceeds to the sensitive area.
This would prevent the following two issues:
*
*The user goes for a meeting or a coffee and forgets to lock the
workstation and a colleague uses the session to access the sensitive
area
*The user enters the credentials of his or her boss (because, let's
say he peeked over the boss' shoulder) to access the sensitive area.
I know, some would look at this as "being paranoid", but also some would say it's common sense and should be build in a framework somewhere (jQuery or .NET)
A: Have the form send the credentials along with the request to perform the action, i.e., some actions require that you provide username/password. Use the PrincipalContext ValidateCredentials method to ensure that the proper credentials have been entered and check that the username supplied matches the current username in the User.Identity object.
public ActionResult SensitiveAction( SensitiveModel model, string username, string password )
{
using (var context = new PrincipalContext(ContextType.Domain))
{
if (!string.Equals(this.User.Identity.Name,username,StringComparison.OrdinalIgnoreCase)
|| !context.ValidateCredentials(username,password))
{
return View("PermissionDenied");
}
}
...
}
A:
The user goes for a meeting or a coffee and forgets to lock the workstation and a colleague uses the session to access the sensitive area
That works only the first time, but now the boss enters a sensitive area, re-enters her credentials, then goes for coffee. Are you going to prompt for every sensitive request? Users won't put up with that.
The user enters the credentials of his or her boss (because, let's say he peeked over the boss' shoulder) to access the sensitive area.
If someone knows and enters the credentials of their boss, there is nothing you can do to detect that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: fileNotFound exception while starting glassfish 3 I am getting the following message while starting glassfish server 3 in netbeans. How to amend this fileNotFound exception ?
Welcome to Felix
================
ERROR: Error creating archive. (java.io.FileNotFoundException: C:\Users\Rajat\.netbeans\6.9\config\GF3\domain1\osgi-cache\felix\bundle136\version0.0\revision.location (The system cannot find the file specified))
java.io.FileNotFoundException: C:\Users\Rajat\.netbeans\6.9\config\GF3\domain1\osgi-cache\felix\bundle136\version0.0\revision.location (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at org.apache.felix.framework.util.SecureAction.getFileInputStream(SecureAction.java:415)
at org.apache.felix.framework.cache.BundleArchive.getRevisionLocation(BundleArchive.java:706)
at org.apache.felix.framework.cache.BundleArchive.<init>(BundleArchive.java:206)
at org.apache.felix.framework.cache.BundleCache.getArchives(BundleCache.java:149)
at org.apache.felix.framework.Felix.init(Felix.java:558)
at org.apache.felix.main.Main.main(Main.java:292)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.enterprise.glassfish.bootstrap.ASMainFelix$1.run(ASMainFelix.java:116)
at java.lang.Thread.run(Thread.java:662)
A: For me it worked just to delete the content of the folder "osgi-cache" and restart the server.
In this case it would be the content of the folder "C:\Users\Rajat.netbeans\6.9\config\GF3\domain1\osgi-cache"
I found the solution via Google there: http://www.java.net/node/698982
A: This is a bug of the GlassFish bundle in NetBeans:
https://netbeans.org/bugzilla/show_bug.cgi?id=196872
.
On the web you can find that it has been reported on NetBeans 6.8 and 6.9. I am running GlassFish bundled in NetBeans 7.0.1 (under Vista and Windows Server 2008) and have never had such issue.
I suggest to upgrade NetBeans or to override the GlassFish installation with the one available here: http://glassfish.java.net/public/downloadsindex.html#top .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Transparent border in WPF programmatically It's trivial to generate a border (to use for Trackball events) transparent over the viewport in the XAML file:
<Border Name="myElement" Background="Transparent" />
But how do I do it in the .cs?
Border border = new Border();
**border.Background = (VisualBrush)Colors.Transparent;**
grid.Children.Add(viewport);
grid.Children.Add(border);
This does not work of course.
A: Use a SolidColorBrush:
border.Background = new SolidColorBrush(Colors.Transparent);
The VisualBrush has a different purpose. See an overview of the main types of WPF brushes here:
http://msdn.microsoft.com/en-us/library/aa970904.aspx
A: You can also create a SolidColorBrush with transparent color:
This will create a fully transparent color
border.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0));
but you can also make semitransparent color by changing alpha (this will look like 50% transparent red:
border.Background = new SolidColorBrush(Color.FromArgb(128, 255, 0, 0));
A: This is because you can't just cast a Color to be a Brush. use the Transparent brush instead
border.Background = Brushes.Transparent;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Why do I get a 404 error with Perl's RabbitMQ consumer? RabbitMQ is setup and I can use the sample script:
use Net::RabbitMQ;
my $mq = Net::RabbitMQ->new();
$mq->connect("localhost", { user => "guest", password => "guest" });
$mq->channel_open(1);
$mq->publish(1, "queuename", "Hi there!");
$mq->disconnect();
It posts messages (I assume). I tried the following for a simple grab of a message off of the queue and I get a 404:
my $mq = Net::RabbitMQ->new();
$mq->connect("localhost", { user => "guest", password => "guest" });
$mq->channel_open(1);
print $mq->get(1, "queuename");
A: The full text of the error message is:
basic_get: server channel error 404, message: NOT_FOUND - no queue 'queuename' in vhost '/' ...
You need to create the queue with auto_delete => 0 - otherwise it will go away when the first process terminates. Have a look at the queue_declare method.
A: I looked at queue_declare and added it to the listener and changed some code as follows:
#!/usr/bin/perl
use strict;
use Data::Dumper;
use Net::RabbitMQ;
my $channel = 1;
my $queue = "MyQueue.q";
my $exchange = "MyExchange.x";
my $routing_key = "foobar";
my $mq = Net::RabbitMQ->new();
$mq->connect("localhost", { user => "guest", password => "guest" });
$mq->channel_open($channel);
$mq->exchange_declare( $channel, $exchange, { auto_delete => 0, });
$mq->queue_declare( $channel, $queue, { auto_delete => 0, });
$mq->queue_bind( $channel, $queue, $exchange, $routing_key);
while(1){
my $hashref = $mq->get($channel, $queue);
next if (! defined($hashref));
print Dumper($hashref);
}
I kick the listener script off, then, when I execute the following, it posts messages:
#!/usr/bin/perl
my $channel = 1;
my $queue = "MyQueue.q";
my $exchange = "MyExchange.x";
my $routing_key = "foobar";
use Net::RabbitMQ;
my $mq = Net::RabbitMQ->new();
$mq->connect("localhost", { user => "guest", password => "guest" });
$mq->channel_open(1);
$mq->publish($channel, $queue, "Message Here");
$mq->disconnect();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PowerShellscript, bad file encoding conversation I have a PowerShell script for the conversation of file character encoding.
Get-ChildItem -Path D:/test/data -Recurse -Include *.txt |
ForEach-Object {
$inFileName = $_.DirectoryName + '\' + $_.name
$outFileName = $inFileName + "_utf_8.txt"
Write-Host "windows-1251 to utf-8: " $inFileName -> $outFileName
E:\bin\iconv\iconv.exe -f cp1251 -t utf-8 $inFileName > $outFileName
}
But instead of utf-8 it converts file character encoding into utf-16. When I invoke the iconv utility from command line it works fine.
What do I wrong?
A: When you redirect output to a file, Powershell is using Unicode as the default encoding. Instead of using the redirection operator, you can pipe to Out-File with a -Encoding UTF8 switch.
E:\bin\iconv\iconv.exe -f cp1251 -t utf-8 $inFileName | Out-File -FilePath $outFileName -Encoding UTF8
The following TechNet article has more information (equivalent to Get-Help Out-File -full in Powershell v2).
*
*Out-File
In case it helps your scenario at all, it's worth noting that you can use Powershell to do the encoding conversion also.
Get-Content $inFileName -Encoding ASCII |
Out-File -FilePath $outFileName -Encoding UTF8
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Using JavaBDD in C# Is there any tutorial for using JavaBDD in C#? I's days i'm looking for it with no chance :(
It's JavaBDD website: http://javabdd.sourceforge.net/
A: I know of none, unless there is, or you can create, an interface that is heterogenous (web service, for example, or wrapping with a COM wrapper?). A quick search shows other BDD libs out there. Have you considered seeing if any provides either a COM or native Win interface. Then you can either add a .NET wrapper (include a reference) or PInvoke the lib.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can i calculate the field of view of the camera of a phone? I need to know the field of view of the camera of the phone to make an augmented reality app, for calculate where i have to write on the camera view the name of a gps located Point of interest of a city on the correct coordinates of the screen, pointing the point of interest.
for example:
distance 5 meters: 6 meters (from left to right FOV)
distance 10 meters: 12 meters (from left to right FOV)
How to calculate it?
A: I think you will never match the FOV definition for every device. (Compare this answer for iPhone.)
Every device is different when using android. Take your device, do the math (or take the results from anywhere else) and decide yourself to choose a reasonable FOV angle.
Maybe you could take account of Camera.Parameters.getSupportedPictureSizes() for getting the camera ratio, but that should be all you can do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to do not apply CSS on a specific TAG I do not know if is possible in CSS, but I would like a general Role to don't apply to a specific element in my case id=special.
In my example all the DIV should be red but I want only id=special to have not applied this color.
I understand I can always overwrite the element with id=special but I'm interested to know if is possible have some sort of exclusion from the general Role.
Any idea in CSS 2 and CSS 3?
Example:
<div>this is red</div>
<div>this is red</div>
<div id="special">this one must be blus</div>
div>this is red</div>
// My General Role
div
{
background-color:Red;
}
A: CSS3 solution:
div:not(#special)
A: You would want to use div:not(#special), but if it's going to be blue anyways then you might as well just override the rule. The :not() selector is a CSS3 property and thus isn't supported by all browsers.
A: This is a great example of how CSS specificity works. A general rule applying to all elements of a certain type (your div rule turning the background red) is superseded by the more specific rule applying to an ID. This concept has existed since CSS1, and is available in all browsers. Thus:
div {
background-color:red;
}
#special {
background-color: blue;
}
... will leave all divs red. By applying the special id to a div, that one div will be blue instead.
See it in action: http://jsfiddle.net/9Hyas/
Check out these articles for more about CSS specificity: http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/ and http://www.htmldog.com/guides/cssadvanced/specificity/
A: CSS3 allows for the :not() selector:
div:not([id])
-or-
div:not(#special)
depending on what you want to exclude
You can read all about the selectors in the w3c docs.
As for CSS2, there's a limited set of selectors, and they don't account for negation.
A: CSS2 Solution
div {
color: red;
}
div#special {
color: inherit;
}
demo: http://jsfiddle.net/zRxWW/1/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: kaminari pagination problem Very simple pagination set up giving me the following error:
NoMethodError in Projects#index
Showing /users/MasterControl/div/ikon/app/views/projects/index.html.erb where line #32 raised:
undefined method `current_page' for nil:NilClass
Extracted source (around line #32):
29: <br />
30:
31:
32: <%= paginate @products %>
Rails.root: /users/MasterControl/div/ikon
Application Trace | Framework Trace | Full Trace
activesupport (3.0.7) lib/active_support/whiny_nil.rb:48:in `method_missing'
kaminari (0.12.4) lib/kaminari/helpers/action_view_extension.rb:21:in `paginate'
app/views/projects/index.html.erb:32:in `_app_views_projects_index_html_erb___59843737_2173384980_0'
actionpack (3.0.7) lib/action_view/template.rb:135:in `send'
actionpack (3.0.7) lib/action_view/template.rb:135:in `render'
activesupport (3.0.7) lib/active_support/notifications.rb:54:in `instrument'
actionpack (3.0.7) lib/action_view/template.rb:127:in `render'
actionpack (3.0.7) lib/action_view/render/rendering.rb:59:in `_render_template'
activesupport (3.0.7) lib/active_support/notifications.rb:52:in `instrument'
activesupport (3.0.7) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (3.0.7) lib/active_support/notifications.rb:52:in `instrument'
actionpack (3.0.7) lib/action_view/render/rendering.rb:56:in `_render_template'
actionpack (3.0.7) lib/action_view/render/rendering.rb:26:in `render'
actionpack (3.0.7) lib/abstract_controller/rendering.rb:115:in `_render_template'
actionpack (3.0.7) lib/abstract_controller/rendering.rb:109:in `render_to_body'
actionpack (3.0.7) lib/action_controller/metal/renderers.rb:47:in `render_to_body'
actionpack (3.0.7) lib/action_controller/metal/compatibility.rb:55:in `render_to_body'
actionpack (3.0.7) lib/abstract_controller/rendering.rb:102:in `render_to_string'
actionpack (3.0.7) lib/abstract_controller/rendering.rb:93:in `render'
actionpack (3.0.7) lib/action_controller/metal/rendering.rb:17:in `render'
actionpack (3.0.7) lib/action_controller/metal/instrumentation.rb:40:in `render'
activesupport (3.0.7) lib/active_support/core_ext/benchmark.rb:5:in `ms'
/usr/local/lib/ruby/1.8/benchmark.rb:308:in `realtime'
activesupport (3.0.7) lib/active_support/core_ext/benchmark.rb:5:in `ms'
actionpack (3.0.7) lib/action_controller/metal/instrumentation.rb:40:in `render'
actionpack (3.0.7) lib/action_controller/metal/instrumentation.rb:78:in `cleanup_view_runtime'
activerecord (3.0.7) lib/active_record/railties/controller_runtime.rb:15:in `cleanup_view_runtime'
actionpack (3.0.7) lib/action_controller/metal/instrumentation.rb:39:in `render'
actionpack (3.0.7) lib/action_controller/metal/implicit_render.rb:14:in `default_render'
actionpack (3.0.7) lib/action_controller/metal/mime_responds.rb:261:in `retrieve_response_from_mimes'
actionpack (3.0.7) lib/action_controller/metal/mime_responds.rb:192:in `call'
actionpack (3.0.7) lib/action_controller/metal/mime_responds.rb:192:in `respond_to'
app/controllers/projects_controller.rb:8:in `index'
actionpack (3.0.7) lib/action_controller/metal/implicit_render.rb:5:in `send_action'
actionpack (3.0.7) lib/action_controller/metal/implicit_render.rb:5:in `send_action'
actionpack (3.0.7) lib/abstract_controller/base.rb:150:in `process_action'
actionpack (3.0.7) lib/action_controller/metal/rendering.rb:11:in `process_action'
actionpack (3.0.7) lib/abstract_controller/callbacks.rb:18:in `process_action'
activesupport (3.0.7) lib/active_support/callbacks.rb:441:in `_run__46567664__process_action__199225275__callbacks'
activesupport (3.0.7) lib/active_support/callbacks.rb:410:in `send'
activesupport (3.0.7) lib/active_support/callbacks.rb:410:in `_run_process_action_callbacks'
activesupport (3.0.7) lib/active_support/callbacks.rb:94:in `send'
activesupport (3.0.7) lib/active_support/callbacks.rb:94:in `run_callbacks'
actionpack (3.0.7) lib/abstract_controller/callbacks.rb:17:in `process_action'
actionpack (3.0.7) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
activesupport (3.0.7) lib/active_support/notifications.rb:52:in `instrument'
activesupport (3.0.7) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (3.0.7) lib/active_support/notifications.rb:52:in `instrument'
actionpack (3.0.7) lib/action_controller/metal/instrumentation.rb:29:in `process_action'
actionpack (3.0.7) lib/action_controller/metal/rescue.rb:17:in `process_action'
actionpack (3.0.7) lib/abstract_controller/base.rb:119:in `process'
actionpack (3.0.7) lib/abstract_controller/rendering.rb:41:in `process'
actionpack (3.0.7) lib/action_controller/metal.rb:138:in `dispatch'
actionpack (3.0.7) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
actionpack (3.0.7) lib/action_controller/metal.rb:178:in `action'
actionpack (3.0.7) lib/action_dispatch/routing/route_set.rb:62:in `call'
actionpack (3.0.7) lib/action_dispatch/routing/route_set.rb:62:in `dispatch'
actionpack (3.0.7) lib/action_dispatch/routing/route_set.rb:27:in `call'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:148:in `call'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:93:in `recognize'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:75:in `optimized_each'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:92:in `recognize'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:139:in `call'
actionpack (3.0.7) lib/action_dispatch/routing/route_set.rb:493:in `call'
actionpack (3.0.7) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
actionpack (3.0.7) lib/action_dispatch/middleware/head.rb:14:in `call'
rack (1.2.3) lib/rack/methodoverride.rb:24:in `call'
actionpack (3.0.7) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.0.7) lib/action_dispatch/middleware/flash.rb:182:in `call'
actionpack (3.0.7) lib/action_dispatch/middleware/session/abstract_store.rb:149:in `call'
actionpack (3.0.7) lib/action_dispatch/middleware/cookies.rb:302:in `call'
activerecord (3.0.7) lib/active_record/query_cache.rb:32:in `call'
activerecord (3.0.7) lib/active_record/connection_adapters/abstract/query_cache.rb:28:in `cache'
activerecord (3.0.7) lib/active_record/query_cache.rb:12:in `cache'
activerecord (3.0.7) lib/active_record/query_cache.rb:31:in `call'
activerecord (3.0.7) lib/active_record/connection_adapters/abstract/connection_pool.rb:354:in `call'
actionpack (3.0.7) lib/action_dispatch/middleware/callbacks.rb:46:in `call'
activesupport (3.0.7) lib/active_support/callbacks.rb:416:in `_run_call_callbacks'
actionpack (3.0.7) lib/action_dispatch/middleware/callbacks.rb:44:in `call'
rack (1.2.3) lib/rack/sendfile.rb:107:in `call'
actionpack (3.0.7) lib/action_dispatch/middleware/remote_ip.rb:48:in `call'
actionpack (3.0.7) lib/action_dispatch/middleware/show_exceptions.rb:47:in `call'
railties (3.0.7) lib/rails/rack/logger.rb:13:in `call'
rack (1.2.3) lib/rack/runtime.rb:17:in `call'
activesupport (3.0.7) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.2.3) lib/rack/lock.rb:11:in `call'
rack (1.2.3) lib/rack/lock.rb:11:in `synchronize'
rack (1.2.3) lib/rack/lock.rb:11:in `call'
actionpack (3.0.7) lib/action_dispatch/middleware/static.rb:30:in `call'
railties (3.0.7) lib/rails/application.rb:168:in `call'
railties (3.0.7) lib/rails/application.rb:77:in `send'
railties (3.0.7) lib/rails/application.rb:77:in `method_missing'
railties (3.0.7) lib/rails/rack/log_tailer.rb:14:in `call'
rack (1.2.3) lib/rack/content_length.rb:13:in `call'
rack (1.2.3) lib/rack/handler/webrick.rb:52:in `service'
/usr/local/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
/usr/local/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
/usr/local/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
/usr/local/lib/ruby/1.8/webrick/server.rb:162:in `start'
/usr/local/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
/usr/local/lib/ruby/1.8/webrick/server.rb:95:in `start'
/usr/local/lib/ruby/1.8/webrick/server.rb:92:in `each'
/usr/local/lib/ruby/1.8/webrick/server.rb:92:in `start'
/usr/local/lib/ruby/1.8/webrick/server.rb:23:in `start'
/usr/local/lib/ruby/1.8/webrick/server.rb:82:in `start'
rack (1.2.3) lib/rack/handler/webrick.rb:13:in `run'
rack (1.2.3) lib/rack/server.rb:217:in `start'
railties (3.0.7) lib/rails/commands/server.rb:65:in `start'
railties (3.0.7) lib/rails/commands.rb:30
railties (3.0.7) lib/rails/commands.rb:27:in `tap'
railties (3.0.7) lib/rails/commands.rb:27
script/rails:6:in `require'
script/rails:6
Controller:
def index
@projects = Project.order("created_at").page(params[:page]).per(2)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @projects }
end
end
Index view:
<%= paginate @products, :window => 3 %>
Not sure what the problem is here find it hard to understand the error, I'll be greatful for any help!
A: @products != @projects
Either you're using the wrong view or you've just fumbled the collection name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: is it possible to merge a twitter and facebook feed into a single feed? Is it possible to merge a twitter and facebook status feeds into a single feed to display on a website?
A: One option is you could use Yahoo pipes which was built for this.
Check out this pipe for an example:
Combine your facebook status with blog feeds, news searches, twitter,
last.fm flickr and youtube.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: multiple regex replacement on variable in bash? I'd like to know if there's a way to make multilple regexp replacements in bash with
${string//substring/replacement} or, possibly, what better solution exists.
I have a script to send updates to statusnet and friendika with curl.
I sign petitions online, for instance, and am offered to tweet them, but would rather send to identica. I'm tired of pasting stuff and having to edit in terminal to escape @ and #, ! and ?.
I'd like to regexp replace them in my script to automagically change
@repbunghole and @SenatorArsehat Stop farking around with #someship! Do you want me to come smack you? | http://someshort.url
to
\@repbunghole \@SenatorArsehat Stop farking around with \#someship\! Do you want me to come smack you\? \| http://someshort.url
I do not have strong sed or awk fu, but imagine they may offer solutions, and I don't know how to use sed without writing the variable to a file, reading the file and acting on it, then setting the var with var=$(cat file). Yes. I'm pretty new at this stuff.
I'm not finding sufficient data with the above ${string//substring/replacement/} for multiple replacements. Running that X times to escape X different characters seems inefficient.
like
read -p "Enter a string: " a
b=${a//\@/\\\@}
c=${b//\#/\\\#}
d=${c//\!/\\\!}
e=${d//\?/\\\?}
f=${e//\"/\\\"}
g=${f//\'/\\\'}
etc., etc.
works in the meantime, but it's ugly...
A: That's what character classes are for:
b=${a//[@#!?"']/\\\0}
A: for "multiple regex replacement on variable in bash?"
both sed and awk can do it.
e.g I want to replace
a->1
b->2
c->3
with sed:
kent$ v=abc
kent$ newV=$(sed -e's/a/1/; s/b/2/; s/c/3/' <<< $v)
kent$ echo $newV2
123
with awk:
kent$ v=abc
kent$ newV2=$(awk '{gsub(/a/,"1");gsub(/b/,"2");gsub(/c/,"3")}1' <<< $v)
kent$ echo $newV
123
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Using composition I'm trying to use a custom class to override a method in its super class using composition.
Below is the code im trying, in the class "Bar" what object calls the method doSomethingElse() ? This is not my code and is linked to question - Using composition over inheritance when overriding
All of the instantiation is taking place within the child class.
class Child extents Parent(){
public Child(){
super();
addButtons():
}
addButtons(){
<custom code here>
}
}
class Parent(){
addButtons(){
add(button1);
}
}
interface SomeMethods {
void doSomething();
void doSomethingElse();
}
class Foo implements SomeMethod {
public void doSomething() { // implementation }
public void doSomethingElse() { // implementation }
}
class Bar implements SomeMethod {
private final Foo foo = new Foo();
public void doSomething() { foo.doSomething(); }
public void doSomethingElse() { // do something else! }
}
A: you are close, just do this with the Bar class
class Bar extends Foo {
// note Bar is still of type SomeMethods because it extends a class of that type.
public void doSomething() {
super.doSomething();
//add more code here if you want to do some more stuff, note you don't need to define this function if you don't need to do anything else.
}
public void doSomethingElse() {
//don't call super, and do whatever you like
}
}
A: If your original point was to override doSomethingElse, then when using Composition instead, in Bar you would delegate all the other methods (in this case, doSomething) to Foo, and add your overridden behaviour in Bar.doSomethingElse()
So that could be something like:
public void doSomethingElse() {
.... // custom stuff
foo.doSomethingElse(); // this is the equivalent of an inheritance super call, so it's optional
.... // other custom stuff
}
Also (unrelated to the original question, but I can't help mentioning it) to produce better code, you should inject the Foo dependency, not couple it to Bar.
class Bar implements SomeMethod {
private final SomeMethod foo;
public Bar(SomeMethod foo) {
this.foo = foo;
}
public void doSomething() { foo.doSomething(); }
public void doSomethingElse() { // do something else! }
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: List to single dimension of multidimensional array Is it possible without looping (i.e. without using for or foreach and with some LINQ or Array method) to insert the elements of a list into a single dimension of a declared multidimensional array?
For example - from list:
List<int> l = new List<int> { 1, 2, 3, 4, 5 };
To multidimensional array:
int [,] a = new int[5, 3]; //5 rows 3 columns
Such that the integers 1 to 5 populate column 3, i.e.
a[0, 2] = 1;
a[1, 2] = 2;
a[2, 2] = 3;
a[3, 2] = 4;
a[4, 2] = 5;
Many Thanks.
A: You can't do it with the standard Linq operators (at least not easily), but you can create a dedicated extension method:
public TSource[,] ToBidimensionalArrayColumn<TSource>(this IEnumerable<TSource> source, int numberOfColumns, int targetColumn)
{
TSource[] values = source.ToArray();
TSource[,] result = new TSource[values.Length, numberOfColumns];
for(int i = 0; i < values.Length; i++)
{
result[i, targetColumn] = values[i];
}
return result;
}
BTW, there is no way to do it without a loop. Even Linq operators use loops internally.
A: List<T> has a ForEach method that you can use -- it's not LINQ, but it will get you what you want:
List l = new List { 1, 2, 3, 4, 5 };
int [,] a = new int[5, 3]; //5 rows 3 columns
int i = 0;
l.ForEach(item => a[i++, 2] = item);
A: This is a weird requirement, I'd be curious what your trying to accomplish with it.
(LinqPad example)
void Main()
{
List<int> l = new List<int> { 1, 2, 3, 4, 5 };
ToFunkyArray<int>(l, 4,3).Dump();
}
public T[,] ToFunkyArray<T>(IEnumerable<T> items, int width, int targetColumn)
{
var array = new T[items.Count(),width];
int count=0;
items.ToList().ForEach(i=>{array[count,targetColumn]=i;count++;});
return array;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Printing values from a JavaScript array I have an array that looks like this (the full list is here):
var verbMap = [
{
infinitive: "gehen",
thirdPres: "geht",
thirdPast: "ging",
aux: "ist",
pastPart: "gegangen",
english: "go"
},
{
infinitive: "gelingen",
thirdPres: "gelingt",
thirdPast: "gelang",
aux: "ist",
pastPart: "gelungen",
english: "succeed"
}
];
I am trying to run through each part and print it into a table. I can access one of the values if I target it specifically, but I need to be able to print all of the values into <td>s. Each part of the array would be a <tr> with the values inside as the <td> tags.
What would be the best way to do this, and is there a better way to set the data up and interact with it?
A: It shouldn't be too hard to create the table using nested for loops (the example uses jQuery to build the elements...but you obviously don't have to):
Edit
Removed the jQuery since it seemed to bother everybody (even though the control structures were the important part of the example):
var table = document.createElement('table');
for(v in verbMap){
var tr = document.createElement('tr');
for(p in verbMap[v]){
var td = document.createElement('td');
var text = document.createTextNode(verbMap[v][p]);
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
A: Try the following
for (var i = 0; i < verbMath.length; i++) {
var row = document.createElement('tr');
var item = verbMath[i];
for (var prop in item) {
if (item.hasOwnProperty(prop)) {
var data = document.createElement('td');
data.innerText = item[prop];
row.appendChild(data);
}
}
// Need to append the row here to the appropriate place in your DOM
}
A: Firefox doesn't support innerText so it's better to create a text node and add that to the child. It may also be better to define an array to guarantee an order of the columns and easily change it if necessary.
var table = document.getElementById("tbl"), i, j, tr, td, text;
var order = ["infinitive", "thirdPres", "thirdPast", "aux", "pastPart", "english"]
for(i=0; i<verbMap.length; i++){
tr = document.createElement('tr');
for(j = 0; j<order.length; j++){
td = document.createElement('td');
text = document.createTextNode(verbMap[i][order[j]]);
td.appendChild(text);
tr.appendChild(td);
}
table.appendChild(tr);
}
JSFiddle
A: There are some very good tools for creating tables from such data structures. Consider using jQuery and the Datatables plug in.
Here are some links:
jQuery: http://jquery.com/
Datatables: http://datatables.net/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to print variables coming from an sql db when using the mail function PHP I have a mail function that sends out an email with content from an sql db.
The message that will be included in the email will be taken from the sql db. The message in the sql db has variables in it.....
example:
In the database:
Hey $name, $owner_name here
Everything works fine, except i cant get PHP to print out that var when it sends the email.
So the final email that goes out is:
Hey $name, $owner_name here
When it should be:
Hey BOB, Johnny here
Here's the mail function code;
get_email_settings($db_host, $db_user, $db_pswrd, $db_name, $email, $pro_msg,$pro_subject);
mail($email_usr, $pro_subject, $pro_msg, "From: $my_email");
Now I've also tried: (NOTE: the double quotes)
mail($email_usr, "$pro_subject", "$pro_msg", "From: $my_email");
And I've also tried inserting the content into the DB with double quotes so: "Hey $name, $owner_name here" instead of Hey $name, $owner_name here...
Both do the same thing...
Any Ideas?
A: The reason it isn't is because PHP isn't evaluating those -- it's not being parsed, just retrieved from the database. You should probably use placeholders rather than putting actual variables in there though. For example, use Hey [NAME], [OWNER_NAME] here and then you can just do a replace on those to get what you want.
If you really want to do it that way, take a look at eval()
A: have you tried this
$pro_msg_with_vars = "";
eval('$pro_msg_with_vars = $pro_msg;');
mail($email_usr, $pro_subject, $pro_msg_with_vars, "From: $my_email");
A: You're probably looking for eval:
http://php.net/manual/en/function.eval.php
I would do something like that: keep in db text "Hello %nickname%, %me% here" and then with php use str_replace(...);
A: Can you please give code for the actual line that is not working?
If I understand you correctly, you are inserting this message as a string into a database, is this correct? If so, then the problem lies where you save the data to the database.
Does the actual data in the database say BOB, or $name?
Try updating the db with:
$query = "INSERT INTO outbound_messages (id, message)VALUES(1, 'Hi {$name}, {$owner_name} here, yada yada');
mysql_query($query);
A: PHP won't recognize those as variables, so you're going to want to manually parse it.
The code is fairly simple, but long enough that I'll just summarize instead of write it.
Essentially, you're going to want to parse through your string and look for anything that has your unique identifier in it (yours is "$"). Each time you find one, extract that string, and compare it to an array.
So if you have in your database:
"Hello, $name. I heard you just turned $age last week. Happy Birthday, dude!"
you're going to want to build an array (I assume this will also be generated from a database) that looks like this.
$db_vars = array(
"name" => "Joe Bob",
"age" => 97
);
That way you can just replace your identified strings with $db_vars[$extracted_string];
A: OK, I got it working.
For anyone else who has this issue, and wants a slightly more clearer answer, here it is:
All I done was a multiple str_replace using arrays.
I'm feeling generous, so I'll go into some detail for you...
example of an str_replace:
$my_text = "my name is [NAME] and my email is [EMAIL]"
$find = array('[NAME]',[EMAIL]);
$and_replace = array('BOB', 'BOB@BOB.com');
// then I just run the str_replace into a variable:
$final_text = str_replace($find, $and_replace, $my_text);
and the final text would be "my name is BOB and my email is BOB@BOB.com"
so as you can see, str_replace searched in the variable $my_text and looked for [NAME] and [EMAIL]. It then replaced them with either BOB (for [NAME]) and BOB@BOB.com (for [EMAIL]). BUT when you do this, make sure the replace variable ($and_replace) has the data in the right order... for example, if i did this $and_replace = array('BOB@BOB.com','BOB'); instead of this $and_replace = array('BOB', 'BOB@BOB.com'); then it would replace [NAME] with BOB@BOB.com and [EMAIL] with BOB. So make sure you get the right order....
So in my case, using str_replace with a string coming from an SQL db:
It's piratically identical to the example i wrote above, instead you just don't create the string variable ($my_text). You just use the variable that has the db content in it (in my case $pro_msg)
so:
$find = array('$name','$owner_name');//<< As some of the other guys said, you should use something like [NAME] instead of $name....
$and_replace = array("$name", "$owner"); //<<<**NOTE: IF REPLACING WITH OTHER VARIABLES, USE DOUBLE QUOTES**
$final_text = str_replace($find, $and_replace, $pro_msg);
So it went into $pro_msg (which contains a string from my sql db) and searched for $name and $owner_name and then replaced it with the appropriate...
ready for mailing...
hope that helped someone out there...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: fine tune rspec before In Rspec, we can setup some global before/after behavior like this:
config.before(:each) {blah...}
I can say:
config.before(:each, :type => :model) {blah...}
To have this block run only with model tests
But this wouldn't work:
config.before(:each, :type => [:model, :controller]) {blah...}
I have to repeat the same thing twice, one for model and one for controller. Is there any other way to do this? Thanks
A: Looking at RSpec filters: https://www.relishapp.com/rspec/rspec-core/docs/hooks/filters
They just match any arbitrary metadata, and rspec-rails adds the metadata :type => :model (or whatever) to each set of tests.
So, this config
config.before(:each, :type => [:model, :controller]) {blah...}
would only match tests with this metadata (matching the same value):
describe "matching tests", :type => [:model, :controller] {blah...}
Which basically means the answer to your question is NO.
Anyway, you could easily DIY it with something like this:
before_controller_and_model = lambda do
do_stuff
end
config.before(:each, :type => :model) { before_controller_and_model.call }
config.before(:each, :type => :controller) { before_controller_and_model.call }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Writing new HTML out to the calling position How do you go about writing out HTML to the calling position of a jQuery function?
I have an HTML page that contains the following jQuery/JS code:
... HTML contents ...
<script>
functionName();
</script>
... More HTML Contents...
How do I get functionName to append/write out new content where it is called, rather than selecting another ID in the document and appending after.
JavaScript's document.write can do this, however, I've read that it screws up jQuery's ability to work with the DOM later.
A: Inspired by this answer.
It appears that scripts are run in order, so at the time of calling, the last script tag at that very moment is the script tag which contains that call.
http://jsfiddle.net/vYPHb/2/
function test() {
// get last script tag at the point of calling - useful case of
// explicitly NOT using '$(document).ready' :)
$("script:last").replaceWith("hacked");
}
HTML:
foo
<script>
test();
</script>
bar
A: It depends how document.write is being used. If it is being used before the page has finished loading, then it is fine, but should it be used after (say triggered from the page load event), then it will put the document in an exception state (write causes the document stream to open and starts writing, which either results in a blank page (in IE), or an open document which never finishes [document.close is explicitly called by the browser once the page has finished loading].
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: GQL Not Recognising a ReferenceProperty in Filter I have a datastore thats has ~850 groups and ~19,000 items. Each item may belong to only one group, I have two models in my app that represent a Group and an Item:
class Group(db.Model):
Id = db.IntegerProperty()
Name = db.StringProperty()
# ... some other properties
class Item(db.Model):
Id = db.IntegerProperty()
Name = db.StringProperty()
Group = db.ReferenceProperty(Group, collection_name="groupItems")
# ... some other properties
I can use the datastore admin to view a specific item (i.e. WHERE Id = 34) and see that it is connected correctly to a Group -
SELECT * FROM Item WHERE Id = 34
This gives me a group with the following properties:
Decoded entity key: Group: id=10321
Entity key: agtzfmV2ZS1taW5lcnIMCxIFR3JvdXAY0VAM
Id: 18
If I alter my GQL query to retrieve all items for this Group I get no results! -
SELECT * FROM Item WHERE Group = KEY('agtzfmV2ZS1taW5lcnIMCxIFR3JvdXAY0VAM') -- No Results
SELECT * FROM Item WHERE Group = KEY('Group', 'agtzfmV2ZS1taW5lcnIMCxIFR3JvdXAY0VAM') -- No Results
If I retrieve just the group, it works as expected -
SELECT * FROM Group WHERE __key__ = KEY('agtzfmV2ZS1taW5lcnIMCxIFR3JvdXAY0VAM') -- Returns 1 Group
This equally applies in my Python code. Calling:
group = Group.gql("WHERE Id = :1", 18).get()
items = Item.gql("WHERE Group = :1", group).fetch(50)
results in a list containing no items. Similarly
group.groupItems.fetch(500) -- Returns no results
My question is - am I doing something particularly stupid? I have created a dummy project with a similar structure to prove to myself that it wasnt a naming problem (i.e. that Group wasn't a reserved word) and that returns just fine. (Attached if anyone is interested).
What am I doing wrong?
EDIT 1 :
As requested, here's the creation code. Reader is a csv reader (using the inbuilt csv library) which opens a CSV stored in the BLOB store. For all intents and purposes its merely parsing a CSV file. As mentioned above. In the data viewer through my dashboard my Item is bound correctly to a group (a group is listed alongside the item and I can click through it's link to view the group) however when passing the group as part of a filter to the Item no results are returned -
Group -
reader = UploaderBase().open_from_blobstore(Settings().get_group_csv_key())
upNum = 0
groupsToPut = []
for row in reader:
group = Group(Id=int(row[0]))
group.Name = row[2]
groupsToPut.append(group)
db.put(groupsToPut)
Item -
groupCache = {}
for group in Group.all().fetch(1000):
groupCache[group.Id] = group
logging.info("Cached %d group entries locally" % len(groupCache))
items = []
reader = UploaderBase().open_from_blobstore(Settings().get_items_csv_key())
upNum = 0
for row in reader:
logging.debug("Adding row %d" % upNum)
item = Item(Id=int(row[0]))
if not row[1] is None and row[1] != "":
item.Group = groupCache[int(row[1])]
item.Name = row[2]
items.append(item)
db.put(items)
A: The most likely explanation is that when you inserted the data, the reference property was set as indexed=False. Changes to a model only affect entities written after the model was changed, so rows inserted while indexing was disabled for that column will not have index rows.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How Do I Configure Json.NET Custom Serialization? For reasons beyond my control, I have data coming back from an external service being formatted as an array of array of string: [["string_one", "string_two"]]
I am trying to deserialize this into an object with two properties:
public class MyObject
{
public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
}
I'm using Json.NET for all JSON serialization/deserialization. When I attempt to convert the array of array of string, I get an exception saying that JsonArray can't be converted to MyObject. What's the appropriate way to implement this?
A: There is quite a big discrepancy between your target object and the JSON. You could do the mapping manually:
string json = "[[\"string_one\", \"string_two\"]]";
dynamic result = JsonConvert.DeserializeObject(json);
var myObject = new MyObject
{
PropertyOne = result[0][0],
PropertyTwo = result[0][1]
};
A: Ended up implementing this using a JsonConverter. I changed MyObject to look like:
[JsonConverter(typeof(MyObjectConverter))]
public class MyObject
{
public string PropertyOne { get; set; }
public string PropertyTwo { get; set; }
}
And then implemented MyObjectConverter:
public class MyObjectConverter : JsonConverter
{
public override object ReadJson (JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
{
int pos = 0;
string[] objectIdParts = new string[2];
while (reader.Read())
{
if (pos < 1)
{
if (reader.TokenType == JsonToken.String)
{
objectIdParts[pos] = reader.Value.ToString();
pos++;
}
}
// read until the end of the JsonReader
}
return new MyObject(objectIdParts);
}
public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException ();
}
public override bool CanWrite {
get {
return base.CanWrite;
}
}
public override bool CanRead { get { return true; } }
public override bool CanConvert (Type objectType)
{
return true;
}
}
A: Honestly, I'd just deserialize it as string[][] and map that within your domain layer. The amount of time you'll spend messing around with custom serialization is rarely worth it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Boyer Moore search for small key First I know very little about algorithms, so bear with me.
As I understand it, the Boyer Moore algorithm is fastest with a long key. So what if I have a very shor key (example 10 chars), and alot of text to search (over 10,000 chars).
Would Boyer Moore be the best search algorithm for this scenario?
If not what would be?
A: According to String searching algorithm, "The Boyer–Moore string search algorithm has been the standard benchmark for the practical string search literature." It's not always the fastest, but in general it's the way to go.
Knuth-Morris-Pratt and Boyer-Moore are very close in running time when you're talking about a small text buffer like 10,000 characters. Even a naive string search will be blindingly fast on a 10K buffer when run on a modern computer. I suspect you'll find that the difference between the KMP and Boyer-Moore two searching for a 10-character string in a 10,000 character buffer will be on the order of nanoseconds.
The best search algorithm in this scenario? That's going to depend on how often you need to call it. If it's something that gets called a few times a second (at most), I'd probably write a naive search and leave it at that. The difference between Boyer-Moore and naive search on that small buffer would be insignificant compared to the running time of your program, and your optimization effort would be better spent somewhere else. If I had to call it hundreds or thousands of times a second, I'd take the time to write an optimized Boyer-Moore search.
A: To answer your question you need to visit one link only: http://www.codeproject.com/Articles/250566/Fastest-strstr-like-function-in-C
In fact the homepage of fastest textual searcher is this:
http://www.sanmayce.com/Railgun/index.html
>So what if I have a very shor key (example 10 chars), and alot of text to search (over 10,000 chars).
Exactly this key range (10-11 chars) is tested in my heavy (1TB) strstr showdown. There 400,000 words are searched in 300,000 words, ONE-BY-ONE, an excellent load for a strstr function!
>Would Boyer Moore be the best search algorithm for this scenario?
According to my tests the fastest text searcher (using Microsoft V16 /Ox) is Railgun_Quadruplet_7Gulliver, yet it is second best when /Ox is used and Intel 12.1, you can test it yourself, see below.
If you have a fast machine, say i7 37*, I would like to see your results of my latest console benchmark package (testing Microsoft v16 vs Intel 12.1 compilers):
http://www.sanmayce.com/Downloads/_KAZE_Benchmark_2013.zip
Test on my T7500 2200Mhz notebook:
E:\_KAZE_Benchmark_2013>RUNME.bat
E:\_KAZE_Benchmark_2013>SKYFALL_TXT2HTML_MicrosoftV16.exe MIX_Tesla_BABAJI_Castaneda_Poirot_Holmes_Sunnah_Hadith_Quran_Bible_Patanjali_Dao_Simplici
ssimus.wrd.txt MASAKARI_General-Purpose_Grade_English_Wordlist_r3_316423_words.wrd /Gulliver
SKYFALL_TXT2HTML, revision 2, written by Kaze.
Size of 1st input file: 8916987
Size of 2nd input file: 3869529
Doing Search for each word with Railgun_Quadruplet_7Gulliver ...
Railgun_Quadruplet_7Gulliver performance: 1944+KB/clock
Average Pattern Length: 11
Function Invocations: 420,640
Function Inner-Loop Iterations: 131,873,881,926
Function Really Traversed: 1,142,740,439KB
E:\_KAZE_Benchmark_2013>SKYFALL_TXT2HTML_MicrosoftV16.exe MIX_Tesla_BABAJI_Castaneda_Poirot_Holmes_Sunnah_Hadith_Quran_Bible_Patanjali_Dao_Simplici
ssimus.wrd.txt MASAKARI_General-Purpose_Grade_English_Wordlist_r3_316423_words.wrd
SKYFALL_TXT2HTML, revision 2, written by Kaze.
Size of 1st input file: 8916987
Size of 2nd input file: 3869529
Doing Search for each word with Railgun_Quadruplet_7 ...
Railgun_Quadruplet_7 performance: 1747+KB/clock
Average Pattern Length: 11
Function Invocations: 420,640
Function Inner-Loop Iterations: 146,826,792,351
Function Really Traversed: 1,142,740,439KB
E:\_KAZE_Benchmark_2013>SKYFALL_TXT2HTML_MicrosoftV16.exe MIX_Tesla_BABAJI_Castaneda_Poirot_Holmes_Sunnah_Hadith_Quran_Bible_Patanjali_Dao_Simplici
ssimus.wrd.txt MASAKARI_General-Purpose_Grade_English_Wordlist_r3_316423_words.wrd /Hasherezade
SKYFALL_TXT2HTML, revision 2, written by Kaze.
Size of 1st input file: 8916987
Size of 2nd input file: 3869529
Doing Search for each word with Railgun_Hasherezade ...
Railgun_Hasherezade performance: 1774+KB/clock
Average Pattern Length: 11
Function Invocations: 420,640
Function Inner-Loop Iterations: 128,900,655,391
Function Really Traversed: 1,142,740,439KB
There are some up-and-downs when 32bit and 64bit code is used also significant margins between Microsoft & Intel.
Gulliver's "engine" is order 2 BM-Horspool tuned by me.
As you can see on my humble laptop Gulliver searches for patterns (Average Pattern Length: 11) at 1898MB/s, even the super beautiful BNDM bends a knee here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I create a chm file with multiple directories via command line? I am working on a project where I need to create a chm through command line. It has multiple directories and I was able to get it to work in FAR, which does not have a command line option to create the chm.
Using the MS HTML Help Workshop command:
"%programfiles%\HTML Help Workshop\hhc" files.hhp > log.txt
where files.hhp looks like:
[OPTIONS]
Flat=No
[FILES]
C:\Files\help\index.html
C:\Files\help\page1.html
C:\Files\help\page2.html
C:\Files\help\etc.html
C:\Files\help\pdfs\graph1.pdf
C:\Files\help\pdfs\graph2.pdf
I was able to create the chm but it puts the pdf files in the root instead of the pdfs directory in the chm.
According to http://helpware.net/FAR/help/dlg_hhpedit_sec.htm the Flat=No option should fix this but its not having any affect.
What am I missing?
A: Do you change the working dir to c:\files\help before executing?
Explanation: The helpfile compiler probably uses the working directory as root to reduce global paths like "c:\files\help..." to paths relative (to the future .CHM root).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: In WiX, Should I have different Product Ids for 32 and 64 bit versions I'm writing a WiX installer, with a common set of WiX sources for the 32 bit and 64 bit versions of the product.
The question is, should I use different Product Ids for the different versions?
A: To answer my own question, which it turns out was actually the wrong one to ask, the MSDN documentation for the ProductCode property says:
The 32-bit and 64-bit versions of an application's package must be assigned different product codes.
Turns out I was confused by the fact that I thought that the product code should never change. This is wrong. Again:
The ProductCode property is a unique identifier for the particular product release. This ID must vary for different versions and languages.
A: First I would make a guard like this for the 32 bit installer:
<Condition Message="This installer does not support 64-bit Windows! ">
<![CDATA[NOT VersionNT64]]>
</Condition>
and this for the 64 bit installer:
<Condition Message="This installer does not support 32-bit Windows! ">
<![CDATA[VersionNT64]]>
</Condition>
But back to your question. I recommend that you set Product Id to "*". This ensures that every build creates a new GUID. You can always find this GUID, if you want to create a patch, using Orca.
The important value is the UpgradeCode. This GUID creates a link between versions. I will recommend one UpgradeCode for all your 32 bit installers and another UpgradeCode for all you 64 bit installers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: objective-c: Webservice, How to tell about specific method to access I am trying to access http://services-staging.cmtnyc.com/payment/payment.asmx web service and
AuthorizeCreditTrip I checked this webservice on .Net application and its working fine but in objective-c it does not responds with the same data.
The web service exposes 5 methods and I want to access 4th. But I think this code do not specify that which methood to access . forHTTPHeaderField:@"SOAPAction" tells but I do not think that its correct link to put here.
Does not responds means it sends nothing in response.
I think that I am unable to set valid SOAPAction
-(IBAction)sendData
{
NSString *soapMsg = [NSString stringWithFormat: @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Header>"
"<AuthenticationHeader xmlns=\"http://services.cmtnyc.com/payment\">"
"<Username>validusername</Username>"
"<Password>validpass</Password>"
"<DataSource>validsource</DataSource>"
"</AuthenticationHeader>"
"</soap:Header>"
"<soap:Body>"
"<AuthorizeCreditTrip xmlns=\"http://services.cmtnyc.com/payment\">"
"<requestId>%d</requestId>"
"<deviceId>abcd</deviceId>"
"<userId>3003</userId>"
"<jobId>000047</jobId>"
"<paymentAmt>1</paymentAmt>"
"<fareAmt>0</fareAmt>"
"<tipAmt>0</tipAmt>"
"<tollAmt>0</tollAmt>"
"<surchargeAmt>0</surchargeAmt>"
"<taxAmt>0</taxAmt>"
"<convenienceFeeAmt>0</convenienceFeeAmt>"
"<swipeData></swipeData>"
"<accountNumber>validaccount</accountNumber>"
"<expiryDate>validdate</expiryDate>"
"<zipCode>73000</zipCode>"
"<cvv2>227</cvv2>"
"<cardReaderMethod>0</cardReaderMethod>"
"<encryptionKeyVersion>0</encryptionKeyVersion>"
"<encryptedToken></encryptedToken>"
"<encryptionAlgorithm>0</encryptionAlgorithm>"
"<pickupDate>2011-09-12</pickupDate>"
"<pickupLatitude>0</pickupLatitude>"
"<pickupLongitude>0</pickupLongitude>"
"<dropoffDate>2011-09-16</dropoffDate>"
"<dropoffLatitude>0</dropoffLatitude>"
"<dropoffLongitude>0</dropoffLongitude>"
"<passengerCount>0</passengerCount>"
"<tripDistance>124</tripDistance>"
"<tripDuration>0</tripDuration>"
"<readyToSettle>false</readyToSettle>"
"</AuthorizeCreditTrip>"
"</soap:Body>"
"</soap:Envelope>",55258];
NSURL *url = [NSURL URLWithString: @"http://services-staging.cmtnyc.com/payment/payment.asmx"];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]];
[req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[req addValue:@"http://services.cmtnyc.com/payment/AuthorizeCreditTrip" forHTTPHeaderField:@"SOAPAction"];
[req addValue:msgLength forHTTPHeaderField:@"Content-Length"]; //---set the HTTP method and body---
[req setHTTPMethod:@"POST"];
[req setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%@", soapMsg);
conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
if (conn)
{
webData = [[NSMutableData data] retain];
}
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
[webData setLength: 0];
}
-(void) connection:(NSURLConnection *) connection didReceiveData:(NSData *) data
{
[webData appendData:data];
}
-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error {
[webData release];
[connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection
{
NSLog(@"..DONE. Received Bytes: %d", [webData length]);
NSString *theXML = [[NSString alloc] //---shows the XML---
initWithBytes:[webData mutableBytes] length:[webData length]
encoding:NSUTF8StringEncoding];
NSLog(@"....%@",theXML);
[theXML release];
// [activityIndicator stopAnimating];
[connection release];
[webData release];
}
A: Here is how I have it working:
NSURL *urlWS = [NSURL URLWithString:kUrlServer];
NSMutableURLRequest *theRequest;
theRequest = [NSMutableURLRequest requestWithURL:urlWS];
NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
[theRequest addValue: @"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
Perhaps you are missing application/soap+xml.
Cheers
A: I've used the below code and has worked fine for me:
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]];
[req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[req addValue:@"http://tempuri.org/SearchCustomer" forHTTPHeaderField:@"SOAPAction"];
[req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
[req setHTTPMethod:@"POST"];
[req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
where url is my Url, soapMsg is my soap message and @"http://tempuri.org/Method" is the soap action.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: php use array as index to array If I have an array $dictionary and an array $words how can I use an array ($words) to index another array ($dictionary)?
The easiest I can think is:
function dict_dispatch($word,$dictionary) {
return $dictionary[$word];
}
$translated = array_map('dict_dispatch', $words,
array_fill(0, count($words), $dictionary));
e.g.
For example:
$dictionary = array("john_the_king"=>"John-The-King", "nick_great"=>"Nick-Great-2001");
$words=array("john_the_king","nick_great");
$translated = <??>
assert($translated==array("John-The-King","Nick-Great-2001"));
Notice that $dictionary might be quite large and it would be very nice if this operation is as fast as possible (that's why I don't use foreach in first place)
A: I don't know how efficient this is, but it works.
$translated = array_values(array_intersect_key($dictionary, array_flip($words)));
A: Are you talking about something like this where you use array of the keys and another for the values?
$translated = array_combine($words, $dictionary);
A: It looks like my original solution is more or less the most efficient.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7585604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.