text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: PHP - checking if two dates match but ignoring the year I have an array which will output a date. This date is outputted in the mm/dd/yyyy format. I have no control over how this outputted so I cant change this.
Array
(
[date] => 04/06/1989
)
I want to use php to check if this date matches the current date (today), but ignoring the year. So in the above example I just want to check if today is the 6th April. I am just struggling to find anything which documents how to ignore the years.
A: if( substr( $date, 0, 5 ) == date( 'm/d' ) ) { ...
Works only if it's certain that the month and date are both two characters long.
A: Came in a little late, but here’s one that doesn’t care what format the other date is in (e.g. “Sep 26, 1989”). It could come in handy should the format change.
if (date('m/d') === date('m/d', strtotime($date))) {
echo 'same as today';
} else {
echo 'not same as today';
}
A: this will retrieve the date in the same format:
$today = date('m/d');
A: Use this:
$my_date = YOUR_ARRAY[date];
$my_date_string = explode('/', $my_date);
$curr_date = date('m,d,o');
$curr_date_string = explode(',', $date);
if (($my_date_string[0] == $curr_date_string[0]) && ($my_date_string[1] == $curr_date_string[1]))
{
DO IT
}
This way, you convert the dates into strings (day, month, year) which are saved in an array. Then you can easily compare the first two elements of each array which contains the day and month.
A: You can use for compare duple conversion if you have a date.
$currentDate = strtotime(date('m/d',time())); --> returns current date without care for year.
//$someDateTime - variable pointing to some date some years ago, like birthday.
$someDateTimeUNIX = strtotime($someDateTime) --> converts to unix time format.
now we convert this timeunix to a date with only showing the day and month:
$dateConversionWithoutYear = date('m/d',$someDateTimeUNIX );
$dateWithoutRegardForYear = strtotime($dateConversionWithoutYear); -->voila!, we can now compare with current year values.
for example: $dateWithoutRegardForYear == $currentDate , direct comparison
A: You can convert the other date into its timestamp equivalent, and then use date() formatting to compare. Might be a better way to do this, but this will work as long as the original date is formatted sanely.
$today = date('m/Y', time());
$other_date = date('m/Y', strtotime('04/06/1989'));
if($today == $other_date) {
//date matched
}
A: hi you can just compare the dates like this
if(date('m/d',strtotime($array['date']])) == date('m/d',strtotime(date('Y-m-d H:i:s',time()))) )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Problems faced when trying to apply good Dependency Injection practice I've been using IoC (mostly Unity) and Dependency Injection in .NET for some time now and I really like the pattern as a way to encourage creation of software classes with loose coupling and which should be easier to isolate for testing.
The approach I generally try to stick to is "Nikola's Five Laws of IoC" - in particular not injecting the container itself and only using constructor injection so that you can clearly see all the dependencies of a class from its constructor signature. Nikola does have an account on here but I'm not sure if he is still active.
Anyway, when I end up either violating one of the other laws or generally ending up with something that doesn't feel or look right, I have to question whether I'm missing something, could do it better, or simply shouldn't be using IoC for certain cases. With that in mind here are a few examples of this and I'd be grateful for any pointers or further discussion on these:
*
*Classes with too many dependencies. ("Any class having more then 3 dependencies should be questioned for SRP violation"). I know this one comes up a lot in dependency injection questions but after reading these I still don't have any Eureka moment that solves my problems:
*
*a) In a large application I invariably find I need 3 dependencies just to access infrastructure (examples - logging, configuration, persistence) before I get to the specific dependencies needed for the class to get its (hopefully single responsibility) job done. I'm aware of the approach that would refactor and wrap such groups of dependencies into a single one, but I often find this becomes simply a facade for several other services rather than having any true responsibility of its own. Can certain infrastructure dependencies be ignored in the context of this rule, provided the class is deemed to still have a single responsibility?
*b) Refactoring can add to this problem. Consider the fairly common task of breaking apart a class that has become a bit big - you move one area of functionality into a new class and the first class becomes dependent on it. Assuming the first class still needs all the dependencies it had before, it now has one extra dependency. In this case I probably don't mind that this dependency is more tightly coupled, but its still neater to have the container provide it (as oppose to using new ...()), which it can do even without the new dependency having its own interface.
*c) In a one specific example I have a class responsible for running various different functions through the system every few minutes. As all the functions rightly belong in different areas, this class ends up with many dependencies just to be able to execute each function. I'm guessing in this case other approaches, possibly involving events, should be considered but so far I haven't tried to do it because I want to co-ordinate the order the tasks are run and in some cases apply logic involving outcomes along the way.
*Once I'm using IoC within an application it seems like almost every class I create that is used by another class ends up being registered in and/or injected by the container. Is this the expected outcome or should some classes have nothing to do with IoC? The alternative of just having something new'd up within the code just looks like a code smell since its then tightly coupled. This is kind of related to 1b above too.
*I have all my container initialisation done at application startup, registering types for each interface in the system. Some are deliberately single instance lifecycles where others can be new instance each time they are resolved. However, since the latter are dependencies of the former, in practice they become a single instance too since they are only resolved once - at construction time of the single instance. In many cases this doesn't matter, but in some cases I really want a different instance each time I do an operation, so rather than be able to make use of the built in container functionality, I'm forced to either i) have a factory dependency instead so I can force this behaviour or ii) pass in the container so I can resolve each time. Both of these approaches are frowned upon in Nikola's guidance but I see i) as the lesser of two evils and I do use it in some cases.
A:
In a large application I invariably find I need 3 dependencies just to access infrastructure (examples - logging, configuration, persistence)
imho infrastructure is not dependencies. I have no problem using a servicelocator for getting a logger (private ILogger _logger = LogManager.GetLogger()).
However, persistence is not infrastructure in my point of view. It's a dependency. Break your class into smaller parts.
Refactoring can add to this problem.
Of course. You will get more dependencies until you have successfully refactored all classes. Just hang in there and continue refactoring.
Do create interfaces in a separate project (Separated interface pattern) instead of adding dependencies to classes.
In a one specific example I have a class responsible for running various different functions through the system every few minutes. As all the functions rightly belong in different areas, this class ends up with many dependencies just to be able to execute each function.
Then you are taking the wrong approach. The task runner should not have a dependency on all tasks that should run, it should be the other way around. All tasks should register in the runner.
Once I'm using IoC within an application it seems like almost every class I create that is used by another class ends up being registered in and/or injected by the container.*
I register everything but business objects, DTOs etc in my container.
I have all my container initialisation done at application startup, registering types for each interface in the system. Some are deliberately single instance lifecycles where others can be new instance each time they are resolved. However, since the latter are dependencies of the former, in practice they become a single instance too since they are only resolved once - at construction time of the single instance.
Don't mix lifetimes if you can avoid it. Or don't take in short lived dependencies. In this case you could use a simple messaging solution to update the single instances.
You might want to read my guidelines.
A: Let me answer question 3. Having a singletons depend on a transient is a problem that container profilers try to detect and warn about. Services should only depend on other services that have a lifetime that is greater than or equals to that of their own. Injecting a factory interface or delegate to solve this is in general a good solution, and passing in the container itself is a bad solution, since you end up with the Service Locator anti-pattern.
Instead of injecting a factory, you can solve this by implementing a proxy. Here's an example:
public interface ITransientDependency
{
void SomeAction();
}
public class Implementation : ITransientDependency
{
public SomeAction() { ... }
}
Using this definition, you can define a proxy class in the Composition Root based on the ITransientDependency:
public class TransientDependencyProxy<T> : ITransientDependency
where T : ITransientDependency
{
private readonly UnityContainer container;
public TransientDependencyProxy(UnityContainer container)
{
this.container = container;
}
public SomeAction()
{
this.container.Resolve<T>().SomeAction();
}
}
Now you can register this TransientDependencyProxy<T> as singleton:
container.RegisterType<ITransientDependency,
TransientDependencyProxy<Implementation>>(
new ContainerControlledLifetimeManager());
While it is registered as singleton, it will still act as a transient, since it will forward its calls to a transient implementation.
This way you can completely hide that the ITransientDependency needs to be a transient from the rest of the application.
If you need this behavior for many different service types, it will get cumbersome to define proxies for each and everyone of them. In that case you could try Unity's interception functionality. You can define a single interceptor that allows you to do this for a wide range of service types.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Javascript, Jquery or css3 oscilating letter animation i'm new in javascript and especially in animation. The challenge for me is to make a letter oscilate back and forth max 30 degrees from the sides. The picture i uploaded is an example of the the animation, the letter will move from the upper right corner or from the pin but i think that is harder.
I need some guidance into this if anyone can help please reply.
Thanks in advance
because i'm new i cannot post images so here is the link: http://i.stack.imgur.com/byzUC.png
A: Well, this took far longer than I care to admit, and is only reliable in (from my own limited testing) Chromium 12+ and Firefox 5+ on Ubuntu 11.04 (it does not work in Opera 11). That being the case I'll show only the excerpts to cover Firefox and Chromium, though the linked JS Fiddle has vendor prefixes to at least try with Opera (even if it fails). Using the following mark-up:
<img src="http://i.stack.imgur.com/byzUC.png" id="envelope" />
The following CSS produces an (infinitely) oscillating envelope for you to adjust to your preferences:
#envelope {
-webkit-animation-name: oscillate;
-webkit-animation-duration: 10s;
-webkit-animation-iteration-count: 10;
-webkit-animation-direction: infinite;
-moz-animation-name: oscillate;
-moz-animation-duration: 10s;
-moz-animation-iteration-count: 10;
-moz-animation-direction: infinite;
}
@-webkit-keyframes oscillate {
0% {
-webkit-transform: rotate(0deg);
-webkit-transform-origin: 108px 23px;
}
33% {
-webkit-transform: rotate(15deg);
-webkit-transform-origin: 108px 23px;
}
100% {
-webkit-transform: rotate(-20deg);
-webkit-transform-origin: 108px 23px;
}
}
@-moz-keyframes oscillate {
0% {
-moz-transform: rotate(0deg);
-moz-transform-origin: 110px 26px;
}
33% {
-moz-transform: rotate(15deg);
-moz-transform-origin: 110px 26px;
}
100% {
-moz-transform: rotate(-20deg);
-moz-transform-origin: 110px 26px;
}
}
JS Fiddle demo.
Given the spectacular failure rate of this approach, though (it certainly doesn't work in Opera 11, and I can only imagine that it achieves nothing in IE...) I'd strongly suggest an animated gif for the sheer simplicity and cross-browser compliance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Working with JApplet with Menus I'm having problems with my code. The sub-menu for the (Music) menu should be a radio button type.
Here's my first code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AMBAT_FLAB1 extends JApplet implements ActionListener{
JMenuBar mainBar = new JMenuBar();
JMenu menu1 = new JMenu("File");
JMenu menu2 = new JMenu("Format");
JMenu menu3 = new JMenu("Background");
//for file
JMenuItem open = new JMenuItem("Open");
JMenuItem save = new JMenuItem("Save");
JMenuItem reset = new JMenuItem("Reset");
//for format
JMenuItem setFont = new JMenuItem("Set Font");
JMenuItem setColor = new JMenuItem("Set Color");
//for background
JMenuItem image = new JMenuItem("Images");
JMenuItem music = new JMenuItem("Music");
//submenu of music
JRadioButtonMenuItem play = new JRadioButtonMenuItem("Play");
JRadioButtonMenuItem loop = new JRadioButtonMenuItem("Loop");
JRadioButtonMenuItem stop = new JRadioButtonMenuItem("Stop");
ButtonGroup group = new ButtonGroup();
//file chooser
//JFileChooser fileChooser = new JFileChooser();
//fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
//text area
JTextArea myArea = new JTextArea(50, 50);
JScrollPane scrollingArea = new JScrollPane(myArea);
Container con = getContentPane();
public void init(){
setJMenuBar(mainBar);
mainBar.add(menu1);
mainBar.add(menu2);
mainBar.add(menu3);
menu1.add(open);
menu1.add(save);
menu1.add(reset);
menu2.add(setFont);
menu2.add(setColor);
menu3.add(image);
menu3.add(music);
music.group.add(play);
//group.add(loop);
//music.add(stop);
open.addActionListener(this);
save.addActionListener(this);
reset.addActionListener(this);
setFont.addActionListener(this);
setColor.addActionListener(this);
image.addActionListener(this);
music.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
}
}
When I try to run it, the Music menu doesn't appear. It changes to the Play (radio button). Does the button group help? When i tried to use the button group nothing happens.
A: Like this?
/* <applet code='AMBAT_FLAB1' width=220 height=100></applet> */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AMBAT_FLAB1 extends JApplet implements ActionListener{
JMenuBar mainBar = new JMenuBar();
JMenu menu1 = new JMenu("File");
JMenu menu2 = new JMenu("Format");
JMenu menu3 = new JMenu("Background");
//for file
JMenuItem open = new JMenuItem("Open");
JMenuItem save = new JMenuItem("Save");
JMenuItem reset = new JMenuItem("Reset");
//for format
JMenuItem setFont = new JMenuItem("Set Font");
JMenuItem setColor = new JMenuItem("Set Color");
//for background
JMenuItem image = new JMenuItem("Images");
JMenu music = new JMenu("Music");
//submenu of music
JRadioButtonMenuItem play = new JRadioButtonMenuItem("Play");
JRadioButtonMenuItem loop = new JRadioButtonMenuItem("Loop");
JRadioButtonMenuItem stop = new JRadioButtonMenuItem("Stop");
ButtonGroup group = new ButtonGroup();
//file chooser
//JFileChooser fileChooser = new JFileChooser();
//fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
//text area
JTextArea myArea = new JTextArea(50, 50);
JScrollPane scrollingArea = new JScrollPane(myArea);
Container con = getContentPane();
public void init(){
setJMenuBar(mainBar);
mainBar.add(menu1);
mainBar.add(menu2);
mainBar.add(menu3);
menu1.add(open);
menu1.add(save);
menu1.add(reset);
menu2.add(setFont);
menu2.add(setColor);
menu3.add(image);
menu3.add(music);
group.add(play);
group.add(loop);
group.add(stop);
music.add(play);
music.add(loop);
music.add(stop);
//music.add(stop);
open.addActionListener(this);
save.addActionListener(this);
reset.addActionListener(this);
setFont.addActionListener(this);
setColor.addActionListener(this);
image.addActionListener(this);
music.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
}
}
The mistakes in the code were basically:
*
*If Music had children, it had to be a JMenu, not a JMenuItem
*A ButtonGroup is a logical group (e.g. to make radio buttons out of a group of buttons), it is not a container. So besides adding the buttons to the group, it is necessary to add them to the Music JMenu.
A: You have a syntax error in your source code. Try commenting out the line that is failing and recompiling. That should give you a bit more information in your interface (GUI).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Uploading multiple files using jsp I am creating a website where the users can upload photos,videos and also write or create posts.It's almost like a blog.I am using JSP.I have used "multipart/form data".But I am facing a problem.Whenever the user is clicking on the submit button,all the photos and videos cannot be uploaded at the same time.Besides,since I am using "multipart/form data" I cannot retrieve the values by request.getParameter() in the next page.So what should I do?I searched across many websites and found a code on uploading which included Disk and Iterator interfaces.But I am having problem in resolving them.Someone help me please.
A: You cannot use request.getParameter() with a form having "multipart/form-data". Use FileUpload API (Apache commons).
A:
Whenever the user is clicking on the submit button,all the photos and videos cannot be uploaded at the same time.
This cannot be true. This problem is caused by something else. Perhaps you're using JavaScript to submit the form on a click/change of the file field, or you are misinterpreting the process at the server side.
Besides,since I am using "multipart/form data" I cannot retrieve the values by request.getParameter() in the next page.So what should I do?
Use the same API as you have used to parse the uploaded file (you did use one, right?). That very same API should be able to give you those parameters back from the multipart/form-data body.
See also:
*
*How to upload files to server using JSP/Servlet?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do i add n custom-cells to my view? I have a table view, amongst the table, in each row i want to display an image to the extreme left, some string in the middle, a number after that and again a string followed by a number, n all that should be in different font styles and sizes. Now i did this using custom-cells, but that is just for one row, what if user wants to enter data and then view the added info in the next row of the table. How do i add multiple custom cells to my view?
A: ---------- Please follow below link for help :
----------http://knol.google.com/k/iphone-sdk-using-table-views#
Sorry if i m wrong. But think this will help you out.
A: Update the datasource of your tableView and call reloadData method
[tableView reloadData];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create DB connection and maintain on multiple processes (multiprocessing) Similar to another post I made, this answers that post and creates a new question.
Recap: I need to update every record in a spatial database in which I have a data set of points that overlay data set of polygons. For each point feature I want to assign a key to relate it to the polygon feature that it lies within. So if my point 'New York City' lies within polygon USA and for the USA polygon 'GID = 1' I will assign 'gid_fkey = 1' for my point New York City.
Okay so this has been achieved using multiprocessing. I have noticed a 150% increase in speed using this so it does work. But I think there is a bunch of unecessary overhead as one DB connection is required for each record.
So here is the code:
import multiprocessing, time, psycopg2
class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
def run(self):
proc_name = self.name
while True:
next_task = self.task_queue.get()
if next_task is None:
print 'Tasks Complete'
self.task_queue.task_done()
break
answer = next_task()
self.task_queue.task_done()
self.result_queue.put(answer)
return
class Task(object):
def __init__(self, a):
self.a = a
def __call__(self):
pyConn = psycopg2.connect("dbname='geobase_1' host = 'localhost'")
pyConn.set_isolation_level(0)
pyCursor1 = pyConn.cursor()
procQuery = 'UPDATE city SET gid_fkey = gid FROM country WHERE ST_within((SELECT the_geom FROM city WHERE city_id = %s), country.the_geom) AND city_id = %s' % (self.a, self.a)
pyCursor1.execute(procQuery)
print 'What is self?'
print self.a
return self.a
def __str__(self):
return 'ARC'
def run(self):
print 'IN'
if __name__ == '__main__':
tasks = multiprocessing.JoinableQueue()
results = multiprocessing.Queue()
num_consumers = multiprocessing.cpu_count() * 2
consumers = [Consumer(tasks, results) for i in xrange(num_consumers)]
for w in consumers:
w.start()
pyConnX = psycopg2.connect("dbname='geobase_1' host = 'localhost'")
pyConnX.set_isolation_level(0)
pyCursorX = pyConnX.cursor()
pyCursorX.execute('SELECT count(*) FROM cities WHERE gid_fkey IS NULL')
temp = pyCursorX.fetchall()
num_job = temp[0]
num_jobs = num_job[0]
pyCursorX.execute('SELECT city_id FROM city WHERE gid_fkey IS NULL')
cityIdListTuple = pyCursorX.fetchall()
cityIdListList = []
for x in cityIdListTuple:
cityIdList.append(x[0])
for i in xrange(num_jobs):
tasks.put(Task(cityIdList[i - 1]))
for i in xrange(num_consumers):
tasks.put(None)
while num_jobs:
result = results.get()
print result
num_jobs -= 1
It looks to be between 0.3 and 1.5 seconds per connection as I have measure it with 'time' module.
Is there a way to make a DB connection per process and then just use the city_id info as a variable that I can feed into a query for the cursor in this open? This way I make say four processes each with a DB connection and then drop me city_id in somehow to process.
A: Try to isolate the creation of your connection in the Consumer constructor, then give it to the executed Task :
import multiprocessing, time, psycopg2
class Consumer(multiprocessing.Process):
def __init__(self, task_queue, result_queue):
multiprocessing.Process.__init__(self)
self.task_queue = task_queue
self.result_queue = result_queue
self.pyConn = psycopg2.connect("dbname='geobase_1' host = 'localhost'")
self.pyConn.set_isolation_level(0)
def run(self):
proc_name = self.name
while True:
next_task = self.task_queue.get()
if next_task is None:
print 'Tasks Complete'
self.task_queue.task_done()
break
answer = next_task(connection=self.pyConn)
self.task_queue.task_done()
self.result_queue.put(answer)
return
class Task(object):
def __init__(self, a):
self.a = a
def __call__(self, connection=None):
pyConn = connection
pyCursor1 = pyConn.cursor()
procQuery = 'UPDATE city SET gid_fkey = gid FROM country WHERE ST_within((SELECT the_geom FROM city WHERE city_id = %s), country.the_geom) AND city_id = %s' % (self.a, self.a)
pyCursor1.execute(procQuery)
print 'What is self?'
print self.a
return self.a
def __str__(self):
return 'ARC'
def run(self):
print 'IN'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Q: get the "display" attribute of the last element Hy guys, How can I get the "display" of the last element?
I'm doing this: $('.slide').filter(':last').attr("display"); but didn't work.
I tried $('.slide:last').attr("display"); and didn't work too.
What am I doing wrong? Tks!
A: Do you mean the CSS display property?
$('.slide:last').css('display')
Note that, if you're looking to check whether something is visible, it would be better to ask that question directly, rather than comparing the display property to "block" or "none".
$('.slide:last').is(':visible')
A: display is a CSS property. Try:
$('.slide:last').css("display");
A: I have a feeling you're talking about the css display property:
$('.slide:last').css("display");
A: Try this
$('.slide:last').css("display");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: oracle - moving data from to identical database I have two databases with identical table layouts. There are a dozen or so tables of interest. They are a number of FK between them.
I have been asked to write a stored procedure to copy data from database A to database B based on the PK of the parent table at the top of the hierarchy. I may receive just one value, or a list of values. I'm supposed to select all records from database A that match the value(s) and insert/update them into database B. This includes all the records in the child tables too.
My questions is whats the best(most efficent/ best practice) way to do this?
Should I write a dozen select from... insert into... statements?
Should I join the tables together an try to insert into all the tables at the same time?
Thanks!
Additional info:
The record should be inserted if it is not already there. (based on the PK of the respective table). Otherwise it should be updated.
Obviously I need to traverse down to all child tables, so There would only be one record to copy in the parent table, but the child table might have 10, and the child's child table might have 500. I would of course need to update the record if it already existed, insert if it does not for the child tables too...
UPDATE:
I think it would make the solution simpler if I just deleted all records related to the top level key, and then insert all the new records rather than trying to do updates.
So I guess the questions is it best to just do a dozen:
delete from ... where ... in ...
select from ... where ... in ...
insert into...
or is it better to do some kinda of fancy joins to do all the inserts in one sql statement?
A: I would do this by disabling all the foreign key constraints, then doing a set of MERGE statements to deal with the updates and inserts, then enable all the constraints.
Think about logging. How much redo do you want to generate?
You might find that it's quicker and better to truncate all the target tables and then do inserts of everything with nolog. Could be simpler than the merges.
One major main alternative would be to drop all the target tables and use export and import. Might be a lot faster.
A second alternative would be to use materialized views, particularly if you don't need to do updates on the target tables. That way, Oracle does all the heavy lifting for you. You can force integrity by choosing refresh groups carefully.
There are several ways to deal with this business problem. A PL/SQL program may not be the best.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WP7 Mango - navigation inside buildings I'm currently working on a app that should be able to navigate you inside a building - the basic idea is to have the building schematics, floor by floor and on every floor it tells you where to go to get to the next one. Once you are on the next floor, you press a button and its schema appears.
While this works fine, I came across and idea to automatize it - use the buildings WiFi access points, meassure the strength of the signal and triangulate your position. However, I read that in WP7 there is no way to access available WiFi networks. Does it still apply in Mango? Or is there some workaround?
Or any other idea how to automatize navigation inside building?
A: There's no API for WiFi (neither with Mango), and as such, you can't triangulate any positions from it.
And there's no workaround.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Setting the character encoding in Day CQ I've got some markup that I'm adding to a page component in Day CQ that was UTF-8 encoded by the author. Initially I couldn't save it in CRXDE, b/c the editor was set to save in ISO-8859-1. I found the setting to change this, but now when the page using this component is rendered to the browser, some of the characters appear to be using a different encoding. Is there a setting for the CQ web server, or servlet engine that I need to change? I'm running CQ 5.3 on Windows 7.
Edit: The HTTP Headers have Content-Type: text/html;charset=UTF-8 and there is a meta tag that specifies meta http-equiv="Content-type" content="text/html; charset=utf-8"
A: I believe the solution was to add pageEncoding="UTF-8" to all JSP's that are part of rendering this page. I also modified the web.xml file per this link: http://www.coderanch.com/t/87264/Tomcat/Character-Encoding-Tomcat, and restarted the server a number of times.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Python 3 Building an array of bytes I need to build a tcp frame with raw binary data, but all examples and tutorials I've found talking about bytes always involve conversion from a string, and that's not what I need.
In short, I need to build just an array of bytes:
0xA2 0x01 0x02 0x03 0x04
Please note that I come from C/C++ world.
I've tried this:
frame = b""
frame += bytes( int('0xA2',16) )
frame += bytes( int('0x01',16) )
frame += bytes( int('0x02',16) )
frame += bytes( int('0x03',16) )
frame += bytes( int('0x04',16) )
Then, throw this frame variable to send method of socket, but not working as expected as frame doesn't contain what I want...
I know this is a very basic question about Python, so if you could point me in the right direction...
A: frame = b'\xa2\x01\x02\x03\x04'
wasn't mentionned till now...
A: Use a bytearray:
>>> frame = bytearray()
>>> frame.append(0xA2)
>>> frame.append(0x01)
>>> frame.append(0x02)
>>> frame.append(0x03)
>>> frame.append(0x04)
>>> frame
bytearray(b'\xa2\x01\x02\x03\x04')
or, using your code but fixing the errors:
frame = b""
frame += b'\xA2'
frame += b'\x01'
frame += b'\x02'
frame += b'\x03'
frame += b'\x04'
A: agf's bytearray solution is workable, but if you find yourself needing to build up more complicated packets using datatypes other than bytes, you can try struct.pack(). http://docs.python.org/release/3.1.3/library/struct.html
A: what about simply constructing your frame from a standard list ?
frame = bytes([0xA2,0x01,0x02,0x03,0x04])
the bytes() constructor can build a byte frame from an iterable containing int values. an iterable is anything which implements the iterator protocol: an list, an iterator, an iterable object like what is returned by range()...
A: Here is a solution to getting an array (list) of bytes:
I found that you needed to convert the Int to a byte first, before passing it to the bytes():
bytes(int('0xA2', 16).to_bytes(1, "big"))
Then create a list from the bytes:
list(frame)
So your code should look like:
frame = b""
frame += bytes(int('0xA2', 16).to_bytes(1, "big"))
frame += bytes(int('0x01', 16).to_bytes(1, "big"))
frame += bytes(int('0x02', 16).to_bytes(1, "big"))
frame += bytes(int('0x03', 16).to_bytes(1, "big"))
frame += bytes(int('0x04', 16).to_bytes(1, "big"))
bytesList = list(frame)
The question was for an array (list) of bytes. You accepted an answer that doesn't tell how to get a list so I'm not sure if this is actually what you needed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
}
|
Q: How to get dictionary values as a generic list I just want get a list from Dictionary values but it's not so simple as it appears !
here the code :
Dictionary<string, List<MyType>> myDico = GetDictionary();
List<MyType> items = ???
I try :
List<MyType> items = new List<MyType>(myDico.values)
But it does not work :-(
A: Off course, myDico.Values is List<List<MyType>>.
Use Linq if you want to flattern your lists
var items = myDico.SelectMany (d => d.Value).ToList();
A: You probably want to flatten all of the lists in Values into a single list:
List<MyType> allItems = myDico.Values.SelectMany(c => c).ToList();
A: Going further on the answer of Slaks, if one or more lists in your dictionary is null, a System.NullReferenceException will be thrown when calling ToList(), play safe:
List<MyType> allItems = myDico.Values.Where(x => x != null).SelectMany(x => x).ToList();
A: Another variant:
List<MyType> items = new List<MyType>();
items.AddRange(myDico.Values);
A: My OneLiner:
var MyList = new List<MyType>(MyDico.Values);
A: How about:
var values = myDico.Values.ToList();
A: Dictionary<string, MyType> myDico = GetDictionary();
var items = myDico.Select(d=> d.Value).ToList();
A: Use this:
List<MyType> items = new List<MyType>()
foreach(var value in myDico.Values)
items.AddRange(value);
The problem is that every key in your dictionary has a list of instances as value. Your code would work, if each key would have exactly one instance as value, as in the following example:
Dictionary<string, MyType> myDico = GetDictionary();
List<MyType> items = new List<MyType>(myDico.Values);
A: List<String> objListColor = new List<String>() { "Red", "Blue", "Green", "Yellow" };
List<String> objListDirection = new List<String>() { "East", "West", "North", "South" };
Dictionary<String, List<String>> objDicRes = new Dictionary<String, List<String>>();
objDicRes.Add("Color", objListColor);
objDicRes.Add("Direction", objListDirection);
A: Another variation you could also use
MyType[] Temp = new MyType[myDico.Count];
myDico.Values.CopyTo(Temp, 0);
List<MyType> items = Temp.ToList();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "87"
}
|
Q: Unable to parser using TouchXML I am unable to parse response recieve using Touch XML My response from SOAP
<CXMLDocument 0x4b30110 [0x4b34c90]> <?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetImagesResponse xmlns="http://tempuri.org/">
<GetImagesResult>;http://www.google.com;http://www.hotmail.com;http://www.yahoo.com</GetImagesResult>
</GetImagesResponse>
</soap:Body>
</soap:Envelope>
/// Touch XML function
-(void) grabRSSFeed:(NSData *)responseData {
// Initialize the blogEntries MutableArray that we declared in the header
self.rssEntries = [[[NSMutableArray alloc] init] autorelease];
// Create a new rssParser object based on the TouchXML "CXMLDocument" class, this is the
// object that actually grabs and processes the RSS data
CXMLDocument *rssParser = [[CXMLDocument alloc] initWithData:responseData options:0 error:nil];
//CXMLDocument *rssParser = [[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil];
NSLog(@"rssParser %@",rssParser);
//NSLog(@"url %@",url);
// Create a new Array object to be used with the looping of the results from the rssParser
NSArray *resultNodes = NULL;
// Set the resultNodes Array to contain an object for every instance of an node in our RSS feed
resultNodes = [rssParser nodesForXPath:@"//GetImagesResult" error:nil];
// Loop through the resultNodes to access each items actual data
for (CXMLElement *resultElement in resultNodes) {
// Create a temporary MutableDictionary to store the items fields in, which will eventually end up in blogEntries
NSMutableDictionary *blogItem = [[[NSMutableDictionary alloc] init] autorelease];
// Create a counter variable as type "int"
int counter;
// Loop through the children of the current node
for(counter = 0; counter < [resultElement childCount]; counter++) {
//[resultElement initWithXMLString:@""];
NSString *strValue = [[resultElement childAtIndex:counter] stringValue];
//strValue = [strValue stringByReplacingOccurrencesOfString:@"\n" withString:@""];
NSString *strName = [[resultElement childAtIndex:counter] name];
if ([resultNodes containsObject:@""] || resultNodes == nil || resultElement == nil || [resultElement isEqual:@""] || [resultElement children] == nil) {
NSLog(@"Null Object");
}
else {
if (strValue && strName) {
// Add each field to the blogItem Dictionary with the node name as key and node value as the value
[blogItem setObject:[[resultElement childAtIndex:counter] stringValue] forKey:[[resultElement childAtIndex:counter] name]];
}
}
}
// Add the blogItem to the global blogEntries Array so that the view can access it.
[self.rssEntries addObject:[blogItem copy]];
NSLog(@"RSS Entries %@",self.rssEntries);
}
[[rssParser retain] release];
}
A: Being "unable to parse response" is a very vague description of your problem. However, at first glance I noticed that this XPath query...
resultNodes = [rssParser nodesForXPath:@"//GetImagesResult" error:nil];
...is most likely not matching any elements and thus returning an empty array.
Why? Your XML has a namespace. Use nodesForXPath:namespaceMappings:error: method instead of nodesForXPath:error:. The former has an extra parameter that lets you provide a namespace mapping dictionary. Then edit your XPath query accordingly. See the example below:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"http://tempuri.org/",
@"tempuri",
nil];
// Set the resultNodes Array to contain an object for every instance of an node in our RSS feed
resultNodes = [rssParser nodesForXPath:@"//tempuri:GetImagesResult" namespaceMappings:dict error:nil];
Also, the last statement of the method is nonsense:
[[rssParser retain] release];
To balance the alloc-init, it should be:
[rssParser release];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Outlook 2010 not launching when I debug my Outlook addin? I'm totally confused as to how to debug an Outlook 2010 addin I'm trying to develop. I created a new Extensibility | Shared Add-in project and just checked Outlook, and it's created a new project for me with a stub implementation of the Extensibility.IDTExtensibility2 interface in my Connect.cs file. However, when I press F5 to debug, although the project compiles OK, a new instance of Visual Studio opens up instead of Microsoft Outlook! How am I supposed to debug my addin?
A: Since Outlook is the host process that will load your code you have to make sure that Outlook is the target application for debugging (go to project properties and select the main Outlook EXE under the Start external program option in the Debug settings).
Then of course you have to also make sure that your plugin is actually being loaded by Outlook. With that in place you should be able to debug your plug-in with VS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to customize the data-prototype attribute in Symfony 2 forms Since umpteens days, I block on a problem with Symfony 2 and forms.
I got a form of websites entities. "Websites" is a collection of website's entities and each website contains two attributes : "type" and "url".
If I want to add more of one website in my database, I can click on a "Add another website" link, which add another website row to my form. So when you click on the submit button, you can add one or X website(s) at the same time.
This process to add a row use the data-prototype attribute, which can generate the website sub-form.
The problem is that I customize my form to have a great graphic rendering... like that :
<div class="informations_widget">{{ form_widget(website.type.code) }}</div>
<div class="informations_error">{{ form_errors(website.type) }}</div>
<div class="informations_widget">{{ form_widget(website.url) }}</div>
<div class="informations_error">{{ form_errors(website.url) }}</div>
But the data-prototype doesn't care about this customization, with HTML and CSS tags & properties. I keep the Symfony rendering :
<div>
<label class=" required">$$name$$</label>
<div id="jobcast_profilebundle_websitestype_websites_$$name$$">
<div>
<label class=" required">Type</label>
<div id="jobcast_profilebundle_websitestype_websites_$$name$$_type">
<div>
<label for="jobcast_profilebundle_websitestype_websites_$$name$$_type_code" class=" required">label</label>
<select id="jobcast_profilebundle_websitestype_websites_$$name$$_type_code" name="jobcast_profilebundle_websitestype[websites][$$name$$][type][code]" required="required">
<option value="WEB-OTHER">Autre</option>
<option value="WEB-RSS">Flux RSS</option>
...
</select>
</div>
</div>
</div>
<div>
<label for="jobcast_profilebundle_websitestype_websites_$$name$$_url" class=" required">Adresse</label>
<input type="url" id="jobcast_profilebundle_websitestype_websites_$$name$$_url" name="jobcast_profilebundle_websitestype[websites][$$name$$][url]" required="required" value="" />
</div>
</div>
</div>
Does anyone have an idea to make that hack ?
A: A bit old, but here is a deadly simple solution.
The idea is simply to render the collection items through a Twig template, so you have full ability to customize the prototype that will be placed in your data-prototype="..." tag. Just as if it was a normal, usual form.
In yourMainForm.html.twig:
<div id="collectionContainer"
data-prototype="
{% filter escape %}
{{ include('MyBundle:MyViewsDirectory:prototype.html.twig', { 'form': form.myForm.vars.prototype }) }}
{% endfilter %}">
</div>
And in MyBundle:MyViewsDirectory:prototype.html.twig:
<div>
<!-- customize as you wish -->
{{ form_label(form.field1) }}
{{ form_widget(form.field1) }}
{{ form_label(form.field2) }}
{{ form_widget(form.field2) }}
</div>
Credit: adapted from https://gist.github.com/tobalgists/4032213
A: I know that answer is very late but it maybe useful for visitors.
on your theme file you can simply use one block for rendering every collection entry of websites widget as following:
{% block _jobcast_profilebundle_websitestype_websites_entry_widget %}
<div class="informations_widget">{{ form_widget(form.type.code) }}</div>
<div class="informations_error">{{ form_errors(form.type) }}</div>
<div class="informations_widget">{{ form_widget(form.url) }}</div>
<div class="informations_error">{{ form_errors(form.url) }}</div>
{% endblock %}
also create theme block for your collection widget row as following:
{% block _quiz_question_answers_row %}
{% if prototype is defined %}
{%- set attr = attr | merge({'data-prototype': form_row(prototype) }) -%}
{% endif %}
{{ form_errors(form) }}
{% for child in form %}
{{ form_row(child) }}
{% endfor %}
{% endblock %}
now the prototype and the rendered collection entry will be the same.
A: I've run into similar problem recently. Here's how you can override the collection prototype without having to explicitly set it in the html:
{% set customPrototype %}
{% filter escape %}
{% include 'AcmeBundle:Controller:customCollectionPrototype.html.twig' with { 'form': form.collection.vars.prototype } %}
{% endfilter %}
{% endset %}
{{ form_label(form.collection) }}
{{ form_widget(form.collection, { 'attr': { 'data-prototype': customPrototype } }) }}
You can do whatever you want then in your custom twig. For example:
<div data-form-collection="item" data-form-collection-index="__name__" class="collection-item">
<div class="collection-box col-sm-10 col-sm-offset-2 padding-top-20">
<div class="row form-horizontal form-group">
<div class="col-sm-4">
{{ form_label(form.field0) }}
{{ form_widget(form.field0) }}
</div>
<div class="col-sm-3">
{{ form_label(form.field1) }}
{{ form_widget(form.field1) }}
</div>
<label class="col-sm-3 control-label text-right">
<button data-form-collection="delete" class="btn btn-danger">
<i class="fa fa-times collection-button-remove"></i>{{ 'form.collection.delete'|trans }}
</button>
</label>
</div>
</div>
Useful when you only have to do it in specific places and don't need a global override that's applicable to all collections.
A: I know this question is quite old, but I had the same problem and this is how I soved it. I'm using a twig macro to accomplish this. Macros are like functions, you can render them with different arguments.
{% macro information_prototype(website) %}
<div class="informations_widget">{{ form_widget(website.type.code) }}</div>
<div class="informations_error">{{ form_errors(website.type) }}</div>
<div class="informations_widget">{{ form_widget(website.url) }}</div>
<div class="informations_error">{{ form_errors(website.url) }}</div>
{% endmacro %}
now you can render this macro wherever you want. Note that information_prototype() is just the name of the macro, you can name it whatever you want. If you want to use the macro to render the given items and the prototype the same way, do something like this:
<div class="collection" data-prototype="{{ _self.information_prototype(form.websites.vars.prototype)|e }}">
{% for website in form.websites %}
{{ _self.information_prototype(website) }}
{% endfor %}
<button class="add-collection">Add Information</button>
</div>
form.websites.vars.prototype holds the prototype data of the form with the prototype_name you specified. Use _self.+macroname if you want to use the macro in the same template.
You can find out more about macros in the Twig documentation
A: You probably have found out since but here is the solution for others.
Create a new template and copy/paste this code in it:
https://gist.github.com/1294186
Then in the template containing the form you want to customise, apply it to your form by doing this:
{% form_theme form 'YourBundle:Deal:Theme/_field-prototype.html.twig' %}
A: I had a somewhat similar issue. You might have to tweak this to work for your case, but someone may find it helpful.
Create a new template file to hold your custom form 'theme'
./src/Company/TestBundle/Resources/views/Forms/fields.html.twig
Normally, you can use the form_row function to display a field's label, error, and widget. But in my case I just wanted to display the widget. As you say, using the data-prototype feature would also display the label, so in our new fields.html.twig type your custom code for how you want the field to look:
{% block form_row %}
{% spaceless %}
{{ form_widget(form) }}
{% endspaceless %}
{% endblock form_row %}
I removed the container div, and the label and error, and just left the widget.
Now in the twig file that displays the form, simply add this after the {% extends ... %}
{% form_theme form 'CompanyTestBundle:Form:fields.html.twig' %}
And now the form_widget(form.yourVariable.var.prototype) will only render the field and nothing else.
A: Application wide form theming will be applied to the prototype.
See Making Application-wide Customizations
A: Here is sample code for custom data-prototype:
{{ form_widget(form.emails.get('prototype')) | e }}
where emails — your collection.
A: To customize differently existing collection items VS prototype, you can override collection_widget like this:
{%- block collection_widget -%}
{% if prototype is defined %}
{%- set attr = attr|merge({'data-prototype': form_row(prototype, {'inPrototype': true} ) }) -%}
{% endif %}
{{- block('form_widget') -}}
{%- endblock collection_widget -%}
And then in your custom entry:
{% block _myCollection_entry_row %}
{% if(inPrototype is defined) %}
{# Something special only for prototype here #}
{% endif %}
{% endblock %}
A: If you do not need to define a template system-wide, simply set a template in your twig template, and ask twig to use it.
{# using the profiler, you can find the block widget tested by twig #}
{% block my_block_widget %}
<div >
<p>My template for collection</p>
<div >
{{ form_row(form.field1)}}
</div>
<div>
{{ form_row(form.field2)}}
</div>
</div>
{% endblock %}
{% form_theme form.my_collection _self %}
<button data-form-prototype="{{ form_widget(form.my_collection.vars.prototype) )|e }}" >Add a new entry</button>
A: There are two blocks that you can possibly target to add a custom theme to a collection field:
_myCollection_row and _myCollection_entry_row
_myCollection_row - renders the whole collection.
_myCollection_entry_row - renders a single item.
The prototype relies on _myCollection_entry_row so if you theme _myCollection_row only your theme will appear in the form, but not the prototype. The prototype uses _myCollection_entry_row.
So it's best to theme _myCollection_entry_row first, and then theme _myCollection_row only if required. BUT - if you theme _myCollection_row make sure it calls _myCollection_entry_row to render each item in your collection.
A: This post focuses on using pre-existing conventions within the twig template.
Basing off "How to Embed a Collection of Forms" from the Symfony Cookbook (http://symfony.com/doc/master/cookbook/form/form_collections.html), you can just enter whatever html_escaped form data you wish in the data-prototype (maybe considered a hack, but works wonderfully) and only pages using that template will change.
In the example, they tell you to put:
<ul class="tags" data-prototype="{{ form_widget(form.tags.vars.prototype)|e }}">
...
</ul>
This can be successfully replaced with something such as:
<table class="tags" data-prototype="<tr> <td><div><input type="text" id="task_tags__name__tagId" name="task[tags][__name__][taskId]" disabled="disabled" required="required" size="10" value="" /></div></td> <td><div><input type="text" id="task_tags__name__tagName" name="task[tags[__name__][tagName]" required="required" value="" /></div></td></tr>">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr>
...pre existing data here...
</tr>
</table>
Where the data-type attribute of the table with the class "tags" above is the html-escaped version (and line breaks removed though spaces are ok and required) of:
<tr>
<td><div><input type="text" id="task_tags__name__tagId" name="task[tags][__name__][taskId]" disabled="disabled" required="required" size="10" value="" /></div></td>
<td><div><input type="text" id="task_tags__name__tagName" name="task[tags[__name__][tagName]" required="required" value="" /></div></td>
</tr>
...but you must also adjust the javascript in the example to add tr's instead of li elements:
function addTagForm(collectionHolder, $newLinkTr) {
...
// Display the form in the page in an tr, before the "Add a question" link tr
var $newFormTr = $('<tr></tr>').append(newForm);
...
};
...
// setup an "add a tag" link
var $addTagLink = $('<a href="#" class="add_tag_link">Add a tag</a>');
var $newLinkTr = $('<tr></tr>').append($addTagLink);
...
For me, the next step is figuring out how to define the prototype in an external file that I can somehow call in the twig template for the data-prototype that dynamically works with the form. Something like:
<table class="tags" data-prototype="{{somefunction('App\Bundle\Views\Entity\TagsPrototypeInTable')}}">
So if one of the other posts is describing this and I am too dense or if someone knows how to do such, say so!
There is a link to something from gitHub from Francois, but I didn't see any explanation so I think that is probably the more dynamic method I'll get to one of these near-future days.
Peace,
Steve
Update:
One can also use just parts of the prototype:
data-prototype="<tr> <td>{{ form_row(form.tags.vars.prototype.tagId) | e }}</td> <td>{{ form_row(form.tags.vars.prototype.tagName) | e }}</td></tr>"
Where the data-type attribute of the table with the class "tags" above is the html-escaped version (and line breaks removed though spaces are ok and required) of:
<td>{{ form_row(form.tags.vars.prototype.tagId) | e }}</td>
<td>{{ form_row(form.tags.vars.prototype.tagName) | e }}</td>
(I used http://www.htmlescape.net/htmlescape_tool.html.)
Symfony will replace the information between the {{}} with an html_escaped (because of the "|e") rendered field when the page is rendered. In this way, any customization at the field-level is not lost, but! you must manually add and remove fields to the prototype as you do so with the entity :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
}
|
Q: Disable default button in ASP.NET
Possible Duplicate:
ASP.NET Canceling the Default Submit Button
I have only 1 button in my ASP.NET page but when I click "Enter" key the button click function is talking place. I don't want that. Only manual click must work. How to make this?
A: Set the button's UseSubmitBehavior = "false"
A: <body onkeypress="return CancelReturnKey();">
<script type="text/javascript">
function CancelReturnKey() {
if (window.event.keyCode == 13)
return false;
}
</script>
A: Please see the links
http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
http://forums.asp.net/t/985791.aspx/1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Find and replace a URL with grep/sed/awk? Fairly regularly, I need to replace a local url with a live in large WordPress databases. I can do it in TextMate, but it often takes 10+ minutes to complete.
Basically, I have a 10MB+ .sql file and I want to:
Find: http://localhost:8888/mywebsite
and
Replace with: http://mywebsite.com
After that, I'll save the file and do a mysql import to the local/live servers. I do this at least 3-4 times a week and waiting for Textmate has been a pain. Is there an easier/faster way to do this with grep/sed/awk?
Thanks!
Terry
A: kent$ echo "foobar||http://localhost:8888/mywebsite||fooooobaaaaaaar"|sed 's#http://localhost:8888/mywebsite#http://mywebsite.com#g'
foobar||http://mywebsite.com||fooooobaaaaaaar
if you want to do the replace in place (change in your original file)
sed -i 's#http://.....#http://mysite#g' input.sql
A: You don't need to replace the http://
sed "s/localhost:8888/www.my-awesome-page.com/g" input.sql > output.sql
A: sed 's/http:\/\/localhost:8888\/mywebsite/http:\/\/mywebsite.com/g' FileToReadFrom > FileToWriteTo
This is running switch (s/) globally (/g) and replacing the first URL with the second. Forward slashes are escaped with a backslash.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: iPhone: call and send parameters to JS function from OBJ-C Any idea how to call and send parameters to JS function from OBJ-C ??
Lets say in my html I have JS
function showPieChart (parameter1, parameter2) { ... }
and from my obj c class in viewDidLoad I want to call this function. Any idea or examples ? Thanks in advance...
A: Add this in the webViewDidFinishLoad: of the UIWebViewDelegate:
NSString *functionCall = [NSString stringWithFormat:@"showPieChart(%@,%@)", param1, param2];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:functionCall];
To set a view controller as delegate of a UIWebView, you have to add the <UIWebViewDelegate> protocol to the @interface header and link the delegate field of the UIWebView to the view controller.
If your parameters are inside an array, you can extract them one by one with [array objectForIndex:i] (i being the index for each parameter) or all at once with componentsJoinedByString:
NSArray *params = [NSArray arrayWithObjects:@"a",@"b",nil];
NSString *functionCall = [NSString stringWithFormat:@"showPieChart(%@)", [params componentsJoinedByString:@","]];
A: 1) Implement the UIWebViewDelegate
2) Override the
-(BOOL)webView:(UIWebView *)aWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType method..
3) In this method you compare the request with a protocole defined.
Example:
NSString *requestString = [[request URL] absoluteString];
NSArray *components = [requestString componentsSeparatedByString:@":"];
if ([components count] > 1 &&
[(NSString *)[components objectAtIndex:0] isEqualToString:@"myapp"]) {
if([(NSString *)[components objectAtIndex:1] isEqualToString:@"myfunction"])
{
NSLog([components objectAtIndex:2]); // param1
NSLog([components objectAtIndex:3]); // param2
// Call your method in Objective-C method using the above...
}
return NO;
}
4) modify your javascript file to create the protocole:
function showPieChart(parameter1,parameter2)
{
window.location="myapp:" + "myfunction:" + param1 + ":" + param2;
}
resouce :http://www.codingventures.com/2008/12/using-uiwebview-to-render-svg-files/
A: I'm guessing you have a UIWebView with a web page loaded. To execute JavaScript, do this:
NSString *result = [_webView stringByEvaluatingJavaScriptFromString:@"showPieChart()"];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problem retrieving dictionary from Isolated Storage During the first run, I am storing a dictionary<string,dictionary<string,string>> (lets call it CategoryDictionary). When I re-run the code (without closing the emulator), the count in the categorydictionary becomes null.
Whatever I am getting from the categorydictionary are suppose to be displayed on the UI, so because of this problem am getting data on the UI only in the first run but 2nd run results in blank screen
while (enum1.MoveNext())
{
KeyValuePair<string, string> keyvalue = (KeyValuePair<string, string>)enum1.Current;
string key = keyvalue.Key;
WidgetBean bean = null;
dict.TryGetValue(key, out bean);
ret.Add(key, bean);
}
So basically in the 2nd run bean has null values for all entries.
A: using System.Runtime.Serialization;
[DataContact]
public class classname()
{
[datamember]
public int propertyname;
}
i did this and the code is working fine now..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CSS PIE - border issue? Facing issue while rendering RGBA color for border. RGBA color for border radius working fine but not border color and it is not showing any border color.
Is there any separate "-pie-" tag in CSSPie for use of RGBA in borders?
My Code:
.border{
position:absolute;
right: 250px;
top: 250px;
width: 400px; height:100px;
z-index: 9999;
border: 3px solid rgba(52, 52, 52, 0.3);
border-radius: 10px; -moz-border-radius: 10px;
behavior: url(PIE.htc);
}
Not able to see the border in IE 7 & 8... Can you help?
Thanks in advance!
A: For Border-radius issue you have to apply the styles position:relative; and z-index:0; for that element. Hope this will work.
A: My educated guess is that IE7 and IE8 only support rgb() and not rgba(), and that would be why the border was not showing.
A: Unfortunately this is not (yet) supported in PIE. If/when it does get implemented, it will undoubtedly require a separate -pie-border or -pie-border-color property, because IE's parser will throw away the entire border value if it contains the unrecognized rgba string.
Here is the ticket tracking this feature: https://github.com/lojjic/PIE/issues/55
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to remove all specific elements from Vector In fact, regarding to the title in the question, I have a solution for this, but my approach seems to waste resources to create a List objects.
So my question is: Do we have a more efficient approach for this?
From the case, I want to remove the extra space " " and extra "a" from a Vector.
My vector includes:
{"a", "rainy", " ", "day", "with", " ", "a", "cold", "wind", "day", "a"}
Here is my code:
List lt = new LinkedList();
lt = new ArrayList();
lt.add("a");
lt.add(" ");
vec1.removeAll(lt);
As you can see the extra spaces in the list of Vector, the reason that happens is that I use Vector to read and chunk the word from word document, and sometimes the document may contain some extra spaces that caused by human error.
A: Your current approach does suffer the problem that deleting an element from a Vector is an O(N) operation ... and you are potentially doing this M times (5 in your example).
Assuming that you have multiple "stop words" and that you can change the data structures, here's a version that should (in theory) be more efficient:
public List<String> removeStopWords(
List<String> input, HashSet<String> stopWords) {
List<String> output = new ArrayList<String>(input.size());
for (String elem : input) {
if (!stopWords.contains(elem)) {
output.append(elem);
}
}
return res;
}
// This could be saved somewhere, assuming that you are always filtering
// out the same stopwords.
HashSet<String> stopWords = new HashSet<String>();
stopWords.add(" ");
stopWords.add("a");
... // and more
List<String> newList = removeStopwords(list, stopWords);
Points of note:
*
*The above creates a new list. If you have to reuse the existing list, clear it and then addAll the new list elements. (This another O(N-M) step ... so don't if you don't have to.)
*If there are multiple stop words then using a HashSet will be more efficient; e.g. if done as above. I'm not sure exactly where the break even point is (versus using a List), but I suspect it is between 2 and 3 stopwords.
*The above creates a new list, but it only copies N - M elements. By contrast, the removeAll algorithm when applied to a Vector could copy O(NM) elements.
*Don't use a Vector unless you need a thread-safe data structure. An ArrayList has a similar internal data structure, and doesn't incur synchronization overheads on each call.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL export/import data consistency problem Currently experiencing an issue whereby I am exporting a MySQL structure and data from a server into a sql file, ready for importing into a local database.
When importing the sql file into a local database, numerous records are changing dramatically. The columns in question tend to be of type bit(1).
The local setup uses the following versions Apache 2.2.17, PHP 5.3.5 and MySQL 5.5.8.
The server is currently using MySQL 5.1.56.
Any ideas what can be done to rectify this scenario?
A: Try using the --hex-blob parameter with the mysqldump utility when obtaining the sql dump.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: pausing execution in custom confirm box I want to create a custom confirm box like this
var should_I_move_forward = myconfirmbox();
myconfirmbox will show a popup with Yes/No button, I want to pause the execution here until user hit yes or no, how can I achieve it?
i.e. same functionality as of js confirm method buy my own UI.
A: You can't.
You will have to move the logic that follows the confirmation inside the myconfirmbox method, or pass it as parameters (to call on demand)..
something like
function ConfirmYes(){
// do something for Yes
}
function ConfirmNo(){
// do something for No
}
function myconfirmbox(yesCallback, noCallback){
// whatever you currently do and at the end
if (confirmation == 'yes'){
yesCallback();
} else {
noCallback();
}
}
myconfirmbox(ConfirmYes, ConfirmNo);
A: What I did is not elegant at all but it working fine for me! I create a custom confirm function like:
function jqConf(msg,y,n){
$('body').append('<div id="confirmBox">msg</div>');
$('#confirmBox').append('<div id="confirmButtons"></div>');
$('#confirmButtons').append('<button onclick="'+y+'();">Yes</button>');
$('#confirmButtons').append('<button onclick="'+n+'();">No</button>');
}
function defaultYes(){
alert('Awesomeness!');
}
function defaultNo(){
alert('No action taken!');
}
The I use it like this:
<button onclick="jqConf('Do you love me?','defaultYes','defaultNo')">Confirm</button>
This way I pass as a string the name of the function to run if Yes and if No individually and is executed by the user event.
As I say, nothing elegant but it works!, no loops or confusing codes, I think?, In the example I'm using jQuery but can be accomplish with plain JavaScript too!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Mouse click handling in As3.0 gallery I'm playing around with a gallery. I want to add some more functionality.
HERE's the initial code:
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.MovieClip;
function doSMTH(luka) {
var catNum:Number = luka;
stop();
goBack.addEventListener(MouseEvent.CLICK, goBacke);
function goBacke(e:MouseEvent):void{
gotoAndStop(1);
stage.removeChild(thumbnail_group);
}
// Tweener
// http://code.google.com/p/tweener/
import caurina.transitions.*;
var filename_list = new Array();
var url_list = new Array();
var url_target_list:Array = new Array();
var title_list = new Array();
var description_list = new Array();
var i:Number;
var tn:Number = 0;
var tween_duration:Number = 0.4;
var move_x:Number = 200;
var move_y:Number = -300;
//var fm_tween:Tween;
var total:Number;
var flashmo_xml:XML = new XML();
var folder:String = "photos/";
var xml_loader:URLLoader = new URLLoader();
xml_loader.load(new URLRequest("gallery.xml"));
xml_loader.addEventListener(Event.COMPLETE, create_thumbnail);
var thumbnail_group:MovieClip = new MovieClip();
stage.addChild(thumbnail_group);
thumbnail_group.x = tn_group.x;
var default_y:Number = thumbnail_group.y = tn_group.y;
tn_group.visible = false;
url_button.visible = false;
tn_title.text = "";
tn_desc.text = "";
tn_url.text = "";
tn_url_target.text = "";
function create_thumbnail(e:Event):void
{
flashmo_xml = XML(e.target.data);
total = flashmo_xml.category[catNum].thumbnail.length();
for( i = 0; i < total; i++ )
{
filename_list.push( flashmo_xml.category[catNum].thumbnail[i].@filename.toString() );
url_list.push( flashmo_xml.category[catNum].thumbnail[i].@url.toString() );
url_target_list.push( flashmo_xml.category[catNum].thumbnail[i].@target.toString() );
title_list.push( flashmo_xml.category[catNum].thumbnail[i].@title.toString() );
description_list.push( flashmo_xml.category[catNum].thumbnail[i].@description.toString() );
}
load_tn();
}
function load_tn():void
{
var pic_request:URLRequest = new URLRequest( folder + filename_list[tn] );
var pic_loader:Loader = new Loader();
pic_loader.load(pic_request);
pic_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, on_loaded);
tn++;
}
function on_loaded(e:Event):void
{
if( tn < total )
{
load_tn();
tn_desc.text = "Loading " + tn + " of " + total + " photos";
}
else
{
tn_title.text = title_list[0];
tn_desc.text = description_list[0];
tn_url.text = url_list[0];
tn_url_target.text = url_target_list[0];
var mc:MovieClip = MovieClip( thumbnail_group.getChildAt(total-2) );
mc.addEventListener( MouseEvent.CLICK, go_out );
Tweener.addTween( mc, { rotation: 0, time: tween_duration, transition: "easeOut" } );
url_button.visible = true;
url_button.addEventListener(MouseEvent.CLICK, goto_URL);
}
var flashmo_bm:Bitmap = new Bitmap();
var flashmo_mc:MovieClip = new MovieClip();
flashmo_bm = Bitmap(e.target.content);
flashmo_bm.x = - flashmo_bm.width * 0.5;
flashmo_bm.y = - flashmo_bm.height * 0.5;
flashmo_bm.smoothing = true;
var bg_width = flashmo_bm.width + 16;
var bg_height = flashmo_bm.height + 16;
flashmo_mc.addChild(flashmo_bm);
flashmo_mc.graphics.lineStyle(1, 0x999999);
flashmo_mc.graphics.beginFill(0xFFFFFF);
flashmo_mc.graphics.drawRect( - bg_width * 0.5, - bg_height * 0.5, bg_width, bg_height );
flashmo_mc.graphics.endFill();
flashmo_mc.x = move_x;
flashmo_mc.y = move_y;
flashmo_mc.rotation = 45;
flashmo_mc.name = "flashmo_" + thumbnail_group.numChildren;
Tweener.addTween( flashmo_mc, { x: Math.random() * 20 - 10, y: Math.random() * 20 - 10,
rotation: Math.random() * 20 - 10,
time: tween_duration * 2, transition: "easeOut" } );
thumbnail_group.addChildAt(flashmo_mc, 0);
}
function go_out(e:MouseEvent):void
{
var mc:MovieClip = MovieClip(e.target);
//var imgFwd:MovieClip = MovieClip(e.target);
mc.removeEventListener( MouseEvent.CLICK, go_out );
//imgFwd.removeEventListener(MouseEvent.CLICK, go_out);
Tweener.addTween( mc, { x: 220, y: -180, rotation: 45, time: tween_duration,
transition: "easeInQuart", onComplete: go_in } );
}
function go_in():void
{
var mc:MovieClip = MovieClip( thumbnail_group.getChildAt(total-1) );
var mc2:MovieClip = MovieClip( thumbnail_group.getChildAt(total-2) );
var s_no:Number = parseInt( mc.name.slice(8,10) ) + 1;
if(s_no == total) s_no = 0;
Tweener.addTween( mc, { x: Math.random() * 20 - 10, y: Math.random() * 20 - 10,
rotation: Math.random() * 20 - 10, time: tween_duration,
transition: "easeOut", onComplete: add_click } );
Tweener.addTween( mc2, { rotation: 0, time: tween_duration, transition: "easeOut" } );
thumbnail_group.addChildAt( mc, 0 );
tn_title.text = title_list[s_no];
tn_desc.text = description_list[s_no];
tn_url.text = url_list[s_no];
tn_url_target.text = url_target_list[s_no];
}
function add_click():void
{
var mc:MovieClip = MovieClip(thumbnail_group.getChildAt(total-1) );
mc.addEventListener( MouseEvent.CLICK, go_out );
}
function goto_URL(me:MouseEvent)
{
navigateToURL(new URLRequest(tn_url.text), tn_url_target.text);
}
link_to_205.addEventListener( MouseEvent.CLICK, goto_205 );
function goto_205(me:MouseEvent)
{
navigateToURL(new URLRequest(""), "_parent");
}
tn_url_target.visible = false;
tn_title.visible = false;
tn_desc.visible = false;
url_button.visible = false;
tn_url.visible = false;
link_to_205.visible = false;
}
I added two buttons for navigation.
*
*goFWD that would have a code imgFwd.addEventListener(MouseEvent.CLICK, go_out);
but by adding this event to the button, button itself does the tween, and now the mc:MovieClip.
I don't know why it does that? maybe any ideas?
I thought, if there's such a thing in AS3.0 - a click on this button makes AS think that mc:MovieClip is clicked?? is there anything like that?
Any ideas how to make it go forward with a button...
Thanks in advance!!!
A: What should be tweening when you click the goFWD button? From a quick look, I would guess you want to tween thumbnail_group. Is that the case?
In your MouseEvent.CLICK handler, go_out, you are casting the current target (the thing that was clicked) by using e.target. If you want to target the thumbnail_group mc, then just change the code like so:
function go_out(e:MouseEvent):void
{
var mc:MovieClip = MovieClip(e.target);
mc.removeEventListener( MouseEvent.CLICK, go_out );
Tweener.addTween( thumbnail_group.getChildAt(total-1), { x: 220, y: -180, rotation: 45, time: tween_duration,
transition: "easeInQuart", onComplete: go_in } );
}
If this is not what you are looking for, then please clarify and I will try to help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: java send mail on Linux: Error certification I try to send mail by Java on Linux server.
I setup to run on Tomcat 6, config SSL
but I got an error message:
Can't send command to SMTP host
javax.mail.MessagingException: Can't send command to SMTP host;
nested exception is: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
My java code like below:
String host = "smtp.gmail.com";
int port = 587;
String username = "java.test@gmail.com";
String password = "aabbcc";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("java.test@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("test504@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler," +
"\n\n No spam to my email, please!");
Transport transport = session.getTransport("smtp");
transport.connect(host, port, username, password);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
System.out.println("ERROR: "+e.getMessage());
System.out.println("ERROR: "+e.toString());
throw new RuntimeException(e);
}
If I config Tomcat without SSL -> It can send mail Success
But within SSL -> I have above error
Please help fix error. Thank guys!
A: I think it needs a secure TLS connection , take a look at this link to know how to do it
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MySQL - How to update atable based on an internal ordering of the table If I make a selection from my MySQL table like:
SELECT * FROM mytable ORDER BY country_id, category
I get the following table:
+------------+----------+-------+
| country_id | category | order |
+------------+----------+-------+
| 1 | A | 0 |
| 1 | B | 0 |
| 1 | F | 0 |
| 3 | A | 0 |
| 3 | C | 0 |
| 5 | B | 0 |
| 5 | L | 0 |
| 5 | P | 0 |
+------------+----------+-------+
What I would like to do is update the order column so that the value of that column is the order of that row for it's country_id. In other words the final table should look like this:
+------------+----------+-------+
| country_id | category | order |
+------------+----------+-------+
| 1 | A | 1 |
| 1 | B | 2 |
| 1 | F | 3 |
| 3 | A | 1 |
| 3 | C | 2 |
| 5 | B | 1 |
| 5 | L | 2 |
| 5 | P | 3 |
+------------+----------+-------+
If I use the original query given at the top in a subquery, that would give me the correct order but I can't figure out how to iterate through the table and suspect I thinking about it wrongly.
How can I get this result?
Many thanks
A: Try to use this query -
UPDATE mytable t1
JOIN (
SELECT t1.country_id, t1.category, COUNT(*) `order`
FROM mytable t1
LEFT JOIN mytable t2
ON t2.country_id = t1.country_id AND t2.category <= t1.category
GROUP BY
t1.country_id, t1.category
) t2
ON t1.country_id = t2.country_id AND t1.category = t2.category
SET t1.`order` = t2.`order`
As an aside note, you can remove order field from the table because this can calculated this on the fly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Objective C: way to check for enabled flags I am using bitflag to enable/disable some functionality in my code. I have following enum.
typedef enum function {
function1 = 1 << 0,
function2 = 1 << 1,
function3 = 1 << 2,
function4 = 1 << 3
};
I know that I need to use following code to check which flag has been enabled.
if((flags & function1) == function1)
{
// do some action
}
In my enum, number of flags is large and to check every flag, I need to have that many "if" condition checks. Is there any way which can minimize the number of if statements required? I am new to objective C and looking to implement it in objective C. Thanks in advance.
A: Yes, combine the flags via a bitwise or:
if (flags & (function1 | function2 | function3 | function4))
{
// any of the flags has been set
}
Moreover, to check for a particular flag you don't need the part == function1, flags & function1 is sufficient as it will evaluate either to zero or function1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jQuery datepicker loses focus after .("show") I'm using the range date-picker of jQuery UI. When selecting the "from date", I want to open automatically the "to date" date-picker. So, I call the .datepicker("show"). The "to date" picker is showing for a second and immediately fade away. Surprisingly, if I go to another application and then come back and focus on the browser window, the "to date" picker is shown.
I also tried to add the $('#toDate').focus(); but it didn't help.
$( ".fromDatePicker" ).datepicker({
defaultDate: "+1w",
dateFormat: 'dd/mm/yy',
altFormat: 'yymmdd',
altField: "#fromDateFormatted",
numberOfMonths: 2,
showOn: "both",
buttonImage: "images/calender_icon_a1.jpg",
buttonText: "open calendar",
buttonImageOnly: true,
onSelect: function( selectedDate ) {
$('#toDate').datepicker( "option", "minDate", selectedDate );
$('#toDate').datepicker("show");
//$('#toDate').focus(); //commented cause it's not working
}
});
A: The reason for the flashing appearance is because show would be called before minDate finishes. This would confuse datepicker when triggering beforeShowDay event just before showing the picker.
One somewhat hacky workaround is to delay the call to show the datepicker. For example, something like the following would work:
onSelect: function( selectedDate ) {
$('#toDate').datepicker( "option", "minDate", selectedDate );
setTimeout(function() { $('#toDate').datepicker("show") }, 50);
}
See this in action: http://jsfiddle.net/william/PVuTC/2/.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using UNIX SAS to ascertain Netezza DISTRIBUTE_ON key Is anybody able to provide some SAS 9.1.3 code for ascertaining the DISTRIBUTE_ON key of a particular Netezza table?
have tried using the guidance here but the table comes back empty..
A: There is a nzsql command called \d which will retrieve the distribution keys on the table. Check the NZ Database User Guide.
Regards,
Venk
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create Link button in android I want to create Link button in android.
Can anyone guide me in how I can create a Link button in android?
A: Uri uri = Uri.parse("http://www.example.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
A: Simple. Just put the link in your TextView.
<TextView
android:id="@+id/txtLink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/about_link"
android:autoLink="all" />
Note: The most important property here is android:autoLink="all". This allow you to link to urls, emails and phone numbers.
In your strings.xml add the link:
<string name="about_link"><a href='http://example.com'>http://example.com</a></string>
<string name="about_email"><a href='mailto:admin@example.com'>admin@example.com</a></string>
I know this answer is coming really late, but hope it helps someone else coming along.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Sharepoint Claims/c2wts issues with Performance Point/Excel Services I have created a custom claims provider to allow users to sign into SharePoint from an existing website. This issues claims including a claim of UPN in the format username@domain. The user can log in fine until I enable mapToWindows and useWindowsTokenService under samlSecurityTokenRequirement in the SharePoint web application web.config. At this point I get a standard SharePoint error message, and the following exception is visible in the trace.
Exception fetching current thread user in SPUtility.CacheClaimsIdentity: Exception of type 'System.ArgumentException' was thrown.
Parameter name: identity 0.00143314303912927 0.001357
Runtime Tag(tkau) System.ArgumentException: Exception of type 'System.ArgumentException' was thrown.
Parameter name: encodedValue
at Microsoft.SharePoint.Administration.Claims.SPClaimEncodingManager.DecodeClaimFromFormsSuffix(String encodedValue)
at Microsoft.SharePoint.Administration.Claims.SPClaimProviderManager.GetProviderUserKey(String encodedSuffix)
at Microsoft.SharePoint.ApplicationRuntime.SPHeaderManager.AddIsapiHeaders(HttpContext context, String encodedUrl, NameValueCollection headers)
at Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.PreRequestExecuteAppHandler(Object oSender, EventArgs ea)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I think that the c2wts impersonation part is working correctly because if I disable the AD account represented by the passed UPN claim then I get a different "access is denied" error shown in SharePoint when trying to log in as that user.
Also in the SharePoint log it does appear that the UPN has been converted to a Windows AD account because I get the following in the log:
Verbose ____Current User=i:DOMAINNAME\SSO_administrator 7b4eac31-d017-429c-87f2-a3100ece6797
Update
It looks like maybe this isn't a supported setting to use within SharePoint. However if I leave the setting off, it seems that Performance Point and Excel Services reports embedded in the SharePoint site do not work properly. I get errors like:
*
*The data connection uses Windows Authentication and user credentials could not be delegated. (Excel)
*$Resources:ppsma.ServerCommon, ErrorCode_DataSourceCannotGetWindowsIdentityForNonWindowsClaim; (Performance Point SSRS report)
Is there a way around this? I need the user's UPN to be the account used to query the SSAS data behind these, so it is not feasible to use fixed connection strings.
A: I think there are a lot of information on a SharePoint forum about Claims-based access platform (Geneva) forums
This is some of the searches which hopefully will helps you to manage the issue:
*
*Claims Login Web Part for SharePoint Server 2010
*SP2010 Custom Role Provider - Roles.GetRolesForUser(userName) raises exception
*How do i redirect the user from Active Directory or Sqlmembership provider to sharepoint default.aspx page or home page after logged in using custom log in page.
*Vittorio Bertocci's Blog
*SAML 2.0 Protocol Blog
*SAML 2.0 Windows Identity Foundation Extension
A: It turns out that the mapToWindows config value is not supported within SharePoint. You have to rely on each part of SharePoint being claims aware and converting the token themselves. This is a bit of pain because PerformancePoint and Excel Services are not claims aware, so you end up being stuck using Windows auth if your SSAS cube requires AD security.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Setting Vertical Scrollbar position in WPF DataGrid I've a datagrid in WPF, It has lots of records hence having a VerticalScrollBar, when i do some activity like delete in some where at bottom of the screen and after this activity set the first index of the row, First row has been selected but scrollbar remains at the same position(bottom). I want it to be at the top or wherever the selected row is.
Thanks
A: After you perform the delete, you can use a combination of UpdateLayout and ScrollIntoView DataGrid methods. Ensure you call the UpdateLayout method before calling the ScrollIntoView method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how can i authenticate an html control in a .aspx page how can i authenticate an html control in a .aspx page.
For eg. I have two labels :: lblusername and lblpassowrd, two textboxes to fetch the values from the user and a submit button.
I want all these controls to be of html controls not the asp.net server side controls, authenticate whether the password already exists, check for password string to be ok and on submit give user the home page.
any code help for this.
would also expect some discussion on the events fired, effect on the asp.net page life cycle and some insight about the performance.
A: Once the HTML controls have the runat="server" attribute, you just use the normal ASP.NET way of authenticating and authorizing.
http://msdn.microsoft.com/en-us/library/ms178329.aspx
http://msdn.microsoft.com/en-us/library/f8kdafb5%28VS.71%29.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Determining the location of Program Files using VBS What would a safe way of extracting the 'Program Files' directory location using VBS?. I would like to get the directory location from the environment as it will avoid localization issues as well as problems between different OS architectures (32/64 bit) and drive (C:\, D:\, etc:).
So far I came across an example given on MSDN yet I can get the script to work in VBS, every run just complains about different errors. Here is what they've got on an example script for .net to get the Sys32 folder.
' Sample for the Environment.GetFolderPath method
Imports System
Class Sample
Public Shared Sub Main()
Console.WriteLine()
Console.WriteLine("GetFolderPath: {0}", Environment.GetFolderPath(Environment.SpecialFolder.System))
End Sub 'Main
End Class 'Sample
'
'This example produces the following results:
'
'GetFolderPath: C:\WINNT\System32
'
As Helen mentioned, this is my script to determine the OS Architecture and depending on the outcome I wish to retrieve the respective 'Program Files' path
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & sPC & "\root\cimv2")
Set colOperatingSystems = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
sSystemArchitecture = objOperatingSystem.OSArchitecture
Next
A: for vbs from How to get program files environment setting from VBScript
Set wshShell = CreateObject("WScript.Shell")
WScript.Echo wshShell.ExpandEnvironmentStrings("%PROGRAMFILES%")
if you are in vba
Sub GetMe()
Set wshShell = CreateObject("WScript.Shell")
MsgBox wshShell.ExpandEnvironmentStrings("%PROGRAMFILES%")
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: view/edit still show in ribbon of DNN after logoff When I log off a DotNetNuke site, the view/edit options still show in the ribbon up top. Anyone run into this before? I was informed that it's a setting; however, I cannot find this.
Any thoughts? All help is very appreciated. Thank you for your time.
A: Personally I would simply try clearing your browser cache. If it is a setting it means the page is editable to anyone. Log back in and go to the page settings and make sure 'edit' in the permissions is onel set for 'Administrators' (or whomever you would like to edit it)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android - ImageView as Offline map I am trying to implement an offline map content into my android app. I need not so much detailed map just for a specific area and mark some places over it. a zoomable and scrollable image seems to be enough for me.
First question is;
1-) what is the best option for offline map in android? My constraint is that my app couldn't use any internet connection. Do I have to use an imageview (by adding button markers on it) or can I use any offline data for Mapview?
I have searched a lot for using imageview as map but couldn't get so much result.
my basic question for imageview is;
2-) How can I add a marker(a button) on a specific position of imageview?
I have found some sample code for scrolling and zoom and implemented them (Scrollview has no diagonal scroll as default) but I couldn't find a way to add marker to an scrollable, zoomable imageview.
Please don't think on sample code, just assume that imageview is in an scrollview and I try to add a marker(button) on it.
Thanks in advance
A: There are other options such as OSMDroid: But personal experience of this library would recommend using an imageview if you can and don't require zooming in and out and having performance issue.
You can have a scrollview, containing a horizontal scrollview, which can then contain a relative layout with an imageview taking up the space. Then add the markers to the relative layout and position accordingly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: String was not recognized as a valid DateTime im trying to parse exact a date based on the capture of information of a user from facebook. I get the error message: String was not recognized as a valid DateTime.
which is the best way to parse a date in the format dd/MM/yyyy
h.AddUser(r.id, r.FBid, accessToken, r.first_name, r.last_name, DateTime.ParseExact(r.birthday, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture), r.email, DateTime.Now, r.gender, "http://graph.facebook.com/" + r.id + "/picture?type=large");
UPDATE:
if r.birthday is in dd/MM/yyyy then
DateTime.ParseExact(r.birthday, "dd/MM/yyyy", new System.Globalization.CultureInfo("en-GB"));
if r.birthday is in MM/dd/yyyy then
DateTime.ParseExact(r.birthday, "dd/MM/yyyy", new System.Globalization.CultureInfo("en-GB"));
i found a solution to my problem, posting it so if others are experiencing the same problem can find the same solution as me
A: So the string to be parsed is in dd/MM/yyyy format ?
Then specify that format to the parseExact method as such
DateTime.ParseExact(r.birthday, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does Prototype has a no conflict option like jQuery? I have tried Googling this but it only ever comes up with the jQuery noconflict option.
I would use this but my site is very jQuery heavy and it will take quite a white, as well as this the prototype code I'm adding may be temporary and is only a few lines.
If there is no prototype no conflict option how would I convert the below code, my javascript codes are limited?
// JavaScript Document
// calculate price based on quantity
function changeQty(change){
var currentQty = parseInt($F('quant')) // Where quant is the id of your quantity input field. Gets value of currentQty field
switch (change) {
case 'add':
currentQty += 1
$('quant').value = currentQty
calculate()
break
case 'subtract':
if (currentQty > 1) { // only subtract if qty is greater than zero
currentQty -= 1
$('quant').value = currentQty
calculate()
}
break
case 'field':
if (currentQty > 0) {
window.setTimeout('calculate()', 500)
}
break
}
}
function calculate(){
var currentQty = parseInt($F('quant')) // Where quant is the id of your quantity input field. Gets value of currentQty field
var jsnormalprice = $F('jsnormalprice') // Where jsnormalprice is the id of your hidden base price field. Gets value of base_price field
var jsspecialprice = $F('jsspecialprice') // Where is the id of your hidden base price field. Gets value of base_price field
if (currentQty > 0) { // Don't want price to display if zero if customer zeros out quantity
var new_jsnormalprice = jsnormalprice * currentQty // Calculate the price.
var new_jsnormalprice = new_jsnormalprice.toFixed(2) // Only allow 2 decimals. I'll let you add rounding features up or down.
var new_jsspecialprice = jsspecialprice * currentQty // Calculate the price.
var new_jsspecialprice = new_jsspecialprice.toFixed(2) // Only allow 2 decimals. I'll let you add rounding features up or down.
} else { // set price back to original price
new_jsnormalprice = jsnormalprice
new_jsspecialprice = jsspecialprice
}
$('jsnormalpriceshow').update(new_jsnormalprice) // Where jsnormalpriceshow is the id of your span for the echoed product price
$('jsspecialpriceshow').update(new_jsspecialprice) // Where jsspecialpriceshow is the id of your span for the echoed product price
}
A: Prototype does not have a no conflict mode...
I've converted your code, but I may have missed a spot or two...
Generally, $('elemID') => $('#elemID') and $F('elemID') => $('#elemID').val() is what I've done..
// JavaScript Document
// calculate price based on quantity
function changeQty(change){
var currentQty = parseInt($('#quant').val()) // Where quant is the id of your quantity input field. Gets value of currentQty field
switch (change) {
case 'add':
currentQty += 1
$('#quant').val(currentQty)
calculate()
break
case 'subtract':
if (currentQty > 1) { // only subtract if qty is greater than zero
currentQty -= 1
$('#quant').val(currentQty)
calculate()
}
break
case 'field':
if (currentQty > 0) {
window.setTimeout('calculate()', 500)
}
break
}
}
function calculate(){
var currentQty = parseInt($('#quant').val()) // Where quant is the id of your quantity input field. Gets value of currentQty field
var jsnormalprice = $('#jsnormalprice').val() // Where jsnormalprice is the id of your hidden base price field. Gets value of base_price field
var jsspecialprice = $('#jsspecialprice').val() // Where is the id of your hidden base price field. Gets value of base_price field
if (currentQty > 0) { // Don't want price to display if zero if customer zeros out quantity
var new_jsnormalprice = jsnormalprice * currentQty // Calculate the price.
var new_jsnormalprice = new_jsnormalprice.toFixed(2) // Only allow 2 decimals. I'll let you add rounding features up or down.
var new_jsspecialprice = jsspecialprice * currentQty // Calculate the price.
var new_jsspecialprice = new_jsspecialprice.toFixed(2) // Only allow 2 decimals. I'll let you add rounding features up or down.
} else { // set price back to original price
new_jsnormalprice = jsnormalprice
new_jsspecialprice = jsspecialprice
}
$('#jsnormalpriceshow').html(new_jsnormalprice) // Where jsnormalpriceshow is the id of your span for the echoed product price
$('#jsspecialpriceshow').html(new_jsspecialprice) // Where jsspecialpriceshow is the id of your span for the echoed product price
}
A: Prototype does not have a no conflict mode.
A: Unfortunately, prototype does not have a no conflict mode.
Fortunately, you do not need to use Prototype to select elements in the DOM. jQuery works perfectly fine for that.
Instead of
$F('quant')
$('quant').value = currentQty
$F('jsnormalprice')
$('jsnormalpriceshow').update(new_jsnormalprice)
You can use the jQuery equivalents:
$("#quant").val()
$("#quant").val(currentQty)
$("#jsnormalprice").val()
$("#jsnormalpriceshow").text(new_jsnormalprice)
And, please, don't evaluate code in a string. Change
window.setTimeout('calculate()', 500)
to the more natural way of doing it:
window.setTimeout(calculate, 500)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to create a table, in which rows are filled in when a user submits a form I'm wanting to create two separate pages, one with a html form on it and the other with a table on it. When the user enters data and submits the form I want the information to be displayed in the table.
Would I need to use Javascript or PHP or neither to achieve this.
Any help would be appreciated,
This is the table:
<table border='1px' >
<tr>
<th>Location</th>
<th>Time</th>
<th>Date</th>
</tr>
<tr>
<td id='location1'>info</td>
<td id="time1">info</td>
<td id="date1">info</td>
</tr>
<tr>
<td id="location2">info</td>
<td id="time2">info</td>
<td id="date2">info</td>
</tr>
<tr>
<td id="location3">info</td>
<td id="time3">info</td>
<td id="date3">info</td>
</tr>
</table>
This is the form:
<form action="" method="post">
Enter Location<input type="text" name="location" id="location" /><br />
Time <input type="text" name="" id="type" /><br />
Date<input type="text" name="pitch" id="pitch" /><br />
<input type="submit" name="submit" value="submit" /><br />
</form>
A: you can use either php or javascript - php would be easier imho. the easiest code sample could look like that:
<table border='1px' >
<tr>
<th>Location</th>
<th>Time</th>
<th>Date</th>
</tr>
<tr>
<td id='location1'><?php isset($_POST['location']) ? $_POST['location'] : '' ?></td>
<td id="time1"><?php isset($_POST['time']) ? $_POST['time'] : '' ?></td>
<td id="date1"><?php isset($_POST['pitch']) ? $_POST['pitch'] : '' ?></td>
</tr>
</table>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pull, rebase, push, in one command (or just a few) When using Git, I often find myself doing the following when working in master:
# work work work...
$ git checkout -b temp
$ git commit -a -m 'more work done'
$ git checkout master
$ git pull origin master
# turns out master was updated since my previous pull
$ git checkout temp
# I don't want a merge commit for a simple bugfix
$ git rebase master
$ git checkout master
$ git merge temp
$ git push origin master
$ git branch -d temp
... and I get tired of doing this. Is there a way to do this dance without all of the checkouts, and preferably without (manually) creating the temporary branch?
A: You can at least optimize the rebasing: git pull --rebase
I'm not exactly sure how you like things, but I like my workflow sort of like this:
git checkout -b temp
git commit -a -m 'more work done'
git pull --rebase origin master
That way I keep my focus on the branch at hand.
Then later, I do
git checkout master
git pull origin master
git merge temp
etc.
A: If you don't mind not creating a branch called temp, you could just do the following all on master:
git commit -a -m 'more work done'
git fetch origin
git rebase origin/master
... or equivalently:
git commit -a -m 'more work done'
git pull --rebase origin master
If you do want to keep the temp branch, however, you can still make this a bit shorter by not checking out master just to do the pull - you only need to fetch and then rebase your branch onto origin/master:
# work work work...
$ git checkout -b temp
$ git commit -a -m 'more work done'
$ git fetch origin
# It looks like origin/master was updated, so:
$ git rebase origin/master
# Then when you finally want to merge:
$ git checkout master
$ git merge temp
$ git push origin master
$ git branch -d temp
sehe's answer reminds me that you could replace:
$ git fetch origin
$ git rebase origin/master
... with:
$ git pull --rebase origin master
... which is nearly equivalent. The difference is that when you run git fetch origin, all of your remote-tracking branches for origin will be updated, whereas when you pull a particular branch from origin, none of them are - it's just the temporary ref FETCH_HEAD that is updated. I personally prefer running one extra command (git fetch origin), and seeing all the remote branches that have changed in the output.
A: git pull --rebase --autostash origin staging && git push origin staging;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: Where could I be doing wrong in this PHP ORACLE pagination script? I have this problem whereby I cannot display records from oracle database to my web application using PHP as a server side scripting language.Could someone kindly tell me where I could be doing wrong? I want by the end of the day to be able to achieve pagination and replace ROWNUM and rnum with variables that users can manipulate when moving fromm page to page.
<?php
/* Connection string to Oracle view */
/* user is patients */
/* password is patients */
$conn=oci_connect('patients','patients','192.168.1.100/hosecare');
/* Query expected to do pagination and get records */
$qry="select *
from (select a.*, ROWNUM rnum
from (select BILL_NO,AK_NO,PAT_NAME,VOUCHER_DATE,USER_NAME,PAYMENT_AMT from patients WHERE VOUCHER_DATE >='01-Sep-2011' AND VOUCHER_DATE <='26-Sep-2011' AND SOURCE_LOCATION='KIAMBU CLINIC' ORDER BY VOUCHER_DATE)a
where ROWNUM <=20)
where rnum >=10;";
$stid=oci_parse($conn,$qry);
oci_execute($stid);
/* Table begins here */
echo "<table border='1'>\n";
echo "<tr>\n";
/* Table Column headers */
echo "<td>".'<h3>BILL NO</h3>'."</td>";
echo "<td>".'<h3>ACCOUNT NO</h3>'."</td>";
echo "<td>".'<h3>PATIENT NAME</h3>'."</td>";
echo "<td>".'<h3>VOUCHER DATE</h3>'."</td>";
echo "<td>".'<h3>USER NAME</h3>'."</td>";
echo "<td>".'<h3>PAYMENT AMOUNT</h3>'."</td>";
echo "</tr>\n";
/* Populating Table cells with records resulting from the pagination query */
while($row=oci_fetch_array($stid,OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
foreach($row as $item){
echo "<td>".($item !==null ? htmlentities($item,ENT_QUOTES) : " ")." </td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
?>
A: If you're getting an error its most likely the ; at the end of your query would cause an error. The ; is not part of SQL itself, its just usually required by whatever client you're playing with to mark the end of the SQL. So when embedding plain SQL in a program you should not end it with a ;
NOTE: If the ; is part of PL/SQL, so if you're embedding that you need to include it
A: Rownum is calculated after the result set is returned so wont help with a pagination script as if you want rows from the inner query returned as rows 10-20 in the full query, it will reset and start at 1.
Try instead to use an analytic query with ROW_NUMBER() instead like this
SELECT * FROM
(SELECT BILL_NO,
AK_NO,
PAT_NAME,
VOUCHER_DATE,
USER_NAME,
PAYMENT_AMT,
ROW_NUMBER() OVER (ORDER BY VOUCHER_DATE ASC) RN
FROM patients
WHERE VOUCHER_DATE >='01-Sep-2011'
AND VOUCHER_DATE <='26-Sep-2011'
AND SOURCE_LOCATION='KIAMBU CLINIC'
ORDER BY VOUCHER_DATE)
WHERE RN BETWEEN 10 and 20;
From a performance point of view though, the above is not great because it will hit the database server and request the full result set each time so maybe better if you can run the query to get the data just once and then use PHP to programmatically step through the result set using the forward/back links.
To try this, have a look at this php pagination script (although it's against mysql, it should give you a starting point to write something similar using Oracle which doesnt cause a performance issue)
//Include the PS_Pagination class
include('ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect('localhost','root','');
mysql_select_db('yourdatabase',$conn);
$sql = 'SELECT post_title FROM wp_posts WHERE post_type="post" ORDER BY ID DESC';
//Create a PS_Pagination object
$pager = new PS_Pagination($conn,$sql,10,10);
//The paginate() function returns a mysql result set
$rs = $pager->paginate();
while($row = mysql_fetch_assoc($rs)) {
echo $row['post_title'],"\n";
}
//Display the full navigation in one go
echo $pager->renderFullNav();
A: I realized the problem came about because of the preceding unnecessary space before SOURCE_LOCATION in the query and the unnecessary semicolon (;) at the end of the query.
The code perfectly works the way I wanted.Thanks to each and everyone of you for the contribution you made towards giving Answers to the Question.
I appreciate all your efforts.
The working code now looks as follows;
<?php
//Connection string to Oracle view
//user is patients
//password is patients
$conn=oci_connect('patients','patients','192.168.1.100/hosecare');
//Query expected to do pagination and get records
//$page will vary depending on which page the user has accessed.
$page=1;
$pageSize=20;
$maxrowfetch=(($page * $pageSize) + 1);
$minrowfetch=((($page - 1) * $pageSize) + 1);
//QUERY WORKING...MODIFIED TO FIT USER REQUIREMENTS
$qry="select *
from (select a.*, ROWNUM rnum
from (select BILL_NO,AK_NO,PAT_NAME,VOUCHER_DATE,USER_NAME,PAYMENT_AMT from smart WHERE VOUCHER_DATE >='20-Sep-2011' AND VOUCHER_DATE <='26-Sep-2011' AND SOURCE_LOCATION='KIAMBU CLINIC' ORDER BY BILL_NO ASC)a
where ROWNUM <="."$maxrowfetch".")
where rnum >="."$minrowfetch"."";
//QUERY NOT WORKING...THE 2 SPACES BEFORE SOURCE_LOCATION IN THE QUERY WAS THE PROBLEM
/***
$qry="select *
from (select a.*, ROWNUM rnum
from (select BILL_NO,AK_NO,PAT_NAME,VOUCHER_DATE,USER_NAME,PAYMENT_AMT from patients WHERE VOUCHER_DATE >='01-Sep-2011' AND VOUCHER_DATE <='26-Sep-2011' AND SOURCE_LOCATION='KIAMBU CLINIC' ORDER BY VOUCHER_DATE ASC)a
where ROWNUM <=20)
where rnum >=10";
***/
//QUERY WORKING...1 SPACE BEFORE SOURCE_LOCATION IN QUERY
/***
$qry="select *
from (select a.*, ROWNUM rnum
from (select BILL_NO,AK_NO,PAT_NAME,VOUCHER_DATE,USER_NAME,PAYMENT_AMT from patients WHERE VOUCHER_DATE >='01-Sep-2011' AND VOUCHER_DATE <='26-Sep-2011' AND SOURCE_LOCATION='KIAMBU CLINIC' ORDER BY VOUCHER_DATE ASC)a
where ROWNUM <=20)
where rnum >=10";
***/
$stid=oci_parse($conn,$qry);
oci_execute($stid);
//Table begins here
echo "<table border='1'>\n";
echo "<tr>\n";
//Table Column headers
echo "<td>".'<h3>BILL NO</h3>'."</td>";
echo "<td>".'<h3>ACCOUNT NO</h3>'."</td>";
echo "<td>".'<h3>PATIENT NAME</h3>'."</td>";
echo "<td>".'<h3>VOUCHER DATE</h3>'."</td>";
echo "<td>".'<h3>USER NAME</h3>'."</td>";
echo "<td>".'<h3>PAYMENT AMOUNT</h3>'."</td>";
echo "</tr>\n";
//Populating Table cells with records resulting from the pagination query
while($row=oci_fetch_array($stid,OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
echo "<td>";
echo $row["BILL_NO"];
echo "</td>";
echo "<td>";
echo $row["AK_NO"];
echo "</td>";
echo "<td>";
echo $row["PAT_NAME"];
echo "</td>";
echo "<td>";
echo $row["VOUCHER_DATE"];
echo "</td>";
echo "<td>";
echo $row["USER_NAME"];
echo "</td>";
echo "<td>";
echo $row["PAYMENT_AMT"];
echo "</td>";
echo "</tr>";
}
echo "</table>\n";
echo "MAX ROW FETCH ".$maxrowfetch."<br>";
echo "MIN ROW FETCH ".$minrowfetch."<br>";
echo $qry."<br>";
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DB information is not renderd out to Calendar I've downloaded the last fullCalendar but the information in db is not renderd out, I can see the information when I use firebug(Response and in tab JSON) , but nothing is visible in Calendar.
Can someone guide me, what have I missed?
A: This is what the code from your server should look like. FC is very particular on how deep each event is.
[{"id":"1311098584475","title":"Cut the lawn","start":"2011-08-28T16:00:00-05:00","allDay":0,"fix":0,"lkd":0,"rlf":0,"end":"2011-08-28T04:30:00-05:00","nid":"2091","vcc":"Vol_Activities|8","mName":"Eric","vdesc":"Lawn Care"}]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python, Paramiko: How to do a "ssh -n user@host cmd" using paramiko? I'm trying to execute a command remotely via SSH from Python, and in this particular case need stdin to be redirected to /dev/null.
That is, the same as using the OpenSSH client with its -n flag:
ssh -n user@host cmd
How do you achieve this (-n) with Paramiko?
paramiko.SSHClient.exec_command() doesn't seem to allow this, but maybe I'm missing something?
A: Unless I understand your question incorrectly: you don't need to achieve this. Nothing is automatically read from stdin/written to the remote process' stdin unless you yourself explicitly do so. So you don't need to prevent reading from stdin from happening?
EDIT: there might be an issue if the remote process expects data on stdin, and keeps waiting for it? Try calling shutdown_write() on the channel:
stdin, stdout, stderr = client.exec_command(cmd)
stdin.channel.shutdown_write()
A: I would ditch paramiko and start using fabric. It will let you do remote calls on the system. It uses paramiko for the ssh connection and provides the nice clean interface for doing alot more.
I am not sure why you need to pip stdin to /dev/null but there are settings to suppress it with fabric.
Goodluck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: AVAudioPlayer freezes when play first song I'm using AVAudioPlayer class to play sound in my app. When i play sound first time, screen freezes for a 2-3 seconds, then it becomes active and without freezes and delays. Even when I change sound. Here is some code:
avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
[avPlayer prepareToPlay];
[avPlayer play];
Sound files are in Documents folder and file paths are correct; How to minimize delay or remove freezes?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: two window objects in extjs I have these two windows defined as shown below. The functionality that I desire is that initially the grid window should be hidden and the login window should be shown. After the user logs in, the login window should be hidden and the grid window should be shown.
var store = new Ext.data.Store({
url: 'sheldon.xml',
reader: new Ext.data.XmlReader({
record: 'Item',
fields: [
{name: 'Title'},
{name: 'Author'},
{name: 'Manufacturer'},
{name: 'ProductGroup'}
]
})
});
LoginWindow = {};
gridWindow = {};
gridWindow.grid = new Ext.grid.GridPanel({
store: store,
columns: [
{header: "Title", width: 120, dataIndex: 'Title', sortable:true},
{header: "Author", width: 180, dataIndex: 'Author', sortable: true},
],
height:200,
viewConfig: {
forceFit:true
}
});
gridWindow = {
xtype: 'window',
id: 'grid',
title: 'Grid',
anchor: '30% 25%',
items:[gridWindow.grid],
frame:true,
layout:'card',
};
LoginWindow.loginForm = {
xtype:'form',
// url:'check.php',
frame: true,
labelAlign:'right',
labelWidth: 70,
items:[
{
xtype:'textfield',
fieldLabel:'Username',
anchor: '100%'
},
{
xtype:'textfield',
fieldLabel:'Password',
inputType:'password',
anchor: '100%',
}
],
buttons:[
{
text:'Login',
handler:
// Dummy function
function(btn, objc) {
Ext.getCmp('loginwindow').hide();
Ext.getCmp('grid').show();
store.load();
},
},
{
text:'Cancel',
handler:function(btn, objc) {
btn.findParentByType('form').getForm().reset();
}
}
]
};
LoginWindow = {
xtype: 'window',
id: 'loginwindow',
title: 'Please Log In',
anchor: '30% 25%',
activeItem: 0,
items:[LoginWindow.loginForm],
frame:true,
layout:'card',
bodyStyle:{}
};
Ext.onReady(function() {
var viewport = new Ext.Viewport({
layout: 'anchor',
items:[
LoginWindow
]
});
Ext.getCmp('loginwindow').show();
Ext.getCmp('grid').hide();
});
When I load the page, I get the error Ext.getcmp('grid') is undefined in firefox.
Could someone please help me out here...
A: Your gridWindow only exists as an object literal (aka xtype config object) and is never 'instantiated' (created). Therefore Ext.getCmp cannot find it, because it doesn't 'exist' yet and hasn't been registered with Ext.ComponentManager.
You could add it to the Viewport and add hidden:true to its config definition so it doesn't show up.
gridWindow = {
xtype: 'window',
id: 'grid',
title: 'Grid',
anchor: '30% 25%',
items:[gridWindow.grid],
frame:true,
layout:'card',
};
Ext.onReady(function() {
var viewport = new Ext.Viewport({
layout: 'anchor',
items:[
LoginWindow, gridWindow
]
});
// no need
//Ext.getCmp('loginwindow').show();
//Ext.getCmp('grid').hide();
});
Note: you might also need to call doLayout() on your viewport in your login handler after showing/hiding the components.
A: Looks like you first define LoginWindow.loginForm, but then redefine LoginWindow with a new object.
LoginWindow.loginForm = {
xtype:'form',
// url:'check.php',
LoginWindow is now set to an object literal with one property loginForm.
{
loginForm: [object]
}
Followed by
LoginWindow = {
xtype: 'window',
id: 'loginwindow',
This will create a completely new object and assign it to LoginWindow. The loginForm property is nowhere to be seen anymore ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery - text color fade in I can't find a simple solution to this problem.
I am trying to fade in a color change for some text when there is an error from a button click.
if (document.getElementById("username").value == ""){ //First Name
$("#login_error").text("Please enetr a username!").css('color', '#FF0000');
$("#username_label").css('color', '#FF0000');fadeIn(3000);
}
I can get the color to change but it is instant. I am wanting to get the change of colour to fade in slowly.
Thanks Guys!
A: If you add jQuery UI, they added support for color animations.
Read http://jqueryui.com/demos/animate/ for details.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function(){
$(".block").toggle(function() {
$(this).animate({ color: "#FF0000" }, 1000);
},function() {
$(this).animate({ color: "#000000" }, 1000);
});
});
</script>
Update: jQuery now offers a color plugin to enable only this feature without including the entire jQuery-UI library.
A: You need to use plugin, it's not part of the built in animation: https://github.com/jquery/jquery-color
Related question: jQuery animate backgroundColor
A: of course .css call is instant, and fadeIn is just chained (started after css is changed)
try using animate
A: You can animate css properties using jQuery .animate function, i.e.
$(this).animate({ height: 250 });
BUT, you cannot animate color, sorry. For that you need to use plugin, see this answer for details.
Also, if you are using jquery UI, then it is possible:
Note: The jQuery UI project extends the .animate() method by allowing some non-numeric styles such as colors to be animated. The project also includes mechanisms for specifying animations through CSS classes rather than individual attributes.
(from http://api.jquery.com/animate/)
You have sample here.
A: I find the method to change the color and found this
https://stackoverflow.com/a/15234173/1128331
already test and it work what I want to :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Video Conference via C# I have searched for various samples online but I'm unable to find a suitable sample which is able to provide enough information.
I have tried Microsoft Expression Encoder, but the delay is too huge if I use broadcast method.
Directshow.net wise, the sample DxWebCam seems promising, but it lacks audio sample.
The idea I had in my mind is to send audio and video (frames) separately via TCP (or maybe UDP as highlighted by @macbral) but I am not sure how to handle synchronisation.
I'm looking at free samples as the current design is a 1 to 1 video conference via intranet.
Thanks for any help in advance.
A: I've been looking for the same and have given up on open source alternatives since none of those seem to work well from .NET.
I'm currently evaluating products from StreamCoders which looks promising: http://www.streamcoders.com/
A: You can check ConferenceXP (a bit old project, but made simple conferences with it myself, after converting code to new visual studio/framework). To encode video, make more advanced streams- you can work with VLC api or Expression Encoder. Also you can try microsoft live messanger api (As i remember they have conferences in it).
PS there also is Skype api, but havent even seen it, so can say nothing about using it..You can research it too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: function argument What is the below highlighted code intended to do ? Why don't we not use the arguments at all ?
int fun( int a, int b)
{
(void) a; // <<<
(void) b; // <<<
printf("Hello World\n");
}
A: It's a way of preventing the compiler from warning about "unused parameters". It doesn't actually consume anything (the expression is discarded).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: string-match problem
EDIT 2: I managed to find the solution with suffix trees Tree::Suffix perl package. Thanks to MarcoS for the trie idea. I figured out from that, that suffix trees could be used as well. The Tree::Trie perl package is implemented as hash of hashes and I guess that's the reason it slow. I tried it and then went back to Tree::Suffix. Thanks to all others for their links to different algorithms. I am already trying to write code for every algorithm mentioned here myself as a learning process
EDIT 1: I changed the title from perl string-match problem to string-match problem.
Suppose that I have two strings, say,
S1 = ACGAGGATAGTATGCCACACAATGAGTACCCGTAC
S2 = CAGTATTGCACGTTGTAAAGTTACCCAGGTACGATGACAGTGCGTGAGCATACGAGGATAGTATGCCA
I initially wanted to check for the occurrence of string S1 (with no or 1 mismatch) in S2. And I have already written the perl code for that.
Now, I would like to develop on it to
1) Search for k-mismatches of S1 in S2.
2) Search for the occurrence of a prefix (yes, prefix, not suffix), of S1 in S2. If you look at the example, the string: ACGAGGATAGTATGCCA occurs at the end of S2 which is the beginning of S1.
3) If possible, search for the prefix with k-mismatches.
The catch is that I have about 100 million such S2 strings. S1 however remains the same and is of a defined constant length for a given problem. Is there an efficient algorithm in the literature that I could use for this problem of mine?
S1 varies between 50 and 80 characters. Also, I am mostly interested in solving problem 2 at first.
Thank you very much.
A: You may be able to modify the Aho-Corasick algorithm for your purposes.
A: For approximate matching, have a look at http://en.wikipedia.org/wiki/Bitap_algorithm as used in agrep.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to work with null pointers in a std::vector Say I have a vector of null terminates strings some of which may be null pointers. I don't know even if this is legal. It is a learning exercise. Example code
std::vector<char*> c_strings1;
char* p1 = "Stack Over Flow";
c_strings1.push_back(p1);
p1 = NULL; // I am puzzled you can do this and what exactly is stored at this memory location
c_strings1.push_back(p1);
p1 = "Answer";
c_strings1.push_back(p1);
for(std::vector<char*>::size_type i = 0; i < c_strings1.size(); ++i)
{
if( c_strings1[i] != 0 )
{
cout << c_strings1[i] << endl;
}
}
Note that the size of vector is 3 even though I have a NULL at location c_strings1[1]
Question. How can you re-write this code using std::vector<char>
What exactly is stored in the vector when you push a null value?
EDIT
The first part of my question has been thoroughly answered but not the second. Not to my statisfaction at least. I do want to see usage of vector<char>; not some nested variant or std::vector<std::string> Those are familiar. So here is what I tried ( hint: it does not work)
std::vector<char> c_strings2;
string s = "Stack Over Flow";
c_strings2.insert(c_strings2.end(), s.begin(), s.end() );
// char* p = NULL;
s = ""; // this is not really NULL, But would want a NULL here
c_strings2.insert(c_strings2.end(), s.begin(), s.end() );
s = "Answer";
c_strings2.insert(c_strings2.end(), s.begin(), s.end() );
const char *cs = &c_strings2[0];
while (cs <= &c_strings2[2])
{
std::cout << cs << "\n";
cs += std::strlen(cs) + 1;
}
A: You don't have a vector of strings -- you have a vector of pointer-to-char. NULL is a perfectly valid pointer-to-char which happens to not point to anything, so it is stored in the vector.
Note that the pointers you are actually storing are pointers to char literals. The strings are not copied.
It doesn't make a lot of sense to mix the C++ style vector with the C-style char pointers. Its not illegal to do so, but mixing paradigms like this often results in confused & busted code.
Instead of using a vector<char*> or a vector<char>, why not use a vector<string> ?
EDIT
Based on your edit, it seems like what your'e trying to do is flatten several strings in to a single vector<char>, with a NULL-terminator between each of the flattened strings.
Here's a simple way to accomplish this:
#include <algorithm>
#include <vector>
#include <string>
#include <iterator>
using namespace std;
int main()
{
// create a vector of strings...
typedef vector<string> Strings;
Strings c_strings;
c_strings.push_back("Stack Over Flow");
c_strings.push_back("");
c_strings.push_back("Answer");
/* Flatten the strings in to a vector of char, with
a NULL terminator between each string
So the vector will end up looking like this:
S t a c k _ O v e r _ F l o w \0 \0 A n s w e r \0
***********************************************************/
vector<char> chars;
for( Strings::const_iterator s = c_strings.begin(); s != c_strings.end(); ++s )
{
// append this string to the vector<char>
copy( s->begin(), s->end(), back_inserter(chars) );
// append a null-terminator
chars.push_back('\0');
}
}
A: So,
char *p1 = "Stack Over Flow";
char *p2 = NULL;
char *p3 = "Answer";
If you notice, the type of all three of those is exactly the same. They are all char *. Because of this, we would expect them all to have the same size in memory as well.
You may think that it doesn't make sense for them to have the same size in memory, because p3 is shorter than p1. What actually happens, is that the compiler, at compile-time, will find all of the strings in the program. In this case, it would find "Stack Over Flow" and "Answer". It will throw those to some constant place in memory, that it knows about. Then, when you attempt to say that p3 = "Answer", the compiler actually transforms that to something like p3 = 0x123456A0.
Therefore, with either version of the push_back call, you are only pushing into the vector a pointer, not the actual string itself.
The vector itself, doesn't know, or care that a NULL char * is an empty string. So in it's counting, it sees that you have pushed three pointers into it, so it reports a size of 3.
A:
What exactly is stored in the vector when you push a null value?
A NULL. You're storing pointers, and NULL is a possible value for a pointer. Why is this unexpected in any way?
Also, use std::string as the value type (i.e. std::vector<std::string>), char* shouldn't be used unless it's needed for C interop. To replicate your code using std::vector<char>, you'd need std::vector<std::vector<char>>.
A: NULL is just 0. A pointer with value 0 has a meaning. But a char with value 0 has a different meaning. It is used as a delimiter to show the end of a string. Therefore, if you use std::vector<char> and push_back 0, the vector will contain a character with value 0. vector<char> is a vector of characters, while std::vector<char*> is a vector of C-style strings -- very different things.
Update. As the OP wants, I am giving an idea of how to store (in a vector) null terminated strings some of which are nulls.
Option 1: Suppose we have vector<char> c_strings;. Then, we define a function to store a string pi. A lot of complexity is introduced since we need to distinguish between an empty string and a null char*. We select a delimiting character that does not occur in our usage. Suppose this is the '~' character.
char delimiter = '~';
// push each character in pi into c_strings
void push_into_vec(vector<char>& c_strings, char* pi) {
if(pi != 0) {
for(char* p=pi; *p!='\0'; p++)
c_strings.push_back(*p);
// also add a NUL character to denote end-of-string
c_strings.push_back('\0');
}
c_strings.push_back(deimiter);
// Note that a NULL pointer would be stored as a single '~' character
// while an empty string would be stored as '\0~'.
}
// now a method to retrieve each of the stored strings.
vector<char*> get_stored_strings(const vector<char>& c_strings) {
vector<char*> r;
char* end = &c_strings[0] + c_strings.size();
char* current = 0;
bool nullstring = true;
for(char* c = current = &c_strings[0]; c != end+1; c++) {
if(*c == '\0') {
int size = c - current - 1;
char* nc = new char[size+1];
strncpy(nc, current, size);
r.push_back(nc);
nullstring = false;
}
if(*c == delimiter) {
if(nullstring) r.push_back(0);
nullstring = true; // reset nullstring for the next string
current = c+1; // set the next string
}
}
return r;
}
You still need to call delete[] on the memory allocated by new[] above. All this complexity is taken care of by using the string class. I very rarely use char* in C++.
Option 2: You could use vector<boost::optional<char> > . Then the '~' can be replaced by an empty boost::optional, but other other parts are the same as option 1. But the memory usage in this case would be higher.
A: You have to be careful when storing pointers in STL containers - copying the containers results in shallow copy and things like that.
With regard to your specific question, the vector will store a pointer of type char* regardless of whether or not that pointer points to something. It's entirely possible you would want to store a null-pointer of type char* within that vector for some reason - for example, what if you decide to delete that character string at a later point from the vector? Vectors only support amortized constant time for push_back and pop_back, so there's a good chance if you were deleting a string inside that vector (but not at the end) that you would prefer to just set it null quickly and save some time.
Moving on - I would suggest making a std::vector > if you want a dynamic array of strings which looks like what you're going for.
A std::vector as you mentioned would be useless compared to your original code because your original code stores a dynamic array of strings and a std::vector would only hold one dynamically changable string (as a string is an array of characters essentially).
A: I have a funny feeling that what you would really want is to have the vector contain something like "Stack Over Flow Answer" (possibly without space before "Answer").
In this case, you can use a std::vector<char>, you just have to push the whole arrays, not just pointers to them.
This cannot be accomplished with push_back, however vector have an insert method that accept ranges.
/// Maintain the invariant that the vector shall be null terminated
/// p shall be either null or point to a null terminated string
void push_back(std::vector<char>& v, char const* p) {
if (p) {
v.insert(v.end(), p, p + strlen(p));
}
v.push_back('\0');
} // push_back
int main() {
std::vector<char> v;
push_back(v, "Stack Over Flow");
push_back(v, 0);
push_back(v, "Answer");
for (size_t i = 0, max = v.size(); i < max; i += strlen(&v[i]) + 1) {
std::cout << &v[i] << "\n";
}
}
This uses a single contiguous buffer to store multiple null-terminated strings. Passing a null string to push_back results in an empty string being displayed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Using MySQL LIKE to match a whole string I have been doing a bit of searching round StackOverflow and the Interweb and I have not had much luck.
I have a URL which looks like this...
nr/online-marketing/week-in-review-mobile-google-and-facebook-grab-headlines
I am getting the article name from the URL and replacing the '-' with ' ' to give me:
week in review mobile google and facebook grab headlines
At this point this is all the information that I have on the article so I need to use this to query the database to get the rest of the article information, the problem comes around but this string does not match the actual headline of the article, this this instance the actual headline is:
Week in review: Mobile, Google+ and Facebook grab headlines
As you can see it include extra punctuation, so I need to find a way of using MYSQL LIKE to match the article.
Hope someone can help, a standard SELECT * FROM table WHERE field LIKE $name does not work , im hoping of finding a way of doing it without splitting up each individual word but if that what it comes down to then so be it!
Thanks.
A: This really seems more like a database design issue... If you're using large texts with different fields as forms of primary keys it could lead to duplicates or synchronization problems.
One potential solution is to give each entry a unique identifier (perhaps an int or uniqueidentifier field if MSQL supports that), and use that field to map the actual healdine to the URL.
another potential solution is to create a table that will associate each headline with its URL and use that table for lookups. This will incur a little extra overhead, but will ensure that special characters in the title will never effect the lookup process.
As for a way to do this with your current design, you may be able to do some kind of regular expression search by tokenizing each word individually and then searching for an entry that includes all tokens, but I'm fairly certain that MSQL doesn't provide this functionality in a basic command.
A: Try MySQL MyISAM engine's full-text search. In your case the query will be:
SELECT * FROM table
WHERE MATCH (title) AGAINST ('week in review mobile google and facebook grab headlines');
That requires you to convert the table to MyISAM. Also depending on the size of the table, test the performance of the query.
See more info under:
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: creating header with axis2 java2wsdl - how? I am using org.apache.axis2 to create wsdl. Our code is implementing ScemaGenerator and has our additions. I am trying to find a way to create the wsdl with the header definition, that will include userName and password. How can I do that through the code and not through file editing after it was created? and If I have no choice and I need to edit the file, what is the correct sintax to do it? What I wrote is creating a wsdl parsing error when it is used for wsdl2Java. My code:
<wsdl:message name="wsDirectLoginRequest">
<wsdl:part name="parameters" element="ns:wsDirectLogin">
</wsdl:part>
<wsdl:part name="request_header" element="intf:pswd">
</wsdl:message>
...
<wsdl:input message="ns:wsDirectLoginRequest" wsaw:Action="urn:wsDirectLogin">
<wsdlsoap:header message="intf:wsDirectLoginRequest" part="request_header" use="literal"/>
<wsdlsoap:body use="literal" parts="parameters"/>
</wsdl:input>
...
What am I doing wrong?
Thank you
A: There is no way to do this with the DefaultSchemaGenerator comes with Axis2.
What is the wsdl error you get? Please look at here for a correct wsdl[1].
But as pointed out in a earlier comment, it is better to thing whether you need to use WS-Security (using rampart) or add headers manually.
[1] http://wso2.org/node/2935/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Synchronize on value, not object I want to do something like this in Java
public void giveMoney(String userId, int money) {
synchronized (userId) {
Profile p = fetchProfileFromDB(userId);
p.setMoney(p.getMoney() + userId);
saveProfileToDB(p);
}
}
But of course, synchronizing on a string is not correct. What's a correct way to do something like this?
A: In principle, you can synchronize on any object in Java. It's not in itself "not correct" to synchronize on a String object; it depends on what exactly you're doing.
But if userId is a local variable in a method, then this is not going to work. Each thread that executes the method with have its own copy of the variable (presumably referring to a different String object for each thread); synchronizing between threads ofcourse only works when you make multiple threads synchronize on the same object.
You'd have to make the object you're synchronizing on a member variable of the object that contains the method in which you have the synchronized block. If multiple threads are then calling the method on the same object, you'll achieve mutual exclusivity.
class Something {
private Object lock = new Object();
public void someMethod() {
synchronized (lock) {
// ...
}
}
}
You could also use explicit locks from the java.util.concurrent.locks package, that can give you more control if you need that:
class Something {
private Lock lock = new ReentrantLock();
public void someMethod() {
lock.lock();
try {
// ...
} finally {
lock.unlock();
}
}
}
Especially if you want an exclusive lock for writing, but you don't want threads to have to wait for each other when reading, you might want to use a ReadWriteLock.
A: I guess there are a few options.
The easiest is that you could map a userId to a lock object in a threadsafe map. Others have mentioned interning but I don't think that's a viable option.
However, the more common option would be to synchronize on p (the Profile). This is appropriate if getProfile() is threadsafe, and by its name I would suspect it might be.
A: Theoretically speaking, since interned objects can be GC-ed, it's possible to synchronized on different objects (of the same value) at different times. Mutual exclusivity is still guaranteed, since it's not possible to synchronized on different objects at the same time.
However, if we synchronized on different objects, the happens-before relation is at doubt. We have to examine the implementation to find out. And since it involves GC, which Java Memory Model does not address, the reasoning can be quite difficult.
That's a theoretical objection; practically I don't think it'll cause any problem.
Still, there can be simple, direct, and theoretically correct solution to your problem. For example Simple Java name based locks?
A: If the set of user ids is limited, you can synchronize on an interned version of the String.
Either use String.intern() (which has a few drawbacks) or something like Guava Interners if you need a bit more control over the interning.
A: You can use a proxy object for the string.
Object userIdMutex = new Object();
synchronized (userIdMutex) {
Profile p = getProfile(userId);
p.setMoney(p.getMoney() + p);
saveProfile(p);
}
Use this mutex whenever you access userId.
A: Based on your example, I assume you want to obtain a lock to a profile class, change it, and then release the lock. Synchronization is not exactly what you need in my opinion. You need a class that manages those records and lets you lock and unlock a record when changes need to be made to it, aka source control style.
Check this out: Lock class Java 5
A: What about this:
String userId = ...;
Object userIdLock = new Object();
synchronized (userIdLock) {
Profile p = getProfile(userId);
p.setMoney(p.getMoney() + p);
saveProfile(p);
}
It's simple and above all obvious.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Vaadin application, jump to page top I have a vaadin application that has an outer panel, and upload this lot, interior panels. This case the entire bottom of the page (the bottom panel) jumps. How I know this time will automatically jump to the top?
The "window.getApplication().getMainWindow.setScrolleft(x)" does not work, because they do not want a scrolling panebut also you want the browser to jump to the top.
Thanks G
I tried vaadin 6.7(still in beta), but still it produces the error.
A: this is most probably due to a bug in vaadin that has been fixed in the 6.7 branch.
HTH
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Save multiple questions in one row I need to make a scheme for an database. My problem is, that I have multiple questions they belong to one exam. That means: One Exam has multiple Questions. I don't know how I can solve that. I have try to fix it with an table between "tabQuestions" and "tabTest" but I doesn't seems to be the correct approach.
I have the following tables:
tabTest: ID, Name, FK_Categorie, FK_Questions
tabQuestions: ID, Question, FK_Answer
tabAnswers: ID, Answer, FK_Solution
tabSolution: ID, Solution
Thank you very much for the help!
Luca
A: You don't need the FK_Question field in your tabTest. What you need is a FK_Test field in your tabQuestion table where you store the id of the test the question belongs to.
...if I understood you right...?
And if I understood you right, then you should use the same for the rest of the schema too. This means you need a reference in your solutions table where you store the answer the solution belongs to etc.
A: You need to create two tables for this. One for exam (test) and one for questions.
The table exam (test) should have:
test_id, test_name
The table question should have:
test_id (references test_id from test table),
question_id ,
question_text.
Now you can have a 1:n relationship where one test has many questions.
But do not, I repeat: do not, store multiple questions in one row. That violates every possible good database design. Your selects, updates and inserts will be near impossible to write.
This website seems to have very good pointers for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: publish jekyll generated to gh-pages and not overwrite the .git in _site I am using jekyll to publish a static site directly on gh-pages branch in Github. The issue I have is that every time I run
$ jekyll --no-auto /Users/khinester/Sites/tzm/
this overwrites the .git directory and I have to recreate this:
$ git init-db
$ git add remote ..
$ git add .
$ git commit -a -m 'message'
$ git branch gh-pages && git checkout gh-pages
etc..
$ git push -f github gh-pages
basically i have the master branch containing the files needed to generate the blog and gh-pages branch which displays the actual blog.
and also note that i have to force push this.
it will be nice to have also be able to version control the updates!
i have read the https://github.com/mojombo/jekyll/wiki/Deployment but this seems has more steps then what i do now.
is there a better way to do this or have i missing something.
A: Jekyll has a config array called keep_files. Everything in that array will be kept when Jekyll rebuilds the site.
Here's where it was added: https://github.com/mojombo/jekyll/pull/630. Searching the issues for keep_files will reveal more of its black magic.
.git and .svn files are added to keep_files by default so this shouldn't be a problem anymore.
A: I used Steven Penny's script to write this one, which out of the box is for Project Pages, not User Pages.
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR
SELF=`basename $0`
SOURCE_BRANCH="master"
DEST_BRANCH="gh-pages"
TMP_DIR="tmp"
git checkout $SOURCE_BRANCH
jekyll build -d $TMP_DIR
git checkout $DEST_BRANCH
# This will remove previous files, which we may not want (e.g. CNAME)
# git rm -qr .
cp -r $TMP_DIR/. .
# Delete this script from the output
rm ./$SELF
rm -r $TMP_DIR
git add -A
git commit -m "Published updates"
# May not want to push straight away
# git push origin master
git checkout $SOURCE_BRANCH
A: I use the following shell script for committing a Hakyll generated site
(in directory _site) to the gh-pages branch. The script:
*
*Does not require you to switch branches... just run the script from master or whatever branch you're on.
*Uses the main repository; it does not matter that jekyll clobbers
the .git directory because... it isn't there!
*Does nothing if nothing has changed!
*Recognises new, previously untracked files (even when there are no changes to existing files)
*Adds a new commit to the gh-pages branch, so you don't need to force push.
*Includes a timestamp in the commit message
Code follows; update paths as necessary
export GIT_INDEX_FILE=$PWD/.git/index-deploy
export GIT_WORK_TREE=$PWD/_site
REF=refs/heads/gh-pages
git read-tree "$REF"
git add --all --intent-to-add
git diff --quiet && exit
git add --all
TREE=$(git write-tree)
COMMIT=$(git commit-tree "$TREE" -p "$REF" -m "snapshot $(date '+%y-%m-%d %H:%M')")
git update-ref "$REF" "$COMMIT"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do I layout a button bar with buttons of different heights? How do I go about implementing a button bar with buttons of different shapes and heights? As an example (please excuse my poor drawing skills for this quick mockup):
The example bar has 3 buttons, with the middle button (3) a different shape and height than the other 2 buttons (1,2). The button bar will be a view that is included and merged into other views so as to seem to float on top of the parent view.
I was thinking of implementing buttons 1 and 2 into a layout, and then button 3 as another layout that I then merge with the first two button's layout.
A: like my previous comrades said, you need some kind of layout or container that can have a background (if you wish for button #3 to hoover above it) then use relative layout for mixing the two the disadvantage of this other than complexity is that youcannot relate to the other two buttons since they reside in a different layout.
More elegant solution may be to have a special background drawable that can:
*
*have a method setCurrentHeight() that will specify the height the actual viewable section should have the rest will be filled with transparent color.
*override it's own draw so just before it's drawing it will have a callback called, call back you can register yourself to.
then you can register the callback in your activity to take the current position of the #3 button and set the height accordingly, this way you are still with one layout with special drawable as background.
A customized LevelDrawable might do the trick.
A: I would layout this bar as follows:
*
*A RelativeLayout as a container for the rest, with height set to wrap_content and alignparentbottom = true
*An ImageView for the bar
*2 Buttons with a transparent background (Button 1 and 2)
*Button 3 is a custom Button with a custom Image of a trapezoid as background
So you will have a Layout similar to this:
<RelativeLayout
...>
<ImageView
.../>
<Button
... Button 1 />
<Button
... Button 2 />
<Button
... Button 3 />
</RelativeLayout>
A: I don't exactly know that this will work, and I can't test it, but you might give something like this a try; I believe it can all be done elegantly through XML.
*
*Have a RelativeLayout (id:mainLayout) that will contain all of your views, wrap_content for both dimensions.
*Have a blank View as your first child that will serve as your background bar
*Set the View's background color/image to what you want; layout_width to fill_parent; layout_height to wrap_content; layout_alignTop="@id/leftButton"; layout_alignBottom="@id/leftButton".
*Add an ImageButton for your center button (id:bigButton), wrap_content for both dimensions; layout_centerInParent="true".
*Add an ImageButton for your left button (id:leftButton), wrap_content for both dimensions; layout_toLeftOf="@id/bigButton"; layout_centerInParent="true".
*Add an ImageButton for your right button (id:rightButton), wrap_content for both dimensions; layout_toRightOf="@id/bigButton"; layout_centerInParent="true".
In my head, I believe this works, but I could be off. Regardless, something to think about, and I hope it helps you find a solution. :)
A: Better you can tablelayout with different button styles or relative layout for button "3"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Google API 3 open Infowindow from divs outside google maps As the title states how can I with Google API 3 open Infowindow from divs outside google maps.
this is what I am doing today but this only working on the last div link and not every link
markerObj = document.getElementById(markerId);
markerObj.onclick = function(){
google.maps.event.trigger(marker, 'click');
}
Any clues?
A: I think to make this work you'd need to have an array of markers. Then you'd trigger the click on the exact marker you want (right now it'll just do it on your last marker).
So, as you add markers to your map, append them into an array:
var markers = [];
var marker = new google.maps.Marker({ ... });
marker.addListener('click', function() {
infowindow.setContent('blah blah');
infowindow.open(map, this);
});
markers.push(marker);
Then on your divs, pass in an ID to work out which of the array you're dealing with.
<div id="link0">1</div> <div id="link1">2</a> (JS arrays start at zero)
Then just a slight amend to your code:
markerObj = document.getElementById(markerId);
// work out which number it is
var linkID = markerId.replace("link", "");
markerObj.onclick = function(){
google.maps.event.trigger(markers[linkID], 'click');
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Questions about EXIF in hexadecimal form I am trying to understand the EXIF header portion of a jpeg file (in hex) and how to understand it so I can extract data, specifically GPS information. For better or worse, I am using VB.Net 2008 (sorry, it is what I can grasp right now). I have extracted the first 64K of a jpg to a byte array and have a vague idea of how the data is arranged. Using the EXIF specification documents, version 2.2 and 2.3, I see that there are tags, that are supposed to correspond to actual byte sequences in the file. I see that there is a “GPS IFD” that has a value of 8825 (in hex). I search for the hex string 8825 in the file (which I understand to be two bytes 88 and 25) and then I believe that there is a sequence of bytes following the 8825. I suspect that those subsequent bytes denote where in the file, by way of an offset, the GPS data would be located. For example, I have the following hex bytes, starting with 88 25: 88 25 00 04 00 00 00 01 00 00 05 9A 00 00 07 14. Is the string that I am looking for longer than 16 bytes? I get the impression that in this string of data, it should be telling me where to find the actual GPS data in the file.
Looking at http://search.cpan.org/~bettelli/Image-MetaData-JPEG-0.153/lib/Image/MetaData/JPEG/Structures.pod#Exif_and_DCT, halfway down the page, it talks about “Each IFD block is a structured sequence of records, called, in the Exif jargon, Interoperability arrays. The beginning of the 0th IFD is given by the 'IFD0_Pointer' value. The structure of an IFD is the following:”
So, what is an IFD0_Pointer? Does it have to do with an offset? I presume an offset is so many bytes from a beginning point. If that is true, where is that beginning point?
Thanks for any responses.
Dale
A: I suggest you to read The Exif Specification (PDF); it is clear and quite easy to follow. For a short primer, here is the summary of an article I wrote:
A JPEG/Exif file starts with the start of the image marker (SOI). The SOI consists of two magic bytes 0xFF 0xD8, identifying the file as a JPEG file. Following the SOI, there are a number of Application Marker sections (APP0, APP1, APP2, APP3, ...) typically including metadata.
Application Marker Sections
Each APPn section starts with a marker. For the APP0 section, the marker is 0xFF 0xE0, for the APP1 section 0xFF 0xE1, and so on. Marker bytes are followed by two bytes for the size of the section (excluding the marker, including the size bytes). The length field is followed by variable size application data. APPn sections are sequential, so that you can skip entire sections (by using the section size) until you reach the one you are interested in. Contents of APPn sections vary, the following is for the Exif APP1 section only.
The Exif APP1 Section
Exif metadata is stored in an APP1 section (there may be more than one APP1 section). The application data in an Exif APP1 section consists of the Exif marker 0x45 0x78 0x69 0x66 0x00 0x00 ("Exif\0\0"), the TIFF header and a number of Image File Directory (IFD) sections.
The TIFF Header
The TIFF header contains information about the byte-order of IFD sections and a pointer to the 0th IFD. The first two bytes are 0x49 0x49 (II for Intel) if the byte-order is little-endian or 0x4D 0x4D (MM for Motorola) for big-endian. The following two bytes are magic bytes 0x00 0x2A (42 ;)). And the following four important bytes will tell you the offset to the 0th IFD from the start of the TIFF header.
Important: The JPEG file itself (what you have been reading until now) will always be in big-endian format. However, the byte-order of IFD subsections may be different, and need to be converted (you know the byte-order from the TIFF header above).
Image File Directories
Once you get this far, you have your pointer to the 0th IFD section and you are ready to read actual metadata. The remaining IFDs are referenced in different places. The offset to the Exif IFD and the GPS IFD are given in the 0th IFD fields. The offset to the first IFD is given after the 0th IFD fields. The offset to the Interoperability IFD is given in the Exif IFD.
IFDs are simply sequential records of metadata fields. The field count is given in the first two bytes of the IFD. Following the field count are 12-byte fields. Following the fields, there is a 4 byte offset from the start of the TIFF header to the start of the first IFD. This value is meaningful for only the 0th IFD. Following this, there is the IFD data section.
IFD Fields
Fields are 12-byte subsections of IFD sections. The first two-bytes of each field give the tag ID as defined in the Exif standard. The next two bytes give the type of the field data. You will have 1 for byte, 2 for ascii, 3 for short (uint16), 4 for long (uint32), etc. Check the Exif Specification for the complete list.
The following four bytes may be a little confusing. For byte arrays (ascii and undefined types), the byte length of the array is given. For example, for the Ascii string: "Exif", the count will be 5 including the null terminator. For other types, this is the number of field components (eg. 4 shorts, 3 rationals).
Following the count, we have the 4-byte field value. However, if the length of the field data exceeds 4 bytes, it will be stored in the IFD Data section instead. In this case, this value will be the offset from the start of the TIFF header to the start of the field data. For example, for a long (uint32, 4 bytes), this will be the field value. For a rational (2 x uint32, 8 bytes), this will be an offset to the 8-byte field data.
This is basically how metadata is arranged in a JPEG/Exif file. There are a few caveats to keep in mind (remember to convert the byte-order as needed, offsets are from the start of TIFF header, jump to data sections to read long fields, ...) but the format is quite easy to read. Following is the color-coded HEX view of a JPEG/Exif file. The blue block represents the SOI, orange is the TIFF header, green is the IFD size and offset bytes, light purple blocks are IFD fields and dark purple blocks are field data.
A: Here is a php script I wrote to modify exif headers.
<?php
$full_image_string=file_get_contents("torby.jpg");
$filename="torby.jpg";
if (isset($_REQUEST['filename'])){$filename=$_REQUEST['filename'];}
if (array_key_exists('file', $_REQUEST)) {
$thumb_image = exif_thumbnail($_REQUEST['file'], $width, $height, $type);
} else {
$thumb_image = exif_thumbnail($filename, $width, $height, $type);
}
if ($thumb_image!==false) {
echo $thumb_image;
$thumblen=strlen($thumb_image);
echo substr_count($full_image_string,$thumb_image);
$filler=str_pad("%%%THUMB%%%", $thumblen);
$full_image_string=str_replace($thumb_image,$filler,$full_image_string);
file_put_contents("torby.jpg",$full_image_string);
exit;
} else {
// no thumbnail available, handle the error here
echo 'No thumbnail available';
}
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: PHP - get server to ping a visitors IP and return the ping in ms I want to do as the title states. To ping a users IP and return a result in ms, for instance:
Ping IP
return 400ms.
I have no idea how to do this but I expect it would be relatively simple. I have access to the exec() function and the functions similar to it as I will be running this script on a virtual private server.
Thanks in advance.
A: try this
<?php
$out = array();
exec('ping -c 4 '.$_SERVER['REMOTE_ADDR'], $out);
print_r($out);
?>
A: Try this:
<?php
$ip = $_SERVER['SERVER_ADDR']; // Get the IP address of the visitor
$result = system('ping -n 1 '.$ip, $retval); // the result contains the last line of the ping command.
if ($retval==0) echo "OK";
if ($retval==1) echo "NOT OK";
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: silverlight-4.0 INotifyDataErrorInfo with Entity Framework I am using EF 4.0 with Silverlight 4.0. I wanted to validate my Entity using INotifyDataErrorInfo. For that do I need to create duplicate class on clientside and implement INotifyDataErrorInfo ? I can not Implement it on autogenerated Entity as entity gets updated when my datasource changes. So How should I do with this ?
A: You can't do that, because INotifyDataErrorInfo is Silverlight only:
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifydataerrorinfo(v=vs.95).aspx
you will have to create separate properties and validate those.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: form_tag isn't working when upgraded to rails 3.0.7 --> 3.1 Just upgraded to rails 3.1 and now my form_tag doesn't work anymore, I don't get any errors at all?
<% form_tag({:action => 'search'}, :remote => true) do %>
<%= select_tag "prod_id", options_for_select(["-"]) %>
...
<% end %>
Have something dramatically changed so I need to change my code?
Thanks in advance
A: Code blocks in your views (like form_for, for instance) now need to use the <%= %> syntax instead of <% %>.
Change the first line of your code to look like this:
<%= form_tag({:action => 'search'}, :remote => true) do %>
and you should be good to go.
As a note, I think this change actually came about in one of the Rails 3.0 betas. Check out http://asciicasts.com/episodes/208-erb-blocks-in-rails-3 for a bit of documentation on it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: javascript Getting distance of child element from top-left corner of Parent element Is there a way to get the offset of a ChildElement from a given parent element?
for example if a DIV in contained within a parent DIV with id "xyz"
is there a way to say
parent = $("xyz");
child = $("abc");
child.offset(parent);
Thank you
A: A convenient method is Element.getPositionedOffset(), but only when the parent element has a position style property.
var offset = $('abc').positionedOffset();
offset.left;
offset.top;
Otherwise it takes a little more work:
var parent = $('xyz',
child = $('abc'),
offset = child.viewportOffset().relativeTo(parent.viewportOffset());
The advantage here is the two elements need not be directly related, any pair of elements on the page can do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Creating AnimationDrawable from assets I locate several .png files (frames of my animation) in assets folder, than I fetch them using AssetManager in my Activity's onCreate() method and fill my AnimationDrawable with them. As described in dev guide it's impossible to start Animation in onCreate() method and if I need to start it immediately than I should override onWindowFocusChanged() method. But even in such implementation my drawable object doesn't appears on the screen. Here is the code of my Activity:
package org.example.Animation;
import java.io.IOException;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
private LinearLayout ll;
private ImageView image;
private AnimationDrawable ad;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ll = new LinearLayout(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-2, -2);
image = new ImageView(this);
ll.addView(image, lp);
setContentView(ll);
AssetManager am = getAssets();
ad = new AnimationDrawable();
StringBuilder sb= new StringBuilder("loader/loader-");
// Fetching frames from assets
for(int i = 1; i < 11; i++) {
sb.append(i);
sb.append(".png");
Log.d("DownloadImageTask", "Fetching image: " + sb.toString());
try {
Drawable d = Drawable.createFromStream(am.open(sb.toString()), null);
ad.addFrame(d, 500);
}
catch (IOException e) {
Log.d("ImageViewAdapter", "IOException: " + e.getMessage());
}
sb.delete(14, sb.length()); // 14 - is the index of first digit of frame
}
image.setBackgroundDrawable(ad);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
ad.start();
}
}
Tell me please what is wrong in my code?
P.S
Please, don't ask me why I'm not using xml file. In shorts my main goal is to avoid uisng of R.java file.
A: Waiting for a long time, found solution myself thanks to this issue. Just need to change values of View's widht and height to fixed or to FILL_PARRENT
A: Frame by frame animation load from images in assets folder
click here
Check this answer https://stackoverflow.com/a/45647381/2902830
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Delete Lines in a textfile Hi I have a text file with table schema and data when user checks not schema required then i need to delete schema and leave the data . I am using StreamReader to read the file and checking one condition and it should delete all the lines in the file till it satisfies my condition .
Let say if i am checking
using (StreamReader tsr = new StreamReader(targetFilePath))
{
do
{
string textLine = tsr.ReadLine() + "\r\n";
{
if (textLine.StartsWith("INSERT INTO"))
{
// It should leave these lines
// and no need to delete lines
}
else
{
// it should delete the lines
}
}
}
while (tsr.Peek() != -1);
tsr.Close();
Please suggest me how to delete lines and note if textline finds "InsertInto" it should not delete any content from there .
A: Use a second file where to put only required lines, and, at the end of the process, remove original file and rename new one to target file.
using (StreamReader tsr = new StreamReader(targetFilePath))
{
using (StreamWriter tsw = File.CreateText(targetFilePath+"_temp"))
{
string currentLine;
while((currentLine = tsr.ReadLine()) != null)
{
if(currentLine.StartsWith("A long time ago, in a far far away galaxy ..."))
{
tsw.WriteLine(currentLine);
}
}
}
}
File.Delete(targetFilePath);
File.Move(targetFilePath+"_temp",targetFilePath);
A: You could use Linq:
File.WriteAllLines(targetFilePath, File.ReadAllLines(targetFilePath).Where(x => x.StartsWith("INSERT INTO")));
A: You read in the file just the same way you were doing. However, if the line doesn't contain what you are looking for, you simply skip it. In the end, whatever data you are left over with you then write to a new text file.
private void button1_Click(object sender, EventArgs e)
{
StringBuilder newText = new StringBuilder();
using (StreamReader tsr = new StreamReader(targetFilePath))
{
do
{
string textLine = tsr.ReadLine() + "\r\n";
{
if (textLine.StartsWith("INSERT INTO"))
{
newText.Append(textLine + Environment.NewLine);
}
}
}
while (tsr.Peek() != -1);
tsr.Close();
}
System.IO.TextWriter w = new System.IO.StreamWriter(@"C:\newFile.txt");
w.Write(newText.ToString());
w.Flush();
w.Close();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MVC 3 default register link not work
Possible Duplicate:
MVC Forms LoginUrl is incorrect
I have deployed the simple mvc 3 to IIS 7.5.
The register redirect url is /Account/LogOn?ReturnUrl=%2fAccount%2fRegister.
It does not redirect to registration web page.
It seems like the Logon problem as the thread:
MVC Forms LoginUrl is incorrect
A: From ASP.NET MVC 3 Release Notes :
There’s a known issue that causes Forms Authentication to always
redirect unauthenticated users to ~/Account/Login, ignoring the forms
authentication setting used in Web.config. The workaround is to add
the following app setting.
<add key="autoFormsAuthentication" value="false" />
Check yourself out :
http://www.asp.net/learn/whitepapers/mvc3-release-notes#0.1__Toc274034230
A: What comes to mind is if you have checked if your register method is without the AuthorizeAttribute?
Maybe you've put the AuthorizeAtrtribute on top of the controller or you you've created a BaseController with the attribute, so every controller deriving from it need the user to be authenticated
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to avoid creation of foreign keys on Django Models? when i create a model with a foreign key relationship, something like this:
class Post(models.Model):
title = models.CharField(max_length=250)
date_created = models.DateTimeField(auto_now=False, auto_now_add=True)
owner = models.ForeignKey(User)
when i do syncdb to dump those models to the DB it creates the table post and a foreign key to the table user. How can avoid the creation of that Foreign Key in MySQL. I hate foreign keys for different reasons.
Thank you!
EDIT:
Please guys, don't answer: "You should use foreign keys". That's not what i'm asking. I've my reasons not to use them.
A: Please don't. Foreign keys are the right thing to have and you should never prevent the database from protecting its own consistency. If you need to do something special to the table (and are sure not to break its integrity) you can temporarily disable the checks:
SET foreign_key_checks = 0
# do something
SET foreign_key_checks = 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: FullCalendar alert on event date my question is:
Is it possible to trigger something (ie. alert, Qtip, whatever) when today's date is the date of an event in the FullCalendar? I am using the XML from my Google calendar as the source and would like something to pop up for people's birthdays.
I already have:
var difference = birthdate - today;
var days = Math.round(difference/(1000*60*60*24));
if (days == 0){
$('#tabs').qtip({
position: {
my: 'bottom right',
at: 'top left',
},
content: "It's someone's birthday!!!",
show: {
when: false,
ready: true
},
hide: false,
style: {
classes: 'ui-tooltip-rounded',
}
});
}
Where birthday is the individuals birthdate (which I set as a var) and today is ,obviously, today's date.
The problem I have is that this is not very dynamic as I will have to do this seperately for everyone.
Many thanks in advance.
A: When you create your calendar object/function you need to create a eventAfterRender function. This only fires when you have a function that has been placed on the calendar. Then you can read the date and compare it to ones birthday and display popup. I hope that is what your were looking for. I gave a little example.
$(document).ready(function () {
$('#calendar').fullCalendar({
height: 600,
width: 700,
header: {
right: 'prev,next today',
center: 'title',
left: 'month,agendaWeek,agendaDay'
},
eventAfterRender: function (event, element, view) {
birthday = new Date('<somedate>');
year = new Date(event.start).getFullYear();
month = new Date(event.start).getMonth();
day = new Date(event.start).getDate();
alert(year + ' ' + month + ' ' + day);
//do some if statement to see if the year matches then if the month, then the day.
//if so then go to another function or just put the code here for the pop
}
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: using NuGet with Visual Studio 2005 What would be the most frictionless workflow for working with NuGet and Visual Studio 2005? Is this at all possible? I understand that the plugin is only available for Visual Studio 2010, but there is still the package manager console wich seems to be nothing more than powershell. Can I run the console without Visual Studio and can the console download and integrate packages into visual studio 2005 projects? If so, how is this done?
A: Scott Hanselman blogged about adding NuGet "support" to Visual Studio 2008. You can probably adapt this slightly to work in Visual Studio 2005 too, though of course you won't get the same experience as in Visual Studio 2010.
Well, not really. A better title would be "How to Cobble Together
NuGet Support for Visual Studio 2008 with External Tools and a
Prayer." The point is, there are lots of folks using Visual Studio
2008 who would like NuGet support. I'm exploring this area and there's
a half-dozen ways to make it happen, some difficult and some less so.
The idea would be to enable some things with minimal effort. It'll be
interesting to see if there are folks in the community who think this
is important enough to actually make it happen. Of course, the easiest
thing is to just use 2010 as it sill supports .NET 2.0, 3.0, 3.5, and
4, but not everyone can upgrade.
Someone could:
*
*Backport the existing NuGet Package References dialog to 2008 using
that version's native extensions (not VSiX)
*Create MEF (Managed
Extensibility Framework) plugins for the nuget.exe command-line to
update the references in a vbproj or csproj
*Use PowerShell scripts and
batch files to get the most basic stuff working (get a package and
update references.)
*
*Maybe write a shim to get DTE automation
working...
But that's coulds and maybes. Let's talk about the MacGyver
solution. more »
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to send bottom aligned background image under the fold when we resize the window height or screen size is shorter? See this example http://jsfiddle.net/nMs56/
it has an iphone image at bottom. currently when I drag browser to decrease the height background image is going towards top.
But I want it as if I resize the browser from bottom. images should not move and should go under the fold when i decrease the size of browser from bottom
like this for example
CSS
html, body { height: 100%; }
body { background: url("img/iphone_34.jpg") no-repeat bottom center; }
A: bottom center is keeping the bottom of the image aligned with the bottom edge of the viewport as you resize it. So when making the window shorter, the image will move up to compensate.
Try top center to always keep the top edge of the image aligned with the top of the viewport.
JSFiddle
EDIT:
As per further discussion with OP, the following was done using JavaScript/jQuery...
1) Initial window height is retrieved.
2) Image height is subtracted from window height to give the offset from the top of the window.
3) The background-position of the image is fixed using jQuery css() with the calculated offset from the top.
4) Resizing the window has no effect on the image's position since position is only calculated when the page initially loads.
Notes: The code assumes it's the same image and you know its height. The code could be altered to calculate an image's height if needed.
Original CSS placing the image is left intact as a fallback. Without JavaScript, image will still be placed at the bottom as in the OP's original code.
Full window demo: http://jsfiddle.net/nMs56/12/show/
Code: http://jsfiddle.net/nMs56/12/
A: Simply specify the vertical position in px like so:
body { background: url("http://digitaldaily.allthingsd.com/files/2007/06/iphone_34.jpg") no-repeat center 100px; }
When you use bottom it makes it relative to the page size. If you want it fixed then specify a value.
UPDATE:
You can also use %
All value types:
background-position: { { percentage | length | left | center | right } 1 or 2 values | inherit } ;
A: This should do it.
http://jsfiddle.net/qHNJL/4/
http://jsfiddle.net/qHNJL/4/show
HTML:
<!-- #hideImg and the image inside it is for getting the image height without defining a static height. -->
<div id="hideImg">
<img src="http://digitaldaily.allthingsd.com/files/2007/06/iphone_34.jpg" alt"" />
</div>
<!-- The actual image -->
<div id="Image"></div>
A: This is normal you have positioned your background "bottom center"
so it will be align to the bottom of the body try to fix it on top and you should be ok.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Multiple SelectMany in Rx I have an interface like this:
interface IProcessor{
IObservable<Item> Process(Item item);
}
I have an array of workers:
IProcessor[] _workers = ....
I want to pass an item through all the workers:
var ret = Observable.Return(item);
for (var i = 0; i < _workers.Length; i++)
{
int index = i;
ret = ret
.SelectMany(r => _workers[index].Process(r))
;
}
return ret;
I'm not too happy with how this looks -- is there a cleaner way?
A: This works for me:
IObservable<Item> ret = _workers.Aggregate(
Observable.Return(item),
(rs, w) =>
from r in rs
from p in w.Process(r)
select p);
Please keep in mind that this kind of aggregation of observables - both in your question and in my answer - can cause memory issues (i.e. stack overflow) quickly. In my tests I could get 400 workers working, but 500 caused a crash.
You're better off changing your IProcessor to not use observables and implement your observable like this:
interface IProcessor{
Item Process(Item item);
}
var f =
_workers.Aggregate<IProcessor, Func<Item, Item>>(
i => i,
(fs, p) => i => p.Process(fs(i)));
var ret = Observable.Start(() => f(item), Scheduler.ThreadPool);
With this approach I can get over 20,000 nested workers before a stack overflow and the results are almost instantaneous up to that level.
A: Maybe something like this:?
var item = new Item();
_workers
.ToObservable()
.SelectMany(worker => worker.Process(item))
.Subscribe(item => ...);
I made an assumption that the workers can process the item in parallel.
P.S. If you'd like sequential processing, it would be
var item = new Item();
_workers
.ToObservable()
.Select(worker => worker.Process(item))
.Concat()
.Subscribe(item => ...);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to fixed the only one "li"? I have number of ul formed as a table. I want to fix the first "li" of each "ul" while scrolling.
i have done some work but can't able to fix the issue,
Here jsfiddle link: http://jsfiddle.net/thilakar/PpYpa/2/
Please help me out from the above issue.
Thanks in advance.
A: Use this...
ul {........}
ul li:first-child {position: fixed;}
This will fix your problem and is supported in most modern browsers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: rails parameters in form_for I am making a form for updating or saving a saved message.
<% form_for @draft, :url => {:controller => "drafts", :action => "draft_actions"} do |f|%>
subject
<%=f.text_field :subject %>
recipients
<%=f.text_field :draft_recipients %>
<br /> <%= f.text_area :body %>
<%= submit_tag "save", :name => "resave_draft"%>
<%= submit_tag "send", :name => "send_draft" %>
<% end %>
but I want the recipients to be displayed in a nice way, separated by commas : user1, user2, user3 instead of user1user2user3
My problem is : I don't understand how to have the :recipients symbol map to my recipient attribute in my draft model, but still have the view displaying the recipients displayed how I want
The code for my draft model is
class Draft < ActiveRecord::Base
belongs_to :message
belongs_to :draft_recipient, :class_name => "User"
delegate :created_at, :subject, :user, :body, :draft_recipients, :to => :message
The code for my Message model is the following
class Message < ActiveRecord::Base
belongs_to :user
has_many :recipients, :through => :message_copies
has_many :draft_recipients, :through => :drafts
has_many :message_copies
has_many :drafts, :class_name => "Draft", :foreign_key => :message_id
attr_accessor :to #array of people to send to
attr_accessible :subject, :body, :to, :recipients, :author, :user
I'm sure there's a fairly straightforward way to do that, but I can't get my head around it.
A: <%=f.text_field :draft_recipients, :value => @draft.draft_recipients.join(',') %>
Might work out for you. However, are you handling the conversion back in the controller? This won't bind exactly right when you submit.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is it possible to use Content-Encoding: gzip in a HTTP POST request? I'm trying to upload some files with compression to a server. The files will be fairly large and the server is a standard HTTP server where the interface defines that they're not compressed. Is it possible to use something like Content-Encoding to indicate that the upload request is compressed, much like it is used for downstream compression?
A: Apache supports it with the mod_deflate module but I does not look a common web server feature. If you have access to the server you can enable this module or rewrite the server side code to handle your compressed data (e.g. a special servlet/php which call the original servlet/php with the decompressed data).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Managing require_once in classes called by Zend and non-Zend classes I have a web Zend framework application that uses registernamespace and Zend_Autoloader_Resource to manage the requires needed for various modules. I also have a series of simple classes that will be called by cron jobs. Between the two are a number of classes that should be shared by both. What's the best way of managing the require_once statements such that neither side gets it knickers twisted?
Clarification:
1. There is no specific error that I'm encountering now, but in my Zend project I notice if I do put in a require_once, it complains.
2. The reason for require_once at all is because I want to use these modules via Zend for GUI, but I also want to use them without Zend, because of it's overhead.
3. Twisted knickers - to get upset over small stuff
A: Zend makes use of a define APPLICATION_PATH. It's simple enough to logic around the bits I don't want included in the classes when being called by Zend to say:
if (!defined('APPLICATION_PATH')){
include_once "path/class";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why are my identifiers marked as not CLS-compliant? I have a some class, which contains three fields:
protected bool _isRunning = false;
protected readonly ParameterCollection _parameters = null;
protected readonly ParameterCollection _defaultParameters = null;
The assembly it is in is marked as CLS-compliant (it is needed), and Visual Studio 2010 says that those three fields' identifiers are not CLS-compliant. What is wrong with them?
P.S.: ParameterCollection is a class, derived from KeyedCollection, if it is important information.
A: Here is the answer from Microsoft, from Name <membername> is not CLS-compliant:
To correct this error
If you have control over the source code, change the member name so that it does not begin with an underscore.
If you require that the member name remain unchanged, remove the CLSCompliantAttribute from its definition or mark it as . You can still mark the assembly as <CLSCompliant(True)>.
A:
what's wrong with them?
They start with an underscore.
For more details, see here:
According to MSDN:
CLS-compliant language compilers must follow the rules of Annex 7 of
Technical Report 15 of the Unicode Standard 3.0, which governs the set
of characters that can start and be included in identifiers. This
standard is available at
http://www.unicode.org/unicode/repor...5/tr15-18.html. For two
identifiers to be considered distinct, they must differ by more than
just their case.
from Unicode Standard 3.0 Technical Report 15, Annex 7:
That is, the first character of an identifier can be an uppercase letter,
lowercase letter, titlecase letter, modifier letter, other letter, or letter
number. The subsequent characters of an identifier can be any of those, plus
non-spacing marks, spacing combining marks, decimal numbers, connector
punctuations, and formatting codes (such as right-left-mark). Normally the
formatting codes should be filtered out before storing or comparing
identifiers.
A: To be CLS compliant, identifiers must follow the guidelines in Annex 7 of Technical Report 15 of the Unicode Standard (MSDN). This includes the requirement that the first character be a letter (source).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to set % height in fluid layout? I am designing fluid layout pages (defining everything in % in CSS) for multiple devices (desktop/tablet/mobile)
Now while I do understand that giving width:100% takes the entire viewport available width (i.e. available browser area) and accordingly calculates all the % widths ?
But my question is how do I set or convert any "pixel" height to % height for defining fluid layouts CSS?
A: You have to give your body styles like so...
body {width: 100%; height: 100%; min-height: 100%; height: auto;}
As your body has a height of the viewport, anything that is a child of it can be specified using percentage, like a div 50% of the screen would be...
body div {height: 50%; min-height: 50%; height: auto;}
Remember % is inherited from its parent.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript replace string characters I already am doing a replace for the commas in an textbox. How would I replace if there is an "$" and a comma also in the same line?
function doValidate()
{
var valid = true;
document.likeItemSearchForm.sup.value = document.likeItemSearchForm.sup.value.replace(/\,/g,'');
return valid;
}
A: Do you want to replace commas and dollar signs? Here's how:
"$foo, bar.".replace(/\$|,/g, "")
The regexp matches dollar signs or commas. The g flag tells it to match the entire string instead of stopping after the first match.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Django nonrel on Google Appengine 3000 file limit I followed the directions on http://www.allbuttonspressed.com/projects/djangoappengine, but afterwards realized that the resulting project has almost 5,000 files, namely because of the django directory.
Am I not supposed to include django 1.3 and just use django 1.2 builtin with Google App Engine? Or am I missing something? I've heard that zipimport is not a good idea with django.
A: There are not a lot of solutions:
*
*You can try to remove every lib unnecessary in the directory of Django
*Use zipimport if you don't want use django 1.2 provides with
*GAE. Reduce the number of files you use in your project.
But note that: For yours instances, load a lot of files is slower because there are a lot of reads in the file system. django.zip is reads only one time and stocked in the memory to unzip it. there is just one read on the file system not 3000 and more...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WinForms DatagridView allows deletion via Shift + Del keys even though AllowUserToDeleteRows property is set to false I'm using the standard .Net Winforms datagridview control to display & manipulate data, however I have (or thought so) suppressed user deletion via:
this.dataGridViewTestSteps.AllowUserToDeleteRows = false;
Now pressing 'Del' does in fact not delete rows, but surprisingly Pressing [Shift] and [Del] at the same time does. What's up with Shift-key overriding the property set above? Is there anything I can do to fully disallow deletion?
A: Oh my - the solution is apparently rather simple, but somewhat unexpected: Shift + Del seems to be a system wide alternative to Ctrl + X. E.g. when editing a text in notepad.exe, selecting some characters and pressing Shift + Del it seems to have the same effect & functionality as a standard Cut / Ctrl + X would do.
Since I do handle Ctrl + x in my application, it does proceed and 'delete' these rows, even though they are actually placed on the clipboard.
So this has nothing to do in particular with the datagridview, usercode for ctrl + x is simply also called when shift + del is pressed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: setNeedsDisplay for UIImage doesn't work I am trying to draw a line on an UIImage with the help of a dataBuffer when a button gets touched, but the drawRect: .. methode doesn´t get called. (so, the line i want to draw does't appear)
I really don't know where the problem could be, so I posted quite a bit more code. Sorry about that.
By the way, I am working on an viewbasedapplication.
here is my code :
-(void) viewDidLoad{
UIImage *image = [UIImage imageNamed:@"playView2.jpg"];
[playView setImage:image];
[image retain];
offScreenBuffer = [self setupBuffer];
}
- (IBAction)buttonTouched:(id)sender {
[self drawToBuffer];
[playView setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect{
CGImageRef cgImage = CGBitmapContextCreateImage(offScreenBuffer);
UIImage *uiImage = [[UIImage alloc] initWithCGImage:cgImage];
CGImageRelease(cgImage);
[uiImage drawInRect: playView.bounds];
[uiImage release];
}
-(void)drawToBuffer {
// Red Gr Blu Alpha
CGFloat color[4] = {1.0, 1.0, 0.0, 1.0};
CGContextSetRGBStrokeColor(offScreenBuffer, color[0], color[1], color[2], color[3]);
CGContextBeginPath(offScreenBuffer);
CGContextSetLineWidth(offScreenBuffer, 10.0);
CGContextSetLineCap(offScreenBuffer, kCGLineCapRound);
CGContextMoveToPoint(offScreenBuffer, 30,40);
CGContextAddLineToPoint(offScreenBuffer, 150,150);
CGContextDrawPath(offScreenBuffer, kCGPathStroke);
}
-(CGContextRef)setupBuffer{
CGSize size = playView.bounds.size;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, size.width*4, colorSpace, kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
return context;
}
A: Where is this code? viewDidLoad is a view controller method, drawRect is a view method. Whatever playView is (presumably a UIImageView?) needs to be a custom UIView subclass with your drawRect inside it, and you'll have to pass the various items to that from your view controller.
A: I know this is an old question but still, someone might come across here:
the same (or very similiar) question is correctly answered here:
drawRect not being called in my subclass of UIImageView
UIImageView class (and it's sublasses) don't call drawRect if you call their setNeedsDisplay.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Facebook PHP API | Incorrect Friend Count I'm using this to get my friends from my profile:
$facebook_friends = $facebook->api('/me/friends');
it works kinda well, except the Friend count does not seem to add up, at the moment i got 193 friends but it only get 189 in the $facebook_friends array. Does this has something to do with maintaining (server side) of profiles or privacy rights ?
A: Facebook users can opt out of the Facebook Application Platform:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Sum up minima of data pairs in a matrix I would like to compare the elements of two rows in a matrix and then sum up the minima of the data pairs.
For example in a matrix like this the result should be 3 (1+1+1+0)
> m
col1 col2 col3 col4
a 2 1 4 4
b 1 2 1 0
I tried it like this:
> findmin <- function (x) for (i in 1:ncol(x)) {min(x[1,i], x[2,i])}
> res <- sum(findmin(m))
> res
[1] 0
I think the problem is that the loop returns NULL as a value. How can i avoid this? Or is there a more elegant way to do it avoiding the for loop?
A: apply() is your friend:
R> M <- matrix(c(2,1,4,4,1,2,1,0), 2, 4, byrow=TRUE)
R> M
[,1] [,2] [,3] [,4]
[1,] 2 1 4 4
[2,] 1 2 1 0
R> apply(M, 1, min) # goes row-wise
[1] 1 0
R> apply(M, 2, min) # goes column-wise
[1] 1 1 1 0
R> sum(apply(M, 2, min))
[1] 3
R>
A: sum(apply(m, 2, min)) does the trick:
> m <- matrix(c(2,1,4,4,1,2,1,0), 2, byrow=TRUE)
> m
[,1] [,2] [,3] [,4]
[1,] 2 1 4 4
[2,] 1 2 1 0
> sum(apply(m, 2, min))
[1] 3
A: A more "R" way to solve this task would be with an apply function: sum(apply(m, 2, min))
Your for loop didn't work because you weren't storing or returning any value. Here's how to fix your for loop. Note that preallocating the size of out makes it execute much faster:
findmin <- function(x){
out <- rep(NA, ncol(x))
for (i in 1:ncol(x)) {
out[i] <- min(x[1,i], x[2,i])
}
return(out)
}
> findmin(m)
[1] 1 1 1 0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting specific rows from recordset I have a big database result set and I want get specific rows from them with 1 Query:
1., 60.
and 61.,120.
and 121.,180.
... and every 60th and 61st record until I have all, the complete result needs to be provided by 1 Query.
Any idea how I can do that?
The LIMIT/OFFSET is not what I'm looking for, as I would need to repeat it many times.
A: I found an article that uses a single select statement to do this. The statement itself is more complex, but certainly not cryptic by any means.
SELECT *
FROM (
SELECT
@row := @row +1 AS rownum, noun
FROM (
SELECT @row :=0) r, nouns
) ranked
WHERE rownum %4 =1
Here is the article.
A: How about
WHERE id % 60 IN ('0','1')
*untested!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Openx 2.8.7 geotargeting does not work I'm not able to make Openx geotargeting work - I have enabled geotargeting as described here: http://www.openx.com/docs/2.8/adminguide/Global%20settings%20-%20geotargeting, but no luck, my test banner it's still not delivered. Did someone succeeded to make it work?
Thanks.
A: Yes, it works for me. A couple of more things to check, besides the maxmind configuration:
*
*If you have a cluster all the machines used for delivery should have the geotargeting properly configured.
*When testing your banners be sure that you are not using an internal IP - for example when I'm connected to my company network I receive an IP which does not exist in maxmind database (and the geolocation will not work). If your openx machine and your test server is inside of the same network you may have this problem too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: In Flash Builder 4.5 (flex mobile app) I'm trying to bind to multiple tables, but for some reason, it keeps referring to the first binding I made to the first table. I binded through ArrayCollection. Is there anyway to bind to multiple tables?
A: Try this:
dataProvider="{new ArrayCollection(tableData1.concat(tableData2,..., tableDataN))}"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ExtJS 4 - How to load grid store with its params carrying latest values from a form? I have a window with a search form at the top and grid at the bottom.
User can enter values in the search form and click button - Get Records.
At the click of this button, I load the store of the grid by passing the values in form fields as parameters in following way:
store.load({
params:{
key1:Ext.getCmp('field1').getValue();
}
});
I tried giving parameters in the store proxy itself, but it unfortunately always takes up initial values (values when the form is rendered) and not the latest one entered by the users in the form fields. Following is the method I used for assigning values to params while creating the store:
extraParams:{
key1:Ext.getCmp('field1').getValue();
}
I wanted to seek guidance at two things:
a. While defining a store, can I ensure that store takes latest/current values from the form fields before querying server, so that I don't have to provide these values while calling load function?
This becomes more necessary as I have a paging toolbar at the bottom which carries a refresh button (along with next, last, previous, first icons for navigation).
Now, whenever user clicks at refresh (or any navigation icon), the store gets loaded without the query parameters.
Thus the second thing is:
b. If the answer of 'a' is that - Pass the latest values to parameters manually when calling load function - then how can I write the handler for 'refresh' button and navigation icons (that is, next, last, previous and first) in the paging toolbar, so that I can pass the latest form values to load function.
Thanks for any help in advance.
PS: I am using ExtJS 4.
A: yourStore.on('beforeload',function(store, operation,eOpts){
operation.params={
status:cmbStatus.getValue(),
value:txtBuscarPor.getValue(),
empresa:'saasd',
app:'dsads'
};
},this);
A: Related to your question (b) (and because you especially asked for this in the comments section):
I see only one standard way to hook into the PagingToolbar button handlers which is very limited.
Ext.toolbar.Paging fires a 'beforechange' event before it actually changes the current page. See API docs. A listener that returns false will stop the page change.
All other methods require extending Ext classes which wouldn't be a problem if the ComboBox would make it easier to use your own implementation of BoundList (which is the class that renders the dropdown) or pass through config parameters to BoundList resp. the paging toolbar.
I tried to bring this lack of flexibility up on the Ext message board once but was pretty much ignored.
A: A possible solution for this is to use 'beforeload' event of the store and provide the list of parameters in it. This way, whenever the store is loaded, then its beforeload event is fired and the values picked up are always the latest. Hope this helps someone looking for something similar.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to parse comments with EBNF grammars When defining the grammar for a language parser, how do you deal with things like comments (eg /* .... */) that can occur at any point in the text?
Building up your grammar from tags within tags seems to work great when things are structured, but comments seem to throw everything.
Do you just have to parse your text in two steps? First to remove these items, then to pick apart the actual structure of the code?
Thanks
A: Normally, comments are treated by the lexical analyzer outside the scope of the main grammar. In effect, they are (usually) treated as if they were blanks.
A: One approach is to use a separate lexer. Another, much more flexible way, is to amend all your token-like entries (keywords, lexical elements, etc.) with an implicit whitespace prefix, valid for the current context. This is how most of the modern Packrat parsers are dealing with whitespaces.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is it possible to join a closed group through a javascript graph api on facebook? Does facebook javascript api support the functionality of sending requests to join groups? I'm making a closed group for my organisation, so everything is pulled from facebook and displayed on our intranet but only if you are a member of that group. I had a request that I should make a functionality of requesting to join a facebook group using the api and not on facebook, as employee are not allowed to see the facebook website unless the specified urls, can someone please let me know if this is possible to do and if maybe you know of some link that I can go a look at. Please let me know, even the iframe will do at this stage.
A: Nope, sorry can't find anything in the Javascript API that allows you to send invites to groups.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Vim Indentation Using ">" I'm using vim under Mac OS 10.7 Terminal.
My .vimrc already specify the tabstop to be 4. However, if I use shift to select multiple lines and then using ">" to indent, it will give me a indention of 8 spaces instead of 4. How can I correct that to be 4?
Part of my .vimrc:
set cindent
set autoindent
set tabstop=4
A: The shiftwidth variable controls the indentation:
set shiftwidth=4
A: set shiftwidth=4
They're different things: tabstop says how many spaces wide to use when displaying a tab character, shiftwidth is for indentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery Isotope hash-history: prettify the hash-URL I'm using Isotope with Hash History. It works great, but I'm not happy with the URL - I'd like to simplify & clean it up.
Currently using:
var href = $this.attr('href').replace( /^#/, '' );
var option = $.deparam( href, true );`
On this markup:
<li><a href="#filter=.work/">Work</a></li>
So, my question: how can I make it work with the following markup?
<li><a href="#/work/">Work</a></li>
I'm only using filters, all other Isotope options are locked down, so I'm hoping to remove the reference to filters.
Thanks in advance!
A: I am using this:
function getHashFilter() {
var hash = location.hash;
// get filter=filterName
var matches = location.hash.match(/^#?(.*)$/)[1]; // this is to get the name of the class
var hashFilter = matches;
return hashFilter;
}
$( function() {
var $container = $('. isotope');
// bind filter button click
var $filters = $('#filters').on( 'click', 'span', function() {
var filterAttr = $( this ).attr('data-filter');
// set filter in hash
location.hash = '/' + filterAttr.substr(1); // adding the slash for the url
});
var isIsotopeInit = false;
function onHashchange() {
var hashFilter = getHashFilter();
if ( !hashFilter && isIsotopeInit ) {
return;
}
isIsotopeInit = true;
// filter isotope
$container.isotope({
itemSelector: '.element-item',
filter: '.' + hashFilter.substr(1) //adding the . so it can match the data-filter
});
// set selected class on button
if ( hashFilter ) {
$filters.find('.is-checked').removeClass('is-checked');
$filters.find('[data-filter=".' + hashFilter + '"]').addClass('is-checked');
}
}
$(window).on( 'hashchange', onHashchange );
// trigger event handler to init Isotope
onHashchange();
});
I realised that * will not work after this. So you need to add another class/data-filter to show all.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Null Exception when retrieving connectionstring in .NET I have the following in my web.config:
<configuration>
<connectionStrings>
<add name="strConDev" connectionString="Data Source=dbSource;Initial Catalog=CatalogInitial;User Id =DEFAULT; Password=PASSWORD" />
</connectionStrings>
</configuration>
I am trying to retrieve the connection string in my global.asa in the Application_Start method with the following code:
var con = ConfigurationManager.ConnectionStrings["strConDev"];
string strConn = con.ConnectionString;
However, this is always returning a null value to con. What am I doing wrong here? This is the syntax I was able to find online.
A: The syntax all appears correct. A couple things you can try:
*
*Copy/paste the connection name from web.config into your code to ensure the names match correctly.
*Ensure the web.config is correctly formatted. Open it, give the compiler a few seconds to verify it, then check your error list for any warnings. i.e. You may have incorrectly typed <connectionStrings> or you may not have added elements into the correct sections
*Are you publishing the website or debugging it? If publishing, ensure you don't have any transformations changing the web.config connection strings - verify this by checking the publish location and opening the web.config there to see if it matches your original.
A: What if you use the WebConfigurationManager class (from System.Web.Configuration) instead
string connString = WebConfigurationManager.ConnectionStrings["strConDev"].ConnectionString;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ASP.NET Set variable if Request.QueryString does not exist I want to set a textbox.text to a certain value if Request.QueryString['EQCN'] does not exist. If it does exist, I would like to set it to the value of Requestion.QueryString['EQCN'].
It seems that if the value doesn't exist it defaults the value to be "".
Any ideas?
Thanks so much!!!
A: If the parameter is not in the query string, the QueryString indexer will return a null reference, so you can use the ?? operator for a default value:
textbox.text = Request.QueryString['EQCN'] ?? "default text";
A: textbox.text = string.IsNullOrEmpty(Request.QueryString["EQCN"]) ? "my value" : Request.QueryString["EQCN"];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: backup and restore clipboard data using win32 api i am looking from win32 APIs which would allow me to make a backup of the clipboard data (in memory/ file system) and later i can reset it using SetClipboardData.
i have seen the win32 API set and understand that OpenClipboard, getClipboardData and SetClipboardData would do the task for me. But i don't understand what format parameter to pass in GetClipboardData function, as i am unaware about the format and don't know any API either to get Format of the Clipboard data.
i want to support maximum possible formats, i know things like delay rendering and some private data types might not be possible to save. What could be the best way out, please suggest...
I am able to backup and restore the text content. how to do the same for Bitmap format. How to basically save the BITMAP in memory from its handle (fetched using GetClipboardData)
A: Find the formats on the clipboard by calling EnumClipboardFormats(). Call GetClipboardData() to get a HGLOBAL that contains the clipboard data for a particular format. You can get the size of the memory by calling GlobalSize(). To read the memory wrapped by the HGLOBAL use GlobalLock() and GlobalFree().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Dynamic SQL Server 2005 Pivot I have worked out how to pivot a row from a table using PIVOT in SQL Server 2005, however, I dont like the method as I have had to hard code the columns (Currency Codes) and I would like to have the Pivot select the columns dynamically.
As an Example, imagine you have the following table (called OrderCash):
OrderID CAD CHF EUR GBP JPY NOK USD
40 0 0 128.6 552.25 -9232 0 -4762
41 0 0 250.2 552.25 -9232 0 -4762
42 233.23 0 552.25 -9232 0 0 -4762
The hard-coded Pivot statement is:
SELECT OrderID,
CurrCode + 'GBP CURNCY' AS Ticker,
Cash AS Position
FROM
(
SELECT OrderID,
CAD,
CHF,
EUR,
GBP,
JPY,
NOK,
USD
FROM OrderCash
) p
UNPIVOT
(
Cash FOR CurrCode IN
(CAD, CHF, EUR, GBP, JPY, NOK, USD)
) AS unpvt
WHERE Cash != 0
And OrderID = 42
This would return the following required table:
OrderID Ticker Position
42 CADGBP CURNCY 233.23
42 EURGBP CURNCY 552.25
42 GBPGBP CURNCY -9232
42 USDGBP CURNCY -4762
The problem arrises further down the road when someone tells me I need to have AUD as a new currency in the table?
FYI, I have a table-valued function that returns all the column names as a table:
ALTER FUNCTION [dbo].[GetTableColumnNames]
(
@TableName NVARCHAR(250),
@StartFromColumnNum INT
)
RETURNS @ReturnTable TABLE
(
ColName NVARCHAR(250)
)
AS
BEGIN
INSERT INTO @ReturnTable
SELECT COLUMN_NAME from information_schema.columns
WHERE TABLE_NAME = @TableName
AND ORDINAL_POSITION >= @StartFromColumnNum
ORDER BY ORDINAL_POSITION
RETURN
END
So the easy bit has been done (SELECT * FROM dbo.GetTableColumnNames('OrderCash',2)), the problem I am having is inserting this 'dynamic' table with the column names into the Pivot?
Any help would be much appreciated.
Many thanks
Bertie.
A: I've done a few too many of these dynamic queries of late... (my columns shift by client by month). Here's one way to do it--no testing, no debugging, there might be a few bugs to iron out:
DECLARE
@Command nvarchar(max)
,@ColumnList nvarchar(max)
,@OrderId int
,@Debug bit
-- Build a comman-delimited list of the columns
SELECT @ColumnList = isnull(@ColumnLIst + ',', , '') + ColName
from dbo.GetTableColumnNames('OrderCash', 2)
-- Insert the list of columns in two places in your query
SET @Command = replace('
SELECT OrderID,
CurrCode + ‘‘GBP CURNCY’‘ AS Ticker,
Cash AS Position
FROM
(
SELECT OrderID, <@ColumnList>
FROM OrderCash
) p
UNPIVOT
(
Cash FOR CurrCode IN
(<@ColumnList>)
) AS unpvt
WHERE Cash != 0
And OrderID = @OrderId
', '<@ColumnList>', @ColumnList)
-- Always include something like this!
IF @Debug = 1
PRINT @Command
-- Using sp_executeSQL over EXECUTE (@Command) allows you execution
-- plan resuse with parameter passing (this is the part you may need
-- to debug on a bit, but it will work)
EXECUTE sp_executeSQL @Command, N'@OrderId int', @OrderId
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get "stronger" simplifications of conjunctions in Z3? Using Z3 version 2.18, I am trying to simplify formulas such as:
*
*(and (> (- (- x 1) 1) 0) (> x 0))
*(or (> (- (- x 1) 1) 0) (> x 0))
hoping to get something like: (> x 2) and (> x 0).
I am running Z3 with the following input file where F is one of the above formulas:
(set-option set-param "STRONG_CONTEXT_SIMPLIFIER" "true")
(declare-const x Int)
(simplify F)
It works well with the disjunction where I get the following output:
(let (($x35 (<= x 0)))
(not $x35))
However, with the conjunction, I get:
(not (or (<= x 0) (<= x 2)))
Is there a way to force Z3 to simplify even more the above formula ? I would hope to be able to get (not (<= x 2)).
PS: Is there a way to force Z3 to inline its output (i.e. having (not (<= x 0)) instead of (let (($x35 (<= x 0))) (not $x35)))
Thanks,
Gus
A: No, you can't do that on Z3 2.x.
Z3 3.x has a new (fully compliant) SMT 2.0 front-end.
Z3 3.x has several new features such as a "strategy specification language" based on tactics and tacticals. I'm not "advertising" that yet because it is working in progress. The basic idea is described in this slide deck. This language can be used to do what you want. You just have to write:
(declare-const x Int)
(assert (not (or (<= x 0) (<= x 2))))
(apply (and-then simplify propagate-bounds))
You can find all available tactics by using the commands:
(help-strategy)
(help apply)
(help check-sat-using)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Eclipse: Conversion to Dalvik format failed with error 1 This happens instantly when I make a new project in Eclipse.
I only have 1 jar file in the project, I have tried to remove it, and add it again, several times, and cleaned the project after this.
I have updated ProGuard (I think), downloaded the new version, and replaced the lib folder as the threads on here said.
My default.properties file looks like this:
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Project target.
target=android-8
So can't comment anything about ProGuard which was also mentioned in another thread.
I feel I have tried everything, and still this bug.
One thing I have noticed though if I go to:
window -> preferences -> android -> build. And uncheck "Force error when external jars contain native libraries". Then I get: "Can't resolve R" instead of the Dalvik error.
There is no import named android.R either.
Anyone with some help please?
A: I had mistakenly added a reference to a copy of android.jar, which was not required as it is an android dependency, I removed this and the error went away.
A: I started having this problem as well... The only thing that fixed it for me was manually downlaoding the newest version of ProGuard (currently 4.6) and replacing the SDK's version of Proguard's bin and lib folders with the newest verison.
After that everything started working again. This is apparently a logged bug...
http://code.google.com/p/android/issues/detail?id=18359
A: This doesn't look like the issue with proguard, since it's not even enabled in your defaults.properties file. Try the following:
*
*Uncheck "Force error when external jars contain native libraries" option (just as you did)
*Select "Project -> Clean…" from the menu
*If that won't help ensure you have the correct R class imported. As stated at source.android.com:
Eclipse sometimes likes to add an import android.R statement at the
top of your files that use resources, especially when you ask eclipse
to sort or otherwise manage imports. This will cause your make to
break. Look out for these erroneous import statements and delete them.
UPDATE
Have a look also at this thread: "Conversion to Dalvik format failed with error 1" on external JAR.
Check the following answers (link will bring you directly to the answer):
*
*michel's answer
*user408841's answer
*Mido's answer
*Joe's Apps' answer
A: Do you have the new Android SDK? If you do, you have to download the proguard.jar from the proguard website and replace it on the SDK directory.
A: I just was fighting with this problem myself what I ended up doing is editing the proguard.bat file and the problem vanished
it's in: [Android SDK Installation Directory]\tools\proguard\bin\proguard.bat
Change
call %java_exe% -jar "%PROGUARD_HOME%"\lib\proguard.jar %*
to
call %java_exe% -jar "%PROGUARD_HOME%"\lib\proguard.jar %1 %2 %3 %4 %5 %6 %7 %8 %9
I tried tons of other stuff but this is what did it for me.
A: You have to clean your project every time if you use CVS update.
A: I have had this problem occasionally and the fix for me is to switch off 'Build Automatically'. In my experience, Eclipse sometimes gets confused when building apks when automatic building is switched on.
A: If none of the solutions work for you try to do the following:
*
*Stop looking for online help.
*Turn to your project. It can be something in the code that Dalvik interprets in wrong way even if there are no reported errors during the run of application.
I had such a problem. Multiple runs/builds/exports of application with Proguard disabled were successful and only after enabling Proguard an error 1 appeared.
Following steps can help you to resolve the problem:
*
*Create a new project.
*In order to detect the suspicious class, begin adding your classes one by one every time running the export signed application tool.
*Narrow the search in that class by adding blocks of code to it also one by one.
In my case the error was caused by:
float[][] array1 = null, array2;
for(int i = 0; i < someVal; i++){
if(array1 == null){
array1 = new float[row][col];
}
else{
array2 = new float[array1.length][array1[0].length]; // ERROR 1
// it was assumed that array1 is still null
}
}
When I replaced it with:
float[][] array1 = new float[1][1], array2;
for(int i = 0; i < someVal; i++){
if(i == 0){
array1 = new float[row][col];
}
else{
array2 = new float[array1.length][array1[0].length]; // ERROR 1
// it was assumed that array1 is still null
}
}
the ERROR 1 disappeared.
A: I've tried many solutions on stackoverflow but nothing worked for me.
I just open the project.properties file in project folder and appcompat library was added twice here like
android.library.reference.1=../appcompat_v7
android.library.reference.1=../appcompat_v7
I just removed one line and this worked for me :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Mail download save in sql server Does anyone know of a script to download email from Gmail and store it to a SQL server? (for backup purposes)
I am looking for a .NET solution (C#).
A: EML files are plain text.
Simply create a table in your database with one column (and all the others you need, that's for you to decide) of type nvarchar(max) that will store the contents of the email file. For example call this column email_content
Then do something like this:
string email = File.ReadAllText("Path/to/EML/File");
And then do something like:
using (SqlConnection con = new SqlConnection("YourConnectionStringHere"))
{
con.Open();
using(SqlCommand command = new SqlCommand("INSERT INTO your_table (email_content) values (@email_content)",con)
{
command.Parameters.AddWithValue("@email_content",email);
command.ExecuteNonQuery();
}
}
*That's assuming you are using SQL Server but the principle is the same for any other database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use Rx to poll for images over an async WCF service I have an async WCF service that takes a "URI" and returns an image (as a Stream).
Want I want to do is:
*
*Ensure a valid WCF channel exists, if no create it
*Make the async service call
*On success save the image to a member variable
*If I get an exception, close the channel
*Whether it fails or succeeds, wait 200ms then start again (looping forever or until cancelled)
So far I have come up with this monstrosity:
private void PollImage(string imageUri)
{
const int pollingHertz = 1;
const int millisecondsTimeout = 1000 / pollingHertz;
Thread.Sleep(millisecondsTimeout);
if (_channel == null)
{
_channel = _channelFactory.CreateChannel();
}
var getImageFunc = Observable.FromAsyncPattern<string, Stream>
(_channel.BeginGetImage, _channel.EndGetImage);
getImageFunc(imageUri)
.Finally(() => PollImage(imageUri))
.Subscribe(
stream => UpdateImageStream(imageUri, stream),
ex =>
{
Trace.TraceError(ex.ToString());
((ICommunicationObject) _channel).CloseOrAbort();
_channel = null;
});
}
I really want to learn Rx but each time I try I get left scratching my head.
Anyone care to give me some pointers on this? Thanks
A: I have a solution for you, but I'm going to suggest a change to your PollImage method to make it more Rx-like.
The signature should look like this:
IObservable<Image> PollImage(string imageUri, TimeSpan gapInterval)
You should consider PollImage to be an observable factory, and it won't actually poll for images until you subscribe to the returned observable. The advantage with this approach is that it makes unsubscribing possible - your last bullet point requires this - and it cleanly separates the code that polls for images and the code that updates the local variables.
So, the call to PollImage then looks like this:
PollImage(imageUri, TimeSpan.FromMilliseconds(200.0))
.Subscribe(image =>
{
/* do save/update images here */
});
And the implementation looks like this:
private IObservable<Image> PollImage(string imageUri, TimeSpan gapInterval)
{
Func<Stream, Image> getImageFromStream = st =>
{
/* read image from stream here */
};
return Observable.Create<Image>(o =>
{
if (_channel == null)
{
_channel = _channelFactory.CreateChannel();
}
var getImageFunc =
Observable
.FromAsyncPattern<string, Stream>(
_channel.BeginGetImage,
_channel.EndGetImage);
var query =
from ts in Observable.Timer(gapInterval)
from stream in getImageFunc(imageUri)
from img in Observable.Using(
() => stream,
st => Observable.Start(
() => getImageFromStream(st)))
select img;
return query.Do(img => { }, ex =>
{
Trace.TraceError(ex.ToString());
((ICommunicationObject)_channel).CloseOrAbort();
_channel = null;
}).Repeat().Retry().Subscribe(o);
});
}
The query observable waits until the gapInterval is complete and then calls the WCF function to return the stream and then converts the stream to an image.
The inner return statement does a number of things.
First it uses a Do operator to capture any exceptions that occur and does your tracing and channel reset as before.
Next it calls .Repeat() to cause query to be re-run effectively making it wait gapInterval before calling the webservice again. I could have used Observable.Interval rather than Observable.Timer in query and drop the call to .Repeat(), but this would have meant the calls to the webservice start every gapInterval rather than wait that long after it completed last time.
Next it calls .Retry() which effectively restarts the observable if it encounters an exception so that the subscriber never sees the exception. The Do operator captures the errors so this is OK.
Finally it subscribes the observer and returns the IDisposable allowing the calling code to unsubscribe.
Other than implementing the getImageFromStream function, that's about it.
Now a word of caution. A lot of people misunderstand how subscribing to observables works and this can lead to hard to discover bugs.
Take this as an example:
var xs = Observable.Interval(TimeSpan.FromSeconds(1.0));
var s1 = xs.Subscribe(x => { });
var s2 = xs.Subscribe(x => { });
Both s1 & s2 subscribe to xs, but rather than share a single timer they each create a timer. You have two instances of the internal workings of Observable.Interval created, not one.
Now this is the correct behaviour for observables. In the event that one fails then the other won't because they don't share any internals - they are isolated from each other.
However, in your code (and mine for that matter) you have a potential threading issue because you share _channel across multiple calls to PollImage. If one call fails it resets the channel and this can cause concurrent calls to then fail as a result.
My suggestion is that you create a new channel for each call to prevent concurrency issues.
I hope this helps.
A: This is what I came up with (with some help!)... still not "perfect" but seems to work.
As @Enigma said I've got rid of the shared _channel now and replaced it with a captured local var. It works but I don't understand Rx enuf to know if this is poor/buggy approach. I suspect there is a cleaner way at least.
Other than that, my main objection is the Do() where I call EnsureChannel... seems a bit smelly. But... it works...
Oh and I must have the _ (underscore) in the SelectMany or else the GetImage is not called again.
private IDisposable PollImage(string imageUri)
{
ICameraServiceAsync channel = _channelFactory.CreateChannel();
return Observable
.Timer(TimeSpan.FromSeconds(0.2))
.Do(_ => { channel = EnsureChannel(channel); })
.SelectMany(_ =>
Observable
.FromAsyncPattern<string, Stream>(channel.BeginGetImage, channel.EndGetImage)(imageUri))
.Retry()
.Repeat()
.Subscribe(stream => UpdateImageStream(imageUri, stream));
}
private ICameraServiceAsync EnsureChannel(ICameraServiceAsync channel)
{
var icc = channel as ICommunicationObject;
if (icc != null)
{
var communicationState = icc.State; // Copy local for debug inspection
if (communicationState == CommunicationState.Faulted)
{
icc.CloseOrAbort();
channel = null;
}
}
return channel ?? _channelFactory.CreateChannel();
}
A: If you really want to use then people have already answered your question and if you are looking for alternate ways then I would suggest have a look at TPL (Task etc objects) that allows you to create task object from a Async method pattern (your web service call) and then start the task with a cancellation token so that after some time if the task is not completed you can cancel it by calling token cancel method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7555974",
"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.