text stringlengths 8 267k | meta dict |
|---|---|
Q: eclipse scala plugin console cannot display hebrew characters I am trying to run the following scala code:
println("world שלום").
but in eclipse, this is what I see in scala interpreter console:
println("world שלום")
world ????
Is it possible to fix that?
A: This works for me with Eclipse Indigo on Linux. It looks like you have some platform specific encoding issue ... but it's impossible to tell without more detail.
A: You should tell where you see this. Is it the console? Also what platform are you running eclipse on.
You could try to add -Dfile.encoding=UTF-8 to your eclipse.ini file.
A: Answer here
http://decoding.wordpress.com/2010/03/18/eclipse-how-to-change-the-console-output-encoding/
relevant for all eclipse languages...
Taking the comment i got below into consideration, the short version of the link I gave says the following:
In eclipse, in the toolbar, in the 'run' button combo options, select 'run configurations'
There, go to the 'common tab' and change your encoding to UTF-8.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use Named Pipes without the computer hanging if no one connects to the network? I’m looking for a way to communicate between programs on the same computer, and have been referred to Named Pipes.
It seems that the only way to connect the server is though WaitForConnection (I don’t know enough to use unmanaged code). But if no one connects to the network – the program hangs indefinitely. How do I make a connection with a timeout limit?
Thanks.
A: Instead of calling the synchronous WaitForConnection method, call BeginWaitForConnection/EndWaitForConnection for a non-blocking server. See here for a similar answer.
The constructor you want is the one with 5 parameters here. You can call it like so:
NamedPipeServerStream pipeServer = new NamedPipeServerStream(
"<pipe-name>",
PipeDirection.InOut,
1,
PipeTransmissionMode.Byte,
PipeOptions.Asynchronous);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: developer manuals My team and I are in the final phase of our software development project.
We are using Visual Studio to compile our project and coding in C#.
We need to build user manuals. Is there any way to generate user manuals from the comments of the application and code?
A: Assuming you have commented your code appropriately there are a number of third-party tools that you can use to generate documentation.
The following list is not exhaustive:
*
*SandCastle
*NDoc
*Doc-O-Matic
*VSdocman
*Doxygen
*...
I just hope your end-users are developers and you are writing some sort of API. These sort of documentation generation tool are usually only suited for internal use or external developers for which you created an API that they can use.
A: If your target audience was other developers, you could do something like what is mentioned in this SO post but if it is end users who aren't developers, then it isn't likely that the comments in your code are going to be all that useful to them, and if they are... then they probably aren't all that useful to the developer.
A: If you were using XML Documentation Commments...you could use the /doc compile option.
XML Documentation Comments
When you compile with the /doc option, the compiler will search for
all XML tags in the source code and create an XML documentation file.
To create the final documentation based on the compiler-generated
file, you can create a custom tool or use a tool such as DocFX or
Sandcastle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: A simple C++ While loop not working I have a simple while loop i'm trying to implement but for the life of me can't figure out what I'm missing. I have currentuser initialized at the top to -1
while(currentuser = -1){
cout << "Enter user ID: ";
cin >> id;
currentuser = search(a, length, id);
}
My search function is this:
int search (User a[ ], int length, string userID){
User u;
string tempid;
int templegnth; //I ignore length for now as I will use it later
for(int i=0; i<50; i++){
tempid = a[i].getID();
templegnth = tempid.length();
if((tempid == userID)){
return i;
}
}
return -1;
}
I know its something very simple but the answer escapes me right now.
A: The = (assignment) operator is not the same as the == (equality) operator.
The line :
while(currentuser = -1){
first assigns -1 to currentuser, and then checks if currentuser has a non-zero value. This will always be the case (-1 != 0), so the loop will never end.
You likely meant this instead :
while(currentuser == -1){
which compares currentuser to -1, and continues the loop as long as that comparison is true.
A: You need to change:
while(currentuser = -1){
to be:
while(currentuser == -1){
Currently you are assigning currentuser to -1 every time your loop runs, rather than checking if it is still assigned to that value.
A: Try == -1 instead of = -1
A: You've got the answers but here is a tip on how to avoid it in the future.
Always try to use
while(-1 == currentuser){
std::cout << "Enter user ID: ";
std::cin >> id;
currentuser = search(a, length, id);
}
as this way
while(-1 = currentuser){
;
}
will be thrown out by the compiler
A: Even with the = changed to ==, the loop still has problems.
while(currentuser == -1){
std::cout << "Enter user ID: ";
std::cin >> id;
currentuser = search(a, length, id);
}
Typing an EOT (control-D on a Linux box, control-Z? on windows) will raise std::cin's end of file condition. The value of id won't be changed, and the lookup will presumably keep on returning -1. The result is an infinite loop with lots of spew to std::cout.
One way to fix this is to break out of the loop when the std::cin >> id; fails. For example, if (! (std::cin >> id)) break;
A: Whenever I use a while loop and a boolean, I try to make sure it only runs if it is above or is 50 but instead whenever I execute a cout with the while and int, the outcome is a literal mess, its like the while loop executes a lot more than it should. Eg.
int Buses;
int People;
cin >> People;
while(People >= 50){
Buses += 1;
People -= 50;
};
cout << Buses << endl;
and when I input 757, my result was 32782.
Even by subtracting the int value by 32767, the values sort of fix itself but not the higher numbers, 99 is 1, 101 is 2 but c++ says that 300 is 3 although it is meant to be 6.
(My solution I found: I had to declare the Person and Buses variable with a 0 because the value was different without the starting 0.)
This is the fixed code:
int Buses = 0;
int People = 0;
cin >> People;
while(People >= 50){
Buses += 1;
People -= 50;
};
cout << Buses << endl;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Testing an IRC bot I am writing an IRC bot in Python using the Twisted library. To test my bot I need to connect several times to an IRC network as my bot requires a restart each time a change is made. Therefore I am often "banned" from these networks for a couple of minutes because I have made a lot of connections.
This makes it annoying testing and writing the bot. Does anyone know of a better way to test the bot or any network which isn't as restrict with the amount of connections as QuakeNet is?
A: You can install UnrealIRCd (it's an irc server) on your local machine and test your bot with it. Any network will ban you if you keep reconnecting all the time. Plus working against a local server will speed up the connection times alot.
There are a bunch of other irc servers out there.
+1 for supy bot.
A: freenode is good.. You can create channels for yourself to test. Also check out this project called supybot, which is good for Python bots.
A: You can take the undernet ircu from http://coder-com.undernet.org and, before compiling it, add #define NOTHROTTLE to ircd_defs.h. This will remove any connection throttling so you can test your bot as much as you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Optimize this C Code How to Optimize this piece of C code...??
int c = no, diff = u - d;
while (no--)
for (d = u; d < p[no]; d += diff)
c++;
A: The best optimization, for size, speed, cleverness, clarity, and anything else you may think of, is to have no code.
So, just remove those 4 lines from your source(s) and you've optimized your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
} |
Q: Given a Uri and a UriTemplate, how to get template parameter values? If I have access to both a Uri and the UriTemplate on which is is based, what is the neatest way to discover the values that have replaced the parameters in the template?
For example, if I know:
var uriTemplate = new UriTemplate("/product-catalogue/categories/{categoryName}/products/{product-name}");
var uri = new Uri("/product-catalogue/categories/foo/products/bar");
is there a built-in way for me to discover that categoryName = "foo" and productName = "bar"?
I was hoping to find a method like:
var parameterValues = uriTemplate.GetParameterValues(uri);
where parameterValues would be:
{ { "categoryName", "foo" }, { "productName", "bar" }}
Clearly, I could write my own, but I was wondering if there was something in framework I could use.
Thanks
Sandy
A: You can call the Match method on the uriTemplate instance and use the returned UriTemplateMatch instance to access the parameter values:
var uriTemplate = new UriTemplate("/product-catalogue/categories/{categoryName}/products/{product-name}");
var uri = new Uri("http://www.localhost/product-catalogue/categories/foo/products/bar");
var baseUri = new Uri("http://www.localhost");
var match = uriTemplate.Match(baseUri, uri);
foreach (string variableName in match.BoundVariables.Keys)
{
Console.WriteLine("{0}: {1}", variableName, match.BoundVariables[variableName]);
}
outputs
CATEGORYNAME: foo
PRODUCT-NAME: bar
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: key logging in unix I am a newbie to unix scripting, I want to do following and I have little clue how to proceed.
I want to log the input and output of certain set of commands, given on the terminal, to a trace file. I should be able to switch it on and off.
E.g.
switch trace on
user:echo Hello World
user:Hello World
switch trace off
Then the trace log file, e.g. trace.log, it's content should be
echo Hello World
Hello World
One thing that I can think to do is to use set -x, redirecting its output to some file, but couldn't find a way to do that. I did man set, or man -x but I found no entry. Maybe I am being too naive, but some guidance will be very helpful.
I am using bash shell.
A: See script(1), "make typescript of terminal session". To start a new transcript in file xyz: script xyz. To add on to an existing transcript in file xyz: script -a xyz.
There will be a few overhead lines, like Script started on ... and Script done on ... which you could use awk or sed to filter out on printout. The -t switch allows a realtime playback.
I think there might have been a recent question regarding how to display a transcript in less, and although I can't find it, this question and this one address some of the same issues of viewing a file that contains control characters. (Captured transcripts often contain ANSI control sequences and usually contain Returns as well as Linefeeds.)
Update 1 A Perl program script-declutter is available to remove special characters from script logs.
The program is about 45 lines of code found near the middle of the link. Save those lines of code in a file called script-declutter, in a subdirectory that's on your PATH (for example, $HOME/bin if that's on your search path, else (eg) /usr/local/bin) and make the file executable. After that, a command like
script-declutter typescript > out
will remove most special characters from file typescript,
while directing the result to file out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Switch between two frames in tkinter? I have built my first few scripts with a nice little GUI on them, as the tutorials have shown me, but none of them address what to do for a more complex program.
If you have something with a 'start menu', for your opening screen, and upon user selection you move to a different section of the program and redraw the screen appropriately, what is the elegant way of doing this?
Does one just .destroy() the 'start menu' frame and then create a new one filled with the widgets for another part? And reverse this process when they press the back button?
A: Here is another simple answer, but without using classes.
from tkinter import *
def raise_frame(frame):
frame.tkraise()
root = Tk()
f1 = Frame(root)
f2 = Frame(root)
f3 = Frame(root)
f4 = Frame(root)
for frame in (f1, f2, f3, f4):
frame.grid(row=0, column=0, sticky='news')
Button(f1, text='Go to frame 2', command=lambda:raise_frame(f2)).pack()
Label(f1, text='FRAME 1').pack()
Label(f2, text='FRAME 2').pack()
Button(f2, text='Go to frame 3', command=lambda:raise_frame(f3)).pack()
Label(f3, text='FRAME 3').pack(side='left')
Button(f3, text='Go to frame 4', command=lambda:raise_frame(f4)).pack(side='left')
Label(f4, text='FRAME 4').pack()
Button(f4, text='Goto to frame 1', command=lambda:raise_frame(f1)).pack()
raise_frame(f1)
root.mainloop()
A:
Note: According to JDN96, the answer below may cause a memory leak by repeatedly destroying and recreating frames. However, I have not tested to verify this myself.
One way to switch frames in tkinter is to destroy the old frame then replace it with your new frame.
I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container object and allows you to use any generic Frame class.
# Multi-frame tkinter application v2.3
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Open page one",
command=lambda: master.switch_frame(PageOne)).pack()
tk.Button(self, text="Open page two",
command=lambda: master.switch_frame(PageTwo)).pack()
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
class PageTwo(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
Explanation
switch_frame() works by accepting any Class object that implements Frame. The function then creates a new frame to replace the old one.
*
*Deletes old _frame if it exists, then replaces it with the new frame.
*Other frames added with .pack(), such as menubars, will be unaffected.
*Can be used with any class that implements tkinter.Frame.
*Window automatically resizes to fit new content
Version History
v2.3
- Pack buttons and labels as they are initialized
v2.2
- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.
v2.1.1
- Remove type-hinting for backwards compatibility with Python 3.4.
v2.1
- Add type-hinting for `frame_class`.
v2.0
- Remove extraneous `container` frame.
- Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
- Frame switching is now done with `master.switch_frame()`.
v1.6
- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.
v1.5
- Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
- Initializing the frame before calling `.destroy()` results
in a smoother visual transition.
v1.4
- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
- Remove `new_frame` variable.
v1.3
- Rename `parent` to `master` for consistency with base `Frame` class.
v1.2
- Remove `main()` function.
v1.1
- Rename `frame` to `_frame`.
- Naming implies variable should be private.
- Create new frame before destroying old frame.
v1.0
- Initial version.
A: One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.
Note: for this to work, all of the widgets for a page must have that page (ie: self) or a descendant as a parent (or master, depending on the terminology you prefer).
Here's a bit of a contrived example to show you the general concept:
try:
import tkinter as tk # python 3
from tkinter import font as tkfont # python 3
except ImportError:
import Tkinter as tk # python 2
import tkFont as tkfont # python 2
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")
# the container is where we'll stack a bunch of frames
# on top of each other, then the one we want visible
# will be raised above the others
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
# put all of the pages in the same location;
# the one on the top of the stacking order
# will be the one that is visible.
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("StartPage")
def show_frame(self, page_name):
'''Show a frame for the given page name'''
frame = self.frames[page_name]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is the start page", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda: controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda: controller.show_frame("PageTwo"))
button1.pack()
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 1", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is page 2", font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button = tk.Button(self, text="Go to the start page",
command=lambda: controller.show_frame("StartPage"))
button.pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.
For example, to create the classes individually you can remove the loop (for F in (StartPage, ...) with this:
self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)
self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")
Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:
*
*Understanding parent and controller in Tkinter __init__
*Tkinter! Understanding how to switch frames
*How to get variable data from a class
*Calling functions from a Tkinter Frame to another
*How to access variables from different classes in tkinter?
*How would I make a method which is run every time a frame is shown in tkinter
*Tkinter Frame Resize
*Tkinter have code for pages in separate files
*Refresh a tkinter frame on button press
A: Perhaps a more intuitive solution would be to hide/unhide frames using the pack_forget method if you are using the pack geometry manager.
Here's a simple example.
import tkinter as tk
class App:
def __init__(self, root=None):
self.root = root
self.frame = tk.Frame(self.root)
self.frame.pack()
tk.Label(self.frame, text='Main page').pack()
tk.Button(self.frame, text='Go to Page 1',
command=self.make_page_1).pack()
self.page_1 = Page_1(master=self.root, app=self)
def main_page(self):
self.frame.pack()
def make_page_1(self):
self.frame.pack_forget()
self.page_1.start_page()
class Page_1:
def __init__(self, master=None, app=None):
self.master = master
self.app = app
self.frame = tk.Frame(self.master)
tk.Label(self.frame, text='Page 1').pack()
tk.Button(self.frame, text='Go back', command=self.go_back).pack()
def start_page(self):
self.frame.pack()
def go_back(self):
self.frame.pack_forget()
self.app.main_page()
if __name__ == '__main__':
root = tk.Tk()
app = App(root)
root.mainloop()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "123"
} |
Q: Manually cast signed char I'm working with some embedded hardware, a Rabbit SBC, which uses Dynamic C 9.
I'm using the microcontroller to read information from a digital compass sensor using one of its serial ports.
The sensor sends values to the microcontroller using a single signed byte. (-85 to 85)
When I receive this data, I am putting it into a char variable
This works fine for positive values, but when the sensor starts to send negative values, the reading jumps to 255, then works its way back down to 0. I presume this is because the last bit is being used to determine the negative/positive, and is skewing the real values.
My inital thought was to change my data type to a signed char.
However, the problem I have is that the version of Dynamic C on the Microcontroller I am using does not natively support signed char values, only unsigned.
I am wondering if there is a way to manually cast the data I receive into a signed value?
A: You just need to pull out your reference book and read how negative numbers are represented by your controller. The rest is just typing.
For example, two's complement is represented by taking the value mod 256, so you just need to adjust by the modulus.
int signed_from_unsignedchar(unsigned char c)
{
int result = c;
if (result >= 128) result -= 256;
return result;
}
One's complement is much simpler: You just flip the bits.
int signed_from_unsignedchar(unsigned char c)
{
int result = c;
if (result >= 128) result = -(int)(unsigned char)~c;
return result;
}
Sign-magnitude represents negative numbers by setting the high bit, so you just need to clear the bit and negate:
int signed_from_unsignedchar(unsigned char c)
{
int result = c;
if (result >= 128) result = -(result & 0x7F);
return result;
}
A: I think this is what you're after (assumes a 32-bit int and an 8-bit char):
unsigned char c = 255;
int i = ((int)(((unsigned int)c) << 24)) >> 24;
of course I'm assuming here that your platform does support signed integers, which may not be the case.
A: Signed and unsigned values are all just a bunch of bits, it is YOUR interpretation that makes them signed or unsigned. For example, if your hardware produces 2's complement, if you read 0xff, you can either interpret it as -1 or 255 but they are really the same number.
Now if you have only unsigned char at your disposal, you have to emulate the behavior of negative values with it.
For example:
c < 0
changes to
c > 127
Luckily, addition doesn't need change. Also subtraction is the same (check this I'm not 100% sure).
For multiplication for example, you need to check it yourself. First, in 2's complement, here's how you get the positive value of the number:
pos_c = ~neg_c+1
which is mathematically speaking 256-neg_c which congruent modulo 256 is simply -neg_c
Now let's say you want to multiply two numbers that are unsigned, but you want to interpret them as signed.
unsigned char abs_a = a, abs_b = b;
char final_sign = 0; // 0 for positive, 1 for negative
if (a > 128)
{
abs_a = ~a+1
final_sign = 1-final_sign;
}
if (b > 128)
{
abs_b = ~b+1
final_sign = 1-final_sign;
}
result = abs_a*abs_b;
if (sign == 1)
result = ~result+1;
You get the idea!
A: If your platform supports signed ints, check out some of the other answers.
If not, and the value is definitely between -85 and +85, and it is two's complement, add 85 to the input value and work out your program logic to interpret values between 0 and 170 so you don't have to mess with signed integers anymore.
If it's one's complement, try this:
if (x >= 128) {
x = 85 - (x ^ 0xff);
} else {
x = x + 85;
}
That will leave you with a value between 0 and 170 as well.
EDIT: Yes, there is also sign-magnitude. Then use the same code here but change the second line to x = 85 - (x & 0x7f).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Error deploying to heroku Please help. I have absoluty no idea what's wrong. The rails app works on my local machine.
If I do this:
git push heroku master
I get this:
Counting objects: 4195, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (3944/3944), done.
Writing objects: 72% (3009/4178), 9.99 MiB | 73 KiB/s
Compressing objects: 100% (3944/3944), done.
**Connection to 10.46.xxx.xxx closed by remote host.KiB/s
error: pack-objects died of signal 13
error: failed to push some refs to 'git@heroku.com:gentle-rain-xxxx.git**
A: I just dealt with 24 hours of this hell. I re-cloned repos, destroyed apps, repacked, pruned... the whole 9 yards.
It turned out that I had a .txt file which was ~250MB in size that, even though I had removed it from my master branch, was still present in my local (as well as github) cache.
I checked out this page and inadvertently found my answer here:
https://help.github.com/articles/remove-sensitive-data
The .txt file had previously been in the doc/ folder, so I pointed this command at where the file would have been in any commits and ran it.
git filter-branch --index-filter 'git rm --cached --ignore-unmatch doc/US.txt'
This is very useful if you realize you have static assets of some sort that don't have to be in your repo and are causing you to get the signal 13 error.
A: I was having problems with a repository as small as 130MB. I don't really want to prune my repository, nor do I feel it is necessary.
I can't help but feel this is a problem with git and/or Heroku, I believe a big push should succeed, even over a "slow" or less than ideal connection.
How I solved/worked-around this issue was to spin up an EC2 instance, checkout my repo there, and push to github. In that way, my deploy speed was 4MiB/s (faster than my own 80KiB/s!). Furthermore, in the cases where the push would fail due to some configuration issues, I could quickly tweak and try again.
For more information on this technique, I've written up the full steps on how to spin up an EC2 instance for this purpose here: http://omegadelta.net/2013/06/16/pushing-large-repositories-to-heroku/
A: Hi I had the same problem trying push to cedar stack. I contacted heroku support and they fixed it. Here is what they said:
It appears to be due to a change in our git server on our end. I'll be
following up with our engineers to make sure we get a permanent fix
rolled out for this.
-Chris
A: This appears to just be a timeout from your push being too large.
I got around this by doing a git reset to a SHA that was around 500 commits back, pushing that, and then pushing the rest of my repo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Android MapActivity cannot retrieve location data I have followed the HelloMapView tutorial for android, and added some code to capture my current location information and display in a textview.
I have tested these code in another program and it worked, it is able to display my longitude and latitude data when the launch that app. However when i copied the code into this MapActivity, it seems that i cannot get the location data.
Here's part of the code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.androidmarker);
itemizedOverlay = new HelloItemizedOverlay(drawable, this);
Button button1 = (Button)this.findViewById(R.id.button1);
tv1 = (TextView) this.findViewById(R.id.textView1);
button1.setOnClickListener(mScan);
latitude = 1.3831625;
longitude = 103.7727321;
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
if (System.currentTimeMillis() - location.getTime() < 3000)
{
longitude = location.getLongitude();
latitude = location.getLatitude();
tv1.setText(Double.toString(longitude));
}
}
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000, 10, locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
tv1.setText(Double.toString(latitude));
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
A: Did you added proper permissions in Manifest? Like this
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Also please check your gps is enabled or working on ur deive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android emulator does not recognize .php extension for web pages I am trying to write a php code for mobile web app. But the problem is when I test that page in android emulator then it says error loading. when I turn it back to .html then it loads that page.
Can someone tell me why and how to solve this?
A: Try your page on web browser before the emulator. Seems it's not a emulator issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails: Changing relationship after initial migration I am having some trouble finding a good answer to my question on rails relationship creation.
If I already ran the initial migration for my user model and my comment model Without declaring a relationship (ie: a user has_many comments, and comments belong_to user) how do I define that relationship later on?
Can I simply:
1-add the user_id column to Comments,
2-declare the relationship and
3-run the new add_user_id_to_comment migration file?
Will this work? If not, how would I go about changing the relationship after already having ran the initial migration for the models? Thank you so much for your help.\
Rails 3.1, Ruby 1.8.7
A: You can just add the reference in another migration, using the change_table migration (documentation):
change_table :comments do |t|
t.references :user
end
Then just add the associations to your models.
class User < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :user
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Magento, how i can send variable from MyController to my view phtml? how i can send variable from MyController to my view phtml?
Zend framework, i send like this:
// MyController
$this->view->name = "Matheus";
or
$this->view->assign('name',"matheus");
// My View
echo $this->name;
in Magento Controller, how i send from MyController to my view, and how i can see in my view the variable?
thanks!
A: Magento MVC is different to Zend one, it is configuration based. View in magento consists of 2 parts - block (class) and template plus layout update in xml file. It can't be described in 2 words, you should read this article.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hadoop: High CPU load on client side after committing jobs I couldn't find an answer to my issue while sifting through some Hadoop guides: I am committing various Hadoop jobs (up to 200) in one go via a shell script on a client computer. Each job is started by means of a JAR (which is quite large; approx. 150 MB). Right after submitting the jobs, the client machine has a very high CPU load (each core on 100%) and the RAM is getting full quite fast. That way, the client is no longer usable. I thought that the computation of each job is entirely done within the Hadoop framework, and only some status information is exchanged between the cluster and the client while the job is running.
So, why is the client fully stretched? Am I committing Hadoop jobs the wrong way? Is each JAR too big?
Thanks in advance.
A: It is not about the jar. The client side is calculating the InputSplits.
So it can be possible that when having large number of input files for each job the client machine gets a lot of load.
But I guess when submitting 200 jobs the RPC Handler on the jobtracker has some problems. How many RPC handlers are active on the jobtracker?
Anyways, I would batch the submission up to 10 or 20 jobs at a time and wait for their completion. I guess you're having the default FIFO scheduler? So you won't benefit from submitting all 200 jobs at a time either.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Stop other websites iframing? We run an online service (aka a script) and we have discovered a few websites over the past few weeks putting our script on their site via iframe.
What precautions can we take to stop other people putting our site into theirs via iframe?
Thank you.
A: A more global solution would be something like this:
<script type="text/javascript">
if (top.location != location) {
top.location.href = document.location.href ;
}
</script>
Place it on the top of your page (inside the "head" tag).
A: On modern browsers, send the header X-Frame-Options with the value DENY. If it's a recent enough browser, it'll obey the header and tell the iframe to pack sand.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Question regarding llply or lapply - applying functions to data.frames in a list Dear R user community,
I have many data.frames in a list, as follows (only one data.frame in the list of 21 shown for convenience):
> str(datal)
List of 21
$ BallitoRaw.DAT :'data.frame': 1083 obs. of 3 variables:
..$ Filename: Factor w/ 21 levels "BallitoRaw.DAT",..: 1 1 1 1 1 1 1 1 1 1 ...
..$ date :Class 'Date' num [1:1083] 7318 7319 7320 7321 7322 ...
..$ temp : num [1:1083] NA 25.8 NA NA NA NA NA NA NA 24.4 ...
If I work on each data.frame in the list individually I can create a zoo object from temp and date, as such:
> BallitoRaw.zoo <- zoo(datal$BallitoRaw.DAT$temp, datal$BallitoRaw.DAT$date)
The zoo object looks like this:
> head(BallitoRaw.zoo)
1990-01-14 1990-01-15 1990-01-16 1990-01-17 1990-01-18 1990-01-19
NA 25.8 NA NA NA NA
How do I use llply or apply (or similar) to work on the whole list at once?
The output needs to go into a new list of data.frames, or a series of independent data.frames (each one named as in the zoo example above). Note that the date column, although a regular time series (days), contains missing dates (in addition to NAs for temps of existing dates); the missing dates will be filled by the zoo function. The output data.frame with the zoo object will thus be longer than the original one.
Help kindly appreciated.
A: makeNamedZoo <- function(dfrm){ dfrmname <- deparse(substitute(dfrm))
zooname <-dfrmname
assign(zooname, zoo(dfrm$temp, dfrm$date))
return(get(zooname)) }
ListOfZoos <- lapply(dflist, makeNamedZoo)
names(ListOfZoos) <- paste( sub("DAT$", "", names(dflist) ), "zoo", sep="")
Here is a simple test case:
df1 <- data.frame(a= letters[1:10], date=as.Date("2011-01-01")+0:9, temp=rnorm(10) )
df2 <- data.frame(a= letters[1:10], date=as.Date("2011-01-01")+0:9, temp=rnorm(10) )
dflist <- list(dfone.DAT=df1,dftwo.DAT=df2)
ListOfZoos <- lapply(dflist, makeNamedZoo)
names(ListOfZoos) <- paste( sub("DAT$", "", names(dflist) ), "zoo", sep="")
$dfone.zoo
2011-01-01 2011-01-02 2011-01-03 2011-01-04 2011-01-05 2011-01-06 2011-01-07
0.7869056 1.6523928 -1.1131432 1.2261783 1.1843587 0.2673762 -0.4159968
2011-01-08 2011-01-09 2011-01-10
-1.2686391 -0.4135859 -1.4916291
$dftwo.zoo
2011-01-01 2011-01-02 2011-01-03 2011-01-04 2011-01-05 2011-01-06 2011-01-07
0.7356612 -0.1263861 -1.6901240 -0.6441732 -1.4675871 2.3006544 1.0263354
2011-01-08 2011-01-09 2011-01-10
-0.8577544 0.6079986 0.6625564
A: This is an easier way to achieve what I needed:
tozoo <- function(x) zoo(x$temp, x$date)
data1.zoo <- do.call(merge, lapply(split(data1, data1$Filename), tozoo))
The result is a nice zoo object.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can we use Spring WS for webservice of type RPC/ENCODED? I have a WSDL of type RPC/Encoded and implementing Message Level Security (my XSD is complex type).
*
*Can I use Spring WS for this type of Web Service?
*is JAX-WS support this type of web service?
What is best way to implement this type of webservice? I need to implement the client.
A: JAX-WS does not support RPC/Encoded type of web services. For this we can use Rampart and also for more reference we can also refer to WSO2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Quickbox with MooTools 1.4 I've been trying out a few lightboxes for my website using MooTools 1.4, and I found this one that works and looks really nice (with easy implementation):
http://andrewplummer.com/code/quickbox/
On the demo website, the lightbox works perfectly, clicking the image brings up the overlay and image, and clicking the overlay removes them.
On my website, when you click an image that's marked appropriately, the lightbox pops up and everything works properly, however, when you exit the lightbox by clicking the overlay or pressing q/x/esc, the overlay hides and everything looks great. The only problem with this is that for some reason, this is being embedded into the body of my code:
<div id="qbOverlay" style="display: block; width: 100%; height: 100%; opacity: 0; "></div>
The problem that this causes is that it isn't ever removed after the lightbox is closed, so the entire page is blanked in
#qbOverlay {
display: block;
position: absolute;
z-index: 100;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: #000;
cursor: pointer;
}
This is a problem because this makes the entire top of the page this overlay, and it's never removed after the lightbox is closed. When it's like this, I can't click any links or use any input boxes in the area that it's covering.
I have a feeling that the thing causing this problem is this:
close: function(){
this.quickBox.setStyle("display", "none");
this.quickBox.setStyle("cursor", "auto");
this.overlay.fade("out");
this.active = false;
}
I've tried using MooTools with compatibility mode and having every extra turned on, but with no luck.
A: This is an actual bug in mootools 1.4 https://github.com/mootools/mootools-core/issues/2074
Its about to be fixed this week in 1.4.1 (hopefully) but you can take the updated Fx.tween element shortcut protiotypes code for the fade here:
https://github.com/cpojer/mootools-core/commit/11b4257f12a51454bd513ab1ac32cd5239d66098
Alternatively, use a simple tween on opacity instead of .fade(), it allegedly works. You can also do a destroy on the overlay, which to me is the best fix
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Simple table query syntax error? I hope someone here can help me see where this error is coming from.
I have a form with two fields: email and password. The form's action takes it to a php page that is supposed to
*
*start a session
*connect to a database via mysql
*run a query and select a row in a table where the email field is similar to the email
submitted in the form.
At this stage it is incomplete, I only echo some of the fields at the end of the script to
see if it works.
I tested it and there was an unexpected end error that came up right at the last line; a bracket I left out. So I though there would be no other errors, but then when I tested it again I got this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@gmail.com' at line 6
@gmail.com is the last bit of the email I submitted.
Here is the code of the php (action) page:
<?php
session_start();
$_SESSION['sessionemail'] = $_POST['email'];
$_SESSION['sessionpassword'] = $_POST['password'];
$_SESSION['authuser'] = 0;
$dbhost = 'somewhere.com';
$dbuser = 'user';
$dbpass = 'pw';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'medreunten_db1';
mysql_select_db($dbname) or die(mysql_error($conn));
$query = 'SELECT
name, smacker, surname, sex, age, nationality, email
FROM
employee
WHERE
email = ' . $_POST['email'];
$result = mysql_query($query, $conn) or die (mysql_error($conn));
extract(mysql_fetch_assoc($result));
while ($row = mysql_fetch_array($result)) {
echo $row['name'];
echo $row['surname'];
echo $row['age'];
}
?>
I tried removed the first 5 lines and I still got the same error.
Somehow, when the php gets parsed, the browser reads the content of the email variable as if it is part of my php code. At least that's what I thought because the error I receive states that there is a problem with the syntax near "@gmail.com".
I hope someone can give me a clue!
A: You have an SQL injection, always apply mysql_real_escape_string() to any user-submitted or otherwise potentially tampered-with data before sending to a MySQL database.
Note the ' around the email variable.
$email = mysql_real_escape_string($_POST['email']);
$query = "
SELECT name, smacker, surname, sex, age, nationality, email
FROM employee
WHERE email = '$email'
";
A: <?php
session_start();
$_SESSION['sessionemail'] = $_POST['email'];
$_SESSION['sessionpassword'] = $_POST['password'];
$_SESSION['authuser'] = 0;
$dbhost = 'dedi147.cpt2.host-h.net';
$dbuser = 'medreunten_1';
$dbpass = 'AGqrVrs8';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'medreunten_db1';
mysql_select_db($dbname) or die(mysql_error($conn));
$query = "SELECT name, smacker, surname, sex, age, nationality, email FROM employee WHERE email = '" . $_POST['email']."'";
$result = mysql_query($query, $conn) or die (mysql_error($conn));
extract(mysql_fetch_assoc($result));
while ($row = mysql_fetch_array($result)) {
echo $row['name'];
echo $row['surname'];
echo $row['age'];
}
?>
try this, should work
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: I cannot, despite all of the available resources, login to my ssh server without a password So I have my home computer & a server. I want the server to be able to SSH into my home computer w/out a password. I have followed various tutorials and can ssh from home to server with no password. Everything works fine. When I try to reverse the process and ssh from server to home I get a permission denied (publickey) error. I can log in to both machines using a password just fine.
The relevant bits from a verbose attempt are as follows:
debug1: Found key in /root/.ssh/known_hosts:1
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Next authentication method: publickey
debug1: Trying private key: /root/.ssh/identity
debug1: Offering public key: /root/.ssh/id_rsa
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: Trying private key: /root/.ssh/id_dsa
debug1: Next authentication method: keyboard-interactive
debug1: Authentications that can continue: publickey,keyboard-interactive
debug1: No more authentication methods to try.
Permission denied (publickey,keyboard-interactive).
My /etc/ssh/sshd_config file on the home PC looks like this:
# Package generated configuration file
# See the sshd_config(5) manpage for details
# What ports, IPs and protocols we listen for
Port 22
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes
# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 768
# Logging
SyslogFacility AUTH
LogLevel INFO
# Authentication:
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile ~/.ssh/authorized_keys
# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes
# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords yes
# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication yes
# Change to no to disable tunnelled clear text passwords
PasswordAuthentication no
# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no
#MaxStartups 10:30:60
#Banner /etc/issue.net
# Allow client to pass locale environment variables
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication. Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM no
The home PC is running Ubuntu and the server is CentOS.
A: Most of the time if key auth fails its because ssh refused to use the authorized_keys file because of bad perms. It should have logged this to syslog. often /var/log/auth.log , /var/log/syslog or /var/log/messages
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Dynamically expanding a scipy array Is there a way to dynamically expand an scipy array
from scipy import sci
time = sci.zeros((n,1), 'double')
Can we increase the size of time array after this?
A: It's possible to expand arrays using the resize method, but it can be a slow operation for large arrays, so avoid it if possible*.
For example:
import scipy as sci
n=3
time = sci.zeros((n,1), 'double')
print(time)
# [[ 0.]
# [ 0.]
# [ 0.]]
time.resize((n+1,2))
print(time)
# [[ 0. 0.]
# [ 0. 0.]
# [ 0. 0.]
# [ 0. 0.]]
* Instead, figure out how large an array you need from the beginning, and allocate that shape for time only once. In general it is faster to over-allocate than it is to resize.
A: The resulting time array being just a Numpy Array, you can use standard Numpy methods for manipulating them, such as numpy#insert which returns a modified array with new elements inserted into it. Examples usage, from Numpy docs (here np is short for numpy) :
>>> a = np.array([[1, 1], [2, 2], [3, 3]])
>>> a
array([[1, 1],
[2, 2],
[3, 3]])
>>> np.insert(a, 1, 5)
array([1, 5, 1, 2, 2, 3, 3])
>>> np.insert(a, 1, 5, axis=1)
array([[1, 5, 1],
[2, 5, 2],
[3, 5, 3]])
Also, numpy#insert is faster than numpy#resize :
>>> timeit np.insert(time, 1, 1, 1)
100000 loops, best of 3: 16.7 us per loop
>>> timeit np.resize(time, (20,1))
10000 loops, best of 3: 27.1 us per loop
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: GrabCut - bgdModel & fgdModel empty - Assertion error I am attempting image segmentation using GrabCut algorithm in OpenCV2.1 (C++)
Here my code:
Mat rgbWorkImage = imread(argv[1]);
Mat mask;
mask = Scalar(0);
Mat bgdModel, fgdModel;
Rect rect = Rect(Point(0,0), imageSize);
grabCut(rgbWorkImage, mask, rect, bgdModel, fgdModel, 0, GC_INIT_WITH_RECT);
grabCut(rgbWorkImage, mask, rect, bgdModel, fgdModel, 2, GC_EVAL);
Unfortunately I am getting this runtime error:
OpenCV Error: Assertion failed (!bgdSamples.empty() && !fgdSamples.empty()) in initGMMs, file /build/buildd/opencv-2.1.0/src/cv/cvgrabcut.cpp, line 368
terminate called after throwing an instance of 'cv::Exception'
what(): /build/buildd/opencv-2.1.0/src/cv/cvgrabcut.cpp:368: error: (-215) !bgdSamples.empty() && !fgdSamples.empty() in function initGMMs
What am I missing here?
Thanks
A: @alexisdm is right,
my rect was rect = (0,0,img.shape[0],img.shape[1]) because I did not know, where foreground and background is.
The solution is not to cover the entire image by changing it to
rect = (1,1,img.shape[0],img.shape[1]).
A: One case where that error could happen is when your image has zero for either its width or height (but not for both) because of this bug: https://code.ros.org/trac/opencv/ticket/691 (which seems to be fixed after OpenCV 2.1).
If the image dimensions are non zero, you should also check that the ROI rect:
*
*is not empty (imageSize has not a zero size) and
*doesn't cover the entire image.
GC_INIT_WITH_RECT marks all pixels outside the given rect as "background" and all pixels inside the rect as "probably foreground", and the assert expect that there is pixels in both foreground (or "probably foreground") and background (or "probably background") list.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: css: How get rid of this extra white space after and before text? Here's an image:
The HTML is in a php which is as follows:
print "<p class = 'Back'>Epic Fail</p>";
print "<p>You forgot to put in your Username or Password.</p>";
The CSS for the Back class and p is as follows:
p.Back
{
font-size: 200px;
display: block;
text-align: left;
font-style: oblique;
}
p
{
font-size: 20px;
color: #292421;
font-family: Times;
}
This is all wrapped in a div tag that has around 25px padding, why is there so much white space? It's a problem because it creates a scroll bar which I don't want and it doesn't look very good.
EDIT:
Here's the div:
#login
{
background: #E0DFDB;
width: 1200px;
margin: auto;
}
I'm using the latest version of Google Chrome (Sorry for not specifying)
The scroll bar is successfully removed by taking away the padding from the login div and the line-height. However, there is still the white space and I have thoroughly ran through all of my code to see if I've added anything to the p tag but I couldn't find anything. Is there a site where I can upload all of my code to show you guys?
RESULT:
Thanks guys, I decided to use the web dev tool that came with google chrome and IT TURNS OUT: THE MARGIN BY DEFAULT SOMEHOW GOT SET TO 200PX??!! so all I had to do was just set the margin for p to auto
A: This happens because, by default, Chrome applies a style of -webkit-margin-before: 1em; -webkit-margin-after: 1em to p elements. In your example, this would create a 200px margin above and below the element. Setting margin: auto or any other margin value overrides this default.
Other browsers apply a default margin to p elements in different ways: e.g. Firefox applies margin: 1em 0 which results in the same effect.
The margin does not appear on jsfiddle because they employ a reset stylesheet which gives p elements margin: 0.
A: I've created a JSFiddle version of the code you've posted -- see http://jsfiddle.net/RukbS/
In my JSFiddle, I can't see the massive empty space beneath the "Epic Fail" which is in your screenshot, so I guess there's something in the code you're running which you haven't shown us.
Without seeing your code actually in action, it's hard to know what the difference is between it and the version I've created, but looking at the screenshot, it looks very much as if the "Epic Fail" paragraph has run over two lines.
The only way I could get my test to replicate this was by putting <br><br> immediately after the word "Fail". I'm assuming you're not doing that.
You might want to consider dropping the line-height attribute from the stylesheet. It isn't really achieving much (as it will pick up that size anyway due to the font size), and is the sort of thing that might be causing what you're seeing. If you really do want a bit of extra space around the text, use padding or margin instead; it's easier to control than line-height.
You didn't state which browser you're using that shows this effect. It is possible that you're seeing something that only shows up in certain browsers. Most browsers these days come with a good debugging tool which can help isolate issues like this. In Firefox, you'll need to install the Firebug plugin; in most other modern browsers, the Developer Tools feature is built in.
Open the Firebug/Dev Tools window, and use it to find the "Epic Fail" element. It will allows you to examine the size and shape of the element, and what styles are being applied to it. This will almost certainly give you the information you need to work out what the problem is.
I know I haven't given you an answer that directly solves the problem, but I hope some of the things I've pointed out here will lead you in the right direction to finding the problem.
A: Not sure what you are trying to accomplish, but the combination of
*
*padding on the div and
*extra line-height
might be causing the excess.
Right now, your adding
*
*50px from padding (25px on top and bottom)
*50px from line-height (which is 50px more than the font-size)
I tried your current code in a fiddle and it seems to work fine (drag the bar to the left to see the entire screen)
http://jsfiddle.net/jasongennaro/aNRhN/
Perhaps there is other code being inserted with the PHP?
Or you have other styles applied to the p.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Add user generated comments to existing javadoc Our team develops software for BlackBerry devices. The BlackBerry API (javadocs) is poorly documented, and sometimes even outdated.
What we would like to do is import this existing documentation into an online system that could then be edited/commented by developers/users - thus creating a far richer user generated API documentation. Maybe we can even add sample code / references to the appropriate methods.
Is there a simple way for doing the above? Any available commenting systems that can integrate with javadocs?
I have done extensive search for a solution on the internet but couldn't find any available software solution to this problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Yahoo OAuth with gtm-oauth for Mac App Has anyone successfully used gtm-oauth to authenticate to Yahoo for a desktop Mac App? I'm able to authenticate to Twitter using this library and I feel that I've made the appropriate updates for Yahoo OAuth but I consistently get a 401 error when I start the request and the view controller is not shown.
I've updated the values in the OAuthSample project as such:
NSURL *requestURL = [NSURL URLWithString:@"https://api.login.yahoo.com/oauth/v2/get_request_token"];
NSURL *accessURL = [NSURL URLWithString:@"https://api.login.yahoo.com/oauth/v2/get_token"];
NSURL *authorizeURL = [NSURL URLWithString:@"https://api.login.yahoo.com/oauth/v2/request_auth"];
NSString *scope = @"https://api.login.yahoo.com";
Does anyone have any suggestions?
A: Yahoo's OAuth server does not expect display name or scope parameters.
To use GTMOAuth with Yahoo's OAuth 1 server, set the scope and the display name to nil, like
windowController = [[[GTMOAuthWindowController alloc] initWithScope:nil
language:nil
requestTokenURL:requestURL
authorizeTokenURL:authorizeURL
accessTokenURL:accessURL
authentication:auth
appServiceName:kYahooKeychainItemName
resourceBundle:nil] autorelease];
[auth setDisplayName:nil];
Also, be sure that the auth callback URL matches the URL registered with Yahoo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to call Bean classes not in default package Netbeans IDE supports beansbinding and we can call easily a bean in the default package (without instantiating beans can be seen in the Inspector).
But if our UI components (swing) is in another package, and beans are in another package, we have to instantiate those beans in our components (JFrame or JPanel) with getters (and setters). I want to know that, is there a way to call beans without instantiating in our components in NetBeans(Just select the source from the bind property box). (Then we can see those beans in the Inspector of the relevant component (JFrame or JPanel).) In other words, is there a way to place our beans classes in the Inspector.(if our JFrame is in default package and bean is also in Default package, then we can click the bean icon from the pallet and give the relavant bean class,Then we can see that bean class in the Inspector)
A: You can just drag the class on the Projects window to the JPanel you want to put in. It will appear in Inspector.
(If I understand the question :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Question about static variable I have read many documentation about static variables. Here is one example which I didn't understand. Suppose that static variable in a class is declared like this:
class Something
{
public:
static int s_nValue;
};
int Something::s_nValue = 1;
int main()
{
Something::s_nValue = 2;
std::cout << Something::s_nValue;
return 0;
}
My question is: we have declared s_nvalue in class already, and why it is required to redefine it again? If we don't write int before, it will show an error. Why is it so?
A: This is a nature of C++, when you define something you have to specify it's exact type, even if you had a declaration previously. This is true for all variables and functions.
Sidenote: you don't redefine it, that would cause a compilation error. You just define it.
A: In a usual C++ program, your classes are defined in headers that get included by all the source files that use them. So if it worked the way you expect, each source file would have its own copy of that static variable, when in reality they are supposed to all share one copy. This would be a violation of the one-definition-rule... each object can only be defined as existing in one place.
So declaring the variable within the class simply announces to the compiler that somewhere there will be a variable with this name and type; it does not instruct the compiler to allocate space for it. At this point, the variable remains undefined in any source files that include it. Then, within one specific source file [usually the implementation file for that particular class], you provide an actual definition, the int Something::s_nValue; line. That asks the compiler to allocate space for the variable, so that it only exists in that one location and there is no ambiguity when you go to link all your object files together.
A: Declaring something is not the same as defining something. Sometimes you can do both at the same time, but either way you need to both declare and define something.
Why?
Well, because the standard says so, but why does the standard say so?
It has to do with how compiling and linking works. If I have a couple of source files, a.cpp and b.cpp and a couple of header files, a.h and b.h then I'll want to compile them. Generally, you compile all the source files individually to get a.o and b.o and then link them together at the end to get your final program.
Say we had:
// a.h =========================
class A { static int n; };
// b.h =========================
class B { static int n; };
// a.cpp =======================
#include "a.h"
#include "b.h"
int foo() { return A::n + B::n; }
// b.cpp =======================
#include "a.h"
#include "b.h"
int bar() { return A::n - B::n; }
Remember that an #include essentially just pastes the other file inside the including file. So all the compiler sees when we compile a.cpp and b.cpp is:
// a.cpp =======================
class A { static int n; };
class B { static int n; };
int foo() { return A::n + B::n; }
// b.cpp =======================
class A { static int n; };
class B { static int n; };
int bar() { return A::n - B::n; }
Which object file should A::n and B::n go in? a.o or b.o? It's declared in both a.cpp and b.cpp so the compiler has no idea where to put it. If you put it in both then you'll define it twice, and the compiler won't know which to use (in that case, the linker would give you a 'multiply defined symbol' error).
That's why we need a definition. The definition tells us which object file to put it in.
// a.cpp =======================
#include "a.h"
#include "b.h"
int A::n = 0; // A::n goes in a.o
int foo() { return A::n + B::n; }
// b.cpp =======================
#include "a.h"
#include "b.h"
int B::n = 0; // B::n goes in b.o
int bar() { return A::n - B::n; }
It's worth pointing out that you could have put both in a.cpp or both in b.cpp. It doesn't matter, as long as it is defined exactly once.
A: Welcome to the wonderful world of C++: declarations VS. definitions. In the code you posted, there is a declaration and a definition. A declaration gives some symbol a name and a type. A definition gives a symbol a "value".
class Something
{
public:
// declaration.
static int s_nValue;
};
// definition.
int Something::s_nValue = 1;
This process is similar to function prototyping:
// declaration.
void f ( int i );
// definition.
void f ( int i )
{
std::cout << i << std::endl;
// ...
}
To add to the confusion, some statements do both at the same time. For example, if you don't declare a function, the definition also acts as a declaration (this is not possible for static variables, as in the Something::s_nValue case you posted).
A: This is similar to the case in C, where in your header file you would do:
extern int Something_s_nValue;
And you your source file you would do:
int Something_s_nValue;
The first part is the declaration which goes in your header file, and the second part is the definition which goes in your source file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Binding from items of an UserControl with custom collection property This question is a "sequel" to this question (I have applied the answer, but it still won't work).
I'm trying to create an extended ToolBar control for a modular application, which can load its items from multiple data sources (but that is not the issue I'm trying to solve right now, now I want it to work when used as regular ToolBar found in WPF).
In short: I want the ToolBar's items to be able to bind to the tb:ToolBar's parents.
I have following XAML code:
<Window Name="myWindow" DataContext="{Binding ElementName=myWindow}" >
<DockPanel>
<tb:ToolBar Name="toolbar" DockPanel.Dock="Top" DataContext="{Binding ElementName=myWindow}>
<tb:ToolBar.Items>
<tb:ToolBarControl Priority="-3">
<tb:ToolBarControl.Content>
<StackPanel Orientation="Horizontal">
<TextBlock>Maps:</TextBlock>
<ComboBox ItemsSource="{Binding SomeProperty, ElementName=myWindow}">
Some info about the types:
*
*tb:ToolBar is an UserControl with dependency property Items of type FreezableCollection<ToolBarControl>.
*tb:ToolBarControl is an UserControl with template pretty much identical to ContentControl's template.
The problem is that the binding in the ComboBox fails (with the usual "Cannot find source for binding with reference"), because its DataContext is null.
Why?
EDIT: The core of the question is "Why is the DataContext not inherited?", without it, the bindings can't work.
EDIT2:
Here is XAML for the tb:ToolBar:
<UserControl ... Name="toolBarControl">
<ToolBarTray>
<ToolBar ItemsSource="{Binding Items, ElementName=toolBarControl}" Name="toolBar" ToolBarTray.IsLocked="True" VerticalAlignment="Top" Height="26">
EDIT 3:
I posted an example of what works and what doesn't: http://pastebin.com/Tyt1Xtvg
Thanks for your answers.
A: I personally don't like the idea of setting DataContext in controls. I think doing this will somehow break the data context inheritance. Please take a look at this post. I think Simon explained it pretty well.
At least, try removing
DataContext="{Binding ElementName=myWindow}"
from
<tb:ToolBar Name="toolbar" DockPanel.Dock="Top" DataContext="{Binding ElementName=myWindow}>
and see how it goes.
UPDATE
Actually, keep all your existing code (ignore my previous suggestion for a moment), just change
<ComboBox ItemsSource="{Binding SomeProperty, ElementName=myWindow}">
to
<ComboBox ItemsSource="{Binding DataContext.SomeProperty}">
and see if it works.
I think because of the way you structure your controls, the ComboBox is at the same level/scope as the tb:ToolBarControl and the tb:ToolBar. That means they all share the same DataContext, so you don't really need any ElementName binding or RelativeSource binding to try to find its parent/ancestor.
If you remove DataContext="{Binding ElementName=myWindow} from the tb:ToolBar, you can even get rid of the prefix DataContext in the binding. And this is really all you need.
<ComboBox ItemsSource="{Binding SomeProperty}">
UPDATE 2 to answer your Edit 3
This is because your Items collection in your tb:ToolBar usercontrol is just a property. It's not in the logical and visual tree, and I believe ElementName binding uses logical tree.
That's why it is not working.
Add to logical tree
I think to add the Items into the logical tree you need to do two things.
First you need to override the LogicalChildren in your tb:ToolBar usercontrol.
protected override System.Collections.IEnumerator LogicalChildren
{
get
{
if (Items.Count == 0)
{
yield break;
}
foreach (var item in Items)
{
yield return item;
}
}
}
Then whenever you added a new tb:ToolBarControl you need to call
AddLogicalChild(item);
Give it a shot.
This WORKS...
After playing around with it a little bit, I think what I showed you above isn't enough. You will also need to add these ToolBarControls to your main window's name scope to enable ElementName binding. I assume this is how you defined your Items dependency property.
public static DependencyProperty ItemsProperty =
DependencyProperty.Register("Items",
typeof(ToolBarControlCollection),
typeof(ToolBar),
new FrameworkPropertyMetadata(new ToolBarControlCollection(), Callback));
In the callback, it is where you add it to the name scope.
private static void Callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var toolbar = (ToolBar)d;
var items = toolbar.Items;
foreach (var item in items)
{
// the panel that contains your ToolBar usercontrol, in the code that you provided it is a DockPanel
var panel = (Panel)toolbar.Parent;
// your main window
var window = panel.Parent;
// add this ToolBarControl to the main window's name scope
NameScope.SetNameScope(item, NameScope.GetNameScope(window));
// ** not needed if you only want ElementName binding **
// this enables bubbling (navigating up) in the visual tree
//toolbar.AddLogicalChild(item);
}
}
Also if you want property inheritance, you will need
// ** not needed if you only want ElementName binding **
// this enables tunneling (navigating down) in the visual tree, e.g. property inheritance
//protected override System.Collections.IEnumerator LogicalChildren
//{
// get
// {
// if (Items.Count == 0)
// {
// yield break;
// }
// foreach (var item in Items)
// {
// yield return item;
// }
// }
//}
I have tested the code and it works fine.
A: I took the pieces of Xaml that you posted and tried to reproduce your problem.
The DataContext seems to be inheriting just fine from what I can tell. However, ElementName Bindings fail and I think this has to do with the fact that even though you add the ComboBox in the Window, it ends up in a different scope. (It is first added to the Items property of the custom ToolBar and is then populated to the framework ToolBar with a Binding)
A RelativeSource Binding instead of an ElementName Binding seems to be working fine.
But if you really want to use the name of the control in the Binding, then you could check out Dr.WPF's excellent ObjectReference implementation
It would look something like this
<Window ...
tb:ObjectReference.Declaration="{tb:ObjectReference myWindow}">
<!--...-->
<ComboBox ItemsSource="{Binding Path=SomeProperty,
Source={tb:ObjectReference myWindow}}"
I uploaded a small sample project where both RelativeSource and ObjectReference are succesfully used here: https://www.dropbox.com/s/tx5vdqlm8mywgzw/ToolBarTest.zip?dl=0
The custom ToolBar part as I approximated it looks like this in the Window.
ElementName Binding fails but RelativeSource and ObjectReference Bindings work
<Window ...
Name="myWindow"
tb:ObjectReference.Declaration="{tb:ObjectReference myWindow}">
<!--...-->
<tb:ToolBar x:Name="toolbar"
DockPanel.Dock="Top"
DataContext="{Binding ElementName=myWindow}">
<tb:ToolBar.Items>
<tb:ContentControlCollection>
<ContentControl>
<ContentControl.Content>
<StackPanel Orientation="Horizontal">
<TextBlock>Maps:</TextBlock>
<ComboBox ItemsSource="{Binding Path=StringList,
ElementName=myWindow}"
SelectedIndex="0"/>
<ComboBox ItemsSource="{Binding Path=StringList,
Source={tb:ObjectReference myWindow}}"
SelectedIndex="0"/>
<ComboBox ItemsSource="{Binding Path=StringList,
RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
SelectedIndex="0"/>
</StackPanel>
</ContentControl.Content>
</ContentControl>
</tb:ContentControlCollection>
</tb:ToolBar.Items>
</tb:ToolBar>
A: Often if there is no DataContext then ElementName will not work either. One thing which you can try if the situation allows it is using x:Reference.
For that you need to move the bound control into the resources of the referenced control, change the binding and use StaticResource in the place where it was, e.g.
<Window Name="myWindow" DataContext="{Binding ElementName=myWindow}" >
<Window.Resources>
<ComboBox x:Key="cb"
ItemsSource="{Binding SomeProperty,
Source={x:Reference myWindow}}"/>
</Window.Resources>
<DockPanel>
<tb:ToolBar Name="toolbar" DockPanel.Dock="Top" DataContext="{Binding ElementName=myWindow}>
<tb:ToolBar.Items>
<tb:ToolBarControl Priority="-3">
<tb:ToolBarControl.Content>
<StackPanel Orientation="Horizontal">
<TextBlock>Maps:</TextBlock>
<StaticResource ResourceKey="cb"/>
A: The proper answer is probably to add everything to the logical tree as mentioned in previous answers, but the following code has proved to be convenient for me. I can't post all the code I have, but...
Write your own Binding MarkupExtension that gets you back to the root element of your XAML file. This code was not compiled as I hacked up my real code to post this.
[MarkupExtensionReturnType(typeof(object))]
public class RootBindingExtension : MarkupExtension
{
public string Path { get; set; }
public RootElementBinding(string path)
{
Path = path;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
IRootObjectProvider rootObjectProvider =
(IRootObjectProvider)serviceProvider.GetService(typeof(IRootObjectProvider));
Binding binding = new Binding(this.Path);
binding.Source = rootObjectProvider.RootObject;
// Return raw binding if we are in a non-DP object, like a Style
if (service.TargetObject is DependencyObject == false)
return binding;
// Otherwise, return what a normal binding would
object providedValue = binding.ProvideValue(serviceProvider);
return providedValue;
}
}
Usage:
<ComboBox ItemsSource={myBindings:RootBinding DataContext.SomeProperty} />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: box2d with custom polygon crashes I created a polygon which has 5 vertices, and all vertices are generated by VertexHelper.
Why does the program get SIGABRT at b2Assert(area > b2_epsilon) in ComputeCentroid() in b2PolygonShape.cpp?
The program runs well when I use shape.SetAsBox(.359375, 1.0) instead of shape.Set(vertices, count).
It seems that somethings wrong during calculating centroid when shape.Set() is used, but I don't know how to deal with this problem.
Here's the code:
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.awake = NO;
bodyDef.position.Set(3.125, 3.125);
bodyDef.angle = -.785398163397;
spriteBody = world->CreateBody(&bodyDef);
spriteBody->SetUserData(sprite);
b2MassData massData = {2.0, b2Vec2(0.021875, 0.203125), 0.0};
spriteBody->SetMassData(&massData);
int32 count = 5;
b2Vec2 vertices[] = {
b2Vec2(-11.5f / PTM_RATIO, -16.0f / PTM_RATIO),
b2Vec2(-10.5f / PTM_RATIO, 15.0f / PTM_RATIO),
b2Vec2(10.5f / PTM_RATIO, 15.0f / PTM_RATIO),
b2Vec2(10.5f / PTM_RATIO, -5.0f / PTM_RATIO),
b2Vec2(-5.5f / PTM_RATIO, -16.0f / PTM_RATIO)
};
b2PolygonShape shape;
shape.Set(vertices, count);
b2FixtureDef fixtureDef;
fixtureDef.shape = &shape;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.2f;
fixtureDef.restitution = 0.7f;
spriteBody->CreateFixture(&fixtureDef);
A: It looks like you've wound your vertices the wrong way. I think they should be anticlockwise in box2d, at least by default.
You're assertion will be failing because the calculation for area will be returning a negative value, far less than b2_epsilon
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C++ Winsock unicode problem I have just converted a program that uses winsock to unicode, and im running into a problem.
Here's my code, well part of it
TCHAR http_request[MAX_REQUEST_LEN];
TCHAR data[65536];
int nDataLen = 0;
/* Create http_request */
send(mySocket, (char*)http_request, lstrlen(http_request), 0)
nDataLen = recv(mySocket, (char*)data, 65536, 0);
I'm pretty sure casting data to a char* is causing the problem, thought i'm not completely sure.
There's no sendW or recvW so i'm wondering how i'm supposed to do this.
EDIT:
It's not crashing anymore thanks to Grim.
But now I've another problem, i've got this code but its returning ERROR_INVALID_PARAMETER
TCHAR http_request[MAX_REQUEST_LEN];
char ansi_data[65536];
TCHAR data[65536];
int nDataLen = 0;
/* Create http_request */
send(mySocket, (char*)http_request, lstrlen(http_request) * sizeof(TCHAR), 0);
nDataLen = recv(mySocket, ansi_data, 65536, 0);
// Convert ansi_data to data, this is what causes the error
if (MultiByteToWideChar(CP_ACP, 0, ansi_data, nDataLen, data, 65536) == 0)
ErrorExit(GetLastError());
A: The main problem is that you are mixing up different concepts.
To get the correct program you have to know what you are doing instead of mechanically replace "char" with "TCHAR" in your entire code.
Your internal string representation and the data you are sending over the network is totally different things.
How you represent text data internally is your choice (whether it is ANSI or UNICODE16 or UTF-8 or whatever) and any choice is OK when you implement it consistently.
But the data you are sending over the network is totally different thing - its format is defined by the protocol you are using. Of course recv function does not convert between character codings - it just sends data buffer over the network (as TCP connection data stream if you are using TCP socket). If you are sending HTTP request (as your variable name implies) then you have to use chars (not TCHARs) because HTTP protocol uses ANSI characters.
A: You are probably having a problem with your send statement. send() expects the 3rd parameter to be size in bytes, you are giving it characters. While this works fine for ANSI strings (sizeof(char) == 1) it won't work correctly for UNICODE.
sizeof(wchar_t) == 2
The correct code should look like this:
send(mySocket, (char*)http_request, lstrlen(http_request)*sizeof(http_request[0]), 0);
A: You can't interchange char and TCHAR types, that would cause a problem. You either need to declare data as an array of char, or change recv to use TCHAR.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Message order in Gmail boxes I wrote a simple script in python using imaplib to download gmail messages from a given box (or a label which behaves like a box). Since some boxes contain very large number of messages, my script allows to download only those numered within an interval like 100-200, so that I can resume downloading as some later time.
My question is whether it is guaranteed that the message order within the box as provided by IMAP is always the same (chronological order). My tests seem to support this conclusion by I would like to be sure.
-- tsf
A: The IMAP RFC states:
Unique identifiers are assigned in a strictly ascending fashion in the
mailbox; as each message is added to the mailbox it is assigned a
higher UID than the message(s) which were added previously.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Entity Framework trying to retrieve non existent column
I'm trying to retrieve the VideoCollection items from the database, but getting {"Invalid column name 'User_Id'."} - when I set a breakpoint I can see that the EF is trying to select User_Id column but it doesn't exist in the Cs object or the database schema. (It does exist in another table but that shouldn't matter). Is there anyway to debug why this is happening?
A: Do you have a User class that has a reference to a VideoCollection? If so, you probably need to explicitly define the relationship between the two. As it is, it looks like EF is inferring that the VideoCollection should contain a foreign key, User_Id that defines the relationship.
A: may be you have inherit your base class in another.. check it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Live 'required fields' with labels inside of the inputs Basically what I'm trying to do is to write inside of the inputs something like "Field is Required" after the first time they press inside or when they try to submit.
I want it to show directly after they press somewhere else or submit without any refreshes.
So basically i need a suggestion for some lines of code (I want it to be the simplest and light-weight it can be) or maybe a suggestion for some kind of little plugin without too much options in it, all the stuff i found on Google made me totally mad cause all of them has too many functions and stuff i don't need...
Thanks!
A: With HTML5 you can specify a "placeholder text" inside the input tags:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Makes the search field have that greyed out text that disappears when you click on it.
Source: http://diveintohtml5.ep.io/forms.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to send a struct through socket? I found the following function, which can send a mail :
bool sendmail( char * smtpserver, char * from, char * to, char * subject, char * msg )
{
int iProtocolPort = 0;
char szSmtpServerName[64] = "";
char szToAddr[64] = "";
char szFromAddr[64] = "";
char szBuffer[4096] = "";
char szLine[255] = "";
char szMsgLine[255] = "";
SOCKET hServer;
WSADATA WSData;
LPHOSTENT lpHostEntry;
LPSERVENT lpServEntry;
SOCKADDR_IN SockAddr;
// Load command-line args
lstrcpyA( szSmtpServerName, smtpserver );
lstrcpyA( szToAddr, to );
lstrcpyA( szFromAddr, from );
// Attempt to intialize WinSock (1.1 or later)
if ( WSAStartup( MAKEWORD( VERSION_MAJOR, VERSION_MINOR ), &WSData ) )
{
printf( "\nCannot find Winsock v%d.%d or later", VERSION_MAJOR, VERSION_MAJOR );
return false;
}
// Lookup email server's IP address.
lpHostEntry = gethostbyname( szSmtpServerName );
if ( !lpHostEntry )
{
printf( "\nCannot find SMTP mail server %s", szSmtpServerName );
return false;
}
// Create a TCP/IP socket, no specific protocol
hServer = socket( PF_INET, SOCK_STREAM, 0 );
if ( hServer == INVALID_SOCKET )
{
printf( "\nCannot open mail server socket!" );
return false;
}
// Get the mail service port
lpServEntry = getservbyname( "mail", 0 );
// Use the SMTP default port if no other port is specified
if ( !lpServEntry ) iProtocolPort = htons( IPPORT_SMTP );
else iProtocolPort = lpServEntry->s_port;
// Setup a Socket Address structure
SockAddr.sin_family = AF_INET;
SockAddr.sin_port = iProtocolPort;
SockAddr.sin_addr = *( (LPIN_ADDR)*lpHostEntry->h_addr_list );
// Connect the Socket
if ( connect( hServer, ( PSOCKADDR ) &SockAddr, sizeof( SockAddr ) ) )
{
printf( "\nError connecting to Server socket!" );
return false;
}
// Receive initial response from SMTP server
Check( recv( hServer, szBuffer, sizeof( szBuffer ), 0), "recv() Reply" );
// Send HELO server.com
sprintf_s( szMsgLine, "HELO %s%s", smtpserver, CRLF );
Check( send( hServer, szMsgLine, strlen( szMsgLine ), 0 ), "send() HELO" );
Check( recv( hServer, szBuffer, sizeof( szBuffer ), 0 ), "recv() HELO" );
// Send MAIL FROM: <sender@mydomain.com>
sprintf_s( szMsgLine, "MAIL FROM:<%s>%s", from, CRLF );
Check( send( hServer, szMsgLine, strlen( szMsgLine ), 0 ), "send() MAIL FROM" );
Check( recv( hServer, szBuffer, sizeof( szBuffer ), 0 ), "recv() MAIL FROM" );
// Send RCPT TO: <receiver@domain.com>
sprintf_s( szMsgLine, "RCPT TO:<%s>%s", to, CRLF );
Check( send( hServer, szMsgLine, strlen( szMsgLine ), 0 ), "send() RCPT TO" );
Check( recv( hServer, szBuffer, sizeof( szBuffer ), 0 ), "recv() RCPT TO" );
// Send DATA
sprintf_s( szMsgLine, "DATA%s", CRLF );
Check( send( hServer, szMsgLine, strlen( szMsgLine ), 0 ), "send() DATA" );
Check( recv( hServer, szBuffer, sizeof( szBuffer ), 0 ), "recv() DATA" );
// Send Subject
sprintf_s( szBuffer, "Subject: %s\n", subject );
Check( send( hServer, szBuffer, strlen( szBuffer ), 0 ), "send() Subject" );
//Send From
sprintf_s( szBuffer, "From: %s\n", from );
Check( send( hServer, szBuffer, strlen( szBuffer ), 0 ), "send() From" );
//Send To
sprintf_s( szBuffer, "To: %s\n\n", to );
Check( send( hServer, szBuffer, strlen( szBuffer ), 0 ), "send() To" );
//Check( send( hServer, szMsgLine, strlen( szMsgLine ), 0 ), "send() Attachment" );
sprintf_s( szMsgLine, "%s%s", msg, CRLF );
Check( send( hServer, szMsgLine, strlen( szMsgLine ), 0 ), "send() message-line" );
// Send blank line and a period
sprintf_s( szMsgLine, "%s.%s", CRLF, CRLF );
Check( send( hServer, szMsgLine, strlen( szMsgLine ), 0 ), "send() end-message" );
Check( recv( hServer, szBuffer, sizeof( szBuffer ), 0 ), "recv() end-message" );
// Send QUIT
sprintf_s( szMsgLine, "QUIT%s", CRLF );
Check( send( hServer, szMsgLine, strlen( szMsgLine ), 0 ), "send() QUIT" );
Check( recv( hServer, szBuffer, sizeof( szBuffer ), 0 ), "recv() QUIT" );
// Close server socket and prepare to exit.
closesocket( hServer );
WSACleanup();
return true;
}
I am making an SQL query, and i would like to send the result in an email, but the result can be more than one line. So i don't know, how could i send the whole result at once. The result of the SQL query will be stored in a struct( but if someone has a better a idee then i'm listening :) ). So my question is, if is there a way to send this struct in email? Or how can i send every line which i get as a result in an email?
Thanks!
A: At the side you would like to send your structure:
// All sorts of initializations and stuff
memcpy(yourbuffer,&yourstructure,sizeof(yourbuffer));
At the other side:
// Trivial stuff like receiving your buffer :-)
memcpy(&yourstructure,yourbuffer,sizeof(yourstructure));
A: To answer your first question, if you want to send a struct through a socket, first you have to serialize it. In particular, the bytes of integers may not be in the same order on the destination machine. There are lots of protocols for serializing data such as ASN.1 and JSON. For C structs you would be better using something like msgpack or protobufs. After serializing the data, you have a byte array which can simple be sent through the socket one chunk at a time. Generally, you would also have a protocol wrapped around that which could be as simple as:
SENDBUF 437\r\n
GSUOHD*)*IHENHD{@DNJDPOJDPJONK:ND{D@O LDK?ND(G(OBDO*U|GR(G(DIU:OBD
Basically it is a command string, followed by the number of bytes in this packet followed by carriage return, linefeed. This is a typical protocol style used by HTTP, memcache and many others. After the linefeed character, you would collect the next n bytes (437 in the example) at the end of your input buffer. Since many structs would be more than one packet you could have BEGIN and END commands, or you could simply close the socket to mark the end of a struct.
The receiving process would collect bytes until the end of the struct, then deserialize it.
If you use a library like ZeroMQ, that will simplify the socket handling, but you would still have to deal with serializing and deserializing structs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: rails 3.1 dynamic controller instantiation I have a Rails Engine gem in which I want to load a HomeController class definition dynamically from an initializer. I can instantiate the class correctly, but when I go to call the index action, I get this error :
TypeError in HomeController#index
can't convert nil into String
Rails.root: /home/chris/test_app
Full Trace:
actionpack (3.1.0) lib/action_view/template/resolver.rb:16:in `<<'
actionpack (3.1.0) lib/action_view/template/resolver.rb:16:in `build'
actionpack (3.1.0) lib/action_view/template/resolver.rb:127:in `find_templates'
actionpack (3.1.0) lib/action_view/template/resolver.rb:45:in `find_all'
actionpack (3.1.0) lib/action_view/template/resolver.rb:76:in `cached'
actionpack (3.1.0) lib/action_view/template/resolver.rb:44:in `find_all'
actionpack (3.1.0) lib/action_view/path_set.rb:21:in `find_all'
actionpack (3.1.0) lib/action_view/path_set.rb:20:in `each'
actionpack (3.1.0) lib/action_view/path_set.rb:20:in `find_all'
actionpack (3.1.0) lib/action_view/path_set.rb:19:in `each'
actionpack (3.1.0) lib/action_view/path_set.rb:19:in `find_all'
actionpack (3.1.0) lib/action_view/path_set.rb:29:in `exists?'
actionpack (3.1.0) lib/action_view/lookup_context.rb:94:in `template_exists?'
I cut the trace off after the actionpack part because it was really long, but I think this is all the relevant information.
Here is my Engine class definition:
module MyGem
class Engine < Rails::Engine
initializer 'my_gem.load_middleware' do |app|
home_controller = create_controller 'HomeController'
end
def create_controller(class_name, &block)
klass = Class.new ApplicationController, &block
Object.const_set class_name, klass
return klass
end
end
end
this is when i have the root path set to home#index . if I create a home_controller.rb in app/controllers in either the application or the gem like so:
class HomeController < ApplicationController
end
then everything works fine and the index action is rendered appropriately, so I'm sure there is no problem with my routes, views, or application controller.
Any light shed on this issue would be much appreciated.
edit
the output of
HomeController.view_paths.join " : "
is
/home/chris/gems/my_gem/app/views : /home/chris/test_app/app/views
A: I'm not sure where you get the DSL "initializer" from... but that seems to cause a problem. It doesn't get executed on new()
This seems to work for me in Rails 3.0.7:
module MyGem
class Engine < Rails::Engine
def initialize
home_controller = create_controller 'HomeController'
end
# this doesn't seem to do anything...
#
# initializer 'my_gem.load_middleware' do |app|
# home_controller = create_controller 'HomeController'
# end
def create_controller(class_name, &block)
klass = Class.new ApplicationController::Base , &block # shouldn't this be ApplicationController::Base ?
# Object.const_set class_name, klass # module of superclass is ApplicationController, not Object
ApplicationController.const_set(class_name, klass) # name of the module containing superclass
puts "Klass created! : #{Object.constants}"
return klass
end
end
end
and running the code:
h = MyGem::Engine.new
Klass created! : [:Object, :Module, :Class, :Kernel, :NilClass, :NIL, :Data, :TrueClass, :TRUE, :FalseClass, :FALSE, :Encoding ... :BasicObject]
=> #<MyGem::Engine:0x00000006de9878>
> ApplicationController.const_get("HomeController")
=> ApplicationController::HomeController
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Zend_Framework Decorators Wrap Label and ViewHelper inside a div I am new to this, zend decoration malarchy, but i have two significant questions that i cant get my head around. Question one is followed by some example
$decorate = array(
array('ViewHelper'),
array('Description'),
array('Errors', array('class'=>'error')),
array('Label', array('tag'=>'div', 'separator'=>' ')),
array('HtmlTag', array('tag' => 'li', 'class'=>'element')),
);
...
$name = new Zend_Form_Element_Text('title');
$name->setLabel('Title')
->setDescription("No --- way");
$name->setDecorator($decorate);
Which outputs
<li class="element">
<label for="title" class="required">Title</label>
<input type="text" name="title" id="title" value="">
<p class="hint">No --- way</p>
<ul class="error">
<li>Value is required and can't be empty</li>
</ul>
</li>
The Question #1
How do i wrap the label and the input around a div tag? So the output is as follows:
<li class="element">
<div>
<label for="title" class="required">Title</label>
<input type="text" name="title" id="title" value="">
</div>
<p class="hint">No --- way</p>
<ul class="error">
<li>Value is required and can't be empty</li>
</ul>
</li>
The Question #2
What is up with the order of the elements in the $decorate array? They MAKE NO SENSE!
A: The decorator pattern is a design pattern for adding functionality to existing classes without altering those existing classes. In stead, a decorator class wraps itself around another class, and generally exposes the same interface as the decorated class.
Basic example:
interface Renderable
{
public function render();
}
class HelloWorld
implements Renderable
{
public function render()
{
return 'Hello world!';
}
}
class BoldDecorator
implements Renderable
{
protected $_decoratee;
public function __construct( Renderable $decoratee )
{
$this->_decoratee = $decoratee;
}
public function render()
{
return '<b>' . $this->_decoratee->render() . '</b>';
}
}
// wrapping (decorating) HelloWorld in a BoldDecorator
$decorator = new BoldDecorator( new HelloWorld() );
echo $decorator->render();
// will output
<b>Hello world!</b>
Now, you might be tempted to think that because the Zend_Form_Decorator_* classes are decorators, and have a render method, this automatically means the output of the decorated class' render method will always be wrapped with additional content by the decorator. But on inspection of our basic example above, we can easily see this doesn't necessarily have to be the case at all of course, as illustrated by this additional (albeit fairly useless) example:
class DivDecorator
implements Renderable
{
const PREPEND = 'prepend';
const APPEND = 'append';
const WRAP = 'wrap';
protected $_placement;
protected $_decoratee;
public function __construct( Renderable $decoratee, $placement = self::WRAP )
{
$this->_decoratee = $decoratee;
$this->_placement = $placement;
}
public function render()
{
$content = $this->_decoratee->render();
switch( $this->_placement )
{
case self::PREPEND:
$content = '<div></div>' . $content;
break;
case self::APPEND:
$content = $content . '<div></div>';
break;
case self::WRAP:
default:
$content = '<div>' . $content . '</div>';
}
return $content;
}
}
// wrapping (decorating) HelloWorld in a BoldDecorator and a DivDecorator (with DivDecorator::APPEND)
$decorator = new DivDecorator( new BoldDecorator( new HelloWorld() ), DivDecorator::APPEND );
echo $decorator->render();
// will output
<b>Hello world!</b><div></div>
This is in fact basically how a lot of Zend_Form_Decorator_* decorators work, if it makes sense for them to have this placement functionality.
For decorators where it makes sense, you can control the placement with the setOption( 'placement', 'append' ) for instance, or by passing the option 'placement' => 'append' to the options array, for instance.
For Zend_Form_Decorator_PrepareElements, for instance, this placement option is useless and therefor ignored, as it prepares form elements to be used by a ViewScript decorator, making it one of the decorators that doesn't touch the rendered content of the decorated element.
Depending on the default functionality of the individual decorators, either the content of the decorated class is wrapped, appended, prepended, discarded or something completely different is done to the decorated class, without adding something directly to the content, before passing along the content to the next decorator. Consider this simple example:
class ErrorClassDecorator
implements Renderable
{
protected $_decoratee;
public function __construct( Renderable $decoratee )
{
$this->_decoratee = $decoratee;
}
public function render()
{
// imagine the following two fictional methods
if( $this->_decoratee->hasErrors() )
{
$this->_decoratee->setAttribute( 'class', 'errors' );
}
// we didn't touch the rendered content, we just set the css class to 'errors' above
return $this->_decoratee->render();
}
}
// wrapping (decorating) HelloWorld in a BoldDecorator and an ErrorClassDecorator
$decorator = new ErrorClassDecorator( new BoldDecorator( new HelloWorld() ) );
echo $decorator->render();
// might output something like
<b class="errors">Hello world!</b>
Now, when you set the decorators for a Zend_Form_Element_* element, they will be wrapped, and consequently executed, in the order in which they are added. So, going by your example:
$decorate = array(
array('ViewHelper'),
array('Description'),
array('Errors', array('class'=>'error')),
array('Label', array('tag'=>'div', 'separator'=>' ')),
array('HtmlTag', array('tag' => 'li', 'class'=>'element')),
);
... basically what happens is the following (actual class names truncated for brevity):
$decorator = new HtmlTag( new Label( new Errors( new Description( new ViewHelper() ) ) ) );
echo $decorator->render();
So, on examining your example output, we should be able to distill the default placement behaviour of the individual decorators:
// ViewHelper->render()
<input type="text" name="title" id="title" value="">
// Description->render()
<input type="text" name="title" id="title" value="">
<p class="hint">No --- way</p> // placement: append
// Errors->render()
<input type="text" name="title" id="title" value="">
<p class="hint">No --- way</p>
<ul class="error"> // placement: append
<li>Value is required and cant be empty</li>
</ul>
// Label->render()
<label for="title" class="required">Title</label> // placement: prepend
<input type="text" name="title" id="title" value="">
<p class="hint">No --- way</p>
<ul class="error">
<li>Value is required and cant be empty</li>
</ul>
// HtmlTag->render()
<li class="element"> // placement: wrap
<label for="title" class="required">Title</label>
<input type="text" name="title" id="title" value="">
<p class="hint">No --- way</p>
<ul class="error">
<li>Value is required and cant be empty</li>
</ul>
</li>
And what do you know; this actually is the default placement of all respective decorators.
But now comes the hard part, what do we need to do to get the result you are looking for? In order to wrap the label and input we can't simply do this:
$decorate = array(
array('ViewHelper'),
array('Description'),
array('Errors', array('class'=>'error')),
array('Label', array('tag'=>'div', 'separator'=>' ')),
array('HtmlTag', array('tag' => 'div')), // default placement: wrap
array('HtmlTag', array('tag' => 'li', 'class'=>'element')),
);
... as this will wrap all preceding content (ViewHelper, Description, Errors and Label) with a div, right? Not even... the added decorator will be replaced by the next one, as decorators are replaced by a following decorator if it is of the same class. In stead you would have to give it a unique key:
$decorate = array(
array('ViewHelper'),
array('Description'),
array('Errors', array('class'=>'error')),
array('Label', array('tag'=>'div', 'separator'=>' ')),
array(array('divWrapper' => 'HtmlTag'), array('tag' => 'div')), // we'll call it divWrapper
array('HtmlTag', array('tag' => 'li', 'class'=>'element')),
);
Now, we're still faced with the problem that divWrapper will wrap all preceding content (ViewHelper, Description, Errors and Label). So we need to be creative here. There's numerous ways to achieve what we want. I'll give one example, that probably is the easiest:
$decorate = array(
array('ViewHelper'),
array('Label', array('tag'=>'div', 'separator'=>' ')), // default placement: prepend
array(array('divWrapper' => 'HtmlTag'), array('tag' => 'div')), // default placement: wrap
array('Description'), // default placement: append
array('Errors', array('class'=>'error')), // default placement: append
array('HtmlTag', array('tag' => 'li', 'class'=>'element')), // default placement: wrap
);
For more explanation about Zend_Form decorators I'd recommend reading Zend Framework's lead developer Matthew Weier O'Phinney's article about Zend Form Decorators
A: Question #1
Change the decorators order and add an HtmlTag helper this way :
$decorate = array(
array('ViewHelper'),
array('Label', array('tag'=>'div', 'separator'=>' ')),
array('HtmlTag', array('tag' => 'div')),
array('Description'),
array('Errors', array('class'=>'error')),
array('HtmlTag', array('tag' => 'li', 'class'=>'element'))
);
Question #2
Decorators are a chain, the output of each one is passed to the input of the next one, in order to be 'decorated' by it.
By default, they append content (description, errors), prepend content (label..) and or wrap something around (HtmlTag). But these are default behaviors, and you can change it for most of them :
array('HtmlTag', array('tag' => 'span', placement=>'APPEND'));
//this would append <span></span> to the output of the previous decorator instead of wrapping it inside the <span>
Let's have a more closer look to what happens in your chain :
*
*ViewHelper renders your form element using it's default viewHelper, declared in the form element's class.
*Label prepends the label to the previous output
*HtmlTag wraps a <div> around
*Description appends the elements description
*Errors appends error messages, if any
*HtmlTag wraps all this in an <li>
EDIT
I wrote this answer without testing anything, so there might be some little inaccuracies here and there. Dear reader, if you see some just drop a comment and i'll update.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: jQuery - Apply CSS to div1 if div2 contains a certain word of text? With jQuery how can I apply css to a div, if another div contains a certain word?
So if div1 contains the text 'TriggerWord', I want div 2 to become red. Below is my attempt.
Thanks
$("document").ready(function () {
if ($("#div1:contains('TriggerWord')")) {
$('#div2').css('color','red');
}
});
A: Don't quote document. Other than that your attempt is correct. The :contains() selector is what you need:
$(document).ready(function() {
if ($('#div1:contains("TriggerWord")').length > 0) {
$('#div2').css('color', 'red');
}
});
or with the shorthand form:
$(function() {
if ($('#div1:contains("TriggerWord")').length > 0) {
$('#div2').css('color', 'red');
}
});
And here's a live demo.
A: $(document).ready(function () {
if ($("#div1").html().indexOf('TriggerWord') >= 0) {
$('#div2').css('color', 'red');
}
});
A: Regex method:
$(function() {
var reg = /Trigger/g;
if($('#div1').text().match(reg)) {
$('#div2').css({color: 'red'});
}
});
Working fiddle: http://jsfiddle.net/each/NJ966/
A: $(function() {
if (/triggerWord/.test($("div1").text()) {
$("div2").css('color', 'red');
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: A good drawing library for Java that uses Jogl (and it is not Java2D) I was wondering if there is a rasterization library (like Cairo is for C) written in Java, that uses Jogl as it's backend.
A: GLG2D does pretty much what you want. You can draw using the Java2D API, specifically Graphics2D, and the rendering is done with OpenGL.
Alternatively, just use JOGL if you have the opportunity to build the application from scratch.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Issue when running in a android google API (2.2 platform) New to android development, be gentle haha. I am wanting to populate a spinner with data from my SQLite database. I have a table that is pre-populated and am able to query it successfully. Problem is that I am able to populate the spinner when running it in my emulater (android 2.2) but not able to run it on my portable devices (tablet and phone) (running android 2.2). I get a generic error message saying that: "applilcation...(app name)...has stopped unexpectedly. Please try again." However, I did notice that in my emulator it works beautifully with the build path being set to "Android 2.2" and yet when I change it to the Google API (2.2 platform), I then encounter it. Am I missing somthing? here is the code being used to populate the spinner control:
final DBAdapter db = new DBAdapter(this);
db.open();
Cursor c = db.getAllStates();
startManagingCursor(c);
String[] columns = new String[]{DBAdapter.KEY_STATE_NAME};
int[] to = new int []{android.R.id.text1};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, columns, to);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//get reference to the spinner...
Spinner s =(Spinner) findViewById(R.id.spinner_state);
s.setAdapter(adapter);
db.close();
Here is my code to get the data:
public Cursor getAllStates()
{
Cursor c = null;
c = db.query(DATABASE_TABLE_STATE, new String[] { KEY_STATE_ID, KEY_STATE_NAME }, null, null, null, null, null);
//c = db.rawQuery("select * from tblStates", null);
return c;
}
LocCat:
: INFO/Database(305): sqlite returned: error code = 1, msg = no such table: tblStates
: DEBUG/AndroidRuntime(305): Shutting down VM
: WARN/dalvikvm(305): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
: ERROR/AndroidRuntime(305): FATAL EXCEPTION: main
: ERROR/AndroidRuntime(305): java.lang.RuntimeException: Unable to start activity ComponentInfo{king.chad.SDE/king.chad.SDE.BuildingAddressActivity}
: android.database.sqlite.SQLiteException: no such table: tblStates: , while compiling: SELECT _id, stateName FROM tblStates
: ERROR/AndroidRuntime(305): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
A: ...after much searching and hair pulling I inserted break points all throughout my code and debugged the hell out of it only to find that the directory (when running on the device vs the emulator) could not be found. Therefore it couldn't read from the database that I pre-populated which explains why the data wasn't getting binded to the spinner control. So at the beginning of my activity I checked for the directory and if it didn't exist I created it. Problem resolved. If anyone else is having same issue as I did feel free to post and I'll be glad to shed what light I can, thanks to all for your suggestions!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Form Application VB.NET File.Create Method, Access Denied to Path I wrote an application which parses a website and downloads an mp4 file from website. User can select the path where he wants to download the video.
When I try to download I get an exception for the file, Access Denied to Path. When I gave the permissions to folder that I chose, then works fine.
How can I resolve that problem? End-User will select the folder. How do I change the permissions? or any other solution ?
A: The end-user can only select a folder that he has write access to.
You're asking to destroy the Windows security model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: If Statement In PHP Script I wonder whether someone can help me please.
I'm using the following script to load marker data into my map.
<?php
require("phpfile.php");
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a MySQL server
$connection=mysql_connect ("hostname", $username, $password);
if (!$connection) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$query = "select l.locationid, f.locationid, l.locationname, l.address, l.osgb36lat, l.osgb36lon, count(f.locationid) as totalfinds from detectinglocations as l left join finds as f on l.locationid=f.locationid group by l.locationid";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("locationid",$row['locationid']);
$newnode->setAttribute("locationname",$row['locationname']);
$newnode->setAttribute("address",$row['address']);
$newnode->setAttribute("osgb36lat",$row['osgb36lat']);
$newnode->setAttribute("osgb36lon",$row['osgb36lon']);
$newnode->setAttribute("totalfinds",$row['totalfinds']);
}
echo $dom->saveXML();
?>
I'd now like to extend the functionality of it further, by adding a new field that converts a numeric value to text. To be more precise if the 'totalfinds' figure is zero then I would like a field that says 'No items found' and if the value is greater than zero then this would return the text 'Items Found'.
From what I've read, I think that I'll need to do this via an 'If' Statement. I am a little new to this, but could someone perhaps confirm for me please whether this is the best way to go about it.
Many thanks
A: You can use the Ternary Operator in PHP. It is a concise way of doing the same thing an If-Else statement would:
$newnode->setAttribute("totalfinds", ($row['totalfinds'] > 0 ? 'Items Found' : 'No items found'));
is the same as
if ($row['totalfinds'] > 0) {
$newnode->setAttribute("totalfinds", 'Items Found');
} else {
$newnode->setAttribute("totalfinds", 'No items found');
}
A: You could do an if, but short question mark notation would fit better in this scenario:
$found_string = ($totalfinds != 0 ? 'Items Found' : 'No items found');
of even shorter (when variable is not zero it equals to true):
$found_string = ($totalfinds ? 'Items Found' : 'No items found');
A: Yes, you can use if, ie
if($row['totalfinds'] == 0) $newnode->setAttribute("totalfinds", "No items found");
else $newnode->setAttribute("totalfinds","Items Found");
instead of
$newnode->setAttribute("totalfinds",$row['totalfinds']);
A: As others have pointed out, this could be done more concisely with the ternary operator. But considering that you asked if this could be done with an if statement, and you are relatively new to php, here is how this might be accomplished using an if statement.
Change this line:
$newnode->setAttribute("totalfinds",$row['totalfinds']);
to
if ($row['totalfinds'] > 0) {
$foundText = 'Items Found';
} else {
$foundText = 'No Items Found';
}
$newnode->setAttribute("totalfinds", foundText);
In case you're still curious, the ternary operator solution looks like this:
$newnode->setAttribute("totalfinds", $row['totalfinds'] > 0 ? 'Items Found' : 'No Items Found');
This could also be accomplished by changing the MySQL query to use a case statement.
$query = "select l.locationid, f.locationid, l.locationname, l.address, l.osgb36lat, l.osgb36lon, case when count(f.locationid) > 0 then 'Items Found' else 'No Items Found' end as totalfinds from detectinglocations as l left join finds as f on l.locationid=f.locationid group by l.locationid";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What's the best way of implementing a 'popular content' display? How do I show a list of 'most popular (articles|posts|whatever) for a period such as the past day? (Essentially replicate the functionality of the Radioactivity Drupal module.)
A: Here's what I would do:
*
*If you're not already, sign up for Google Analytics and add the google analytics javascript to each of your pages. This will track view count for you.
*Using the google data API library, fetch the information you want. For example, you could ask for the most popular pages on your site in the last day.
*Once you have a script that fetches the data you're interested in, you can use django-celery to schedule a periodic task (e.g. once an hour, once a day) to run your script and cache the output in your database for display on your site.
A: Maybe you could decide which posts are popular based on the number of comments on those posts
A: http://popularposts.benguild.com/ ... that's why I built this. It just receives data from Google Analytics scheduled emails and reminds you to extend them before they stop working after a year.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Update bidirectional ManyToMany from both sides referring the question Saving bidirectional ManyToMany i want to obtain exacltly what accepted answer explain as incorrect:
A a1 = new A();
A a2 = new A();
B b = new B();
a1.getB().add(b);
b.getA().add(a2);
If this state could be persisted, you would end up with the following entries in the join table:
a1_id, b_id
a2_id, b_id
But upon loading, how would JPA know that you intended to only let b know about a2 and not a1 ? and what about a2 that should not know about b ?
in my case it is correct that b knows about a1 and a2 in EVERY situation.
think about parent-child relation:
*
*b is parent of a1 AND a1 is child of b (naturally)
and for me it is erroneous to define only one direction:
*
*b is parent of a1 AND NOT a1 is child of b (???)
to obtain what accepted answer is explaining i think i need TWO join tables:
a_has_b:
a1_id, b_id
b_has_a
b_id, a2_id
am i wrong??
*
*however, how to obtain a "synchronized" bidirectional relation (not just ManyToMany)?
*is it possible with standard JPA features?
*otherwise, is there any specific provider implementation?
i think that implementing
...
public void addB(A a)
{
getA().add(a);
a.getB().add(this);
}
is a really ugly hack...
and using two unidirectional OneToMany on both sides does not work in EclipseLink 2.2.0 (not so sure, i'm currently trying)
thx :)
A: Using,
public void addA(A a)
{
getA().add(a);
a.getB().add(this);
}
Is not a hack. This is good object-oriented programming. In any Java model, ignoring persistence, if you have a bi-directional relationship, you must add to both sides to correct related anything. Your code should not change just because you are, or are not, using persistence.
If you want to maintain the relationships separately, you need to have two different join tables. If you want a single ManyToMany relationship (it seems you do), then you must use @ManyToMany and set the mappedBy on one side.
See,
http://en.wikibooks.org/wiki/Java_Persistence/ManyToMany
A: using two unidirectional OneToMany will do the trick:
@Entity
@Table
public class A implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id", nullable = false)
private Long id;
@OneToMany
@JoinTable(name="a_b",
joinColumns = @JoinColumn(name = "a_id", nullable = false),
inverseJoinColumns = @JoinColumn(name = "b_id", nullable = false)
)
private List<B> bList = new ArrayList<B>();
}
---------------------------------------------------------------------------------
@Entity
@Table
public class B implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id", nullable = false)
private Long id;
@OneToMany
@JoinTable(name="a_b",
joinColumns = @JoinColumn(name = "b_id", nullable = false),
inverseJoinColumns = @JoinColumn(name = "a_id", nullable = false)
)
private List<A> aList = new ArrayList<A>();
}
refreshing entity will fill list
A: I faced the problem on updating via the non-owning side. I put @ManyToMany and @JoinTable on both side (no mappedBy). It is working nicely. I am using Hibernate 4.1.10.Final. As per wiki documents, it is not right. Confused ??
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Jsoup get element in value=" " I want to find the element "buddyname" and get the element of value= "" in a HTML file which i put into a StringBuffer, in this case 5342test.
The element in value= "" can change so i can not search directly for 5342test.
<fieldset style="display:none"><input type="hidden" name="buddyname" value="5342test"/></fieldset>
How can i do this with jsoup? or is there an easier way, I already tried Pattern/Matcher but that did not work out as i had issues with the Pattern.compile("<input[^>]*?value\\s*?=\\s*?\\\"(.*?)\\\")");
Below some example code.
Thank you in advance.
Document doc = Jsoup.parse(page); // page is a StringBuffer
Elements td = doc.select("fieldset");
for (Element td : tds) {
String tdText = td.text();
System.out.println(tdText);
}
A: Just use the attribute selector [attrname=attrvalue].
Element buddynameInput = document.select("input[name=buddyname]").first();
String buddyname = buddynameInput.attr("value");
// ...
Do not use regex to parse HTML. It makes no sense if you already have a world class HTML parser at your hands.
See also:
*
*Jsoup CSS selector syntax cookbook
*Jsoup Selector API documentation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Infinite loop when updating JPanel's graphics So, I am drawing a graphic in a JPanel object using Grahics2D.
The JPanel is placed in a JScrollPane for the cases when my graphic is bigger than the window.
But after I draw my graphic the JPanel's size does not change and I cannot scroll to see the rest of my graphic, so I locate the lowest and most left points and set the size manually in the method that does the drawing (method is called drawTrack()).
When I switch windows or do something else that makes the JPanel to be drawn again, my graphic disappears, so I rewrote paint(), repaint(), validate(), invalidate() methods and in there I invoke the drawTrack() method to draw my graphic on every possible case of redrawing the JPanel.
The problem is that when the JPanel invokes one of the methods that do the redrawing I invoke drawTrack() in them, which after redrawing my graphic sets the size manually so that I can scroll the JScrollPane and see my whole graphic. But when I invoke setSize() method on the JPanel that makes it to be redrawn again, which means to invoke drawTrack() and so on and so on.
The scroll bars appear because the size is correct but it creates an infinite loop that redraws my graphic over and over. And if I don't invoke the setSize() method my JPanel gets default size so it can fit in the JScrollPane's viewport and thus I cannot scroll it to see my graphic.
Any suggestions?
A: When you resize a JPanel you stimulate a repaint, and so if you change the size in a paint or paintComponent method or a method called in either of these methods, it makes sense to me that you are at risk of causing an infinite loop.
Solution: Don't resize anything in a paint or paintComponent method. That method is just for painting and nothing else. Instead if you want to set the size of your JPanel, override its getPreferredSize() method.
Here's a "colorful" example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class ImageReSize extends JPanel {
private static final int INIT_WIDTH = 400;
private static final int MAX_WIDTH = 1200;
private static final int TIMER_DELAY = 20;
protected static final int WIDTH_STEP = 5;
private int width = INIT_WIDTH;
private int height = INIT_WIDTH;
private boolean growing = true;
public ImageReSize() {
new Timer(TIMER_DELAY, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (growing && width < MAX_WIDTH) {
width += WIDTH_STEP;
height += WIDTH_STEP;
} else {
growing = false;
}
if (!growing && width > INIT_WIDTH) {
width -= WIDTH_STEP;
height -= WIDTH_STEP;
} else {
growing = true;
}
// get the parent container which is the scrollpane's viewport
JComponent parent = (JComponent)getParent();
parent.revalidate(); // let it relayout the changed size JPanel
parent.repaint(); // and repaint all
}
}).start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
float x = (float)width / 10;
float y = (float)height / 10;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(new GradientPaint(x, 0, Color.green, 0, y, Color.black, true));
g2.fillRect(0, 0, getWidth(), getHeight());
g2.setPaint(new GradientPaint(0, 0, Color.blue, x, y, Color.red, true));
g2.fillOval(0, 0, width, height);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
private static void createAndShowUI() {
ImageReSize imageReSize = new ImageReSize();
JFrame frame = new JFrame("ImageReSize");
frame.getContentPane().add(new JScrollPane(imageReSize));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
A:
so I rewrote paint(), repaint(), validate(), invalidate() methods and in there I invoke the drawTrack() method
This is unnecessary. The custom painting code should only ever be invoked from the paintComponent() method.
A: Faced similar problem: JPanel's paintComponent method called other "methods", that involved changes in Graphics and therefore called for another paintComponent loop.
I haven't found a structural way to move these "methods" outside paintComponent, but found the following solution: surround these "methods" with if clause and break the loop with a boolean flag:
boolean flag;
@Override
public void paintComponent(Graphics g) {
if (flag) {
gModify(); // Method that modifies Graphics g object and calls another paintComponent loop.
flag = !flag; // True to false - miss gModify() in the second paintComponent entry to break the loop.
} else {
flag = !flag; // False to true - allow gModify() after second paintComponent entry.
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to sort DIVs by height? I have three divs and I want to sort them by height, from largest to smallest.
<div>smallest</div>
<div>largest</div>
<div>middle</div>
Any idea?
A: Since jQuery returns an array, you can use the sort method on array to reorder the elements. Once they are sorted in the proper order, you can then remove them from the DOM and reinsert them in the order desired.
$('div.sortable').sort( function(a,b) {
return $(b).height() - $(a).height();
}).appendTo('#container');
A: It's quite simple. Use .sort():
$('div').sort(function (a, b) {
return $(a).height() > $(b).height() ? 1 : -1;
}).appendTo('body');
Code: http://jsfiddle.net/fEdFt/2/
A: I think http://james.padolsey.com/javascript/sorting-elements-with-jquery/ might provide you a good starting point.
A: I don't recall if jQuery will wrap the regular array object or not, but if not you can use a selector to get the divs and then use Array.sort(sortFunc) to sort them.
var divsToSort = $('div'); // I believe this returns an array object.
function sortByHeight(a, b) {
return $(a).height() - $(b).height();
}
divsToSort.sort(sortByHeight);
A: function sortNumber(a, b) {
return a - b;
}
$(function () {
var divOrder = [];
$.each($('div'), function () {
divOrder.push($(this).height());
});
var sortedByHeight = divOrder.sort(sortNumber);
for (i = 0; i < sortedByHeight.length; i++) {
$('div').eq(i).height(sortedByHeight[i]);
}
});
The html for this was:
<div style='border:solid 1px #ccc; width:100px; height:100px; float:left;'></div>
<div style='border:solid 1px #ccc; width:100px; height:400px; float:left;'></div>
<div style='border:solid 1px #ccc; width:100px; height:200px; float:left;'></div>
<div style='border:solid 1px #ccc; width:100px; height:300px; float:left;'></div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Handling SQL Server concurrency issues Sometimes I need to acquire a unique ID and store it with a record, but I am unable to use an identity column. So instead I have a table which provides unique IDs using a label field and an integer. When a unique ID is needed, I call a stored procedure and pass in the label, and it spits out the next ID associated with it.
Of course it's important for this to be reliable in an environment with concurrent transactions. That is, the stored procedure should never return the same value twice for a given label. My limited understanding of transaction isolation has led me to do the following:
1) Set transaction isolation level to serializable
2) SELECT id FROM UniqueIdTable WHERE label = @inputLabel
3) UPDATE UniqueIdTable SET id = id + 1 WHERE label = @inputLabel
4) Return the id retrieved in 2)
But is this actually safe? Isn't it still possible for two threads to concurrently execute up to step 2), even with serializable isolation? It's my understanding that the highest isolation level only guarantees that a single transaction will execute without experiencing phantom rows or changing data from other threads. If this is the case, two simultaneous calls to the GetID function could return the same value.
Am I misunderstanding something about the isolation levels? How can I guarantee this won't occur?
I have another problem I need to sort out. Suppose I have a table with a field in it which holds foreign keys for a second table. Initially records in the first table do not have a corresponding record in the second, so I store NULL in that field. Now at some point a user runs an operation which will generate a record in the second table and have the first table link to it. This is always a one-to-one relationship, so if two users simultaneously try to generate the record, a single record is created and linked to, and the other user receives a message saying the record already exists.
How do I ensure that duplicates are not created in a concurrent environment?
A: You could increment and fetch the ID in the update statement using output.
update UniqueIdTable
set ID = ID + 1
output deleted.ID
where label = @inputLabel
A: I think you are correct that two threads can read the same value in step 2. I can think of two alternatives:
*
*Add a predicate for id in the update statement so that it updates
only if the value hasn't changed. If the update does not update any
record (don't know how to check in SQL Server but must be possible)
then retry the operation.
*Execute the update statement first. Only one thread will be able to execute. Then select the updated value.
I have two other suggestions
*
*Do this in a separate transaction so that a long running transaction does not block another
*Reserve a thread-local block at the application layer. Increment by large value then 1 and use the ids from the thread-local block. This will reduce server roundtrips and updates to the table
A: Create a custom table in some database where you can include an incremental ID field. Any app needing this number will create a record and utilize the returned value. Even if you take this value and don't apply it to the table where you need it, it will still be unique even if you apply it a year later.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Sorting a dictionary in python
Possible Duplicate:
Python: Sort a dictionary by value
I need to sort by values a original dictionary on a descending order.
As keys I have numbers and as values I have some date and time (string).
This means I have:
{1: '2011-09-25 16:28:18', 2: '2011-09-25 16:28:19', 3: '2011-09-25 16:28:13', 4: '2011-09-25 16:28:25'}
And I want to have:
{4: '2011-09-25 16:28:25', 2: '2011-09-25 16:28:19', 1: '2011-09-25 16:28:18', 3: '2011-09-25 16:28:13'}
Please, look at the times (value). I want to sort the times on a descending order. This means, the most recent time first.
Thanks in advance!
A: import operator
x = { 1: '2011-09-25 16:28:18',
2: '2011-09-25 16:28:19',
3: '2011-09-25 16:28:13',
4: '2011-09-25 16:28:25',
}
sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)
print(sorted_x)
This results in a list of (key, value) tuples:
[(4, '2011-09-25 16:28:25'),
(2, '2011-09-25 16:28:19'),
(1, '2011-09-25 16:28:18'),
(3, '2011-09-25 16:28:13')]
A: Python builtin dict dictionaries aren't ordered, so you cannot do that, you need a different container.
With Python 3.1 or 2.7 you can use collections.OrderedDict. For earlier version see this recipe.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: NodeJS get IP used by remoteAddress I have 3 simple NodeJS servers usign NET, HTTP and UDP. Each server listens on port X but has multiple IP addresses. I would like to retrive the actual IP address of the server when the client connects to the server (the IP to where the client connected, the IP that client had to write to connect to the server).
var httpService = http.createServer(function(req, res){
req.getActualServerAddress();
});
httpService.listen(8000);
var netService = net.createServer(function(socket) {
socket.getActualServerAddress();
});
netService.listen(8001);
var udpService = dgram.createSocket("udp4");
udpService.on("message", function (msg, rinfo){
rinfo.getActualServerAddress();
});
udpService.bind(8002);
Thx.
A: If you do not specify the hostname, the server will start at 0.0.0.0. So you may not get your desired outcome[ read Maqurading]. For HTTP you can use the HTTP "Host" header [mandatory since HTTP/1.1] which might be fruitful for your case.
Still you may give a try with:
socket.address()
Returns the bound address and port of the socket as reported by the
operating system. Returns an object with two properties, e.g.
{"address":"192.168.57.1", "port":62053}
Here is a sample for tcp:
var netService = require('net').createServer(function(socket) {
address = netService.address();
console.log("Stream on %j", socket.address());
console.log("opened server on %j", address);
});
netService.listen(8001);
Sample for http:
var httpService = require('http').createServer(function(req, res){
console.log("Stream on %j", req.connection.address());
res.end("Hi");
});
httpService.listen(8000);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How is made link like this www.facebook.com/Lukavyi? How to make link like www.facebook.com/Lukavyi ?
Must every user have separate php file to have such link? I know, that you can somehow change url with apache, but is link being changed back, when user clicks on it?
A: This can be done with Apache's mod_rewrite URL rewrite engine. You can specify a URL pattern and direct all requests to a page or PHP script of your liking.
It works by creating a .htaccess file and setting the rules in there. For example:
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^users/(.*)$ users.php?username=$1
The first two rows make sure the rewrite engine is enabled, and the third one orders all incoming requests for addresses like /users/MyUserName to be redirected internally to users.php?username=MyUserName. The user will not see the final address, only the "clean" version.
If you don't want the users/ part in the URL and instead want yoursite.com/MyUserName to work instead, you'll have to create a front controller that will handle all incoming requests.
A: By using .htaccess and mod_rewrite you can handle this.
For example:
You want every user to have it's own URL like www.example.com/user/UserName
but want your server to call www.example.com/user.php?name=UserName you create a .htaccess like this:
RewriteEngine on
RewriteRule ^user/(.*)$ /user.php?name=$1 [L]
If you get an error or it doesn't work, try adding this code on top of the .htaccess:
Options +FollowSymLinks
Adding the [L] in your .htaccess will prevent your browser from redirecting to user.php?name=UserName and still shows /user/Username but /user.php?name=UserName is used. Using [R] will redirect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is Apex Code? Is it related to Java? I have being called for an training program for application development for Force.com. Since I am looking forward to work in a java based development environment, will it help me as a java developer in the future?
A: Apex itself is based on Java, however syntax and some classes aside the style of programming is quite different in nature as it's more like web development than standalone application development.
Furthermore, even though Eclipse is the SDK of choice, you don't really use it as anything more than a glorified text editor, and one where auto-complete etc. regularly fail at that. It will help you practice coding and experience is always one of the best teachers, but with regards to general application development the amount of help it will provide is limited.
Cheers,
Matt
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to force commit changes on chrome local storage I have an extension which using chrome local storage. I connect to the local storage with another application while chrome is open and I see the changes in this external application only when I'm closing chrome. I guess the changes are done just for the current session and I need to commit those changes. If I'm totally wrong please tell me, but if not, do I have a way to commit the changes made on the chrome extension local storage through javascript?
Thanks.
A: Ok I found out the problem. Im updating the storage using sqlite through another application and I guess it causing problems. the changes are instantly committed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble with the Asset Pipeline on deploying (production mode) I just switched from Ruby on Rails 3.0.10 to 3.1.0 and I am using jQuery UI 1.8.14. I have a problem to load css files in production mode on the remote machine.
In my app/views/layouts/application.html.erb file I have:
<%= stylesheet_link_tag 'application', 'jquery-ui-1.8.14.custom', 'jquery-ui-1.8.14.custom_redefinition' %>
<%= javascript_include_tag 'application' %>
Note: the jquery-ui-1.8.14.custom file is the CSS file generated by using the Theme Roller and the jquery-ui-1.8.14.custom_redefinition is my "custom redefinition" file that override some CSS classes. These files (both with the extension .css) are located at vendor/assets/stylesheets.
In development mode on my local machine all seems to work, but when I deploy with Capistrano to the remote machine it doesn't work anymore. That is, the jQuery UI related files are not loaded as expected: if I try to access them, them content is blank\empty (I can see that in the source HTML code generated for my application web pages).
How can I solve that?
At this time in my config/environments/production.rb file I have:
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
#
# Note: Since, at this time, the asset Pipeline doesn't work for me I am
# following the "Live Compilation" approach (more info at
# http://guides.rubyonrails.org/asset_pipeline.html#in-production)
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
In my app/assets/stylesheets/application.css.scss file I have:
/*
*= require_self
*= require_tree .
*/
In my app/assets/stylesheets/application.js file I have:
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require_tree .
Before deploy, in my local machine, I run the following command:
bundle exec rake assets:precompile
Note: if I run the above command, jquery-ui-1.8.14.custom and jquery-ui-1.8.14.custom_redefinition files are generated in the public/assets directory as expected.
Maybe the problem is related to the require_tree . statement in the app/assets/stylesheets/application.css.scss file that doesn't not load files present in the vendor/assets/stylesheets directory.
A: There are a few issues here, and I'll deal with each one separately.
Why this is broken
There are differences in the way assets are accessed in production and development modes with digest switched on. In development things works as normal. Sprockets serves things under app/assets with their undigested filenames. This works pretty much as though Sprockets wasn't there, but remember /assets is a mount point (Sprockets is a Rails engine), so the files under that are all being served through Sprockets.
In production filenames with digests are used, so Sprockets is expecting those names to be requested instead of the originals. They are effectively hidden behind the /assets mount point
How to fix this
The first thing is to update you application.css to this:
/*
*= require_self
*= require jquery-ui-1.8.14.custom'
*= jquery-ui-1.8.14.custom_redefinition:
*/
and the stylsheet link tag to this:
<%= stylesheet_link_tag 'application' -%>
This ensures that your CSS is served (and compiled) to one file. When you run precompile the UI files end up in the /assets directory because of a bug in Rails, so don't rely on that (it will be fixed in Rails 3.1.2)
The second thing you need to do is to move your images (if you have not already done so) into assets/images.
The third thing is to add the extension .erb to the UI files in the stylesheets folder:
jquery-ui-1.8.14.custom.css.erb
The last thing is to change all reference to images in the CSS files to use the asset_path helper. From this:
url(images/ui-bg_gloss-wave_35_f6a828_500x100.png)
to this:
url(<%= asset_path('ui-bg_gloss-wave_35_f6a828_500x100.png') %>)
Run this in development mode as a test - it should work fine.
In production mode the helper replaces the normal filename with the correct fingerprinted name, so the asset can be accessed.
For production things get a bit tricky. You should be sticking with the defaults, which is to precompile all assets to the /assets directory in public.
I would check the last section of the pipeline guides and make sure that all your config files match the settings in the examples.
The very last thing is to make sure you have Capistrano setup to run the precompile job for you. Check the precompiling assets section of the guide for info on how to set that up.
That should get things working again.
You could (as an alternative to not use the pipeline for these images) move the UI files into a directory under /public and access them from the CSS. You would need to change all the image references. Since you have to change them anyway, I'd stick with the pipeline way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Visual Web Development IDE For JSP, JSF, and Servlets Is there any tool (IDE) that provides a visual web Development for JSP and JSF?
Before, Netbeans 5 has a visual web development plugins, but in the new version this plugins are not available I do not why?
Please, if anyone knows any visual tools or plugins that can be use it with netbeans or eclipse, provide its name and link.
A: JBoss Tools plugin for Eclipse has collection of editors for JSP, JSF etc.: http://docs.jboss.org/tools/3.2.1.GA/en/visual_web_tools_ref_guide/html/Visual_Web_Tools.html#key_features although it is relatively slow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Record ajax content Dear all I have searched in this form and others but cant solve my problem, please help.
I have several rows and each of them has hidden (next) rows for details of this row.
I want to click on any row and see the details of the clicked product.
The problem I am facing is that when I click on the first and then second row, the first row automatically gets the same values as second.
<script type="text/javascript">
$(document).ready(function(){
$("#items tr.itemDetail").hide();
$("#items tr.data td.clickable").click(function(){
$("#items tr.itemDetail").hide();
$(this).parent().next("tr").toggle().toggleClass('highlight');
$.ajax({
url: "<?php echo site_url('progress/getAppDetails'); ?>",
type: 'POST',
data:'app_id='+$(this).parent().attr('id'),
success: function(msg) {
$("tr[id^='det']").html(msg);// want to record/leave data, but instead updates all the fields.
}
});
});
and the table
<tr class='data' id=".$row['aid'].">
<td class='clickable'> ".$row['aid']."</td>
</tr>
<tr class='itemDetail' id=det".$row['aid'].">
<td colspan='4'>Details of the product</td>
</tr>
A: try this :
success: function(msg) {
$(this).next('.itemDetail:first').html(msg);
}
tip :
dont ever use this kind of setting value as
id^='det'
use classes and id's.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to change color of vim cursor in Visual Studio 2010 I have installed the Vim key bindings extension in Visual Studio 2010. I also have a color scheme setup with a dark background. This creates a problem since Vim key bindings extension has set my cursor to black, which is against a dark background .... not good. How can I change that cursor to a different color?
Thanks.
A: If you are using VsVim then I had the same problem. Eventually worked out that I needed to change the VsVim Block Caret display item under Tools > Options > Environment > Fonts and Colors > Display items. I changed the foreground color to 'Gray' and the background color to 'White' (which seems back to front) but that looks good for me on a dark background.
A: for those who hit upon this question in future - You can change the block caret color settings in Tools > Options > VsVim > Defaults > Item Colors > Block Caret
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: NLS missing message: CANNOT_FIND_FACELET_TAGLIB I am getting this warning in Eclipse:
NLS missing message: CANNOT_FIND_FACELET_TAGLIB in:
org.eclipse.jst.jsf.core.validation.internal.facelet.messages ICEfacesPage1.xhtml /myapp/src/main/webapp
On the following lines:
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
Any ideas why, and how to solve it?
A: This is an Eclipse quirk. Try one of the following things:
*
*Close/reopen project.
*Rightclick project > Validate.
*Project > Clean... and clean selected project.
*Restart Eclipse.
A: This was also the case when I imported a JSP taglib, for example:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fmt="http://java.sun.com/jstl/fmt">
</html>
I closed the project and reopened, and it worked!
Eclipse Java EE IDE for Web Developers.
Version: Indigo Service Release 1
Build id: 20110916-0149
A: I realize that this is an old post but I hope this may help somebody.
I recently installed the ICEfaces plugin (IF-3.3.0-IM-1.3.0-Eclipse-4.3-plugins-B.zip) for Eclipse 4.3 (Kepler).
I created a New ICEface Facelets Composition Page using the page creation wizard.
After creating the page, I got the same warning message.
I checked the the index.xhtml that was generated out of the box when I created my ICEfaces application and there's a discrepancy.
Changing my new page ns from www.icesoft.org to www.icefaces.org made the warning disappear.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Abstract Class in Design Pattern For Facade Design Pattern in the book the book Elements of Reusable Object Oriented Software by Erich Gamma on degign patterns, the implementation part talks about making the facade class an abstract class as it reduces the client and subsystem coupling.
I am not able to understand this point. How can making a class abstract help in reducing the coupling. Somebody please help me in understanding this.
Original Code without Facade class as an abstract class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Facade_CSharp
{
class Program
{
static void Main(string[] args)
{
Facade facade = new Facade();
facade.ProcessA();
facade.ProcessB();
// Wait for user
Console.ReadKey();
}
}
/// <summary>
/// The 'Subsystem ClassA' class
/// </summary>
class SubSystemOne
{
public void MethodOne()
{
Console.WriteLine(" SubSystem One");
}
}
/// <summary>
/// The 'Subsystem ClassB' class
/// </summary>
class SubSystemTwo
{
public void MethodTwo()
{
Console.WriteLine(" SubSystem Two");
}
}
/// <summary>
/// The 'Subsystem ClassC' class
/// </summary>
class SubSystemThree
{
public void MethodThree()
{
Console.WriteLine(" SubSystem Three");
}
}
/// <summary>
/// The 'Subsystem ClassD' class
/// </summary>
class SubSystemFour
{
public void MethodFour()
{
Console.WriteLine(" SubSystem Four");
}
}
/// <summary>
/// The 'Facade' class
/// </summary>
class Facade
{
private SubSystemOne _one;
private SubSystemTwo _two;
private SubSystemThree _three;
private SubSystemFour _four;
public Facade()
{
Console.WriteLine("\nRequests received from Client System and Facade is in execution... ");
_one = new SubSystemOne();
_two = new SubSystemTwo();
_three = new SubSystemThree();
_four = new SubSystemFour();
}
public void ProcessA()
{
Console.WriteLine("\nProcessA of Facade uses the following subsystems to accomplish the task:");
_one.MethodOne();
_two.MethodTwo();
_four.MethodFour();
}
public void ProcessB()
{
Console.WriteLine("\nProcessB of Facade uses the following subsystems to accomplish the task:");
_two.MethodTwo();
_three.MethodThree();
}
}
}
Code with Facade class as an Abstract Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Facade_abstract
{
class Program
{
static void Main(string[] args)
{
FacadeAbs facade = new FacadeAbs();
facade.ProcessA();
facade.ProcessB();
// Wait for user
Console.ReadKey();
}
}
class SubSystemOne
{
public void MethodOne()
{
Console.WriteLine(" SubSystem One");
}
}
/// <summary>
/// The 'Subsystem ClassB' class
/// </summary>
class SubSystemTwo
{
public void MethodTwo()
{
Console.WriteLine(" SubSystem Two");
}
}
/// <summary>
/// The 'Subsystem ClassC' class
/// </summary>
class SubSystemThree
{
public void MethodThree()
{
Console.WriteLine(" SubSystem Three");
}
}
/// <summary>
/// The 'Subsystem ClassD' class
/// </summary>
class SubSystemFour
{
public void MethodFour()
{
Console.WriteLine(" SubSystem Four");
}
}
/// <summary>
/// The 'Facade' class
/// </summary>
public abstract class Facade
{
//public abstract Facade();
public abstract void ProcessA();
public abstract void ProcessB();
}
public class FacadeAbs : Facade
{
private SubSystemOne _one;
private SubSystemTwo _two;
private SubSystemThree _three;
private SubSystemFour _four;
public FacadeAbs()
{
Console.WriteLine("\nRequests received from Client System and Facade is in execution... ");
_one = new SubSystemOne();
_two = new SubSystemTwo();
_three = new SubSystemThree();
_four = new SubSystemFour();
}
public override void ProcessA()
{
Console.WriteLine("\nProcessA of Facade uses the following subsystems to accomplish the task:");
_one.MethodOne();
_two.MethodTwo();
_four.MethodFour();
}
public override void ProcessB()
{
Console.WriteLine("\nProcessB of Facade uses the following subsystems to accomplish the task:");
_two.MethodTwo();
_three.MethodThree();
}
}
}
Both giving output as:
Requests received from Client System and Facade is in execution...
ProcessA of Facade uses the following subsystems to accomplish the task:
SubSystem One
SubSystem Two
SubSystem Four
ProcessB of Facade uses the following subsystems to accomplish the task:
SubSystem Two
SubSystem Three
A: Abstract classes separate interface from implementation, at least when a method is demarked as abstract or virtual. Interfaces are the logical extreme for abstract classes, because they are 100% pure, virtual, abstract methods.
When a client deals with an interface type, they have no idea about how it's implemented. There's no knowledge at all about how the abstract methods work, hence greater decoupling.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: adding a progress bar I have an a windows form application that use one class (its name is Parser)
this form has a button and when i click on the windows form application button it call one of the parser class method .
this method simply read text file line after line and write each line to separate file...
i would like to add a progress bar to the form in order to show the progress( it is a very large file )
any idea how to do that? I have in the Parse class 2 property one for the number of line in the file and the second how much lines already checked.
here is my button2_Click function
private void button2_Click(object sender, EventArgs e)
{
if (this.textBox1 != null & this.textBox2 != null)
{
inst.init(this.textBox1.Text, this.textBox2.Text);
//this.progressBar1.Show();
inst.ParseTheFile();
System.Windows.Forms.MessageBox.Show("Parsing finish successfully");
}
}
A: You could do:
private void button1_Click(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem((obj) =>
{
var lines = File.ReadLines(@"D:\test.txt");
var count = lines.Count();
for(int i = 0; i < count; i++)
{
// some parse work
Invoke(new Action(() =>
{
progressBar1.Value = (i * 100) / count;
}));
}
});
}
In the example above, it simply creates a background thread in order not to block the UI thread, until the Invoke method is called.
The Invoke method is necessary, in order to manipulate with a Control that the current thread isn't the owner of. It takes a delegate, and runs this delegate on the thread that owns the Control.
You could even go as far, as making the foreach loop parallel, if it's a time consuming task to parse the lines. An example:
private void button1_Click(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem((obj) =>
{
var lines = File.ReadLines(@"D:\test.txt");
var count = lines.Count();
Parallel.For(0, count, i =>
{
// some parse work
Invoke(new Action(() =>
{
progressBar1.Value = (i * 100) / count;
}));
});
});
}
A: normaly you should go on and write some on what you allready tried.
As I think you are more on the *begining" side I would advise looking into the BackgroundWorker and its ProgressChanged event / system (Here is a intro to it).
Of course you have to move your ParseTheFile-code into this.
For more advanced stuff there are a few options:
*
*add a parameter to the ParseTheFile (for example a Action) that is used to set the progress
*return a IObservable from your ParseTheFile that indicates the progress
*use some static service ParseTheFile is using to indicate the progress (not adviced)
*... (I'm sure other poeple will find a lot more options)
(Please not that most of this options require to use Control.Invoke to get back to your UI-Thread for setting progress-bars value if you use another thread - and I would advise you using another thread if the file is that big)
For starter I would go with the backgroundworker - IMHO it's fine if you don't want to go SOLID (desing patterns/priciples) on your first run ;)
A: Just use Math to Calculate Percentage
Like :
//While Reading
NumOfLines++;
int Percentage = (NumOfLines * 100) / TotalLines ;
ProgressBar.Value = Percentage;
And probably put int.ParseTheFile(); into a Background Worker and/or within a Thread.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: BroadcastReceiver TTS and Volume I have a BroadCastReceiver that starts a background service. This service speaks some text using TTS. Since it all starts with a BroadcastReceiver, there is no UI.
I want to give the user an opportunity to mute when he presses volume down key.
Please guide me how this is possible. I have seen few other related questions but did not get any clear idea. Is it possible to do or not. Please suggest.
Your response is highly appreciated.
Thanks
A: Your App can not responds any broadcast until user start it explicitly.It means that:The application must first be invoked by the user through of activity,and so your App has to have at least on Activity and UI.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ViewPager as a circular queue / wrapping I am using a ViewPager with the FragmentStatePagerAdapter to allow navigation between some fragments.
Let's say I have three fragments: A, B and C. The ViewPager shows Fragment A initially, and allows you to navigate to Fragment B by swiping from right-to-left, and then to Fragment C by swiping again. This allows the following navigation paths: A <--> B <--> C.
What I would like is to be able to swipe from left-to-right on Fragment A and have the ViewPager show Fragment C, i.e. for it to behave as a circular queue and allow ... --> C <--> A <--> B <--> C <--> A <-- ...
I do not want the Fragments duplicated in other positions (i.e. ending up with more than three instances).
Is this wrapping functionality possible with a ViewPager?
A: Just now saw this question and found a solution. Solution Link
Make the following changes to your onPageScrollStateChanged function. Consider you have 4 tabs.
private int previousState, currentState;
public void onPageScrollStateChanged(int state) {
int currentPage = viewPager.getCurrentItem(); //ViewPager Type
if (currentPage == 3 || currentPage == 0){
previousState = currentState;
currentState = state;
if (previousState == 1 && currentState == 0){
viewPager.setCurrentItem(currentPage == 0 ? 3 : 0);
}
}
}
If the state variable is in the existing tabs, its value is 1.
It becomes 0 once you try to navigate before your first tab or after your last tab. So, compare the previous and current states, as shown in the code and you are done.
See onPageScrollStateChanged function here.
Hope it helps.
A: Another way to do this is to add a fake copy of the first element in the view pager to the end of your adapter, and a fake copy of the last element to the beginning. Then when you are viewing the first/last element in the view pager, change pages without animating.
So basically, the first/last elements in your view pager are fakes, just there to produce the correct animation, and then switch over to the end/beginning.
Example:
list.add(list.get(0)); //add the first item again as the last, to create the wrap effect
list.add(0, list.get(list.size()-2)); //insert a copy of the last item as the new first item, so we can scroll backwards too
viewPager.setAdapter(list);
viewPager.setCurrentItem(1, false); //default to the second element (because the first is now a fake)
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
private void handleScrollState(final int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) { //this is triggered when the switch to a new page is complete
final int lastPosition = viewPager.getAdapter().getCount() - 1;
if (currentPosition == lastPosition) {
viewPager.setCurrentItem(1, false); //false so we don't animate
} else if (currentPosition == 0) {
viewPager.setCurrentItem(lastPosition -1, false);
}
}
}
A: This almost accomplishes what antonyt wants, it wont let you go from A -> C though. (Not tested vigorously, but seems to work well enough)
public class MyAdapter extends PagerAdapter {
private List<Object> mItems;
private int mFakeCount = 0;
public MyAdapter(Context context, List<Object> items) {
mItems = items;
mFakeCount = mItems.size()+1;
}
@Override
public int getCount() {
return mFakeCount;
}
@Override
public Object instantiateItem(View collection, int position) {
// make the size larger, and change the position
// to trick viewpager into paging forever
if (position >= mItems.size()-1) {
int newPosition = position%mItems.size();
position = newPosition;
mFakeCount++;
}
// do your layout inflating and what not here.
// position will now refer to a correct index into your mItems list
// even if the user has paged so many times that the view has wrapped
}
}
A: I've implemented a ViewPager/PagerAdapter that can allow for pseudo-infinite paging behaviour. It works by specifying a very large number as the actual count, but maps them to the actual range of the dataset/pageset. It offsets the beginning by a large number also so that you can immediately scroll to the left from the 'first' page.
It doesn't work so well once you get to 1,000,000th page (you will see graphical glitches when scrolling), but this is typically not a real-world use-case. I could fix this by resetting the count to a lower number once in a while, but I will leave it how it is for now.
The InfinitePagerAdapter wraps an existing ViewPager, and so the usage is quite transparent. The InfiniteViewPager does does a bit of work to make sure you can potentially scroll to the left and right many times.
https://github.com/antonyt/InfiniteViewPager
A: Simple idea how to achieve this. When you have your Array with pages simply add this array to another array exactly in the middle.
For example you have array with 15 elements. So place it into 400 element array in the middle (200 position)
Next simply fill array to the left and right so you can move around.
Sample image:
How it looks?
https://youtu.be/7up36ylTzXk
Let the code talk :)
https://gist.github.com/gelldur/051394d10f6f98e2c13d
public class CyclicPagesAdapter extends FragmentStatePagerAdapter {
public CyclicPagesAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return _fragments.get(position).createInstance();
}
@Override
public int getCount() {
return _fragments.size();
}
public void addFragment(FragmentCreator creator) {
_fragments.add(creator);
}
public interface FragmentCreator {
Fragment createInstance();
}
public void clear() {
_fragments.clear();
}
public void add(FragmentCreator fragmentCreator) {
_fragments.add(fragmentCreator);
}
public void finishAdding() {
ArrayList<FragmentCreator> arrayList = new ArrayList<>(Arrays.asList(new FragmentCreator[MAX_PAGES]));
arrayList.addAll(MAX_PAGES / 2, _fragments);
int mrPointer = _fragments.size() - 1;
for (int i = MAX_PAGES / 2 - 1; i > -1; --i) {
arrayList.set(i, _fragments.get(mrPointer));
--mrPointer;
if (mrPointer < 0) {
mrPointer = _fragments.size() - 1;
}
}
mrPointer = 0;
for (int i = MAX_PAGES / 2 + _fragments.size(); i < arrayList.size(); ++i) {
arrayList.set(i, _fragments.get(mrPointer));
++mrPointer;
if (mrPointer >= _fragments.size()) {
mrPointer = 0;
}
}
_fragmentsRaw = _fragments;
_fragments = arrayList;
}
public int getStartIndex() {
return MAX_PAGES / 2;
}
public int getRealPagesCount() {
return _fragmentsRaw.size();
}
public int getRealPagePosition(int index) {
final FragmentCreator fragmentCreator = _fragments.get(index);
for (int i = 0; i < _fragmentsRaw.size(); ++i) {
if (fragmentCreator == _fragmentsRaw.get(i)) {
return i;
}
}
//Fail...
return 0;
}
private static final int MAX_PAGES = 500;
public ArrayList<FragmentCreator> _fragments = new ArrayList<>();
public ArrayList<FragmentCreator> _fragmentsRaw;
}
A: This is a solution without fake pages and works like a charm:
public class CircularViewPagerHandler implements ViewPager.OnPageChangeListener {
private ViewPager mViewPager;
private int mCurrentPosition;
private int mScrollState;
public CircularViewPagerHandler(final ViewPager viewPager) {
mViewPager = viewPager;
}
@Override
public void onPageSelected(final int position) {
mCurrentPosition = position;
}
@Override
public void onPageScrollStateChanged(final int state) {
handleScrollState(state);
mScrollState = state;
}
private void handleScrollState(final int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
setNextItemIfNeeded();
}
}
private void setNextItemIfNeeded() {
if (!isScrollStateSettling()) {
handleSetNextItem();
}
}
private boolean isScrollStateSettling() {
return mScrollState == ViewPager.SCROLL_STATE_SETTLING;
}
private void handleSetNextItem() {
final int lastPosition = mViewPager.getAdapter().getCount() - 1;
if(mCurrentPosition == 0) {
mViewPager.setCurrentItem(lastPosition, false);
} else if(mCurrentPosition == lastPosition) {
mViewPager.setCurrentItem(0, false);
}
}
@Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
}
}
You just have to set it to your ViewPager as onPageChangeListener and that's it: ( ** deprecated now ** check the edit notes)
viewPager.setOnPageChangeListener(new CircularViewPagerHandler(viewPager));
To avoid having this blue shine at the "end" of your ViewPager you should apply this line to your xml where the ViewPager is placed:
android:overScrollMode="never"
We have improved the solution above and created a little library on github. Feel free to check it out :)
Edit:: As per the @Bhavana comment , Just use addOnPageChangeListener instead of setOnPageChangeListener as later is deprecated.
viewPager.addOnPageChangeListener(new CircularViewPagerHandler(viewPager));
A: I've been trying all the suggestions, solutions, libraries, etc but they're not pure circular and most of the time don't have support for only 3 pages.
So I implemented a circular ViewPager example using the new ViewPager2, the new ViewPager uses a RecyclerView and ViewHolders to handle the views recycling and works as expected!
TLDR: GITHUB
In this example, will be building a single activity app with ViewPager2 and a FragmentPagerAdapter supporting circular navigation between 3 pages or more.
I'm using an alpha version of the library androidx.viewpager2:viewpager2, but the version 1.0.0-alpha06 is the last one planned before google freezing the API and moving to beta.
1. Add the ViewPager2 library to the dependencies in your build.gradle
dependencies {
implementation 'androidx.viewpager2:viewpager2:1.0.0-alpha06'
}
2. Add the ViewPager2 view to your project:
<androidx.viewpager2.widget.ViewPager2 xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/vwpHome"
android:layout_width="match_parent"
android:layout_height="match_parent" />
3. Create the FragmentStateAdapter adapter:
getItemCount() needs to returns a huuuuge number. (2147483647)
getCenterPage() returns the central page based on the huuuuge number.
This method is used to get the position of the initial page to set in the ViewPager2, in this case the user needs to swipe ˜1073741823 time to reach the end of the ViewPager2.
class CircularPagerAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) : FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount() = Integer.MAX_VALUE
/**
* Create the fragment based on the position
*/
override fun createFragment(position: Int) = HomePagerScreens.values()[position % HomePagerScreens.values().size].fragment.java.newInstance()
/**
* Returns the same id for the same Fragment.
*/
override fun getItemId(position: Int): Long = (position % HomePagerScreens.values().size).toLong()
fun getCenterPage(position: Int = 0) = Integer.MAX_VALUE / 2 + position
}
HomeScreens is a ENUM with the page info.
enum class HomePagerScreens(@StringRes val title: Int,
val fragment: KClass<out Fragment>) {
HOME_1(R.string.home_1, FragmentHome::class),
HOME_2(R.string.home_2, FragmentHome::class),
HOME_3(R.string.home_3, FragmentHome::class)
}
4. Set the adapter to the ViewPager
val circularAdapter = CircularPagerAdapter(supportFragmentManager, lifecycle)
vwpHome.apply {
adapter = circularAdapter
setCurrentItem(circularAdapter.getCenterPage(), false)
}
A: I have a solution I believe will work. It isn't tested, but here it is:
A wrapper around FragmentPagerAdapter as the super class:
public abstract class AFlexibleFragmentPagerAdapter extends
FragmentPagerAdapter
{
public AFlexibleFragmentPagerAdapter(FragmentManager fm)
{
super(fm);
// TODO Auto-generated constructor stub
}
public abstract int getRealCount();
public abstract int getStartPosition();
public abstract int transformPosition(int position);
};
Then the standard FragmentPagerAdapter implementation subclass this new abstract class:
public class SomeFragmentPagerAdapter extends
AFlexibleFragmentPagerAdapter
{
private Collection<Fragment> someContainer;
public SomeFragmentPagerAdapter(FragmentManager fm, Container<Fragment> fs)
{
super(fm);
someContainer = fs;
}
@Override
public int getRealCount() { return someContainer.size(); }
@Override
public int getStartPosition() { return 0; }
@Override
public int transformPosition(int position) { return position; }
};
And the Cyclic Pager Adapter implementation.
public class SomeCyclicFragmentPagerAdapter extends
SomeFragmentPagerAdapter
{
private int realCount = 0;
private int dummyCount = 0;
private static final int MULTI = 3;
public SomeFragmentPagerAdapter(FragmentManager fm, ...)
{
super(fm);
realCount = super.getCount();
dummyCount *= MULTI;
}
@Override
public int getCount() { return dummyCount; }
@Override
public int getRealCount() { return realCount; }
@Override
public int getStartPosition() { return realCount; }
@Override
public int transformPosition(int position)
{
if (position < realCount) position += realCount;
else if (position >= (2 * realCount)) position -= realCount;
return position;
}
};
ViewPager initialization
this.mViewPager.setCurrentItem(this.mPagerAdapter.getStartPosition());
And finally, the callback implementation:
@Override
public void onPageSelected(int position)
{
this.mTabHost.setCurrentTab(position % mPagerAdapter.getRealCount());
this.mViewPager.setCurrentItem(this.mPagerAdapter
.transformPosition(position));
}
@Override
public void onTabChanged(String tabId)
{
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(this.mPagerAdapter
.transformPosition(pos));
}
A: *
*Set for the items count some large value, say 500000.
*Return from adapter this value * number of actual items.
*On getItem(int i) adjust the i to -> i = i % number of actual items.
*On onCreate(Bundle savedInstanceState) set current item for page 500000/2
public class MainActivity extends FragmentActivity {
private final static int ITEMS_MAX_VALUE = 500000;
private int actualNumCount = 10;
private ViewPager mPager = null;
private class OptionPageAdapter extends FragmentStatePagerAdapter {
public OptionPageAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
try {
i = i % OptionType.values().length;
OptionPage optionPage = new OptionPage(i);
optionPage.id = i;
return optionPage;
} catch (Exception e) {
VayoLog.log(Level.WARNING, "Unable to create OptionFragment for id: " + i, e);
}
return null;
}
@Override
public int getCount() {
return ITEMS_MAX_VALUE * actualNumCount;
}
}
public static class OptionPage extends Fragment {
private int id = 0
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.main_page, container, false);
return mainView;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPager = (ViewPager) findViewById(R.id.main_pager);
mPager.setOffscreenPageLimit(3);
mPager.setAdapter(new OptionPageAdapter(this.getSupportFragmentManager()));
mPager.setCurrentItem(ITEMS_MAX_VALUE/2,false);
}
}
A: *
*add fake copy of the Last Element at the begining of your list.
*add fake copy of the First Element at the end.
*select real First Element somewhere in init code:
mViewPager.setCurrentItem(1);
*modify setOnPageChangeListener:
@Override
public void onPageSelected(int state) {
if (state == ITEMS_NUMBER + 1) {
mViewPager.setCurrentItem(1, false);
} else if (state == 0) {
mViewPager.setCurrentItem(ITEMS_NUMBER, false);
}
}
A: based on this approach
true loop, pager title strip, true no refresh scrolling
private static final int ITEM_NUM = 5 ; // 5 for smooth pager title strip
private void addFragment(String title, String className) {
if (fragments.size() < ITEM_NUM) {
Bundle b = new Bundle();
b.putInt("pos", fragments.size());
fragments.add(Fragment.instantiate(this, className, b));
}
titles.add(title);
itemList.add(className);
}
view page adapter:
public static class MyFragmentPageAdapter extends FragmentPagerAdapter {
private HashMap<Long, Fragment> mItems = new HashMap<Long, Fragment>();
public MyFragmentPageAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
@Override
public long getItemId(int position) {
int id = java.lang.System.identityHashCode(fragments.get(position));
return id;
}
@Override
public Fragment getItem(int position) {
long id = getItemId(position);
if (mItems.get(id) != null) {
return mItems.get(id);
}
Fragment f = fragments.get(position);
return f;
}
@Override
public int getCount() {
return ITEM_NUM;
}
@Override
public CharSequence getPageTitle(int position) {
String t = titles.get(getItem(position).getArguments()
.getInt("pos"));
return t;
}
@Override
public int getItemPosition(Object object) {
for (int i = 0; i < ITEM_NUM; i++) {
Fragment item = (Fragment) fragments.get(i);
if (item.equals((Fragment) object)) {
return i;
}
}
return POSITION_NONE;
}
}
using:
itemList = new ArrayList<String>();
fragments = new ArrayList<Fragment>();
titles = new ArrayList<String>();
addFragment("Title1", Fragment1.class.getName());
...
addFragment("TitleN", FragmentN.class.getName());
mAdapter = new MyFragmentPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id...);
mViewPager.setAdapter(mAdapter);
mViewPager.setCurrentItem(2);
currPage = 2;
visibleFragmentPos = 2;
mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int curr) {
dir = curr - currPage;
currPage = curr;
}
private void shiftRight() {
fragments.remove(0);
int pos = visibleFragmentPos + 3;
if (pos > itemList.size() - 1)
pos -= itemList.size();
if (++visibleFragmentPos > itemList.size() - 1)
visibleFragmentPos = 0;
insertItem(4, pos);
}
private void shiftLeft() {
fragments.remove(4);
int pos = visibleFragmentPos - 3;
if (pos < 0)
pos += itemList.size();
if (--visibleFragmentPos < 0)
visibleFragmentPos = itemList.size() - 1;
insertItem(0, pos);
}
private void insertItem(int datasetPos, int listPos) {
Bundle b = new Bundle();
b.putInt("pos", listPos);
fragments.add(datasetPos,
Fragment.instantiate(ctx, itemList.get(listPos), b));
}
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (dir == 1) {
shiftRight();
} else if (dir == -1) {
shiftLeft();
}
mAdapter.notifyDataSetChanged();
currPage = 2;
}
}
});
A: You may use simple view from https://github.com/pozitiffcat/cyclicview
One of features is:
Do not duplicate first and last views, used bitmap variants instead
Example:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CyclicView cyclicView = (CyclicView) findViewById(R.id.cyclic_view);
cyclicView.setAdapter(new CyclicAdapter() {
@Override
public int getItemsCount() {
return 10;
}
@Override
public View createView(int position) {
TextView textView = new TextView(MainActivity.this);
textView.setText(String.format("TextView #%d", position + 1));
return textView;
}
@Override
public void removeView(int position, View view) {
// Do nothing
}
});
}
}
A: My answer is probably similar to others out there. However I couldn't find a solution in ViewPager2 with FragmentStateAdapter.
public class ScreenSlidePagerAdapter extends FragmentStateAdapter {
private final Fragment[] fragments = {new Fragment4(), new Fragment1(),
new Fragment2(), new Fragment3(),
new Fragment4(), new Fragment1()};
public ScreenSlidePagerAdapter(FragmentActivity fa) { super(fa); }
@NonNull
@Override
public Fragment createFragment(int position) {
return fragments[position];
}
@Override
public int getItemCount() { return fragments.length; }
}
Where Fragment1 is the first to be displayed.
The in your MainActivity (or whichever activity has the ViewPager):
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager2 viewPager = findViewById(R.id.viewpager);
ScreenSlidePagerAdapter adapter = new ScreenSlidePagerAdapter(this);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(1, false);
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
if (position == 0) {
viewPager.setCurrentItem(5, false);
}
else if (position == 5) {
viewPager.setCurrentItem(1, false);
}
}
});
}
}
You'll obviously have to change the positions depending on the number of Fragments you have.
A: Sorry for the delay, but I've seen the answers and I I was unable to hold, got to answer it too :).
On your adapter, on the method get count, proceed as follows:
@Override
public int getCount() {
return myList.size() % Integer.MAX_VALUE;
}
That will work!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "64"
} |
Q: convert a text link to image link I am in the middle of making a post system for my website, and i would like some javascript that would turn a text link like
<a href="path/to/image.jpg">Image</a>
into
<a href="path/to/image.jpg"><img src="path/to/image.jpg" /></a>
but only turn it into an image link when something such as a regex recognises that the link is to an image.
Or i dont mind doing something like adding a data-type="image" attribute to the link, but i still need the code to turn it into an image link.
A: $('a[href$=".png"], a[href$=".jpg"], a[href$=".gif]"').each(function(){
$(this).html('<img src="' + $(this).attr('href') + '" />');
});
Code: http://jsfiddle.net/FcQzG/1/
A: I'd recommend putting a class on all of the anchors links you want to convert. Let's say you choose to use a convert class. Then, you could use jQuery the add an img tag inside the anchor tag:
// for each anchor that needs converting
$('.convert').each(function() {
// get the href of the anchor
var href = $(this).attr('href');
// create the string we want to append to the anchor
var imgString = '<img src="' + href + '" alt="" />';
// and then append it
$(this).append(imgString);
});
A: @Alex solution is a better one, but if you could not add a class
$('a').each(function(){
var a = $(this)
if(a.text() == 'Image')
a.html('<img src="'+a.href+'" >')
})
http://jsfiddle.net/7AvJT/2/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Optimized solutions for my homework A snail creeps x ft up a wall during the daytime. After all the labor it does throughout the day, it stops to rest a while... but falls asleep!! The next morning it wakes up and discovers that it has slipped down y ft while sleeping.
If this happens every day, how many times will the snail creep to cover n walls of different height?
I have written a function to count the number of creeps of the snail as shown below:
void count(int move_forward, int move_backward, int number_walls, int[] height)
{
int count = number_walls, diff = move_forward - move_backward;
while (number_walls--)
for (move_backward = move_forward; move_backward < height[number_walls]; move_backward += diff)
count++;
}
It's working fine. But I wanted to know if there is any other way of solving this problem to optimize the speed of the program further.
A: solution is ((height-x)/(x-y))+1, no loops required.
the snail needs to climb to: height-x, and it takes him ((height-x)/(x-y)) days. Once it is there, it takes him an extra day to climb the remaining x.
EDIT: as mentioned in the comments, this solution solves the problem for each wall, you'll need to iterate over your heights array, and summarize these results, saving you at least the inner loop, making it O(n), instead O(n*h), where n is the number of walls, and h is the walls' heights.
(*)note: that you might want to save the reminder for each wall [i.e. how much the snail can keep going after he had passed this wall], and subtract it from the next wall, dependes on the task description... If the snail can pass a maximum of one wall per day, ignore this last comment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Threading tutorial needed I hava an app that load images from the internet and display using the combination of gallery widget and imageview. I would like to put the downloading images part to a separate thread but i had no idea how to do it even after a few google searches. Below is my code, anyone can please help me. Thanks in advance.
package com.example.gallery;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
public class GalleryActivity extends Activity {
public Bitmap[] bmps;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gal = (Gallery)findViewById(R.id.gallery);
final ImageView iv = (ImageView)findViewById(R.id.imageView);
gal.setAdapter(new ImageAdapter(this));
gal.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
Bitmap bm = bmps[position];
if(bm.getHeight() > 800 || bm.getWidth() > 600)
{
Bitmap rbm = Bitmap.createScaledBitmap(bm, bm.getWidth()/2, bm.getHeight()/2, true);
iv.setImageBitmap(rbm);
}
else
{
iv.setImageBitmap(bm);
}
}
});
}
public void initBmps(int length)
{
bmps = new Bitmap[length];
}
public void setBmps(Bitmap bm, int pos)
{
bmps[pos] = bm;
}
public class ImageAdapter extends BaseAdapter
{
int mGalleryItemBackground;
private Context mContext;
private String[] mImageIds = {"http://4.bp.blogspot.com/-bQQ6UcJhpoA/TfOeymYKMeI/AAAAAAAAAIo/30kj0KUAgxo/s1600/snsd1.jpg",
"http://www.sweetslyrics.com/images/img_gal/13192_snsd-group-31.jpg",
"http://kojaproductions.files.wordpress.com/2008/12/snsd_teases_kjp.jpg",
"http://solar.envirohub.net/images/solar-power.jpg",
"http://scm-l3.technorati.com/11/05/27/35419/solar-power.jpg?t=20110527104336",
"http://www.solarstorms.org/Pictures/GridMap.gif",
"http://static.electro-tech-online.com/imgcache/11039-power%20lines.jpg"};
public ImageAdapter(Context c)
{
mContext = c;
TypedArray a = mContext.obtainStyledAttributes(R.styleable.Theme);
mGalleryItemBackground = a.getResourceId(R.styleable.Theme_android_galleryItemBackground, 0);
initBmps(mImageIds.length);
a.recycle();
}
public int getCount()
{
return mImageIds.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView i = new ImageView(mContext);
DownloadImageTask down = new DownloadImageTask();
down.excecute(mImageIds[position]);
if(down..getStatus() == AsyncTask.Status.FINISHED)
{
Bitmap rbm = Bitmap.createScaledBitmap(bm, 200, 200, true);
i.setImageBitmap(rbm);
i.setLayoutParams(new Gallery.LayoutParams(150, 150));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
}
return i;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... url) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), url[0], Toast.LENGTH_SHORT).show();
URL aURL;
Bitmap bm = null;
try {
aURL = new URL(url[0]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
//setBmps(bm, position);
bis.close();
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute (Bitmap result) {
setBm(result);
}
}
}
}
A: I suggest you use an AsyncTask to do your image download, that's what I've been using:
http://developer.android.com/reference/android/os/AsyncTask.html
http://developer.android.com/resources/articles/painless-threading.html
A: Well, googling 'Android threading', this seems to be an article on pretty much what you're trying to do:
http://developer.android.com/resources/articles/painless-threading.html
In general:
http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html
The API:
http://developer.android.com/reference/java/lang/Thread.html
A: Ok
Here are some ImageDownloader references.
*
*Reference 1
*Reference 2
*GalleryView with Image downloading (using caches)
They delegate the image downloading to an AsyncTask
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Tinysort sort by multiple attributes (more than 1) I'm trying to use tinysort as part of a mobile application that I'm building with jquery mobile. My app finds places near a users location and I want to be able to sort results quickly on the fly without having to spend the time re-querying the db.
So, what I want to do is be able to use tinysort to re-sort results based on if a user has a favorite place in the area and then by distance, additionally I want to be able to sort by an attribute "beenthere" if the user has marked they've been to a place.
This is what I want to do:
Sort by favorite:
$("ul#places>li").tsort('',({order:"desc",attr:"myfav"},{order:"asc",attr:"dist"}));
Sort by Been There:
$("ul#places>li").tsort('',({order:"desc",attr:"beenthere"},{order:"asc",attr:"dist"}));
Sort by default: // This is easy and works no problem:
$("ul#places>li").tsort('',{order:"desc",attr:"dist"});
With a default list order like:
<ul id="places">
<li myfav="0" beenthere="0" dist=".02">Hot Dog Stand</li>
<li myfav="1" beenthere="0" dist=".08">Joe's Shack</li>
<li myfav="0" beenthere="1" dist=".10">Frick frack</li>
<li myfav="1" beenthere="1" dist=".15">Mama's</li>
</ul>
Sort by fav should return:
*
*Joe's Shack
*Mama's
*Hot Dog Stand
*Frick frack
Sort by been there should return:
*
*Frick frack
*Mama's
*Hot Dog Stand
*Joe's Shack
And then back to sorting by distance:
*
*Hot Dog Stand
*Joe's Shack
*Frick frack
*Mama's
My calls to tsort above just aren't working with the multiple attribute selectors and either my syntax is wrong or you can't sort on more than one criteria.
Any ideas of how I can accomplish this with tsort or other solution is appreciated!
A: I understood that Mottie's solution worked, but it seems a little bit complex... Calling the tsort twice worked for me:
listOfItems.tsort({data:sorter, order:direction})
.tsort({data: sorterAlt, order:direction})
In your case, it'd be (if '' are just referring to selected items, you can remove them):
$("ul#places>li").tsort({order:"desc",attr:"myfav"})
.tsort({order:"asc",attr:"dist"})
$("ul#places>li").tsort({order:"desc",attr:"beenthere"})
.tsort({order:"asc",attr:"dist"})
Also use the data-attrname style for HTML5, as Mottie suggested. You can always use data: attrname inside the tsort.
Hope it may still help you or others!
A: The results you have above are actually sorted by "asc" and not "desc" as you indicated. Either way, I don't think TinySort has multiple attribute sorting built in, so the next best thing would be to just combine the attributes you want to sort.
Since the distance is the default sort, I thought it would be best to combine it with a number value from the other attribute. For example, the myfav attribute is set to "1" to indicate that it is true (I'm assuming this, but it seems like your intent). If I stick this one in front of the distance, it's value ends up being higher than the false value of zero - this is opposite of the sort direction you wanted, so I assigned a true value to be "0" instead of "1" and a false value to be "9" instead of "0". I know it sounds confusing, but check this out:
Sort by Fav:
Location fav been dist combined
1. Joe's Shack 1 0 .08 0.08
2. Mama's 1 1 .15 0.15
3. Hot Dog Stand 0 0 .02 9.02
4. Frick frack 0 1 .10 9.10
Sort by Been There:
Location fav been dist combined
1. Frick frack 0 1 .10 0.10
2. Mama's 1 1 .15 0.15
3. Hot Dog Stand 0 0 .02 9.02
4. Joe's Shack 1 0 .08 9.08
I hope that makes it clear... anyway, here is a demo, where I made the sort order toggle, and the code I used:
var list = $("ul#places>li"),
sortit = function(el, att){
$(el).toggleClass('desc');
var combo,
order = $(el).is('.desc') ? 'desc' : 'asc';
// make combo attribute
if (att !== 'dist') {
list.each(function(){
// attr value = 1 means true, so assign it as a zero
// attr value = 0 means false, so assign it as a nine
// these numbers + distance, makes sure the lower
// values are sorted first
combo = $(this).attr(att) === '1' ? '0' : '9';
$(this).attr('combo', combo + $(this).attr('dist'));
});
att = 'combo';
}
list.tsort('',({order:order,attr:att}));
};
// Sort by favorite:
$('button:contains(Fav)').click(function(){ sortit(this, 'myfav'); });
// Sort by favorite:
$('button:contains(Been)').click(function(){ sortit(this, 'beenthere'); });
// Sort by default
$('button:contains(Dist)').click(function(){sortit(this, 'dist'); });
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Check if NSString contains alphanumeric + underscore characters only I've got a string that needs to be only a-z, 0-9 and _
How do I check if the input is valid? I've tried this but it accepts letter like å,ä,ö,ø etc.
NSString *string = [NSString stringWithString:nameField.text];
NSCharacterSet *alphaSet = [NSCharacterSet alphanumericCharacterSet];
[string stringByTrimmingCharactersInSet:alphaSet];
[string stringByReplacingOccurrencesOfString:@"_" withString:@""];
BOOL valid = [[string stringByTrimmingCharactersInSet:alphaSet] isEqualToString:@""];
A: Create your own character set using [NSCharacterSet characterSetWithCharactersInString:], then trim as you were doing to see if the returned string has a length value.
Or you could use invertedSet to remove all non-set characters, if that would help to produce a cleaned string.
A: You can use a predicate:
NSString *myRegex = @"[A-Z0-9a-z_]*";
NSPredicate *myTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", myRegex];
NSString *string = nameField.text;
BOOL valid = [myTest evaluateWithObject:string];
Edit:
I don't noticed that you are using [NSString stringWithString:nameField.text].
Use nameField.text instead.
A: You could loop through the every character in the string and check that it's alphanumeric:
BOOL isMatch = YES;
for (int i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if (!isalnum(c) && c != '_') {
isMatch = NO;
break;
}
}
if (isMatch) {
// valid
} else {
// invalid
}
A: Here's how you can do it in Swift (as an extension of the String class):
extension String {
func containsValidCharacters() -> Bool {
var charSet = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_")
charSet = charSet.invertedSet
let range = (self as NSString).rangeOfCharacterFromSet(charSet)
if range.location != NSNotFound {
return false
}
return true
}
}
A: You can create your own character set:
NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"];
Once you have that, you invert it to everything that's not in your original string:
s = [s invertedSet];
And you can then use a string method to find if your string contains anything in the inverted set:
NSRange r = [string rangeOfCharacterFromSet:s];
if (r.location != NSNotFound) {
NSLog(@"the string contains illegal characters");
}
A: Some more easy way,
NSMutableCharacterSet *allowedSet = [NSMutableCharacterSet characterSetWithCharactersInString:@"_"];
[allowedSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
NSCharacterSet *forbiddenSet = [allowedSet invertedSet];
It'll combine alphanumeric along with _underscore.
you can use it like,
NSRange r = [string rangeOfCharacterFromSet:forbiddenSet];
if (r.location != NSNotFound) {
NSLog(@"the string contains illegal characters");
}
PS. example copied from @DaveDeLong example :)
A: Updating @vikzilla answer for Swift 5:
extension String {
func containsValidCharacters() -> Bool {
var charSet = NSCharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_")
charSet = charSet.inverted as NSCharacterSet
let range = (self as NSString).rangeOfCharacter(from: charSet as CharacterSet as CharacterSet)
if range.location != NSNotFound {
return false
}
return true
}
}
A: this is a quick helper if it helps
-(BOOL)isString:(NSString *)s{
char letter = 'A';
//BOOL isLetter=NO;
for (int i=0; i<26; i++) {
NSString *temp = [NSString stringWithFormat:@"%c",letter+i];
if ([s isEqualToString:temp]) {
return YES;
}
}
return NO;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
} |
Q: Calling a function within the function inside the class in php I don't understand what's going on with this. I need to call Func1 from Func2 and parametr for Func1 should be given inside the object.
class MyClass {
function Func1($a) {
return $a;
}
function Func2() {
echo $this->Func1($a);
}
}
$c = new MyClass();
$c->Func1('parametr'); // prints: 1
$c->Func2();
A: What about setting the parameter as class variable (property)?
class MyClass {
private $a;
function Func1($a) {
$this->a = $a;
return $a;
}
function Func2() {
echo $this->Func1($this->a);
}
}
This sets the parameter first time you call Func1. Then everytime you call Func2, it uses the parameter. You can also skip passing the parameter like this:
class MyClass {
private $a;
function Func1($a = null) {
if ($a === null) {
return $this->a;
} else {
$this->a = $a;
return $a;
}
}
function Func2() {
echo $this->Func1();
}
}
I.e if you call func1 without any parameter, it uses the stored variable (property), otherwise it uses the given parameter. This can be used in various ways depending on your exact needs.
A: The instruction:
echo $this->Func1($a);
is wrong: the variable $a is out of the scope of Func2. $a is a parameter of Func1 so is only int he scope of Func1.
A: You should read more about variable scopes at PHP http://php.net/manual/en/language.variables.scope.php
quick glimpse:
1) you can have global variables. to access those, use keyword global in functions that need access to that
2) you can have local variables, available only within a scope of a function
3) you can pass references to variables, so that variable from one scope is made accessible to other function/scope
4) you can have objects's internal variables of different kind (private, public, protected, static)
I suggest you get familiar with this stuff real well.
As for you code, problem is obvious. In Func2 the $a is local variable, thus when passed to $this->Func1($a), it is undefined. As your example code suggests, you might want to introduce class property private $a, and then use that. e.g.:
class X {
private $a;
function set($val){
$this->a = $val;
}
function get(){
return $this->a;
}
function doSomethingWithA(){
$this->set($this->get() * 2);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CodeIgniter: get_instance inside My_Lang I found this useful Internationalization code:
http://pastebin.com/SyKmPYTX
everything works well except I am unable to use CI functions inside this class .
I want to set $languages and $special variable from DB .
but when I am using $CI =& get_instance(); in instance function its showing following error :
Fatal error: Class 'CI_Controller' not found in /system/core/CodeIgniter.php on line 231
A: The language class is loaded before the CodeIgniter instance exists, which is why you get the error.
You can use a post_controller_constructor hook to set your variables.
Here is a thread from the CodeIgniter forums where someone is tried to do something similar: http://codeigniter.com/forums/viewthread/108639/
A: The easiest way
in My_Lang.php
var $languages = array();
function __construct()
{
parent::__construct();
require_once( BASEPATH .'database/DB'. EXT );
$db =& DB();
$query = $db->query( 'SELECT * FROM languages');
$result = $query->result();
foreach( $result as $row )
{
$this->languages[$row->short_name] = $row->full_name;
}
}
i did this and is working fine :)) i also added default_uri in foreach.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: GoogleApp Engine authentication using Google ID from Blackberry I am developing an app to be hosted on Google App Engine. Users will be able to use their Google IDs to login to the app. The app also has a client counterpart in the form of a Blackberry Application.
My question is - is there a suggested way for my app to collect the user's Google credentials so that I can authenticate it against Google using OpenID semantics? In Android, for example, I can use the Accounts API so that I don't need to explicitly ask the user to enter credentials. What's the way to do this in Blackberry?
I see 2 ways, neither of which is ideal:
*
*Write my own form in my native Blackberry app where the user enters Google ID and password, which I then use to obtain the authenticator token and perform the rest of the authentication behind the scenes. But the point is - it is inappropriate to ask a user to trust my app with their Google credentials.
*Use standard Google Open ID Authentication mechanism - which opens up the web browser and displays Google's Open ID login page. Although this is a one-time thing (after which I can save the authentication token so that future requests to GAE do not require any prompting for credentials), the user experience is still disruptive since it involves opening the browser in addition to my native BB app.
So, what's the suggested way forward?
A: Using the browser to authenticate is pretty much the only standard way to do this. A number of Android apps do this for OAuth or OpenID endpoints too. Depending on how the Blackberry's protocol handlers work, you should be able to set a continue URL that results in your app being called back by the browser when authentication completes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What Can I Use Besides usleep in a Modern POSIX Environment? I'm fairly new to C but writing a small multithreaded application. I want to introduce a delay to a thread. I'd been using 'usleep' and the behavior is what I desire - but it generates warnings in C99.
implicit declaration of function ‘usleep’
It's only a warning, but it bothers me. I've Googled for an answer but all I could find was a while-loop / timer approach that seemed like it would be CPU intensive.
EDIT:
My includes are:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
And I'm invoking the compiler with:
c99 program.c -Wall -pedantic -W -lpthread
EDIT #2:
I've created a new file that contains:
#include <unistd.h>
int main(void) {
usleep(10);
}
And I still get the warning.
EDIT #3:
As suggested, I've updated the text of the question.
A: The problem is that you are using a standard C99 compiler, but you're trying to access POSIX extensions. To expose the POSIX extensions you should for example define _POSIX_C_SOURCE to 200809L (for the current standard). For example this program:
#include <time.h>
int main(void) {
struct timespec reqtime;
reqtime.tv_sec = 1;
reqtime.tv_nsec = 500000000;
nanosleep(&reqtime, NULL);
}
will compile correctly and wait for 1.5 seconds (1 second + 500000000 nanoseconds) with the following compilation command:
c99 main.c -D _POSIX_C_SOURCE=200809L
The _POSIX_C_SOURCE macro must be defined with an appropriate value for the POSIX extensions to be available.
Also the options -Wall, -pedantic and -W are not defined for the POSIX c99 command, those look more like gcc commands to me (if they work on your system then that's fine, just be aware that they are not portable to other POSIX systems).
A: You are probably on a modern POSIX system:
POSIX.1-2008 removes the specification of usleep().
On my system (linux) there is a detailed explanation of the macros that must be set to get that function back. But you should just follow the advice that zvrba already gave, use nanosleep instead.
A: From the manual page: This function is obsolete. Use nanosleep instead.
A:
implicit declaration of function ‘usleep’
This warning usually means that you didn't #include the right header file, in this case unistd.h.
A: Did you have the #include <unistd.h> ?.
And you can use some of the similar methods instead: nanosleep() for nanoseconds and sleep() for seconds. Or another way could be using clock(), but i think this is more CPU wasting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Rails 3.1 simple_datatables I have been looking at Simple Datatables but the documentation and example provided are not very clear. It appears to implement jsonify and utilize a template handler but I am not sure. Also the provided code does not compile; is the author using some other gem to parse the views? For example, it says to put this in your search view...
@products.each do |product|
json << [product.name, product.manufacturer.name]
end
which I assuming has to be translated to...
<%= @products.each do |product| %>
<% json << [product.name, product.manufacturer.name] %>
<% end %>
but it comes back and says 'undefined local variable or method 'json' for class blah blah'
same type of deal for the index view. The example says to just throw this in your view,
%table#products
%thead
%tr
%th= Product.human_attribute_name :name
%th= Product.human_attribute_name :manufacturer
%tbody
but if I do that it simply puts that raw text in my view. Again, it seems like the author is using some gem to parse his views but not referencing it in the docs. Any thoughts? Thanks!
Edit:
Ok, so I got the table to load correctly by calling it as a table... duh...
<table class="products">
<thead>
<tr>
<th>Name</th>
<th>Manufacturer</th>
</thead>
<tbody></tbody>
</table>
but it is now telling me it has no data to load. I checked the route and /search works but /search.datatables comes back telling me there is no template. Thanks again,
A: The author isn't using any other gem as far as I can tell.
@products.each do |product|
json << [product.name, product.manufacturer.name]
end
You need to put the above code into a search.datatables.jsonify file instead of just search.datatables.
Also you should change the class="products" to id="products" in your table markup. You will also want to put the corresponding id's into the th tags too.
Finally the javascript was a bit mangled too, try the following
$("#products").dataTable( {
"sAjaxSource" : "/products/search.datatables",
"aaSorting" : [[0, 'asc']],
"aoColumns" : [
{"sName":"name"},
{"sName":"manufacturer_name"},
],
"bServerSide" : true,
"fnServerData" : simpleDatatables
});
Hope this helps.
A: The index view is using the haml gem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Publish post with picture and link on event's wall Is there a way to publish a post with a picture and a link on an event's wall? Currently I can publish only statuses (messages). On the user's wall there is no such issue. I've tried the new Graph API as well as the old REST API ('stream.publish' method) with no success (using PHP SDK).
Thank you in advance.
The code I use for Graph API:
$attachment = array(
'message' => 'my message',
'name' => 'This is my demo Facebook application!',
'caption' => "Caption of the Post",
'description' => 'this is a description',
'picture' => 'link to an image',
'actions' => array(array('name' => 'See recipe',
'link' => 'http://www.google.com'))
);
$facebook->api('/'.$eventID.'/feed/','post',$attachment);
The code for REST API:
$url = "https://api.facebook.com/method/stream.publish?".$access_token;
$attachment = array('name' => 'This is my demo Facebook application!',
'href' => 'http://news.google.com',
'description' => 'It is fun!',
'media'=> array(array(
'type'=> 'image',
'src' => 'link to an image',
'href' => 'http://www.google.gr'))
);
$params = array();
$params['message'] = "my message";
$params['attachment'] = json_encode($attachment);
$params['target_id'] = $eventID;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
curl_close($ch);
As I mentioned above, both is working if I publish on user's wall. On event's wall a status message is published showing only the content of 'message' parameter.
A: I have the same problem. The event wall post only appears as text message, it is not possible to post a "link" or a "post" to the event wall via any API.
The same post appears differently on the users wall or on the event wall.
The behavior can be tested here:
http://developers.facebook.com/docs/reference/rest/stream.publish/
Just fill out the form and post the same message with a valid attachment once to the users wall and once with a target id (for an event) and see the difference.
This behavior is not documented and also google gives not much help.
Any workarounds or explanations would be appreciated.
Here is a demo attachment (working on the users wall):
{
"name": "Test name",
"href": "http://www.google.com",
"description": "Test Desc",
"media": [
{
"type": "image",
"src": "(any image)",
"href": "http://www.google.com"
}
]
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Add to favorites, jquery I am creating a 'favorites' style system for a property webiste where users can save a property to be viewed later. The system works using Jquery so the page doesn't have to refresh. The details page of a property contains a 'add to favorites button' and this works fine:
$("#addFavorites").click(function() {
var locationID = $("#locationID").val();
But how would I code this when all of the properties are listed together on one page, each 'add to favorites' button would have to use a unique id or something but not sure how to approach this.
A: Well the most precise way would be a default HTML-Formular. I'll make it a short one:
<form ...>
<label for="fav1">Fav1</label>
<input type="checkbox" name="favorites[]" id="fav1" value="1" />
<label for="fav2">Fav2</label>
<input type="checkbox" name="favorites[]" id="fav2" value="2" />
<submit>
</form>
Now that's the ugly form, you can make this beautiful with CSS. With jQuery you now always submit the form when the user checks any of the checkboxes, like:
$('input[type=checkbox]').change(//do ajax submit);
In the AJAX File you simply read the array:
foreach($_POST['favorites'] as $fav) {
addFavToUser($fav, $user);
}
This is like simply explained to give you an idea, not the whole "clean" solution. But i hope this helps you - if it does, i always appreciate the vote for it ;)
A: Each of your 'favorites' would need a unique id
...
...
Then..
$('.favorite').click(function(){
$(this).whateveryouwanttodo();
});
$(this) will contain the clicked anchor tag. from that you can get the id, and call your ajax post or whatever you want to do with it.
A: In jQuery you can use relative positioning to select the item of interest. So, for example, if each item was followed by a favorite button, you can traverse the DOM from the clicked item to find the related item. You can then post this back via AJAX to store it an update the element as needed to reflect the updated status.
HTML (assumes you use styling to show the icon and favorite status)
<span class="normal" data-location="A">Location A</span> <span class="icon-favorite"></span>
JS
$('.favorite').click( function() {
var data = [],
newClass = 'favorite',
oldClass = 'normal',
$this = $(this),
$location = $(this).prev('span');
// if already favorited, reverse the sense of classes
// being applied
if ($location.hasClass('favorite')) {
newClass = 'normal';
oldClass = 'favorite';
}
data['location'] = $location.attr('data-location');
$.post('/toggle_favorite', data, function(result) {
if (result.Success) {
$location.removeClass(oldClass).addClass(newClass);
$this.removeClass('icon-'+newClass).addClass('icon-'+oldClass);
}
else {
alert('could not mark as favorite');
}
},'json');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET mvc 3 razor : Html Helper Extension Method - executed but dosen't print html Hi I have problem with my html helper extension method in razor view engine. I want to render SideMenu if I have any nodes to print:
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
</head>
@using MyNamespace.Helpers
<body>
<div id = "page" style = "width: 90%; margin: 0 auto" class="pageSection">
<div id="logo" class="pageSection">aaaa</div>
<div id = "LeftMenuContainer">
@{ if (ViewBag.Menu.LeftMenu.Count > 0)
{
Html.RenderSideMenu((ICollection<MyNamespace.MenuNode>)(ViewBag.Menu.LeftMenu));
}
}
</div>
<div id="content" class="pageSection">@RenderBody()</div>
<div id="footer" class="pageSection"></div>
</div>
</body>
</html>
and here's my method:
public static MvcHtmlString RenderSideMenu(this HtmlHelper helper, ICollection<MenuNode> nodes)
{
string result = "<h3>Menu</h3>";
result += "<ul class=\"SideMenu\">";
foreach (var node in nodes)
result += MenuRenderEngine.RenderNode(node);
result += "</ul>";
return MvcHtmlString.Create(result);
}
The problem is that method is executed and returns well prepared string but doesn't print it in view so I'm confused what did I wrong?
A: Use @ if you want to output the result on the page:
<div id = "LeftMenuContainer">
@if (ViewBag.Menu.LeftMenu.Count > 0)
{
@Html.RenderSideMenu((ICollection<MyNamespace.MenuNode>)(ViewBag.Menu.LeftMenu));
}
</div>
Also, as a side note, don't use ViewBag, use view models instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to Preserve/Protect Certain Fields in Edit in ASP.NET MVC In an Edit action in ASP.NET MVC, certain fields can be hidden from user with HiddenFieldFor. However this doesn't protect the fields (such as ID, data creation date) from being edited.
For example, a model Student has fields Id, Name and Birthday. I like to allow users to update the Name, but not Id nor Birthday.
For an Edit action like this
public ActionResult Edit(Student student)
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
How can I prevent Id and Birthday from being edited? Thanks!
A: You should use a view model which contains only the properties that you want to be edited:
public class EditStudentViewModel
{
public string Name { get; set; }
}
and then:
public ActionResult Edit(StudentViewModel student)
{
...
}
Another technique which I don't recommend is to exclude certain properties from binding:
public ActionResult Edit([Bind(Exclude = "Id,Birthday")]Student student)
{
...
}
or include:
public ActionResult Edit([Bind(Include = "Name")]Student student)
{
...
}
A: I assume you have to have the properties in your Model so that in View you can use them to render useful information e.g. an ActionLink with ID or some readonly Text.
In this case you can define your model with an explicit binding:
[Bind(Include = "Name")]
public class Student
{
int Id { get; set; }
int Name { get; set; }
DateTime Birthday { get; set; }
}
This way when updating your model, if the user submits an extra Id it will not be bound.
Another idea I like is having your model know its bindings per scenario and have them compiler validated:
public class ModelExpression<T>
{
public string GetExpressionText<TResult>(Expression<Func<T, TResult>> expression)
{
return ExpressionHelper.GetExpressionText(expression);
}
}
public class Student
{
public static string[] EditBinding = GetEditBinding().ToArray();
int Id { get; set; }
int Name { get; set; }
DateTime Birthday { get; set; }
static IEnumerable<string> GetEditBinding()
{
ModelExpression<Student> modelExpression = new ModelExpression<Student>();
yield return modelExpression.GetExpressionText(s => s.Name);
}
}
This way in your Action when calling TryUpdateModel you can pass this information.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Creating lambda inside a loop I am trying to create lambdas inside a loop that iterates over a list of objects:
lambdas_list = []
for obj in obj_list:
lambdas_list.append(lambda : obj.some_var)
Now, if I iterate over the lambdas list and call them like this:
for f in lambdas_list:
print(f())
I get the same value. That is the value of the last obj in obj_list since that was the last variable in the block of the list iterator. Any ideas for a good (pythonic) rewrite of the code to make it work?
A: You can do something like that:
def build_lambda(obj):
return lambda : obj.some_var
lambdas_list = []
for obj in obj_list:
lambdas_list.append(build_lambda(obj))
A: Use this line instead:
lambdas_list.append(lambda obj=obj: obj.some_var)
A: You either have to capture the variable using default assignments
lambdas_list = [ lambda i=o: i.some_var for o in obj_list ]
or, use closures to capture the variable
lambdas_list = [ (lambda a: lambda: a.some_var)(o) for o in obj_list ]
In both cases the key is to make sure each value in the obj_list list is assigned to a unique scope.
Your solution didn't work because the lexical variable obj is referenced from the parent scope (the for).
The default assignment worked because we reference i from the lambda scope. We use the default assignment to make "passing" the variable implicit by making it part of the lambda definition and therefore its scope.
The closure solution works because the variable "passing" is explicit, into the outer lambda which is immediately executed, thus creating the binding during the list comprehension and and returning the inner lambda which references that binding. So when the inner lambda actually executes it will be referencing the binding created in the outer lambda scope.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
} |
Q: Deleting of an item, indexing problem... for (var i = 0; i < max; i++) {
deleteButton[i].addEventListener('click', function (e) {
AddPatientVitalsModel.globalData.splice(i, 1);
});
}
When i click on a button, a new table is added... i change some information in table and again add another table... and i delete this table... but the array value does delete the first index alone.
The Value of i is always zero and it deletes the first item in the Array. How can i ensure that for each table it has different ID.
For each click i feel so that i value always starts from Zero....
A: You're overwriting the value of i at each loop. You could use an anonymous function to pass the variable by value:
for (var i = 0; i < max; i++) {
(function(i){ //i is now defined within the scope of this anonymous function
deleteButton[i].addEventListener('click', function (e) {
AddPatientVitalsModel.globalData.splice(i, 1);
}, true);
})(i); //Pass i to the anonymous function
}
Note that i can have a different name inside the anonymous function, without making a difference.
ANother notice: Pass three arguments to addEventListener, because many browsers will throw an error if the third argument is omitted.
A: Because i scope is outside event. You need get index from variable e, or maybe work this code:
for (var i = 0; i < max; i++) {
var ii = i;
deleteButton[i].addEventListener('click', function (e) {
AddPatientVitalsModel.globalData.splice(ii, 1);
});
}
But I am not sure it works on javascript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: copy full local Wordpress website from a computer to another I have a wordpress website which is installed by Microsoft Webtrix on my computer A.
I have installed Microsoft Webmatrix on my computer B so that I can continue my work on computer B so that I can continue work on computer B.
I want to copy my full wordpress website (website content + database) from computer A to B.
I can not find a tutorial which teaches how to copy database from computer A to B.
I am totally new to creating web so please kindly help.
Thanks
A: Your best long term solution is to learn how to export WordPress sites from local to local development environments as well as local to live host.
*
*Within your present set up simply copy all files from wp-content of the site and transfer them to your new set up.
*Add a plugin to your original site such as WP Database Backup. This will allow you to dump the .sql (database) and keep a copy as a backup.
*Over to the new set up (B computer). Create a new wordpress site.
*Copy and paste the wp-content folder into the new site.
*Now this is where you need to check with web matrix on your new set up. You'll need to make sure the wp-config.php file has the correct settings such as db name and password user etc.
*Finally upload the backup db .sql file via the db plugin mentioned in step 2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Translation rule I like to create a translation rule to a VoIP system to obtain the following result:
If someone dials the 4545 the system must convert this to 1234545, I managed to do this with the following rule: s/^4545/1234545/
My problem now is if someone dials 454567 my rule will convert this to 123454567 and I want to get 1234545
thx
A: Not clear on why should 454567 become 1234545? Should a string with a run of 4545 anywhere in it be come 1234545?
If you just want to change the exact string 4545 to 1234545 then you can use s/^4545$/1234545/.
If you want a string with a run of 4545 anywhere in it to become 1234545 then you can use s/.*4545.*/1234545.
A: $number='1234545' if ($number eq '4545'); #eq because phone number can contain non-digits.
If you want to convert any number that starts with '4545', use this code:
s/^4545.*/1234545/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Visual Studio 2010 C# Windows-Forms Editor Bug I currently have an annoying bug with the Editor in Visual Studio 2010 Express. Whenever I add a CustomControl in the Editor, any changes I make after that to the form, isn't saved in the .cs File, which basically means that when I add f.e. a MenueStrip to the Form, the code won't be generated and will not be added to the .cs file, but it will be displayed in the Editor correctly. Any idea how I can fix this?
The Custom Control is a XNA-Control and it works properly.
EDIT: Someone suggested restarting VS. It did work but I do have another Bug now. I can now apply changes to the Form and add / delete Stuff, but when ever I run the app the CustomControl will be deleted from the .cs after I stopped debugging, which means that I need to re-add the CustomControl after every run.
EDIT2: I found a workaround. After running the app, the Editor-Window can be bugged, so no changes you make are applied to the .cs file, a simple closing and re-oppening of the Editor of the Form will fix the Problem.
A: The one time I've come across this kind of behavior, it was related to the InitializeComponent() function signature being modified by the developer. Which is probably not the case here.
Could you post a small working example that reproduces the problem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: mysql TEMPORARY TABLE stored in ram? I've developed a small c# application that uses quite intensive Database calculations.
I am hosting my application in a shared hosting environment.
I am getting :
mysql out of memory exception
I am using quite a lot of temporary tables. Where are these tables stored?
Could this be the reason for this error?
Thank you
A: Temporary tables are stored in memory, but if the temporary table gets too large it will get moved to the file system. Lots of temporary tables can definitely eat up a lot of memory and cause other kinds of performance problems as well. Also, large result sets can cause similar issues, so it's a good idea to check you're only fetching what you need and that the keys and indexes are correctly defined.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Php call Soap function and passing data i'm trying launching a simple Soap call in my application.
The Soap Web Service is located: 'http://www.asd.com?wsdl'
The Soap Web Service expose method : upload() , to the Ws upload() method i can pass a string data: 'arg0'
so my code looks like as shown:
$wsdl = "http://www.asd.com?wsdl";
$ws = new SoapClient($wsdl);
$vem = $ws->__soapCall('upload', array('arg0'=>'sgfsg'));
Seems that WS method receives arg0 = NULL, is this PHP code ok?
the WS wsdl
<wsdl:definitions name="aWS" targetNamespace="http://validator.aWS.it/">
<wsdl:import location="http://asd.com/aWS?wsdl=aWSDL.wsdl" namespace="http://interfaces.aWS.it/">
</wsdl:import><wsdl:binding name="aWSSoapBinding" type="ns1:...">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="Upload">
<soap:operation soapAction="" style="document"/>
<wsdl:input name="Upload">
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output name="UploadResponse"><soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="ping">
<soap:operation soapAction="" style="document"/>
<wsdl:input name="ping">
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output name="pingResponse">
<soap:body use="literal"/>
</wsdl:output>
<wsdl:fault name="NonBlockingExecption">
<soap:fault name="NonBlockingExecption" use="literal"/>
</wsdl:fault>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="aWS">
<wsdl:port binding="tns:aWSSoapBinding" name="aWSPort">
<soap:address location="http://asd.com/aWS"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
the wsdl types
<wsdl:definitions name="aWS" targetNamespace="http://interfaces.aWS.it/">
<wsdl:types>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="unqualified" targetNamespace="http://interfaces.aWS.it/">
<xs:element name="Upload" type="tns:Upload"/>
<xs:element name="UploadResponse" type="tns:UploadResponse"/>
<xs:element name="ping" type="tns:ping"/>
<xs:element name="pingResponse" type="tns:pingResponse"/>
<xs:complexType name="Upload">
<xs:sequence>
<xs:element minOccurs="0" name="arg0" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="UploadResponse">
<xs:sequence/>
</xs:complexType>
<xs:complexType name="ping">
<xs:sequence/>
</xs:complexType>
<xs:complexType name="pingResponse">
<xs:sequence>
<xs:element name="return" type="xs:int"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="NonBlockingExecption">
<xs:sequence/>
</xs:complexType>
<xs:element name="NonBlockingExecption" type="tns:NonBlockingExecption"/>
</xs:schema>
</wsdl:types>
<wsdl:message name="NonBlockingExecption">
<wsdl:part element="ns1:NonBlockingExecption" name="NonBlockingExecption">
</wsdl:part>
</wsdl:message>
<wsdl:message name="Upload">
<wsdl:part element="ns1:Upload" name="parameters">
</wsdl:part>
</wsdl:message>
<wsdl:message name="pingResponse">
<wsdl:part element="ns1:pingResponse" name="parameters">
</wsdl:part>
</wsdl:message>
<wsdl:message name="ping">
<wsdl:part element="ns1:ping" name="parameters">
</wsdl:part>
</wsdl:message>
<wsdl:message name="UploadResponse">
<wsdl:part element="ns1:UploadResponse" name="parameters">
</wsdl:part>
</wsdl:message>
<wsdl:portType name="aWS">
<wsdl:operation name="Upload">
<wsdl:input message="ns1:Upload" name="Upload">
</wsdl:input>
<wsdl:output message="ns1:UploadResponse" name="UploadResponse">
</wsdl:output>
</wsdl:operation>
<wsdl:operation name="ping">
<wsdl:input message="ns1:ping" name="ping">
</wsdl:input>
<wsdl:output message="ns1:pingResponse" name="pingResponse">
</wsdl:output>
<wsdl:fault message="ns1:NonBlockingExecption" name="NonBlockingExecption">
</wsdl:fault>
</wsdl:operation>
</wsdl:portType>
</wsdl:definitions>
A: Try to change the soap method invocation (third instruction) with:
$vem = $ws->upload("sgfsg");
Usually in WSDL mode soap function are called as methods of the Soap Client object instead of using soapCall.
I tried to open http://www.asd.com?wsdl but i can't see any wsdl code.
If the operation upload only needs a string as parameter you can pass it without building an array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create dynamic video/slideshow from pictures in PHP I have a dynamic archive (a folder on my ftp space) where are loaded images from webcam. Now i want to create an easy slideshow or video with these images each time the user want to watch it.
No any transition options or others....i need to build a siple timelapse from images captured by camera.
i've just try this http://www.maani.us/xml_slideshow/ it works fine (i can build with php a dynamic xml configuration file for the swf script) but i can't set the time transition less than 1 second...and is not free...
Any simple solution? (also javascript if it is better...)
Thanx!
A: If you want the end result to be a video file you could do something similar to what I did when turning a series of Google Streetview panoramas into an immersive time-lapse video.
It's all done on the server using PHP & ffmpeg. Here's some sample code pared down from the original source.
ffmpeg command:
$makeMovieFfmpeg = "ffmpeg -r 4 -f image2 -i dir/%d.jpg -s 800x600 -r 15 -s 800x600 -b 1500kbs myvideo.avi 2>&1";
Explanation:
-r 4 //input framerate of 4fps
-f image2 //invoke the image2 file demuxer since we're working with a series of images
-i //location of image files with applied pattern where %d represents numeric sequence
-s //input image size
-r //output framerate of 15fps
-s //output video size
-b //set the bitrate
2>&1 //redirects stderr to stdout in order to make output available to PHP
Execute command:
print_r (exec($makeMovieFfmpeg,$ret,$err));
A: PHP is a merely string manipulation language
You cannot create a slideshow in PHP. It's server-side language.
A: I think You can create GIF sequence like one in here:
http://www.dreamincode.net/forums/topic/53942-create-gif-images-using-gd/
A: That's the best way i found: simple and speedy
<HTML>
<HEAD>
<TITLE>Video</TITLE>
</HEAD>
<BODY BGCOLOR="#000000">
<img name="foto">
<SCRIPT LANGUAGE="JavaScript">
var Pic = new Array();
Pic[0] = '/images/image1.jpg'
Pic[1] = '/images/image2.jpg'
Pic[2] = '/images/image3.jpg'
//this part in real code is replaced with a PHP script that print image location dinamically
var t;
var j = 0;
var p = Pic.length;
var preLoad = new Array();
for (i = 0; i < p; i++) {
preLoad[i] = new Image();
preLoad[i].src = Pic[i];
}
//all images are loaded on client
index = 0;
function update(){
if (preLoad[index]!= null){
document.images['foto'].src = preLoad[index].src;
index++;
setTimeout(update, 1000);
}
}
update();
</script>
</BODY>
</HTML>
A: Ffmpeg is your best solution. https://www.ffmpeg.org/download.html
Fast way to create slideshow from image is running below command
ffmpeg -framerate 20 \
-loop 1 -t 0.5 -i 1.jpg \
-loop 1 -t 0.5 -i 2.jpg \
-loop 1 -t 0.5 -i 3.jpg \
-loop 1 -t 0.5 -i 4.jpg \
-c:v libx264 \
-filter_complex " \
[1:v][0:v]blend=all_expr='A*(if(gte(T,0.5),1,T/0.5))+B*(1-(if(gte(T,0.5),1,T/0.5)))'[b1v]; \
[2:v][1:v]blend=all_expr='A*(if(gte(T,0.5),1,T/0.5))+B*(1-(if(gte(T,0.5),1,T/0.5)))'[b2v]; \
[3:v][2:v]blend=all_expr='A*(if(gte(T,0.5),1,T/0.5))+B*(1-(if(gte(T,0.5),1,T/0.5)))'[b3v]; \
[0:v][b1v][1:v][b2v][2:v][b3v][3:v]concat=n=7:v=1:a=0,format=yuv420p[v]" -map "[v]" out.mp4
it will create a slideshow with blend effect.
You can check below memo for other effect https://github.com/letungit90/ffmpeg_memo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how can i find a key in a map based on a pattern matching in scala I want to find a key in a map that is similar to a specific text. should I use for loop or is there a more elegant way?
A: The direct translation of your question is map.keys.find(_.matches(pattern)) which given a map, gets they keys and finds the first key that matches the regexp pattern.
val map = Map("abc" -> 1, "aaa" -> 2, "cba" -> 3)
map.keys.find(_.matches("abc.*"))
// Some(abc)
map.keys.find(_.matches("zyx"))
// None
A loop may be counter productive if you don't want to scan all keys.
A: Suppose you have some regular expression which you wish to match on:
val RMatch = """\d+:(\w*)""".r
And a function, which takes the matched group for the regex, and the value in the map
def f(s: String, v: V): A
Then you can match on the regex and collect the value of the function:
map collectFirst { case (RMatch(_), v) => f(txt, v) }
If you just wanted the value...
map collectFirst { case (RMatch(txt), v) => v }
Note: the implementation of this method effects a traversal on the map, in case that is not what you were desiring
A: It depends on the pattern and the map's underlying implementation. If the map is a HashMap, then it can only give you an exact match against a key, so you can't do anything better than loop over its keys. If the map is a SortedMap and you know the beginning of the text you're looking for, then you can use the range method to obtain a part of the map based on the pattern, and loop over that range.
A: It really depends on what you mean by 'similar to' and 'text'. If you are using English words you could use the Soundex algorithm (http://en.wikipedia.org/wiki/Soundex) to give you a code for each word and use that as a hash key, collecting all the words with the same Soundex value together in a list. If you want to do full text matching then it's a lot more complicated and you need to use techniques such as Inverted Indexes (http://en.wikipedia.org/wiki/Inverted_index). In that case you'd be best looking at something pre-written such as Apache Lucene (http://lucene.apache.org/java/docs/) which gives you much more besides simple inverted indexes. Lucene is written in Java, so it is directly usable from Scala.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Mouse hover event not working for the second time I am using asp.net text box and I am showing the border for the text box on mouse hover event and its pretty well doing it's job for the first time and when I click on the text box and again click outside the textbox and If I mouse hover the same textbox it dosen;t show me the border.
Can anyone say me where I am doing wrong?
Thanks in advance!
Here is my css code:
.onfocus
{
border-width: thin;
border-color: #0033CC;
}
.onblur
{
border:0px;
}
.MyTextbox:hover{border:1px solid red;}
Here is how I am using it:
<script type ="text/javascript">
function Change(obj, evt) {
if (evt.type == "focus")
obj.className = "onfocus";
else if (evt.type == "blur")
obj.className = "onblur";
}
<asp:TextBox ID="txtUsername" runat="server" Style="position: absolute; top: 76px;
left: 24px; width: 189px; height: 24px; outline: none;" onfocus ="Change(this, event)"
onblur ="Change(this, event)" BackColor="#FAFFBD" CssClass="MyUsername" ></asp:TextBox>
A: " outline: none;"
where is the style attr ?
A: The hover is not working the second time because your javascript code on focus/blur is changing the class value for the textbox so that it no longer has the "MyTextbox" class. Since your border change on hovering is done based on the MyTextbox class, it no longer works after that.
What you should be doing instead of setting obj.className = "onfocus", is to add the "onfocus" class to the existing value so that it is not lost. Then, during the blur event, you would remove the onfocus class, and add in the onblur class (again, not just totally replacing the className value).
This question has some good answers about how you can properly add/remove the extra classes in either plain javascript or with jQuery (which makes it much easier).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a pattern or trick to force evaluation on both expressions in an OR conditional statement? What is the best way (pattern) around return method1() || method2() not invoking method2() if method1() returns true?
Example
I'm using this class to bound a table:
class Bounds {
// return true iff bounds changed
boolean set(int start, int end);
}
and I want this function to resize both the rows and columns and return true iff either was modified:
public boolean resizeToFirstCell(Bounds rows, Bounds columns) {
return rows.set(0, 1) || columns.set(0, 1);
}
A: Use a non-short circuiting (sometimes called "Eager") operator, |.
public boolean resizeToFirstCell(Bounds rows, Bounds columns) {
return rows.set(0, 1) | columns.set(0, 1);
}
You can read more about that in the operator documentation for || (C# specific link, but still holds true for Java and C++).
A: public boolean resizeToFirstCell(Bounds rows, Bounds columns) {
// Intermediate values are used to explicitly avoid short-circuiting.
bool rowSet = rows.set(0, 1);
bool columnSet = columns.set(0, 1);
return rowSet || columnSet;
}
A: Here's a "pattern" that scales well for more statements:
bool fun() {
bool changed = false;
changed |= rows.set(0, 1);
chnaged |= columns.set(0, 1);
return changed;
}
A: Please use the | eager evaluation instead of shortcircuit operator http://en.wikipedia.org/wiki/Short-circuit_evaluation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do i display my data when overriding getview Ive been learning about the getview . But i cant get it to display the data in my listview. Can anyone help code is below
//public class OrderProductSearch extends Activity {
public class OrderProductSearch extends Activity {
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
HashMap<String,String> item = new HashMap<String,String>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.orderproducts);
}
catch (Exception e) {
//
String shaw="";
shaw = e.getMessage();
}
//Create view of the list where content will be stored
final ListView listContent = (ListView)findViewById(R.id.orderproductlistview);
//Set for fast scrolling
listContent.setFastScrollEnabled(true);
//Create instance of the database
final DbAdapter db = new DbAdapter(this);
//Open the Database and read from it
db.openToRead();
//Routine to call all product sub groups from the database
final Cursor cursor = db.getAllSubGroupProduct();
//Manages the cursor
startManagingCursor(cursor);
int i=0;
cursor.moveToFirst();
while (cursor.getPosition() < cursor.getCount()) {
item.put("ProdName",cursor.getString(2));
item.put("ProdSize", cursor.getString(3));
item.put("ProdPack",cursor.getString(4));
item.put("OrdQty","0");
//list.add(item);
list.add(i, item);
item = new HashMap<String,String>();
cursor.moveToNext();
i = i + 1;
}
String[] from = new String[] {"ProdName", "ProdSize", "ProdPack", "OrdQty"};
int[] to = new int[] { R.id.productlinerow, R.id.productlinerow2, R.id.productlinerow3, R.id.productlinerow4};
//SimpleAdapter notes = new SimpleAdapter(OrderProductSearch.this,list,R.layout.productlinerow,from,to);
NewAdapter notes = new NewAdapter(OrderProductSearch.this,list,R.layout.productlinerow,from,to);
listContent.setAdapter(notes);
//Close the database
db.close();
}
class NewAdapter extends SimpleAdapter{
int resource;
Context cxt;
private Context context;
List<? extends Map<String, ?>> DataList;
public NewAdapter(Context context, List<? extends Map<String, ?>> data,
int _resource, String[] from, int[] to) {
super(context, data, _resource, from, to);
resource = _resource;
this.context = context;
DataList = data;
// TODO Auto-generated constructor stub
}
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.productlinerow, null);
}
// TextView bTitle = (TextView) v.findViewById(R.id.productlinerow);
// bTitle.setText(DataList[position,1][1].toString());
return v;
}
}
}
A: If you're using a SimpleAdapter, you don't need to extend the class and customize the getView() as the SimpleAdapter handles the mapping of data to your layout via the resource, from and to parameters. Take a look at this tutorial for the idea:
http://vbsteven.com/archives/24
If you want to do more involved customization, use a BaseAdapter, which the SimpleAdapter actually extends. Here's a tutorial with examples of that:
http://android.amberfog.com/?p=296
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Add Checkbox Cell to NSTableView with Cocoa Bindings? I'm new in Cocoa. I have a table that stores Contacts. I'm not using NSTableView Protocol. I'm using Cocoa Bindings , and Mutable Array for storing in it. The question is , I want to be able to have checkbox on each row, and select contacts that I want, and be able to get selected rows. How can I do it? When I try to put Check box cell in column of Table, nothing works. Here my code how I'm filling my NSTableView for contacts. So what should be done to be able add checkboxes and handle them? Thanks.
NSMutableDictionary *dict =[NSMutableDictionary dictionaryWithObjectsAndKeys:
Name, @"Name",
Surname, @"Surname",
Education,@"Education",
nil];
//controller for binding data to NSTableView
[controllerContacts addObject:dict];
//Table for viewing data.
[viewTableOfContacts reloadData];
A: If you want to use checkbox at each row via bindings, you need to define a key in dict corresponding to your binding for check box.
In your case, it can be like this-
NSMutableDictionary *dict =[NSMutableDictionary dictionaryWithObjectsAndKeys:
Name, @"Name",
Surname, @"Surname",
Education,@"Education",
[NSNumber numberWithInt:0],@"selectedStudent",
nil];
Then bind that column for "selectedStudent" key.
Also if you want to retrieve only selected rows, you can use NSPredicate like this-
NSPredicate *selectedStudentPredicate = [NSPredicate predicateWithFormat:@"selectedStudent == 1"];
NSArray *selectedStudents = [controllerContacts filteredArrayUsingPredicate:selectedStudentPredicate];
Hope this helps !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rails 3 HTML Injection Currently following the Learning Rails Screencasts at http://www.buildingwebapps.com/learningrails, making any necessary changes to work in Rails 3. However, in the tenth episode, I'm having a problem when rendering html code out of the database. The Page model in the tutorial has a body field, where the html of each page is put. The viewer controller's 'show' method grabs a Page from the database, and yields the contents of @page.body into the view. However, instead of rendering tags such as h1 properly, when I view the html source in the browser my tags are being rendered as <h1;@gt. Is there any way I can fix this?
Just for reference, my 'show' view is as follows:
<%= @page.body %>
A: Try this:
<%= raw(@page.body) %>
Raw method prevents escaping HTML characters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add 2 variables in Javascript I want to add two variables which have numeric values using javascript.
var seconds = 1100;
var time = 300;
var newV = seconds + time;
$('.show').html(newV);
But it is saying undefined
thanx
A: http://jsfiddle.net/n9NcY/
This HTML is probably what you were missing
<div class="show"> </div>
your code
$(document).ready(function() {
var seconds = 1100;
var time = 300;
var newV = seconds + time;
$('.show').html(newV);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-8"
} |
Q: How to create, open, save and close a file or directory in javascript? Is there a cross-platform way to do these actions? Or only open files, the user download the files. I want to make a mmo side-scrolling game, and it needs to save maps, sprites and musics.
A: It's not possible to access the local filesystem at the client's side. If your data is text (image -> text through base64 data uri's), the DOM Storage may be interesting for you. The files must be base64-encoded at the server's side, though.
References:
*
*https://developer.mozilla.org/en/data_URIs
*https://developer.mozilla.org/en/DOM/Storage
A: JavaScript has no I\O capabilities by itself.
If you want to reduce the traffic use the model in Travian:
*
*the user can save all of the resource files needed to his PC, device etc;
*the user submits to the server the path, where the resource files are saved;
*the game generates custom css with localpath (the path to the files on his machine).
This will reduce the traffic enormously.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Search for a keyword in C# and output the line as a string How would it be possible to search for a string e.g. #Test1 in a text file and then output the line below it as a string e.g.
Test.txt
#Test1
86/100
#Test2
99/100
#Test3
13/100
so if #Test2 was the search keyword "99/200" would be turned into a string
A: Parse the file once, store the results in a dictionary. Then lookup in the dictionary.
var dictionary = new Dictionary<string, string>();
var lines = File.ReadLines("testScores.txt");
var e = lines.GetEnumerator();
while(e.MoveNext()) {
if(e.Current.StartsWith("#Test")) {
string test = e.Current;
if(e.MoveNext()) {
dictionary.Add(test, e.Current);
}
else {
throw new Exception("File not in expected format.");
}
}
}
Now you can just say
Console.WriteLine(dictionary["#Test1"]);
etc.
Also, long-term, I recommend moving to a database.
A: Use readline and search for the string (ex. #Test1) and then use the next line as input.
A: If the exactly above is the file format. Then you can use this
1. read all lines till eof in an array.
2. now run a loop and check if the string[] is not empty.
Hold the value in some other array or list.
now you have items one after one. so whenever you use loop and use [i][i+1],
it will give you the test number and score.
Hope this might help.
A: How about RegularExpressions? here's a good example
A: This should do it for you:
int lineCounter = 0;
StreamReader strReader = new StreamReader(path);
while (!strReader.EndOfStream)
{
string fileLine = strReader.ReadLine();
if (Regex.IsMatch(fileLine,pattern))
{
Console.WriteLine(pattern + "found in line " +lineCounter.ToString());
}
lineCounter++;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Array of struct pointers and assigning struct data I have run into a problem or maybe I am just doing something wrong since I am new to C and structs. I want to take a text file such as this:
3
Trev,CS,3.5
Joe,ART,2.5
Bob,ESC,1.0
and read in the first line as the number of students then from there out gather student info and put them in a struct called StudentData:
typedef struct StudentData{
char* name;
char* major;
double gpa;
} Student;
Where I run into a problem is after I seemingly assign the data to an individual struct, the struct data becomes mixed up. I have commented out exactly what is going on (or at least what I believe is). Hopefully it isn't painful to read.
main(){
int size, i;
char* line = malloc(100);
scanf("%d\n", &size);//get size
char* tok;
char* temp;
Student* array[size]; //initialize array of Student pointers
for(i = 0; i<size;i++){
array[i] = malloc(sizeof(Student));//allocate memory to Student pointed to by array[i]
array[i]->name = malloc(50); //allocate memory for Student's name
array[i]->major = malloc(30);//allocate memory for Student's major
}
for(i = 0; i<size;i++){
scanf("%s\n", line);//grab student info and put it in a string
tok = strtok(line, ","); //tokenize string, taking name first
array[i]->name = tok;//assign name to Student's name attribute
// printf("%s\n",array[i]->name);//prints correct value
line = strtok(NULL, ",");//tokenize
array[i]->major = line;//assign major to Student's major attribute
// printf("%s\n",array[i]->major);//prints correct value
temp = strtok(NULL, ",");//tokenize
array[i]->gpa = atof(temp);//assign gpa to Student's gpa attribute
// printf("%.2f\n\n",array[i]->gpa); //prints correct value
}
for(i=0;i<size;i++){ //this loop is where the data becomes jumbled
printf("%s\n",array[i]->name);
printf("%s\n",array[i]->major);
printf("%.2f\n\n",array[i]->gpa);
}
}
The output looks like this:
Trev
Joe
3.50
Joe
Bob
2.50
Bob
ESC
1.00
I can't really understand what is going on in the memory between assigning values and printing them.
A: You can't use regular assignment with char * like that. You will need to use strcpy. For example:
strcpy(array[i]->name,tok);
Otherwise you are making all the array[i]->name point to the same string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL & PHP get depth of item in hierarchy with parent_id I have a common database structure using parent_id for a hierarchy.
I'm trying to find out the depth of an item.
So take for example this:
ID Name Parent_id
1 Games 0
2 Nintendo 1
3 DS 2
4 3D 3
If I wanted to find out the depth of ID 4 (3D), the answer is 3. Any idea how I would query this or a combination of sql and php?
Thank you!
A: Do you have a naive implementation? are you looking for the best way? Trees are recursive, so I think you will query the db as much as the tree height.
this pseudo-php
function getHeigth($item_name) {
$res = 0;
$current_parent_id = executeSql("SELECT parent_id FROM games g WHERE g.name= ? " , $item_name);
while ($current_parent_id != 0) {
$current_parent_id = executeSql("SELECT parent_id FROM games g WHERE g.id = ? " , $current_parent_id);
$res = $res + 1;
}
return $res;
}
This algorithm will perform bad if your three is not balanced.
Storing depth would improve performance, but will impact in UPDATE and INSERT queries.
Also if your tree is broken, this Psuedo-PHP could loop forever
A: The better way to get depth is to store it along with data in a separate field.
An even better way is to use a little more intelligent way of storing hierarchal data, such as Nested Sets or Materialized Path.
Although you can get your depth from your current table setup, it would be most ugly way, recursion, of course.
However, if your table is relatively small, it won't be a big deal though
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem with output, Java I need for my output to be the first 100 pentagonal numbers, ten per row , counting in succession. As it stands my output just repeats itself, i am sure this is a simple answer but i cant seem to come up with it. This was homework and already graded but i would like to figure it out for me to learn. Thanks in advance for any input and help.
package chapter_5;
/**
*
* @author jason
*/
public class Five_One {
public static void main(String[] args) {
for (int k = 1; k < 11; k++) {
for (int n = 1; n < 11; n++) {
System.out.print(getPentagonalNumber(n)+ "\t");
}
System.out.println();
}
}
public static int getPentagonalNumber(int n) {
return n * (3 * n - 1) / 2;
}
}
A: It should be:
System.out.print(getPentagonalNumber((k-1) * 10 + n) + "\t");
because if not, you are writing the first 10 pentagonal numbers, ten times.
In any case, I'd rather try to focus on creating a code that is as easy to read/maintain as possible, so I'd use only one loop:
for (int i = 0; i < 100; i++) {
System.out.print(getPentagonalNumber(i + 1) + "\t");
if (i % 10 == 0) {
System.out.println();
}
}
A: you are repeatedly calling getPentagonalNumber() with numbers in range [1,10], instead of calling numbers in increasing range. can be solved by adding 10*k [and running k from 0 to 10 instead 1 to 11]
public static void main(String[] args) {
for (int k =0; k < 10; k++) { //range is [0,10) instead [1,11)
for (int n = 1; n < 11; n++) {
System.out.print(getPentagonalNumber((10*k)+n)+ "\t"); //10*k + n instead of n
}
System.out.println();
}
}
A: If you need the first 100 pentagonal numbers, you only need one for-loop going from 1 to 100.
Hope this helps.
A: Your output contains
getPentagonalNumber(n)
where n is the column number. Thus each row is the same.
You'll have to incorporate the row number k also in you calculation:
getPentagonalNumber((k-1) * 10 + n)
i.e. from row to row your index is increased by 10.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Question about pathname encoding What have I done to get such a strange encoding in this path-name?
In my file manager (Dolphin) the path-name looks good.
#!/usr/local/bin/perl
use warnings;
use 5.014;
use utf8;
use open qw( :encoding(UTF-8) :std );
use File::Find;
use Devel::Peek;
use Encode qw(decode);
my $string;
find( sub { $string = $File::Find::name }, 'Delibes, Léo' );
$string =~ s|Delibes,\ ||;
$string =~ s|\..*\z||;
my ( $s1, $s2 ) = split m|/|, $string, 2;
say Dump $s1;
say Dump $s2;
# SV = PV(0x824b50) at 0x9346d8
# REFCNT = 1
# FLAGS = (PADMY,POK,pPOK,UTF8)
# PV = 0x93da30 "L\303\251o"\0 [UTF8 "L\x{e9}o"]
# CUR = 4
# LEN = 16
# SV = PV(0x7a7150) at 0x934c30
# REFCNT = 1
# FLAGS = (PADMY,POK,pPOK,UTF8)
# PV = 0x7781e0 "Lakm\303\203\302\251"\0 [UTF8 "Lakm\x{c3}\x{a9}"]
# CUR = 8
# LEN = 16
say $s1;
say $s2;
# Léo
# Lakmé
$s1 = decode( 'utf-8', $s1 );
$s2 = decode( 'utf-8', $s2 );
say $s1;
say $s2;
# L�o
# Lakmé
A: Unfortunately your operating system's pathname API is another "binary interface" where you will have to use Encode::encode and Encode::decode to get predictable results.
Most operating systems treat pathnames as a sequence of octets (i.e. bytes). Whether that sequence should be interpreted as latin-1, UTF-8 or other character encoding is an application decision. Consequently the value returned by readdir() is simply a sequence of octets, and File::Find doesn't know that you want the path name as Unicode code points. It forms $File::Find::name by simply concatenating the directory path (which you supplied) with the value returned by your OS via readdir(), and that's how you got code points mashed with octets.
Rule of thumb: Whenever passing path names to the OS, Encode::encode() it to make sure it is a sequence of octets. When getting a path name from the OS, Encode::decode() it to the character set that your application wants it in.
You can make your program work by calling find this way:
find( sub { ... }, Encode::encode('utf8', 'Delibes, Léo') );
And then calling Encode::decode() when using the value of $File::Find::name:
my $path = Encode::decode('utf8', $File::Find::name);
To be more clear, this is how $File::Find::name was formed:
use Encode;
# This is a way to get $dir to be represented as a UTF-8 string
my $dir = 'L' .chr(233).'o'.chr(256);
chop $dir;
say "dir: ", d($dir); # length = 3
# This is what readdir() is returning:
my $leaf = encode('utf8', 'Lakem' . chr(233));
say "leaf: ", d($leaf); # length = 7
$File::Find::name = $dir . '/' . $leaf;
say "File::Find::name: ", d($File::Find::name);
sub d {
join(' ', map { sprintf("%02X", ord($_)) } split('', $_[0]))
}
A: The POSIX filesystem API is broken as no encoding is enforced. Period.
Many problems can happen. For example a pathname can even contain both latin1 and UTF-8 depending on how various filesystems on a path handle encoding (and if they do).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to calculate ffmpeg output file size? I am using ffmpeg to convert home videos to DVD format and want to calculate the output file size before doing the conversion.
My input file has a bit rate of 7700 kbps and is 114 seconds long. The audio bitrate is 256 kbit (per second?) The input file is 77MB. To get this information I ran:
mplayer -vo null -ao null -frames 0 -identify input.MOD
So in theory, the input file should have (roughly) a file size of:
((7700 / 8) * 114) / 1024
That is, (7700 / 8) is kilobytes/second, multiplied by 114 seconds, and then converted to megabytes. This gives me 107MB, which is way beyond my 77. Thus I am skeptical of his formula.
That said, after converting the video:
ffmpeg -i input.MOD -y -target ntsc-dvd -sameq -aspect 4:3 output.mpg
The numbers seem to make more sense. Bitrate is 9000 kbps, and applying the above formula, I get 125MB, and my actual output file size is 126MB.
So, two questions:
*
*How do I factor the audio bitrate into this calculation? Is it additive (video file size + audio file size)?
*Do DVDs always have a 9000 kilobit/second rate? Is that the definition of a DVD? Or might that change depending on video quality of my input video? What does "-target ntsc-dvd" guarantee about my video?
*Why does my input file not "match" the calculation, but the output file does? Is there some other variable I'm not accounting for?
What is the correct way to calculate filesize?
A: What you have to keep in mind, is that there are few different bitrate measurements to consider:
*
*maximum bitrate - the bitrate of the most action intensive fragment of the video
*average (target) bitrate - the bitrate calculated precisely using your formula
*rate control (how quickly encoder reacts to changes in complexity of the video)
Lossy video encoding works by eliminating features that are hard for human eye to see. This means, that a slow motion, a talking head, can be compressed further than a spinning full-screen zoom/panorama.
Why does it matter? Standards do specify a 'maximum' bitrate for a reason - this is how fast player needs to be in order to read and decode a standards-compliant video. DVD has it around 9000kbps.
Finally, since it's a lossy compression, one can specify the average bitrate. This is used if you need to fit the content in limited space or bandwidth (possibly permitting buffering for the more intense fragments).
For instance, you can have a video with maximum bitrate of 7000kbps and the average bitrate of 5500kbps. Finally, rate control, is the algorithm used to decide how much 'space' encoder should assign to different fragments. If you do multi-pass encoding, you are reusing this information from previous passes - improving the quality and bitrate distribution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Is there a tool to check if an XSLT stylesheet follows coding standards? How can we check whether an XSLT stylesheet is following all the coding standards? Is there a tool where we can specify our own rules and find out if the stylesheet conforms?
A: First of all, there is nothing like
"all coding standards"
...
This said, take a look at the XSLT Lint, developed by Mukul Ghandi, and published Dec. 2008:
http://lists.xml.org/archives/xml-dev/200812/msg00178.html
There is also one published recently by Andriy Gerasika:
http://www.biglist.com/lists/lists.mulberrytech.com/xsl-list/archives/201102/msg00103.html
In case you are interested in functional programming with XSLT, take a look at FXSL.
Finally, if by "all coding standards" you mean "style", you may look at my answers in the xslt tag of SO, to learn a little bit more about "push style" and programming without explicit logical instructions.
A: Well, if the stylesheet works, it should be valid, right?
Other than that, i think all the big XML IDEs like Altova's XMLSpy provide some sort of schema validation, if that's what you're looking for.
A: XSL stylesheets is a XML language. So, validation tools available for XML still applies here. So, DTD or XML namespaces can be used to define the rules to check. Link to the location where the DTD/ns reside in the XSL sheet. Then tools like Xerces can be used for validating the document.
If you are using ANT, xmlvalidate task will do this automatically by invoking Xerces SAXParser.
<target name="validate" if="perform-validation-dtd">
<xmlvalidate file="${input-xml}"
classname="org.apache.xerces.parsers.SAXParser"/>
</target>
A: xmllint program validates an XML file against its DTD (Document Type Definition) and reports on any differences. Read more here
A: Well, an XSLT stylesheet is XML itself of course; you could easily write an XSLT that looks for patterns.
For example:
<xsl:template match="xsl:for-each">
<xsl:text>Inappropriate use of xsl:for-each; should be using templates instead</xsl:text>
</xsl:template>
if your policy includes not using xsl:for-each.
Or, you could write a schema that expands on the xslt one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7546350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.