text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Flash sending 2 variables to php script, 1 of them being xml So this is probably a simple question, but for some reason, I'm having problems with it. I have no ideia why, but I suspect the fact that sending a xml with full "< something >" tags may cause the php to behave wrongly.
So all I need is to send (from a swf as3 client) a filename and a xml. The php will write a xml file with the required filename.
Everything should be okay with the php side, because I tried it using " $_GET " variables, but whenever I try using the flash client, It just doesent work, and the php log says that "the filename variable can't be empty". Whenever I try some static filename (not using GET or POST), it works.
Sooo... Can someone help me out with this one?
Thanks.
EDIT: Code added.
var xmlURLReq:URLRequest = new URLRequest("www.url.com");
var test:URLVariables = new URLVariables;
test.filename = "01.xml";
test.xmldata = xmltosave;
xmlURLReq.data = teste;
xmlURLReq.contentType = "text/xml";
xmlURLReq.method = URLRequestMethod.POST;
var xmlSendLoad:URLLoader = new URLLoader();
xmlSendLoad.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
xmlSendLoad.addEventListener(IOErrorEvent.IO_ERROR, onIOError, false, 0, true);
xmlSendLoad.load(xmlURLReq);
var alertBox:alertBoxClass = new alertBoxClass();
alertBox.x = 0;
alertBox.y = 200;
function onComplete(evt:Event):void
{
try
{
var xmlResponse = new XML(evt.target.data);
alertBox.alertText.text = "Inserção de dados bem sucedida!";
addChild(alertBox);
removeEventListener(Event.COMPLETE, onComplete);
removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
writeXML()
}
}
I also tried Object and LoadVars classes instead of URLVariables, no luck so far.
EDIT: Might as well add the php code as well.
<?php
$filename = "http://url.com/".$_POST["filename"];
$xml = $_POST["xmldata"];
$file = fopen($filename , "wb");
fwrite($file, $xml);
fclose($file);
?>
A: I see one possible problem in your code;
You are setting the data to a URLVariables instance, but the contentType to "text/xml". It should be "application/x-www-form-urlencoded" when using URLVariables.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLRequest.html#contentType
Hope that solves it!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery sliding drawer menu is blocking other content My Working Menu (with a minor problem)...
I have a sliding drawer menu system I've been using successfully for quite a while. It uses rollover images and this working jsFiddle (#1) below nicely demonstrates just the relevant operation with static div's in place of the image rollovers.
My system uses container div's with overflow:hidden; and drawer div's inside each. When a jQuery animation slides the drawer outside the container it's automatically hidden. Various other techniques are used to stop the animation when you move your mouse from the drawer back to the menu in order to prevent the drawer from closing prematurely.
Lots of time and effort was put into this system thanks to the help of the SO community. It served me well but now the menu drawers contain a lot more content. The larger/longer drawers have revealed this new issue as I'll describe below.
Just for demonstration purposes, I've outlined the containers to show their positions and slowed the animation. The final project is faster and does not have these outlines.
#1 - http://jsfiddle.net/PayFw/143/
As you can see, when content (a link for example) requiring interaction is behind or partially blocked by these containers, the link is not clickable as it's being covered. This problem can be seen in Mozilla and Webkit but not IE-8. (In this case, I think IE it not working as expected.) I have not tested other versions.
Playing with z-index is not a solution because that only causes the drawers to slide behind the content. Obviously, I want the drawers to slide over the content while in use.
What I've been trying...
Various solutions to the small issue above only seems to lead to more complicated issues.
I thought this one would be simple... just change make the containers invisible with visibility:hidden;. Then when you hover to invoke the sliding drawer, change to visibility:visible; and back to visibility:hidden; after the drawer closes. Even with the added complication of the animation, this is done with a callback to allow the closing animation to complete before making the container invisible again.
It's working very good when you enter the menu item "cleanly" ("cleanly" defined: from the top/bottom while not touching adjacent menu items).
However, this solution has created a whole new problem. When you move from one menu item to another, the jQuery animation stop() interferes with the opening of the next menu and slams it shut while you're still hovering it. And it's making the callback function unreliable.... sometimes, as you can see via the gray outline, leaves the container visible, defeating the whole purpose of this solution.
#2 - http://jsfiddle.net/PayFw/144/
Questions:
*
*Is there another way to prevent system #1 from always blocking content even when the drawers are closed?
*If not, is there a way to fix the problems with version #2? i.e. - get the container's visibility to properly toggle with the drawer animation while maintaining the same clean/reliable operation as in version #1.
*If there is no simple or practical solution, is there a jQuery plugin that can be easily integrated with my system? If so, which one and how? I know there are tons of jQuery menu drawer systems but I need something that can just put customizable sliding drawers under my already existing image rollovers (while not blocking the click-ability of any content that might fall into the drawers' zone of operation).
EDIT:
Regarding answer posted by vzwick: His solution is simple and brilliant but it needs further explanation. His statement about using display:none; & display:block; in place of visibility:hidden; & visibility:visible; is only part of the story.
I was using visibility:hidden; on the containers.
Instead, I should have been using display:none; on the drawers.
Why?
By toggling visibility:hidden;, the container stays within the content flow. The containers are within the flow and have an automatic size that is determined by the drawer size.
By toggling display:none;, the drawer is removed from the content flow. By removing the drawer from the flow, its container becomes zero size. So although the containers are still in the content flow, they are collapsed, zero size, no longer interfering with the page's content and therefore no longer a need to make them invisible.
http://jsfiddle.net/PayFw/146/
Brilliant. Thanks to vzwick.
A: Your problem is easily fixed by using display:block and display:none respectively:
$('div[id|="m"]').each(function (i) {
$(this).hover(enter, leave);
$ht[i] = ($('#menu-'+i).height());
$('#menu-'+i).css({
'top': '-'+$ht[i]+'px',
'display': 'none' // <--- changed
});
});
function enter() {
j = $(this).attr('id').replace(/m-/, "");
$('#menu-'+j).data({closing: false}).stop(true, false).animate({top: '0'},800).css({'display' : 'block'}); // <--- changed
};
function leave() {
$('#menu-'+j).data({closing: true}).delay(100).animate({top: '-'+$ht[j]+'px'},800, function(){ $(this).css({'display' : 'none'}) }); // <--- changed
};
See this fiddle for a working example.
Edit:
For clarification:
Setting the visibility property to hidden is basically just another way of saying opacity:0. The element still retains its dimensions and position in the box model. In your case, this means that it overlays other content.
The display property, in contrast, when set to none, removes the element from the box model/flow entirely.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why does CredentialCache.DefaultCredential contain empty strings for domain, username, and password Does anyone have any ideas as to why CredentialCache.DefaultCredential would return an ICredential instance with empty strings for domain, username, and password? I'm running a WCF service on IIS 7.5. It works fine on one server but never works on another. I have verified that the IIS application has Windows Authentication enabled....
Here is how it's being used:
string url = string.Format("{0}/departments/finance/_vti_bin/listdata.svc", _IntranetAddress);
var financeDataContext = new FinanceDataContext(new Uri(url))
{
Credentials = CredentialCache.DefaultCredentials
};
A: I am not sure how it is working in one of your servers? I hope you already read this
http://msdn.microsoft.com/en-us/library/system.net.credentialcache.defaultcredentials.aspx
but it clearly says "The ICredentials instance returned by DefaultCredentials cannot be used to view the user name, password, or domain of the current security context."
A: The NetworkCredential returned from CredentialCache.DefaultCredential is just a placeholder. If you look at it using the Debugger, you'll see that it's of type SystemNetworkCredential. Internal API check for this type to see if integrated authentication should be used or not. There are other ways to get the current username (like WindowsIdentity.GetCurrent()).
EDIT:
To specify impersonation for a WCF operation, add this attribute to the method implementing a contract:
[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public void SomeMethod()
{
// do something here
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I pass an argument that was passed to main (in argv) to my function? How can i pass argv[] to my function?, I am getting the errors when I run my program. I am new to c++ but i think i am not passing it right look at the error and my code. Now dont worry about the Depth First algorithm.. i will get to that later.. I am just trying to make this work.., basically I just want to pass the *argv[] to evaluate them in my printDepthFirst() but something is not right (obviously) .. Thank you
myprogram.c: In function ‘main’:
myprogram.c:18:4: warning: passing argument 1 of ‘opendir’ makes pointer from integer without a cast
/usr/include/dirent.h:135:13: note: expected ‘const char *’ but argument is of type ‘char
code
A: I think you meant to write opendir(arg_temp). arg_temp[1] is the second character of arg_temp. I wouldn't recommend using global variables to pass things to your function though anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java issue with var-args and boxing I have a question related to the following code snippet:
class VarArgsTricky {
static void wide_vararg(long... x) {
System.out.println("long...");
}
static void wide_vararg(Integer... x) {
System.out.println("Integer...");
}
public static void main(String[] args) {
int i = 5;
wide_vararg(i, i, i); // needs to widen and use var-args
Long l = 9000000000l;
wide_vararg(l, l); // prints sucessfully "long..."
}
}
The first call to wide_vararg fails to compile(saying that the method is ambigous) while the second compiles just fine.
Any explanations about this behaviour?
Thanks!
A: The first wide_vararg call is ambiguous because the compiler could either:
*
*widen the ints to longs, and call the first wide_vararg method, or
*autobox the ints to Integers, and call the second wide_vararg.
It doesn't know which it should do, however, so it refuses to compile the ambiguous method call. If you want the first call to compile, declare i as an Integer or a long, not an int.
A: When a var-arg method is invoked, the parameters get converted into an array of that type at compile time.
In the first call, the parameters get converted to an int[]. As all arrays in Java are direct sub types of the Object class, the concept of primitive widening does not apply in which case, both the overloads become equally applicable because long[] and Integer[] are at the same level. Hence the ambiguity
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: IIS url rewrite - css and js incorrectly being rewritten Having an issue with my urlrewrites - anytime I point to a page that is to be rewritten it fails to display because it is also applying the rule to the css & js files that are referenced within my webpage.
To try and remedy this I put in a fully qualified path to the css and js - this renders fine on any page where the rewrite isnt applied yet when i try to access a rewritten page the browser hangs.
Has anyone encountered something similar and if so have you a solution? Appreciate any help. Tried looking on the site at similar issues but none have helped so far.
<rewrite>
<outboundRules>
<rule name="OutboundRewriteUserFriendlyURL1" preCondition="ResponseIsHtml1" stopProcessing="true">
<match filterByTags="A, Form, Img" pattern="^(.*/)myapplicationname/Index\.html\?team=([^=&]+)$" />
<action type="Rewrite" value="{R:1}team/{R:2}/" />
</rule>
<preConditions>
<preCondition name="ResponseIsHtml1">
<add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html" />
</preCondition>
</preConditions>
</outboundRules>
<rules>
<rule name="RedirectUserFriendlyURL1" stopProcessing="true">
<match url="^myapplicationname/Index\.html$" />
<conditions>
<add input="{REQUEST_METHOD}" pattern="^POST$" negate="true" />
<add input="{QUERY_STRING}" pattern="^([^=&]+)=([^=&]+)$" />
</conditions>
<action type="Redirect" url="{C:1}/{C:2}" appendQueryString="false" />
</rule>
<rule name="RewriteUserFriendlyURL1" stopProcessing="true">
<match url="^([^/]+)/([^/]+)/?$" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="Index.html?{R:1}={R:2}" appendQueryString="false" />
</rule>
</rules>
</rewrite>
within my webpage:
<script src="/myapplicationname/Scripts/jquery-1.4.1.js" type="text/javascript"> </script>
<link href="/myapplicationname/Styles/MainStyle.css" rel="stylesheet" type="text/css" />
it is applying the rewrite to these and trying to find /myapplicationname/Team/Styles/MainStyle.css and similar with the JS file.
A: Try to find out which rule is causing the problem by removing them one by one. Now add a condition to that rule:
<rule name="Some rule">
...
<conditions logicalGrouping="MatchAny">
<add input="{URL}" pattern="^.*\.(ashx|axd|css|gif|png|jpg|jpeg|js|flv|f4v)$" negate="true" />
</conditions>
</rule>
This will avoid running the rule on files ending with .js, .css, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Why is Heroku skipping precompile step in Rails 3.1 app? I'm messing around with a rails 3.1 app and deploying to Heroku Cedar.
When pushing an app, Heroku skips over the precompile step without throwing an error:
Your bundle is complete! It was installed into ./vendor/bundle
Cleaning up the bundler cache.
-----> Writing config/database.yml to read from DATABASE_URL
-----> Rails plugin injection
Injecting rails_log_stdout
Injecting rails3_serve_static_assets
-----> Discovering process types
Procfile declares types -> (none)
Default types for Ruby/Rails -> console, rake, web, worker
-----> Compiled slug size is 16.2MB
-----> Launching... done, v35
The last time I pushed to Heroku (maybe a month ago) it had no problem precompiling assets.
gem 'rails', '3.1.1.rc2', :git => 'git://github.com/rails/rails.git', :branch => '3-1-stable'
UPDATE:
I was able to get Heroku to precompile by removing the following from application.rb:
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require *Rails.groups(:assets => %w(development test))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
and replacing with:
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require *Rails.groups(:assets) if defined?(Bundler)
A: I know this may sound conceiting, but did you make sure you create the Heroku app with -stack cedar?
A: You could also check to see that sprockets is enabled as I did here when I was having the same problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Importing code from file into Python and adding file dialog box I have a python script signalgen.py that plays audio using equations but I would like to be able to hard code the file where the equation is stored in eq1.txt or choose a file and import the equation.
The problems I'm having are:
1) How can I hard code a file and it's path correctly so it will play the equation as audio
I get an error
Traceback (most recent call last):
File "signalgen.py", line 484, in need_data
v += (datum * self.sig_level)
TypeError: can't multiply sequence by non-int of type 'float'
The specific block of code which I believe is causing the issue
def equation_import_function(self,t,f):
fileobj=open("/home/rat/eq1.txt","r")
eqdata =fileobj.read() #read whole file
fileobj.close()
#return math.tan(2.0*math.pi*f*t)
return eqdata
I have this line of code in the eq1.txt file-> math.tan(2.0*math.pi*f*t)
2) How can I add a file open dialog box to be able to choose a file and import the equation.
PS I'm using Ubuntu 10.04 (Linux) and the equations will be several pages long this is the reason I would like to import them into python from text files
Here's the entire code if you want to look at what I'm using below or seen on pastebin which includes line numbers http://pastebin.com/HZg0Jhaw
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ***************************************************************************
# * Copyright (C) 2011, Paul Lutus *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU General Public License as published by *
# * the Free Software Foundation; either version 2 of the License, or *
# * (at your option) any later version. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU General Public License for more details. *
# * *
# * You should have received a copy of the GNU General Public License *
# * along with this program; if not, write to the *
# * Free Software Foundation, Inc., *
# * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
# ***************************************************************************
# version date 01-12-2011
VERSION = '1.1'
import re, sys, os
import gobject
gobject.threads_init()
import gst
import gtk
gtk.gdk.threads_init()
import time
import struct
import math
import random
import signal
import webbrowser
class Icon:
icon = [
"32 32 17 1",
" c None",
". c #2A2E30",
"+ c #333739",
"@ c #464A4C",
"# c #855023",
"$ c #575A59",
"% c #676A69",
"& c #CC5B00",
"* c #777A78",
"= c #DB731A",
"- c #8A8C8A",
"; c #969895",
"> c #F68C22",
", c #A5A7A4",
"' c #F49D4A",
") c #B3B5B2",
"! c #DEE0DD",
" &&&&&&& ",
" &&&===='''''& ",
" &'''''====&'& ",
" +++++&'&&&&& &'& ",
" +@$%****&'&+ &'& ",
" +@**%$@++@&'&*@+ &'& ",
" +@**@+++++++&'&@**@+ &'& ",
" +$*$+++++++++&'&++$*$+ &'& ",
" @*@++++++++++&'&+++@#&&&'& ",
" +*@++++++++#&&&'&+++#=''''& ",
" +*$++++++++#=''''&+++&'>>>'& ",
" @*+++++++++&'>>>'&+++#='''= ",
" +%$++++++++@#='''=#@@++#&&&# ",
" +*@+++++++@@@#&&&#@@@@@++@*+ ",
" +*+++++++@@@@++@$%$$@@@@++*+ ",
" +*++++++@@+@;,,*@@*$$$@@@+*+ ",
" +*@++++@@@%!!!!,;@$*$$$@@@*+ ",
" +%$++++@@+)!!!),-*+-%$$$@$%+ ",
" +@*+++@@@+-!!!,;-%@;%%$$+*@+ ",
" +*@++@@@@+$*-*%@+*-%%$@@*+ ",
" ++*@+@@@$$%@++@%;;*%%$@-$+ ",
" +@%+@@@$$%*;;;;-*%%%@**+ ",
" .+$%@@@$$$*******%$$*-+. ",
" .+@%%@@$$*@*@%%%$%-%+. ",
" .++@%$$$$$$%%%%--@+. ",
" +++@@$%*****%+++ ",
" +++++++++++++@. ",
" @--%@++@$*-%+ ",
" +%,))),;%+. ",
" ++++++. ",
" ",
" "
]
# this should be a temporary hack
class WidgetFinder:
def localize_widgets(self,parent,xmlfile):
# an unbelievable hack made necessary by
# someone unwilling to fix a year-old bug
with open(xmlfile) as f:
for name in re.findall('(?s) id="(.*?)"',f.read()):
if re.search('^k_',name):
obj = parent.builder.get_object(name)
setattr(parent,name,obj)
class ConfigManager:
def __init__(self,path,dic):
self.path = path
self.dic = dic
def read_config(self):
if os.path.exists(self.path):
with open(self.path) as f:
for record in f.readlines():
se = re.search('(.*?)\s*=\s*(.*)',record.strip())
if(se):
key,value = se.groups()
if (key in self.dic):
widget = self.dic[key]
typ = type(widget)
if(typ == list):
widget[0] = value
elif(typ == gtk.Entry):
widget.set_text(value)
elif(typ == gtk.HScale):
widget.set_value(float(value))
elif(typ == gtk.Window):
w,h = value.split(',')
widget.resize(int(w),int(h))
elif(typ == gtk.CheckButton or typ == gtk.RadioButton or typ == gtk.ToggleButton):
widget.set_active(value == 'True')
elif(typ == gtk.ComboBox):
if(value in widget.datalist):
i = widget.datalist.index(value)
widget.set_active(i)
else:
print "ERROR: reading, cannot identify key %s with type %s" % (key,type(widget))
def write_config(self):
with open(self.path,'w') as f:
for key,widget in sorted(self.dic.iteritems()):
typ = type(widget)
if(typ == list):
value = widget[0]
elif(typ == gtk.Entry):
value = widget.get_text()
elif(typ == gtk.HScale):
value = str(widget.get_value())
elif(typ == gtk.Window):
_,_,w,h = widget.get_allocation()
value = "%d,%d" % (w,h)
elif(typ == gtk.CheckButton or typ == gtk.RadioButton or typ == gtk.ToggleButton):
value = ('False','True')[widget.get_active()]
elif(typ == gtk.ComboBox):
value = widget.get_active_text()
else:
print "ERROR: writing, cannot identify key %s with type %s" % (key,type(widget))
value = "Error"
f.write("%s = %s\n" % (key,value))
def preset_combobox(self,box,v):
if(v in box.datalist):
i = box.datalist.index(v)
box.set_active(i)
else:
box.set_active(0)
def load_combobox(self,obj,data):
if(len(obj.get_cells()) == 0):
# Create a text cell renderer
cell = gtk.CellRendererText ()
obj.pack_start(cell)
obj.add_attribute (cell, "text", 0)
obj.get_model().clear()
for s in data:
obj.append_text(s.strip())
setattr(obj,'datalist',data)
class TextEntryController:
def __init__(self,parent,widget):
self.par = parent
self.widget = widget
widget.connect('scroll-event',self.scroll_event)
widget.set_tooltip_text('Enter number or:\n\
Mouse wheel: increase,decrease\n\
Shift/Ctrl/Alt: faster change')
def scroll_event(self,w,evt):
q = (-1,1)[evt.direction == gtk.gdk.SCROLL_UP]
# magnify change if shift,ctrl,alt pressed
for m in (1,2,4):
if(self.par.mod_key_val & m): q *= 10
s = self.widget.get_text()
v = float(s)
v += q
v = max(0,v)
s = self.par.format_num(v)
self.widget.set_text(s)
class SignalGen:
M_AM,M_FM = range(2)
W_SINE,W_TRIANGLE,W_SQUARE,W_SAWTOOTH,W_EQUATION_IMPORT = range(5)
waveform_strings = ('Sine','Triangle','Square','Sawtooth', 'Equation_Import')
R_48000,R_44100,R_22050,R_16000,R_11025,R_8000,R_4000 = range(7)
sample_rates = ('48000','44100','22050','16000', '11025', '8000', '4000')
def __init__(self):
self.restart = False
# exit correctly on system signals
signal.signal(signal.SIGTERM, self.close)
signal.signal(signal.SIGINT, self.close)
# precompile struct operator
self.struct_int = struct.Struct('i')
self.max_level = (2.0**31)-1
self.gen_functions = (
self.sine_function,
self.triangle_function,
self.square_function,
self.sawtooth_function,
self.equation_import_function
)
self.main_color = gtk.gdk.color_parse('#c04040')
self.sig_color = gtk.gdk.color_parse('#40c040')
self.mod_color = gtk.gdk.color_parse('#4040c0')
self.noise_color = gtk.gdk.color_parse('#c040c0')
self.pipeline = False
self.count = 0
self.imod = 0
self.rate = 1
self.mod_key_val = 0
self.sig_freq = 440
self.mod_freq = 3
self.sig_level = 100
self.mod_level = 100
self.noise_level = 100
self.enable = True
self.sig_waveform = SignalGen.W_SINE
self.sig_enable = True
self.sig_function = False
self.mod_waveform = SignalGen.W_SINE
self.mod_function = False
self.mod_mode = SignalGen.M_AM
self.mod_enable = False
self.noise_enable = False
self.sample_rate = SignalGen.R_22050
self.left_audio = True
self.right_audio = True
self.program_name = self.__class__.__name__
self.config_file = os.path.expanduser("~/." + self.program_name)
self.builder = gtk.Builder()
self.xmlfile = 'signalgen_gui.glade'
self.builder.add_from_file(self.xmlfile)
WidgetFinder().localize_widgets(self,self.xmlfile)
self.k_quit_button.connect('clicked',self.close)
self.k_help_button.connect('clicked',self.launch_help)
self.k_mainwindow.connect('destroy',self.close)
self.k_mainwindow.set_icon(gtk.gdk.pixbuf_new_from_xpm_data(Icon.icon))
self.title = self.program_name + ' ' + VERSION
self.k_mainwindow.set_title(self.title)
self.tooltips = {
self.k_sample_rate_combobox : 'Change data sampling rate',
self.k_left_checkbutton : 'Enable left channel audio',
self.k_right_checkbutton : 'Enable right channel audio',
self.k_sig_waveform_combobox : 'Select signal waveform',
self.k_mod_waveform_combobox : 'Select modulation waveform',
self.k_mod_enable_checkbutton : 'Enable modulation',
self.k_sig_enable_checkbutton : 'Enable signal',
self.k_noise_enable_checkbutton : 'Enable white noise',
self.k_mod_am_radiobutton : 'Enable amplitude modulation',
self.k_mod_fm_radiobutton : 'Enable frequency modulation',
self.k_quit_button : 'Quit %s' % self.title,
self.k_enable_checkbutton : 'Enable output',
self.k_help_button : 'Visit the %s Web page' % self.title,
}
for k,v in self.tooltips.iteritems():
k.set_tooltip_text(v)
self.config_data = {
'SampleRate' : self.k_sample_rate_combobox,
'LeftChannelEnabled' : self.k_left_checkbutton,
'RightChannelEnabled' : self.k_right_checkbutton,
'SignalWaveform' : self.k_sig_waveform_combobox,
'SignalFrequency' : self.k_sig_freq_entry,
'SignalLevel' : self.k_sig_level_entry,
'SignalEnabled' : self.k_sig_enable_checkbutton,
'ModulationWaveform' : self.k_mod_waveform_combobox,
'ModulationFrequency' : self.k_mod_freq_entry,
'ModulationLevel' : self.k_mod_level_entry,
'ModulationEnabled' : self.k_mod_enable_checkbutton,
'AmplitudeModulation' : self.k_mod_am_radiobutton,
'FrequencyModulation' : self.k_mod_fm_radiobutton,
'NoiseEnabled' : self.k_noise_enable_checkbutton,
'NoiseLevel' : self.k_noise_level_entry,
'OutputEnabled' : self.k_enable_checkbutton,
}
self.cm = ConfigManager(self.config_file,self.config_data)
self.cm.load_combobox(self.k_sig_waveform_combobox,self.waveform_strings)
self.k_sig_waveform_combobox.set_active(self.sig_waveform)
self.cm.load_combobox(self.k_mod_waveform_combobox,self.waveform_strings)
self.k_mod_waveform_combobox.set_active(self.mod_waveform)
self.cm.load_combobox(self.k_sample_rate_combobox,self.sample_rates)
self.k_sample_rate_combobox.set_active(self.sample_rate)
self.k_sig_freq_entry.set_text(self.format_num(self.sig_freq))
self.k_sig_level_entry.set_text(self.format_num(self.sig_level))
self.k_mod_freq_entry.set_text(self.format_num(self.mod_freq))
self.k_mod_level_entry.set_text(self.format_num(self.mod_level))
self.k_noise_level_entry.set_text(self.format_num(self.noise_level))
self.k_main_viewport_border.modify_bg(gtk.STATE_NORMAL,self.main_color)
self.k_sig_viewport_border.modify_bg(gtk.STATE_NORMAL,self.sig_color)
self.k_mod_viewport_border.modify_bg(gtk.STATE_NORMAL,self.mod_color)
self.k_noise_viewport_border.modify_bg(gtk.STATE_NORMAL,self.noise_color)
self.sig_freq_cont = TextEntryController(self,self.k_sig_freq_entry)
self.sig_level_cont = TextEntryController(self,self.k_sig_level_entry)
self.mod_freq_cont = TextEntryController(self,self.k_mod_freq_entry)
self.mod_level_cont = TextEntryController(self,self.k_mod_level_entry)
self.noise_level_cont = TextEntryController(self,self.k_noise_level_entry)
self.k_mainwindow.connect('key-press-event',self.key_event)
self.k_mainwindow.connect('key-release-event',self.key_event)
self.k_enable_checkbutton.connect('toggled',self.update_values)
self.k_sig_freq_entry.connect('changed',self.update_entry_values)
self.k_sig_level_entry.connect('changed',self.update_entry_values)
self.k_sig_enable_checkbutton.connect('toggled',self.update_checkbutton_values)
self.k_mod_freq_entry.connect('changed',self.update_entry_values)
self.k_mod_level_entry.connect('changed',self.update_entry_values)
self.k_noise_level_entry.connect('changed',self.update_entry_values)
self.k_sample_rate_combobox.connect('changed',self.update_values)
self.k_sig_waveform_combobox.connect('changed',self.update_values)
self.k_mod_waveform_combobox.connect('changed',self.update_values)
self.k_left_checkbutton.connect('toggled',self.update_checkbutton_values)
self.k_right_checkbutton.connect('toggled',self.update_checkbutton_values)
self.k_mod_enable_checkbutton.connect('toggled',self.update_checkbutton_values)
self.k_noise_enable_checkbutton.connect('toggled',self.update_checkbutton_values)
self.k_mod_am_radiobutton.connect('toggled',self.update_checkbutton_values)
self.cm.read_config()
self.update_entry_values()
self.update_checkbutton_values()
self.update_values()
def format_num(self,v):
return "%.2f" % v
def get_widget_text(self,w):
typ = type(w)
if(typ == gtk.ComboBox):
return w.get_active_text()
elif(typ == gtk.Entry):
return w.get_text()
def get_widget_num(self,w):
try:
return float(self.get_widget_text(w))
except:
return 0.0
def restart_test(self,w,pv):
nv = w.get_active()
self.restart |= (nv != pv)
return nv
def update_entry_values(self,*args):
self.sig_freq = self.get_widget_num(self.k_sig_freq_entry)
self.sig_level = self.get_widget_num(self.k_sig_level_entry) / 100.0
self.mod_freq = self.get_widget_num(self.k_mod_freq_entry)
self.mod_level = self.get_widget_num(self.k_mod_level_entry) / 100.0
self.noise_level = self.get_widget_num(self.k_noise_level_entry) / 100.0
def update_checkbutton_values(self,*args):
self.left_audio = self.k_left_checkbutton.get_active()
self.right_audio = self.k_right_checkbutton.get_active()
self.mod_enable = self.k_mod_enable_checkbutton.get_active()
self.sig_enable = self.k_sig_enable_checkbutton.get_active()
self.mod_mode = (SignalGen.M_FM,SignalGen.M_AM)[self.k_mod_am_radiobutton.get_active()]
self.noise_enable = self.k_noise_enable_checkbutton.get_active()
def update_values(self,*args):
self.restart = (not self.sig_function)
self.sample_rate = self.restart_test(self.k_sample_rate_combobox, self.sample_rate)
self.enable = self.restart_test(self.k_enable_checkbutton,self.enable)
self.mod_waveform = self.k_mod_waveform_combobox.get_active()
self.mod_function = self.gen_functions[self.mod_waveform]
self.sig_waveform = self.k_sig_waveform_combobox.get_active()
self.sig_function = self.gen_functions[self.sig_waveform]
self.k_sample_rate_combobox.set_sensitive(not self.enable)
if(self.restart):
self.init_audio()
def make_and_chain(self,name):
target = gst.element_factory_make(name)
self.chain.append(target)
return target
def unlink_gst(self):
if(self.pipeline):
self.pipeline.set_state(gst.STATE_NULL)
self.pipeline.remove_many(*self.chain)
gst.element_unlink_many(*self.chain)
for item in self.chain:
item = False
self.pipeline = False
time.sleep(0.01)
def init_audio(self):
self.unlink_gst()
if(self.enable):
self.chain = []
self.pipeline = gst.Pipeline("mypipeline")
self.source = self.make_and_chain("appsrc")
rs = SignalGen.sample_rates[self.sample_rate]
self.rate = float(rs)
self.interval = 1.0 / self.rate
caps = gst.Caps(
'audio/x-raw-int,'
'endianness=(int)1234,'
'channels=(int)2,'
'width=(int)32,'
'depth=(int)32,'
'signed=(boolean)true,'
'rate=(int)%s' % rs)
self.source.set_property('caps', caps)
self.sink = self.make_and_chain("autoaudiosink")
self.pipeline.add(*self.chain)
gst.element_link_many(*self.chain)
self.source.connect('need-data', self.need_data)
self.pipeline.set_state(gst.STATE_PLAYING)
def key_event(self,w,evt):
cn = gtk.gdk.keyval_name(evt.keyval)
if(re.search('Shift',cn) != None):
mod = 1
elif(re.search('Control',cn) != None):
mod = 2
elif(re.search('Alt|Meta',cn) != None):
mod = 4
else:
return
if(evt.type == gtk.gdk.KEY_PRESS):
self.mod_key_val |= mod
else:
self.mod_key_val &= ~mod
def sine_function(self,t,f):
return math.sin(2.0*math.pi*f*t)
def triangle_function(self,t,f):
q = 4*math.fmod(t*f,1)
q = (q,2-q)[q > 1]
return (q,-2-q)[q < -1]
def square_function(self,t,f):
if(f == 0): return 0
q = 0.5 - math.fmod(t*f,1)
return (-1,1)[q > 0]
def sawtooth_function(self,t,f):
return 2.0*math.fmod((t*f)+0.5,1.0)-1.0
def equation_import_function(self,t,f):
fileobj=open("/home/rat/eq1.txt","r")
eqdata =fileobj.read() #read whole file
fileobj.close()
#return math.tan(2.0*math.pi*f*t)
return eqdata
def need_data(self,src,length):
bytes = ""
# sending two channels, so divide requested length by 2
ld2 = length / 2
for tt in range(ld2):
t = (self.count + tt) * self.interval
if(not self.mod_enable):
datum = self.sig_function(t,self.sig_freq)
else:
mod = self.mod_function(t,self.mod_freq)
# AM mode
if(self.mod_mode == SignalGen.M_AM):
datum = 0.5 * self.sig_function(t,self.sig_freq) * (1.0 + (mod * self.mod_level))
# FM mode
else:
self.imod += (mod * self.mod_level * self.interval)
datum = self.sig_function(t+self.imod,self.sig_freq)
v = 0
if(self.sig_enable):
v += (datum * self.sig_level)
if(self.noise_enable):
noise = ((2.0 * random.random()) - 1.0)
v += noise * self.noise_level
v *= self.max_level
v = max(-self.max_level,v)
v = min(self.max_level,v)
left = (0,v)[self.left_audio]
right = (0,v)[self.right_audio]
bytes += self.struct_int.pack(left)
bytes += self.struct_int.pack(right)
self.count += ld2
src.emit('push-buffer', gst.Buffer(bytes))
def launch_help(self,*args):
webbrowser.open("http://arachnoid.com/python/signalgen_program.html")
def close(self,*args):
self.unlink_gst()
self.cm.write_config()
gtk.main_quit()
app=SignalGen()
gtk.main()
A: The imp module will help you to cleanly load Python code chunks from arbitrary files.
#!/usr/bin/env python
# equation in equation-one.py
def eqn(arg):
return arg * 3 + 2
#!/usr/bin/env python
# your code
import imp
path = "equation-one.py"
eq_mod = imp.load_source("equation", path, open(path))
print("Oh the nice stuff in eq_mod: %s" % dir(eq_mod))
In your custom function definition, you can create a file selector dialog, get the selected file path, load the code using imp, and return the result of the function inside the imported module.
A: I was commenting before, but I stared at your code long enough and kinda realized what you were trying to do, so it was easier for me to post an answer. Please refer to cJ Zougloubs answer as I expand on his suggestion to use the imp module.
Your equation files should implement a common interface:
# equation1.py
def eqn(*args):
return sum(*args)
Then you would load them in using cj Zougloubs suggestion, but with a common interface:
# python_rt.py
def equation_import_function(self, *args):
filepath = ''
# filepath = ... do file chooser dialog here ...
eq_mod = imp.load_source("equation", filepath)
eqdata = eq_mod.eqn(*args)
return eqdata
Now you have a function in your main code that takes any number of arguments, asks the user to pick the equation file, and gets the result for you.
Edit To address your comment more specifically
# equation1.py
import math
def eqn(*args):
f = args[0]
t = args[1]
return math.tan(2.0*math.pi*f*t)
And in your main tool, you would use imp.load_source to bring it in. Wherever you needed that equation for your audio, you could then do:
eq_mod.eqn(f, t)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: storing/retrieving IPv4 & IPv6 addresses in MySQL Sorry I don't know much about this subject, but all I'm looking for is a quick-and-easy solution for uniquely representing any IP address (v4/v6) in MySQL so I can easily retrieve the last time (if any) that a particular computer has visited my site.
I don't need to do any computations on the addresses, just retrieval, so any unique representation should be ok. I do plan on storing a lot of these (don't have an estimate yet), so space may become a concern.
I've seen many solutions for storing IP addresses, but it's unclear which work for both versions. MySQL's built-in INET_ATON doesn't seem to support IPv6. PHP's inet_pton seems promising but requires prior knowledge of the address's format. I'm also unsure about its usage (MySQL field type and writing the insertion statement via PHP). I've seen varchar(39) used to represent IPv6 addresses as strings, and I like that this solution is somewhat independent of server configuration; however, I'm a little uneasy about disk space. Would this approach be sufficient for all addresses that $_SERVER['HTTP_CLIENT_IP'] might output?
I'm a little surprised there isn't an obvious generic solution. I assumed this was a very common task. I'm having indecision about this single issue, and would like to move on with my project. Is a quick-and-easy solution unreasonable?
Thanks very much for any guidance...
A: I would go with this: citat from there : How to store IPv6-compatible address in a relational database "Final decision taken: 2xBIGINT if the second bigint is NULL, then it means IPv4"
A: It sounds like your main concern is about space. If that's the case, then you could use the fact that IPv4 addresses are (essentially) 32-bit numbers and IPv6 are 128. An IPv4 address can be stored in an INT column, but IPv6 would require two BIGINT columns in MySQL. This is likely to be much more space-efficient than storing strings.
The cost of doing this is that you need to do the conversion from address -> number before inserting the value into the database. That will (slightly) increase CPU load on your web server, so you need to figure out where your bottleneck is going to be and optimise for that.
An added benefit of storing the addresses as numbers is that you can have a very efficient index on the column(s) so looking up an address will be lightning fast. Indexing varchar columns is very expensive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL: Join a table to itself I have a table of preferences, called "txp_prefs". I would like to return multiple preferences into a single row; the reason I prefer this to a simple concatenation is that I'm using a plugin in textpattern which can process the single row.
Here is the testing data I have:
------------------------------------------------
|Id | event | name |value |
------------------------------------------------
| 1 | season | season_start | 12/10/2011 |
-----------------------------------------------
| 2 | season | season_end | 29/10/2011 |
------------------------------------------------
| 3 | season | season_countdown | 7 |
------------------------------------------------
| 4 | another | test1 | result1 |
------------------------------------------------
| 3 | | test2 | result2 |
------------------------------------------------
The final result I would like to get is:
----------------------------------------------------------
|event | season_start | season_end | season_countdown |
----------------------------------------------------------
|season | 12/10/2011 | 29/10/2011 | 7 |
----------------------------------------------------------
I can (obviously) create the separate queries to get each result independently; for example
SELECT t1.event, t1.val AS season_start FROM txp_prefs t1 WHERE t1.event="season" AND t1.name="season_start" (to get the season_start)
SELECT t2.event, t2.val AS season_end FROM txp_prefs t2 WHERE t2.event="season" AND t2.name="season_end" (to get the season_end)
But I get errors when I try to join the two together, eg like this:
SELECT t1.event, t1.val AS season_start FROM txp_prefs t1 WHERE t1.event="season" AND t1.name="season_start"
LEFT JOIN
(SELECT t2.event, t2.val AS season_end FROM txp_prefs t2 WHERE t2.event="season" AND t2.name="season_end") t3
ON t1.event=t3.event
The error messages says it is something to do with the join (which I guessed anyway - the two individual queries work.
Any ideas? I have recently figured through joining different tables together, so I assume it is possible to join a table to itself.
A: Based on the structure given you can use
SELECT
MAX(CASE WHEN name = 'season_start' THEN value END) AS season_start,
MAX(CASE WHEN name = 'season_end' THEN value END) AS season_end,
MAX(CASE WHEN name = 'season_countdown' THEN value END) AS season_countdown
FROM txp_prefs
WHERE event='season'
A: select you are looking for is:
SELECT distinct
t0.event,
t1.val AS season_start ,
t2.val as seasson_end,
t3.val as season_countdown
FROM
txp_prefs t0
left outer join
txp_prefs t1
on ( t1.event=t0.event AND t1.name="season_start" )
left outer join
txp_prefs t2
on ( t2.event=t0.event AND t2.name="season_end" )
left outer join
txp_prefs t3
on ( t3.event=t0.event AND t3.name="season_countdown" )
WHERE
t0.event="season"
(the standard way to get only one row is 'distintc' reserved word. Another solution is append 'LIMIT 1' to query, but this is MySQL dependant)
are you sure that your database is right normalized?
see you.
A: You can do this by pivoiting. Asper my past project I demostrate you in following query hope will be useful to you.
My table transaction is having following fields
NAME VARCHAR2(10)
branch_code NUMBER(4)
Ruppes NUMBER(4)
SQL> select * from transaction;
NAME branch_code Ruppes
---------- ---------- ----------
Hemang 2602 1000
Hemang 2603 2000
Hemang 2400 3000
Yash 2602 1500
Yash 2603 1200
Yash 2400 1340
Krupesh 2602 1250
Krupesh 2603 2323
Krupesh 2400 8700
9 rows selected.
Now pivoting.
SQL> select branch_code,
2 max( decode( name, 'Hemang', Ruppes, null ) ) "Hemang",
3 max( decode( name, 'Yash', Ruppes, null ) ) "Yash",
4 max( decode( name, 'Krupesh', Ruppes, null ) ) "Krupesh"
5 from
6 (
7 select name, branch_code, Ruppes
8 from transaction
9 )
10 group by branch_code ;
branch_code Hemang Yash Krupesh
---------- ---------- ---------- ----------
2602 1000 1500 1250
2603 2000 1200 2323
2400 3000 1340 8700
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Internal Error in Eclipse I'm trying to launch a program in Eclipse, but I keep getting an error message saying:
An internal error occurred during: "Launching WindChillTester".
org/eclipse/jdt/debug/core/JDIDebugModel**
WindChillTester is the name of my program. What should I do to fix this?
A: Adding
-Dcom.ibm.icu.util.TimeZone.DefaultTimeZoneType=ICU
...at the end of eclipse.ini seems to have solved the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I get Flash to give me hints on objects that are on the stage? If I have an element on the stage (let's say a TextField, or a component ComboBox, for example). And I would like, when I reference it in the action script, for the IDE to give me the prompt to show me all the properties associated with that element, how do I create a reference to it, without creating code clutter? I mean, I have a reference to it already on the IDE (the instance name).
So, in the IDE I call it myElement.
Now, if in code I say var myElement:ComboBox; It throws a conflict at compile time. However, if I just reference it as myElement, it has no idea what sort of element it is, so it offers me no help. I know I can say var myCodeElement:ComboBox = myElement as ComboBox, but I really want to avoid that.
What's the correct approach here?
A: Ah! The solution is to wrap the instance name in a constructor of the type that it is, and then proceed as you would otherwise... so...
In my IDE I have a ComboBox component which I have given the instance name of myComboBox.
Later in my code when I wish to address it, rather than just saying myComboBox, I reference it as ComboBox(myComboBox) and the IDE then gives me all the pop up contextual help I need to work with it. I'm not sure if this is causing any extra work behind the scenes, but I think that since I'm not calling new on it, it's just using it in a static way. If anyone has any thoughts on this, I'd love to see them.
A: There is an arbitrary naming convention for this iirc;
end the instance name with the specified suffix:
_mc = MovieClip
_txt = TextField
etc.
They are all defined in a file called ActionsPanel*.xml where they are defined.
Something like this:
<typeinfo pattern="*_mc" object="flash.display.MovieClip"/>
<typeinfo pattern="*_array" object="Array"/>
<typeinfo pattern="*_str" object="String"/>
<typeinfo pattern="*_btn" object="flash.display.SimpleButton"/>
<typeinfo pattern="*_txt" object="flash.text.TextField"/>
<typeinfo pattern="*_fmt" object="flash.text.TextFormat"/>
<typeinfo pattern="*_date" object="Date"/>
<typeinfo pattern="*_sound" object="flash.media.Sound"/>
<typeinfo pattern="*_xml" object="XML"/>
<typeinfo pattern="*_xmlnode" object="flash.xml.XMLNode"/>
<typeinfo pattern="*_xmlsocket" object="flash.net.XMLSocket"/>
<typeinfo pattern="*_color" object="fl.motion.Color"/>
<typeinfo pattern="*_cm" object="flash.ui.ContextMenu"/>
<typeinfo pattern="*_cmi" object="flash.ui.ContextMenuItem"/>
<typeinfo pattern="*_pj" object="flash.printing.PrintJob"/>
<typeinfo pattern="*_err" object="Error"/>
<typeinfo pattern="*_cam" object="flash.media.Camera"/>
<typeinfo pattern="*_lc" object="flash.net.LocalConnection"/>
<typeinfo pattern="*_mic" object="flash.media.Microphone"/>
<typeinfo pattern="*_nc" object="flash.net.NetConnection"/>
<typeinfo pattern="*_ns" object="flash.net.NetStream"/>
<typeinfo pattern="*_so" object="flash.net.SharedObject"/>
<typeinfo pattern="*_video" object="flash.media.Video"/>
You can probably add in your own definitions there if you dare :)
A: One approach is to turn of the "Automatically declare stage instances" option and instead declare the instances yourself, in your code.
I'm a bit rusty with regards to the Flash CS IDE, I use Flash Builder nowadays, but if I remember it right, if you name instances on stage and declare public variables with the same name and type, they will be connected. So if you for example have a TextField named myTextField on the stage, you would declare this in code:
public var myTextField:TextField;
You then get the code completion hints while you code, and then when you build and run your swf, the instance on the stage is connected to the variable you declared, so to speak. Or the declared variable reference the instance on stage, whichever way you prefer to look at it.
A: The IDE will give code hinting only when it knows the type/class of the var.
There are many methods to do this as you can see from the response you got here.
I would do it in 1 of 2 ways depending on if I had an instance already made.
First method is if the instance does not exist
// create a var, type cast it, and use new on it
var tf:TextField = new TextField();
tf. // whenever you type a dot after tf it will trigger the hinting.
Second method is to type cast an already existing instance
(myComboBox as ComboBox). //again typing a "." dot after the ")" will trigger code hinting.
And to combo the 2 methods
var myCombo:ComboBox = (myComboBox as ComboBox)
myCombo // again typing the dot will do it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Advantage of over What are the advantages of using <h:graphiImage> over normal <img> (in terms of performance e.g. parse/render time, possible http caching if any?, etc.) for JSF2?
A: You don't get server-side attributes on <img> elements.
A: There is no safe and easy way to set an absolute path for the src attribute. This is important because you may well be referencing the same image from multiple pages that reside in different directories. Would you want the hassle of maintaining their relative location? Sure, you can use <img src="#{resource['images:myImage.png']}"/> to get a safe absolute path. Wouldn't it just be easier to use <h:graphicImage name="myImage.png" library="images"/>?
What's this about a "safe" absolute path?
You could leave your images outside the usual resources folder and specify them in an absolute path like this, for example: <img src="/myApp-web/faces/images/myImage.png"/> and that would work. But then what happens when you want to deploy your app? Do you want your URLs to be like http://www.mysite.com/faces/myPage.xhtml? Of course not. You want to set the context root to the server root. But you don't want the hassle of changing all your img tags for a production deployment, nor do you want some hack that involves getting the base URL from an application-scoped bean and hoping you remember to change a property for production deployment. So you're better off, at the very least, using <img src="#{resource['images:myImage.png']}"/> or the much easier to remember <h:graphicImage name="myImage.png" library="images"/>.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: "Message Must be multiple of 16" Encrypted Audio over the Network with Python I am sending encrypted audio through the network in Python. This app works momentarily then breaks saying it must be a multiple of 16.
Not sure what I am doing wrong. Or where to look in the code to solve this.
I would appreciate any help you have to offer
EDIT * I believe I have it working now if anyone is interested in taking a look I made a google code project
http://code.google.com/p/mii-chat/
A: msg = conn.recv(2024)
if msg:
cmd, msg = ord(msg[0]),msg[1:]
if cmd == CMD_MSG:
listb1.insert(END, decrypt_my_message(msg.strip()) + "\n")
The snippet above from your code reads 2024 bytes of data (which isn't a multiple of 16) and then (if the "if" statements are True) then calls decrypt_my_message with msg.strip() as the argument. Then decrypt_my_message complains that it was given a string whose length wasn't a multiple of 16. (I'm guessing that this is the problem. Have a look in the traceback to see if this is the line that causes the exception).
You need to call decrypt_my_message with a string of length n*16.
You might need to rethink your logic for reading the stream - or have something in the middle to buffer the calls to decrypt_my_message into chunks of n*16.
A: I did a quick scan of the code. All messages are sent after being encrypted, so the total data you send is a multiple of 16, plus 1 for the command. So far, so good.
On the decrypting side, you strip off the command, which leaves you with a message that is a multiple of 16 again. However, you are calling msg.strip() before you call decrypt_my_message. It is possible that the call to strip corrupts your encrypted data by removing bytes from the beginning or the end.
I will examine the code further, and edit this answer if I find anything else.
EDIT:
You are using space character for padding, and I suppose you meant to remove the padding using the strip call. You should change decrypt_my_message(msg.strip()) to decrypt_my_message(msg).strip().
You are using TCP to send the data, so your protocol is bound to give you headaches in the long term. I always send the length of the payload in my messages with this sort of custom protocol, so the receiving end can determine if it received the message block correctly. For example, you could use: CMD|LEN(2)|PAYLOAD(LEN) as your data frame. It means, one byte for command, two more bytes to tell the server how many bytes to expect, and LEN bytes of actual message. This way, your recv call can loop until it reads the correct amount. And more importantly, it will not attempt to read the next packet when/if they are sent back-to-back.
Alternatively, if your packets are small enough, you could go for UDP. It opens up another can of worms, but you know that the recv will only receive a single packet with UDP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery dropdown menu won't show hidden divs There is something obvious I'm missing about this.. just trying to display hidden divs based on the value of dropdown menu... here's a jsfiddle:
jsFiddle example
and the code..
<p id="data"></p>
<select id="dropdown">
<option label="US CERT1">"#divone"</option>
<option label="US CERT2">"#divtwo"</option>
<option label="NIST">"#divfour"</option>
<option label="DHS NY">"#divfive"</option>
<option label="DHS News">"#divsix"</option>
</select>
<div id="divone" class="section" >
Contents of divone
</div>
<script>
$(document).ready(function () {
function displayVals() {
var targetdiv = $("#dropdown").val();
$("#data").html("<b>Var data:</b> " + targetdiv );
$('.section').css('display','none');
$(targetdiv).css('display','block');
}
$("select").change(displayVals);
displayVals();
});
</script>
A: Remove the quotations from your option values:
<option label="US CERT1">#divone</option>
<option label="US CERT2">#divtwo</option>
<option label="NIST">#divfour</option>
<option label="DHS NY">#divfive</option>
<option label="DHS News">#divsix</option>
Updated Example: http://jsfiddle.net/andrewwhitaker/nKL5v/
The reason being that this line:
$(targetdiv)
Is equivalent to something like $("\"#divone\""), which contains an invalid selector.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Expression Blend VSM vs Event Driven I recently used Expression Blend and I found that it has something called Visual State Manager, what is the difference between it and the regular event driven model, and which is better?
A: Events are for instances of "things" happening e.g.:
*
*Was I clicked?
*Did my timer fire?
*Is my data ready?
The Visual State Manager is used to manage multiple simultaneous states of a control.
*
*Am I pressed?
*Is the mouse over me?
*Am I checked?
Events are just callbacks to listening objects, while states are visual states, so basically there are used for completely different purposes. Events can trigger state changes, but that is the only overlap.
A: An object fires an event to indicate that something has occurred. The event carries an arbitrary payload (the event args) plus (by convention) the object which sent the event. Visual states define the different states of a control or user control. A visual state defines how a control looks, how it transitions to that look, and how it transitions away from that look. ("Transition" can involve anything from toggling the visibility all the way though a complicated animation.) Visual states are part of a control, but you can't directly subscribe to them as you can with events.
One model is not better than the other: they're simply different. Think of using events in your view model and model/service layers and visual states in your view layer.
A: Visual State manager is used for managing state (surprisingly). So for example your button can be in multiple sates:
*
*Mouse over
*Mouse down
*Disabled
*Enabled
You code doesn't really need to know about it, so all visual states of your application should be kept within XAML.
Also Visual state managers helps to reduce your code behind which is more error prone.
And as for events, in fact I tend to use commands more often now, I find them to be more useful than events on its own.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Confused with syntax, calling a JS function with an input button I am having troubles understanding the xhtml syntax for calling a function with an input button. I have searched for this, but cannot find a clear explanation.
This snippet of code is from my book, and it works ok, but I'm not sure exactly how the following line works:
onclick="checkGrade(document.gradeForm.grade.value);"
From what I can figure out, gradeForm is the form, and then grade is the switch statement? So would you use Foo if you had another switch statement called foo inside the checkGrades function? And I am not sure what document or value are for inside the onClick checkGrade function.
Any help would be very much appreciated!
<script type="text/javascript">
function checkGrade(grade) {
switch (grade.toUpperCase()) {
case "A":
window.alert("Your grade is excellent.")
break;
case "B":
window.alert("Your grade is good.")
break;
case "C":
window.alert("Your grade is fair.")
break;
case "D":
window.alert("You are barely passing.")
break;
case "F":
window.alert("You failed.")
break;
default:
window.alert("You did not enter a valid letter grade.");
break;
}
}
</script>
<p>Please enter your grade below:</p>
<form action="#" name="gradeForm">
<input type="text" name="grade" />
<input type="button" value="Check Grade" onclick="checkGrade(document.gradeForm.grade.value);" />
</form>
A: No, grade refers to the textbox. You're passing the value of the textbox into the checkGrade function. The switch statement is running over the grade variable, which holds the value of the grade textbox.
You can't really "name" a switch statement. The argument to the switch represents the value you are testing.
document represents your HTML document, and value is the value of the textbox named grade. On another note, it is not recommended to use the onClick attribute in XHTML/HTML. Unobtrusive Javascript is preferred, where you bind a handler to the button. For more details, I recommend reading up on the Document Object Model, specifically The DOM and Javascript.
How old is this book you're using?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: implementation counting sort here is code for counting sorting
#include <iostream>
using namespace std;
int main(){
int a[]={2,3,1,2,3};
int n=sizeof(int)/sizeof(int);
int max=a[0];
for (int i=1;i<n;i++) {
if (a[i]>max) {
max=a[i];
}
}
int *output=new int[n];
for (int i=0;i<n;i++) {
output[i]=0;
}
int *temp=new int[max+1];
for (int i=0;i<max+1;i++) {
temp[i]=0;
}
for (int i=0;i<n;i++){
temp[a[i]]=temp[a[i]]+1;
}
for (int i=1;i<max+1;i++) {
temp[i]=temp[i]+temp[i-1];
}
for (int i=n-1;i>=0;i--) {
output[temp[a[i]]-1]=a[i];
temp[a[i]]=temp[a[i]]-1;
}
for (int i=0;i<n;i++) {
cout<<output[i]<<" ";
}
return 0;
}
but output is just 2,only one number. what is wrong i can't understand please guys help me
A: int n=sizeof(int)/sizeof(int);
is wrong. That just assigns 1 to n.
You mean
int n=sizeof(a)/sizeof(int);
I've not looked beyond this. No doubt there are more problems, but this is the most significant.
This is the kind of thing you can work out very easily with a debugger.
A: Look at this expression:
int n=sizeof(int)/sizeof(int);
What do you think the value of n is after this? (1)
Is that the appropriate value? (no, the value should be 5)
Does that explain the output you are seeing? (yes, that explains why only one number is shown)
A: My advice would be that if you're going to do this in C++, you actually try to use what's available in C++ to do it. I'd look up std::max_element to find the largest element in the input, and use an std::vector instead of messing with dynamic allocation directly.
When you want the number of elements in an array in C++, you might consider a function template something like this:
template <class T, size_t N>
size_t num_elements(T const (&x)[N]) {
return N;
}
Instead of dumping everything into main, I'd also write the counting sort as a separate function (or, better, a function template, but I'll leave that alone for now).
// warning: Untested code:
void counting_sort(int *input, size_t num_elements) {
size_t max = *std::max_element(input, input+num_elements);
// allocate space for the counts.
// automatically initializes contents to 0
std::vector<size_t> counts(max+1);
// do the counting sort itself.
for (int i=0; i<num_elements; i++)
++counts[input[i]];
// write out the result.
for (int i=0; i<counts.size(); i++)
// also consider `std::fill_n` here.
for (int j=0; j<counts[i]; j++)
std::cout << i << "\t";
}
int main() {
int a[]={2,3,1,2,3};
counting_sort(a, num_elements(a));
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Avoiding `save!` on Has Many Through Association I have a has_many through association with an attribute and some validations on the "join model". When I try to do something like @user.projects << @project and the association has already been created (thus the uniqueness validation fails), an exception is raised instead of the error being added to the validation errors.
class User
has_many :project_users
has_many :projects, :through => :project_users
class Project
has_many :project_users
has_many :users, :through => :project_users
class ProjectUser
belongs_to :user
belongs_to :project
# ...
if @user.projects << @project
redirect_to 'somewhere'
else
render :new
end
How can I create the association like I would with the << method, but calling save instead of save! so that I can show the validation errors on my form instead of using a rescue to catch this and handle it appropriately?
A: I don't think you can. From the API:
collection<<(object, …) Adds one or more objects to the collection by
setting their foreign keys to the collection’s primary key. Note that
this operation instantly fires update sql without waiting for the save
or update call on the parent object.
and
If saving fails while replacing the collection (via association=), an
ActiveRecord::RecordNotSaved exception is raised and the assignment is
cancelled.
A workaround might look like this:
if @user.projects.exists? @project
@user.errors.add(:project, "is already assigned to this user") # or something to that effect
render :new
else
@user.projects << @projects
redirect_to 'somewhere'
end
That would allow you to catch the failure where the association already exists. Of course, if other validations on the association could be failing, you still need to catch the exception, so it might not be terribly helpful.
A: Maybe you could try to add an validation to your project model, like:
validates :user_id, :uniqueness => {:scope => :user_id}, :on => :create
Not sure if that helps to avoid the save! method..
A: Try declaring the associations as
has_many :projects, :through => :project_users, :uniq => true
Checkout out section 4.3.2.21 in http://guides.rubyonrails.org/association_basics.html.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Two operators simultaneity overload in c++ I want to represent my object like an array. I mean that the programmer can write in his code
myobject[3]=2
In the back (in myobject code) there isn't an array at all, it's only representation.
So I need to overload [] and = simultaneously.
How can this be done?
thank you,
and sorry about my poor English.
A: operator[] should return a reference to object you are trying to modify. It may be some kind of metaobject, that overloads operator= to do whatever you wish with your main object.
Edit: As the OP clarified the problem, there is a way to do this. Look here:
#include <vector>
#include <iostream>
int & func(std::vector<int> & a)
{
return a[3];
}
int main()
{
std::vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
func(a) = 111;
std::cout << a[3] << std::endl;
}
A:
So I need to overload [] and = simultaneity. How can it's can be done?
It can't be done. What you can do instead is override operator[] to return a 'proxy reference'. That is, an object that has knowledge of the object 'myobject' to which it was applied and the index used '3', and provides appropiate conversion operators to the mapped type (I pressume int) as well as assignment operators. There are a few examples of proxy references in the standard library itself. Something in the lines of:
class proxy
{
public:
proxy( object& object, int index ) : _object( object ), _index( index ) {}
operator int() const { return _object.implementation.value_at( index ); }
proxy operator=( int value ){ _object.implementation.value_at( index, value ); return *this; }
private:
object& _object;
int _index;
};
A: @yoni: It is possible to give address of any member of the vector (as long as it exists). Here's how it's done.
int& MyObject::operator[](size_t index)
{
return mVector[index];
}
const int& MyObject::operator[](size_t index) const
{
return mVector[index];
}
This is possible because std::vector is guaranteed to be storing elements in a contiguous array. The operator[] of std::vector returns a reference-type of the value it stores. By you overloading the operator[], you just need to pass that reference out of your operator[] function.
NOTE: std::vector will take care of bounds check. With the solution that @Griwes gives, there's no bounds checking.
EDIT: Seems like Griwes has edited his solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: PHPUNIT without installation I'm sorry if the question is stupid for some reason. I'm not a phpunit expert and what I'm asking could sound ridiculous.
Is it possible to use phpunit without installation? Just "include" the libraries without installing anything on the server?
I'm asking this because at my workplace nobody wants to try some unit testing or TDDing but I'm pretty sure that I can do a better work when I program with the help of the tests and besides I want to show my coworkers that "it works" after the fact, not just by talking*.
Thanks for your help
*Talking already happened and the answer is always something like "We have too much work to do to consider these fancy things". Life seems to be too short to do a good job.
A: The readme on PHPUnit's github repository has instructions for this. Scroll down to Using PHPUnit From a Git Checkout for a list of commands you can copy-n-paste into your shell.
One thing to make clear to your coworkers is that while writing tests in addition to your regular code may seem like more work up front, well-written tests will save you time over the long run as you fix bugs and add features. They also give you the confidence to make more drastic changes as necessary whereas you might normally consider rewriting the project from scratch.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Googlemaps return object from initialize function I have a list of infowindows lets say numbered 1 to 5.
and they have a form to get directions. When I draw the route the infowindow should colapse. Everything works, I just want the infowindow object available outside the function
infowindow.close() works fine if its in initialize, however the function calcRoute() is outside of the initialize function. I'm trying to return the infowindow from the function but not sure where I am going wrong
here is the jest of what I'm doing
function initialize() {
........
var infowindow3 = new google.maps.InfoWindow({
content: iwindow('marker3','st pete','27.81884967015435','-82.65828121138918','727-822','4011 mlk','Fl','33703','201'),
maxWidth: 300
});
.........
return infowindow3;
}
// I have tried alerting every combination of this, window and even the function name
alert(this.window.infowindow3);
// if it would alert ObjectObject I would have it.
I know I'm close and hopefully someone familiar with the maps can shed some light.
A big thank you in advance. (I have spent days trying to get this one)
A: This may be a stupid question, but are you saving the return value of initialize? Of course you are not showing your whole code, but that's not clear from what is there. Something like this:
var infowindow3 = initialize();
alert(infowindow3);
Of course, the typical way to call initialize is via the load event, so you wouldn't be able to get the return value that way. So you would set up a (in your example) global variable, and that set that global variable inside of initialize (and not returning anything).
Update:
Ok, after looking through the page you linked to (in your comment) I see that you are calling the alert(infowindow3); before infowindow3 gets defined. You can also see that in the page itself, the alert pops up with "undefined" and the page isn't loaded yet - you can't see any map and consequently initialize() hasn't run yet. Bear in mind that during a page load, any script outside of a function (or a function's code if the function call is in that "open space") will get executed the moment the browser reads it. This alert is an example of that. You need to put that alert (or any code that uses this variable) in a function that does not get called until it is defined by initialize(). Examples of this are functions that get called with onclick. In fact, initialize itself is an example of that (it gets called with onload).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Make parameters available in an application What is the standard way of storing a command line argument so that it can be accessed when required?
I can see 2 scenarios:
*
*The argument is consumed immediately (A logging level)
*The argument is not needed immediately (On failure send email to address X)
With scenario 1 It would seem quite natural to configure it upfront, however when it is a scenario more in the vein of scenario 2 I would prefer to configure that component as and when necessary (IE not up front)
So to phrase the question slightly differently how do I make my configuration options available to my entire application?
A: You can have a singleton Configuration object, in which all relevant things are stored.
public class Configuration {
private static final Configuration conf = new Configuration();
public static Configuration get() {
return conf;
}
private String failureEmailAddress;
public String getFailureEmailAddress() {
return failureEmailAddress;
}
public void parseCommandLine(String[] args) {
// ...
}
}
A: You can use something like that (you can store the CommandLine somewhere or use the opions right away):
Options options = createOptions();
CommandLineParser parser = new GnuParser();
CommandLine cmdLine;
int timeoutHumanMove;
try
{
cmdLine = parser.parse(options, args, true);
timeoutHumanMove = getTimeoutOption(cmdLine, "thm", 300);
}
catch(ParseException e)
{
return;
}
private static int getTimeoutOption(CommandLine cmdLine, String opt, int defaultSeconds)
throws ParseException
{
if(cmdLine.hasOption(opt))
{
Number val = (Number)cmdLine.getParsedOptionValue(opt);
return (int)(val.doubleValue() * 1000D);
} else
{
return 1000 * defaultSeconds;
}
}
private static Options createOptions()
{
Options options = new Options();
options.addOption(OptionBuilder.withDescription("print this help and exit").create(OptionBuilder.withLongOpt("help"), 104));
// ...
return options;
}
A: There is no standard way to store application wide configuration information such as you describe. However, most of the time you store it in a class which is specific to the job (ApplicationContext), and then the instance is passed into the other classes as parameters or in a constructor or something like that. I usually make the ApplicationContext immutable.
Some applications I've come across use a static global context, effectively a global variable. This isn't necessarily a good idea, for the same reason that you should avoid global variables.
However, I would say that you should always verify that the command line options are valid up front. You don't want to do 3 hours of processing and then find out that someone hadn't configured the email address correctly on the command line. This should be a fail-fast situation.
A: You could store your command args into System properties using System.setProperty() then you can access your properties anywhere via System.getProperty()..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I create vertex attributes based on vertices' neighbors' attributes in igraph? For example, how would I calculate, for each vertex, the percentage of ties directed outward toward males?
g <- erdos.renyi.game(20, .3, type=c("gnp"), directed = TRUE)
V(g)$male <- rbinom(20,1,.5)
V(g)$male[10] <- NA
A: A possible (not necessary optimal) solution is as follows (this is one single line, I just break it down for sake of readability):
unlist(lapply(get.adjlist(g, mode="out"),
function (neis) {
sum(V(g)[neis]$male, na.rm=T)
}
)) / degree(g, mode="out")
Now let's break it up into smaller pieces. First, we get the adjacency list of the graph using get.adjlist(g, mode="out"). This gives you a list of vectors, each vector containing the out-neighbors of a vertex. Then we apply a function to each vector in this list using lapply. The function being applied is as follows:
function (neis) {
sum(V(g)[neis]$male, na.rm=T)
}
The function simply takes the neighbors of a node in neis and uses that to select a subset of vertices from the entire vertex set V(g). Then the male attribute is retrieved for this vertex subset and the values are summed, removing NA values on the fly. Essentially, this function gives you the number of males in neis.
Now, returning to our original expression, we have applied this function to the adjacency list of the graph using lapply, obtaining a list of numbers, each number containing the number of male neighbors of a given vertex. We convert this list into a single R vector using unlist and divide it elementwise by the out-degrees of the vertices to obtain the ratios.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Would it make sense to make a web server/app server for Rails in NodeJS OK, NodeJS is all the buzz these days because it handles things in a non-blocking asynchronous way. Because of this, it is very well suited to being a server of some sort, handling requests from multiple clients concurrently. So my question is whether it would make sense, from a technical perspective, to write a general-purpose Rails app AND web server for production use. To be clear, it would take the place of (for example) Apache and Phusion Passenger. Would this setup, in theory, not be faster at handling requests and responding?
A: You could use Nginx, Lighttpd or Mongrel2 that are event based and probably still keep your Ruby on Rails. To my knowledge, all three of those use event I/O and don't build and tear down threads or forks on each new connection. This way, you can keep your Ruby on Rails. If you need bidirectional communication for any AJAX, then I'd suggest putting in a Node.JS Socket.IO server.
A: Apache is very inefficient at handling concurrent connections. If you have a high volume traffic scenario then node should do a better job than Apache at handling the connections. However, node itself is much more than just a http server, it is possible to write brand new MVC frameworks not unlike Rails for building web applications. It is perhaps not wise to write a http server in node to replace Apache / Phusion Passenger just yet. Node is young and has not yet released version 1.0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to emulate pressing home button in android emulator In android emulator as I understand you can emulate most of the functionality of regular phone, back is emulated by ESC , what is shortcut for pressing home button in android emulator.
A: Did you try the Home key on your keyboard?
http://developer.android.com/guide/developing/tools/emulator.html
A: The keyboard Home button. The list of keyboard shortcuts is available here.
A: From developer android:
----------------------------------------------------------------------------------
| Emulated Device Key | Keyboard Key |
----------------------------------------------------------------------------------
| Home | HOME (FN + left_arrow on Macbooks)|
----------------------------------------------------------------------------------
| Menu (left softkey) | F2 or Page-up button |
----------------------------------------------------------------------------------
| Star (right softkey) | Shift-F2 or Page Down |
----------------------------------------------------------------------------------
| Back | ESC |
----------------------------------------------------------------------------------
| Call/dial button | F3 |
----------------------------------------------------------------------------------
| Hangup/end call button | F4 |
----------------------------------------------------------------------------------
| Search | F5 |
----------------------------------------------------------------------------------
| Power button | F7 |
----------------------------------------------------------------------------------
| Audio volume up button | KEYPAD_PLUS, Ctrl-F5 |
----------------------------------------------------------------------------------
| Audio volume down button | KEYPAD_MINUS, Ctrl-F6 |
----------------------------------------------------------------------------------
| Camera button | Ctrl-KEYPAD_5, Ctrl-F3 |
----------------------------------------------------------------------------------
| Switch to previous layout orientation | KEYPAD_7, Ctrl-F11 |
|(for example,portrait,landscape) | |
----------------------------------------------------------------------------------
| Switch to next layout orientation | KEYPAD_9, Ctrl-F12 |
|(for example,portrait,landscape) | |
----------------------------------------------------------------------------------
|Toggle cell networking on/off | F8 |
----------------------------------------------------------------------------------
| Toggle code profiling | F9 (only with -trace startup option)|
----------------------------------------------------------------------------------
| Toggle fullscreen mode | Alt-Enter |
----------------------------------------------------------------------------------
| Toggle trackball mode | F6 |
----------------------------------------------------------------------------------
| Enter trackball mode temporarily | Delete |
|(while key is pressed) | |
----------------------------------------------------------------------------------
| DPad left/up/right/down | KEYPAD_4/8/6/2 |
----------------------------------------------------------------------------------
| DPad center click | KEYPAD_5 |
----------------------------------------------------------------------------------
| Onion alpha increase/decrease |KEYPAD_MULTIPLY(*) / KEYPAD_DIVIDE(/)|
----------------------------------------------------------------------------------
A: The keyboard shortcut changed in new version, Press F1 in emulator, to get complete shortcuts. Android API_25+
A: For Android Emulator in JavaScript using Webdriver.io:
await driver.pressKeyCode(3)
// This is the keyCode for the home btn
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: A regular expression in Visual Studio to do search and replace on this example line? I'd like to replace lines like the following:
Debug.Assert(value == 10.01);
with a line like the following:
MyAssert.Equals(value, 10.01);
What is the regular expression to perform this, in Visual Studio Studio 2010?
Clarification
There is 1000x instances, each with a different first and second parameter. This problem requires some form of search/replace regular expression.
A: Try this:
Find:
Debug.Assert\({[^]*} == {[^)]*}\)
Replace With:
MyAssert.Equals(\1, \2);
A: You can replace
Debug.Assert(value ==
with
MyAssert.Equals(value,
It may not need any regular expression.
So you can use a regular expression. For example,
Debug.Assert\((.*) ==
and replacement string
MyAssert.Equals(\1,
A: I think you want to do the following:
Find all Debug.Assert(<someName> == <someValue>); and replace this with MyAssert.Equals(<someName>, <someValue>);
With a search replace you couldn't keep the someName.
I would try it with:
Search: Debug.Assert\({[\S]+} == {[^)]+}\);
Replace:MyAssert.Equals\(\1, \2\);
But I don't have any Visual Studio (I am on OS X) to try it on :-)
A: In Visual Studio 2012, you use the $ sign to enter a matched group.
E.g.
Find
.([a-zA-Z]*)XYZ
Replace
.$1ABC
This regex find/replace will replace all the fields suffixed with XYZ and change then to fields suffixed with ABC.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery delay execution of function I need a little guidance. I am trying to delay the execution of these two functions until after the page is fully loaded or timebomb them to happen after 5000 ms.
I am using the latest jquery 1.6
Thank you in advance for your help and code snippits :)
$("a.siteNavLink").each(function() {
var _href = $(this).attr("href");
$(this).attr("href", _href + '?p=client');
});
$("a.footernav").each(function() {
var _href = $(this).attr("href");
$(this).attr("href", _href + '?p=client');
});
A: You can use
$(window).load(function(){ your code here }) // page has loaded including images
or
$(document).ready(function(){ your code here }) // dom has loaded
A: $(document).ready(function() {
// Your code here
});
That will make your code run only when the document is fully loaded
jQuery ready() documentation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Listening socket connecting without accept being called on Linux I am running code on Ubuntu Linux it is supposed to use a Set and select to check when a listening socket has activity (ie someone trying to connect) and let them connect, the trouble is select ALLWAYS returns 0, and when I try to connect it just connects straight away.
but on the server Accept is never called as select always returns 0, so I am wondering what could cause this?
namespace SocketLib
{
const int MAX = FD_SETSIZE;
class SocketSet
{
public:
SocketSet();
void AddSocket( const Socket& p_sock );
void RemoveSocket( const Socket& p_sock );
inline int Poll( long p_time = 0 )
{
// this is the time value structure. It will determine how long
// the select function will wait.
struct timeval t = { 0, p_time * 1000 };
// copy the set over into the activity set.
m_activityset = m_set;
// now run select() on the sockets.
#ifdef WIN32
return select( 0, &m_activityset, 0, 0, &t );
#else
if( m_socketdescs.size() == 0 ) return 0;
return select( *(m_socketdescs.rbegin()), &m_activityset, 0, 0, &t );
#endif
}
inline bool HasActivity( const Socket& p_sock )
{
return FD_ISSET( p_sock.GetSock(), &m_activityset ) != 0;
}
protected:
// a set representing the socket descriptors.
fd_set m_set;
// this set will represent all the sockets that have activity on them.
fd_set m_activityset;
// this is only used for linux, since select() requires the largest
// descriptor +1 passed into it. BLAH!
#ifndef WIN32
std::set<sock> m_socketdescs;
#endif
};
is the code running the poll in case it helps
Additional code is:
#include <algorithm>
#include "SocketSet.h"
namespace SocketLib
{
SocketSet::SocketSet()
{
FD_ZERO( &m_set );
FD_ZERO( &m_activityset );
}
void SocketSet::AddSocket( const Socket& p_sock )
{
// add the socket desc to the set
FD_SET( p_sock.GetSock(), &m_set );
// if linux, then record the descriptor into the vector,
// and check if it's the largest descriptor.
#ifndef WIN32
m_socketdescs.insert( p_sock.GetSock() );
#endif
}
void SocketSet::RemoveSocket( const Socket& p_sock )
{
FD_CLR( p_sock.GetSock(), &m_set );
#ifndef WIN32
// remove the descriptor from the vector
m_socketdescs.erase( p_sock.GetSock() );
#endif
}
} // end namespace SocketSet
also it is being used here
{
// define a data socket that will receive connections from the listening
// sockets
DataSocket datasock;
// detect if any sockets have action on them
int i=m_set.Poll();
if( i > 0 )
{
// loop through every listening socket
for( size_t s = 0; s < m_sockets.size(); s++ )
{
// check to see if the current socket has a connection waiting
if( m_set.HasActivity( m_sockets[s] ) )
{
try
{
// accept the connection
datasock = m_sockets[s].Accept();
// run the action function on the new data socket
m_manager->NewConnection( datasock );
}
as you can see, it wont do a .Accept until AFTER it has got activity from the select, but it never gets that far
Bind and listen call is here
template
void ListeningManager::AddPort( port p_port )
{
if( m_sockets.size() == MAX )
{
Exception e( ESocketLimitReached );
throw( e );
}
// create a new socket
ListeningSocket lsock;
// listen on the requested port
lsock.Listen( p_port );
// make the socket non-blocking, so that it won't block if a
// connection exploit is used when accepting (see Chapter 4)
lsock.SetBlocking( false );
// add the socket to the socket vector
m_sockets.push_back( lsock );
// add the socket descriptor to the set
m_set.AddSocket( lsock );
}
A: select() requires the largest fd+1. You give it the largest fd, unmodified. If you see this error on Linux and not Windows, this is the most likely cause.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What happens when mongodb is out of memory? For example i have db with 20 GB of data and only 2 GB ram,swap is off. Will i be able to find and insert data? How bad perfomance would be?
A: It really depends on the size of your working set.
MongoDB can handle a very large database and still be very fast if your working set is less than your RAM size.
The working set is the set of documents you are working on a time and indexes.
Here is a link which might help you understand this : http://www.colinhowe.co.uk/2011/02/23/mongodb-performance-for-data-bigger-than-memor/
A: it's best to google this, but many sources say that when your working set outgrows your RAM size the performance will drop significantly.
Sharding might be an interesting option, rather than adding more RAM..
http://www.mongodb.org/display/DOCS/Checking+Server+Memory+Usage
http://highscalability.com/blog/2011/9/13/must-see-5-steps-to-scaling-mongodb-or-any-db-in-8-minutes.html
http://blog.boxedice.com/2010/12/13/mongodb-monitoring-keep-in-it-ram/
http://groups.google.com/group/mongodb-user/browse_thread/thread/37f80ff39258e6f4
Can MongoDB work when size of database larger then RAM?
What does it mean to fit "working set" into RAM for MongoDB?
You might also want to read-up on the 4square outage last year:
http://highscalability.com/blog/2010/10/15/troubles-with-sharding-what-can-we-learn-from-the-foursquare.html
http://groups.google.com/group/mongodb-user/browse_thread/thread/528a94f287e9d77e
http://blog.foursquare.com/2010/10/05/so-that-was-a-bummer/
side-note:
you said "swap is off" ... ? why? You should always have a sufficient swap space on a UNIX system! Swap-size = 1...2-times RAM size is a good idea. Using a fast partition is a good idea. Really bad things happen if your UNIX system runs out of RAM and doesn't have Swap .. processes just die inexplicably.. that is a bad very thing! especially in production. Disk is cheap! add a generous swap partition! :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Trying to use $.each jquery iterator. What is the difference between these two? vertices is an array of google.maps.LatLng objects, so they should be returning latlng points. It works just fine for the first code snipet. I am having problems when using the second.
// Iterate over the vertices.
for (var index =0; index < vertices.length; index++) {
var value = vertices.getAt(index);
contentString += "<br />" + "Coordinate: " + index + "<br />" + value.lat() +"," + value.lng();
}
I feel like this code should mean the exact same thing, but when I use the each iterator I get a javascript error : Uncaught TypeError: Cannot call method 'lat' of undefined
$.each(vertices, function(index, value){
contentString += "<br />" + "Coordinate: " + index + "<br />" + value.lat() +"," + value.lng();
});
A: It throws an error because vertices is not a normal javascript array (there is no getAt method on the Array object in Javascript). As per Google docs:
A polyline specifies a series of coordinates as an array of LatLng objects. To retrieve these coordinates, call the Polyline's getPath(), which will return an array of type MVCArray.
Note: you cannot simply retrieve the ith element of an array by using the syntax mvcArray[i]; you must use mvcArray.getAt(i).
So you should still have:
$.each(vertices, function(i) { var value = vertices.getAt(i); ... });
A: If you were iterating over a normal array, these would be functionally very similar, and your second version would work. But it looks like you're iterating over a MVCArray, probably from polyline.getPath, and that's not an array.
It looks from the docs like you can call .getArray() to get the base array of vertices:
$.each(vertices.getArray(), function(index, value){
contentString += "<br />" + "Coordinate: " + index + "<br />" + value.lat() +"," + value.lng();
});
A: The latter runs a function that also provides you a new scope.
You may not know this but the var value you declared inside the for is actually declared on the same scope as the for itself (it's parent) ..
JavaScript has no block scope but only function scope. So any var that is not declared near the beginning of the function is actually declared for the whole function, even it it's nested inside an if or loop.
Also, you don't get the browser abstraction jQuery provides. jQuery will detect what browser you run on and may choose a more performant path to execute your foreach, while the other will always use Array.getAt - even if there may be a better way to do that (let's say a browser starts providing a native function for example - always assuming you update jQuery)
In short: The jQuery guys know a lot more about browsers and their quirks than you do, and their way provides you with a loop scope for free. Writing your own is more error prone and can end up less efficient.
A: You first need to be sure what google api is returning. means when you use this
$.each(vertices, function(index, value){
for(var i in value){
alert('key =>'+i+' value=>'+value[i]);
}
});
This will give you the proper understanding of what google api is returning and are you able to call .lng() and .lat() function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: change order divs with jQuery <div class="test one">aaa</div>
<div class="test two">bbb</div>
<div class="test three">ccc</div>
Is possible change order this divs with jQuery? I would like receive:
<div class="test two">bbb</div>
<div class="test three">ccc</div>
<div class="test one">aaa</div>
i can use only jQuery
LIVE: http://jsfiddle.net/cmVyM/
I will make this only one - if document is ready.
A: Here is a simple example with navigate buttons.
HTML
<ul>
<li>1 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>2 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>3 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>4 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>5 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
<li>6 <a class='up' href='#'>up</a> <a class='down' href='#'>down</a></li>
</ul>
Javascript with JQuery
$('.up').on('click', function(e) {
var wrapper = $(this).closest('li')
wrapper.insertBefore(wrapper.prev())
})
$('.down').on('click', function(e) {
var wrapper = $(this).closest('li')
wrapper.insertAfter(wrapper.next())
})
Try it here: https://jsfiddle.net/nguyenvuloc/vd105gst
A: Sounds like you want to move the first div after the last.
$.fn.insertAfter inserts the matched elements after the parameter:
$(".test.one").insertAfter(".test.three");
http://jsfiddle.net/rP8EQ/
Edit: If you want a more general solution of adding the first to last, without resorting to the explicit classes:
var tests = $('.test');
tests.first().insertAfter(tests.last());
A: Just do $('.one').insertAfter('.three');
A: $("#botao").click(function(){
$("#a3").insertBefore("#a1");
});
<div id="a1">a1</div>
<div id="a2">a2</div>
<div id="a3">a3</div>
<div>
<a id="botao">altera</a>
</div>
See: http://jsfiddle.net/GeraldoVilger/2B6FV/
A: Just use insertAfter like the previous answer said
http://jsfiddle.net/cmVyM/68/
var eerste = $('.one');
var tweede = $('.two');
var derde = $('.three');
tweede.insertAfter(derde);
eerste.insertAfter(tweede);
A: If you want to change the order of group of divs with same class name (eg. given below):
<div class="wrapper">
<span class="text">First Heading</span>
<span class="number">1</span>
</div>
<div class="wrapper">
<span class="text">Second Heading</span>
<span class="number">2</span>
</div>
<div class="wrapper">
<span class="text">Third Heading</span>
<span class="number">3</span>
</div>
You can reorder it by the following jQuery code:
$('.wrapper .number').each(function () {
$(this).insertBefore($(this).prev('.text'));
});
https://jsfiddle.net/farhanmae/9th3drvd/
A: appendTo also is an alternative solution for this with JQuery.
var nav = $('.one').clone(true);
$('.one').remove();
nav.appendTo('.three');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="test one">aaa</div>
<div class="test two">bbb</div>
<div class="test three">ccc</div>
A: You can do it by this
var obj = $('.test.two');
obj.after(obj.prev());
so, div one and div two will change their's position.
I hope it can help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: Equivalent to jQuery closest() in ASP.NET Web Forms Im trying to figure out a way to build a somewhat clever version of the jQuery closest method in C#. Im using a generic method to find the desired control and then index the control chain
public static T FindControlRecursive<T>(Control control, string controlID, out List<Control> controlChain) where T : Control
{
controlChain = new List<Control>();
// Find the control.
if (control != null)
{
Control foundControl = control.FindControl(controlID);
if (foundControl != null)
{
// Add the control to the list
controlChain.Add(foundControl);
// Return the Control
return foundControl as T;
}
// Continue the search
foreach (Control c in control.Controls)
{
foundControl = FindControlRecursive<T>(c, controlID);
// Add the control to the list
controlChain.Add(foundControl);
if (foundControl != null)
{
// Return the Control
return foundControl as T;
}
}
}
return null;
}
To Call it
List<Control> controlChain;
var myControl = FindControls.FindControlRecursive<TextBox>(form, "theTextboxId"), out controlChain);
To find the closest element of id or type
// Reverse the list so we search from the "myControl" and "up"
controlChain.Reverse();
// To find by id
var closestById = controlChain.Where(x => x.ID.Equals("desiredControlId")).FirstOrDefault();
// To find by type
var closestByType = controlChain.Where(x => x.GetType().Equals(typeof(RadioButton))).FirstOrDefault();
Would this be a good approach or are there any other cool solutions out there creating this?
Whats your consideration?
Thanks!
A: Maybe something like this
public static IEnumerable<Control> GetControlHierarchy(Control parent, string controlID)
{
foreach (Control ctrl in parent.Controls)
{
if (ctrl.ID == controlID)
yield return ctrl;
else
{
var result = GetControlHierarchy(ctrl, controlID);
if (result != null)
yield return ctrl;
}
yield return null;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Add dynamically TinyMCE Textarea on Newly tabs I using tab's JQuery plugin UI each tab contains TextArea then are manage by TinyMCE librarie.
I want to do : When you click on tab "+" , that add new tab which contains textarea too.
To create new tab with textearea , it's good. The problem is : I can't edit textarea value and if i click on TinyMCE 's option ( like Bold ) : J is null error on Javascript console
My JS Code :
$('li > a.moretxt').click(function(){
// Number of element in tabs
var size = $( "#tabs" ).tabs("length");
// Content to add on new tab
var content = "<div id='divcontent"+size+"'><textarea id=\'txtcontent"+size+"'\' cols=\'60\' rows=\'5\'></textarea></div>";
// Some variable
var path = '#divcontent'+size;
var title = 'content'+size;
var idtxt = 'txtcontent'+size;
// Add new div Textarea before the end
$('div#morecontent').before(content);
//Add control ?
tinyMCE.execCommand('mceAddControl', true, idtxt);
// Add new TAB
$( "#tabs" ).tabs("add",path,title,(size));
var index = $( "#tabs" ).tabs("option", "selected");
});
The follow code , well add tab with tiny TextArea but it doesn't works ...
A: TinyMCE needs to have the object in the DOM to apply itself. I'm not sure why TinyMCE isn't working as you appear to be are adding the container prior to adding TinyMCE, however if you move the "addControl" to after you've added the new Tab it should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android proguard obfuscated code is causing NullPointerException when it really shouldn't be I have distributed an application on the Android Marketplace. I am getting error reports back in from a small handful of users (maybe 2%) where they are getting NullPointerExceptions where it doesn't make logical sense.
I have never been able to replicate this myself. The code is relatively straightforward and is a common code path that EVERY user has to follow. I've actually taken every separate line of code that could possibly be creating the NPE and wrapped it in a try-catch block and throw a custom runtime exception, but I'm still getting NullPointerException errors not caught.
At this point, the only thing I can imagine it would be is something related to my Proguard obfuscation. I have seen some other article talking about taking out the -overloadaggressively option if you notice odd behavior, but as far as I can tell, I'm not using that option.
Has anybody else experienced mysterious NPEs using android and proguard. Are there any other settings people can recommend to dial down the optimizations that might be causing this issue?
Any other ideas?
For reference, here is the unobfuscated function that is getting the NPE:
public MainMenuScreen(final HauntedCarnival game) {
super(game);
game.startMusic("data/music/intro.mp3");
stage = new Stage(Screen.SCREEN_WIDTH, Screen.SCREEN_HEIGHT,true);
stage.addActor(new Image("background", Assets.mainMenuBackground));
Image title = new Image("title", Assets.mainMenuTitle);
title.x = 0;
title.y = 340;
resetEyeBlink();
stage.addActor(title);
dispatcher.registerInputProcessor(stage);
settings = game.getSettings();
eyeBlinkImage = new Image("eyeBlink", Assets.eyeBlink);
if (settings.getPlayers().isEmpty()) {
settings.addPlayer("Player One");
settings.save(game);
}
setupContinue();
}
So the only possibilities I can see are game, dispatcher and settings.
game gets set via this code in another class. game is a final variable in that other class:
game.setScreen(new MainMenuScreen(game));
dispatcher gets set within in the call to super above.
getSettings() returns a settings object that gets set at the very start of the application, is private and never gets unset. Its also used before this method several times.
There are not auto-boxing primitives.
here is the proguard config:
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-keepattributes Signature
-keep public class com.alkilabs.hauntedcarnival.settings.Settings
-keep public class com.alkilabs.hauntedcarnival.settings.Settings {
*;
}
-keep public class com.alkilabs.hauntedcarnival.settings.Player
-keep public class com.alkilabs.hauntedcarnival.settings.Player {
*;
}
-keepnames public class com.alkilabs.hauntedcarnival.world.World
-keepnames public class * extends com.alkilabs.hauntedcarnival.world.upgrades.Upgrade
-keepnames public class * extends com.alkilabs.hauntedcarnival.world.achievments.Achievement
-keepnames public class com.alkilabs.hauntedcarnival.world.monsters.MonsterType
-keepclassmembers class * extends com.alkilabs.hauntedcarnival.world.monsters.Monster {
public <init>(com.alkilabs.hauntedcarnival.world.monsters.MonsterType, java.lang.Integer, com.alkilabs.hauntedcarnival.world.World);
}
-keepnames public class com.alkilabs.hauntedcarnival.world.items.ItemType
-keepclassmembers class * extends com.alkilabs.hauntedcarnival.world.items.Item {
public <init>(com.alkilabs.hauntedcarnival.world.World, java.lang.Integer, java.lang.Integer);
}
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-dontwarn com.badlogic.gdx.scenes.scene2d.ui.utils.DesktopClipboard
-dontwarn com.badlogic.gdx.utils.JsonWriter
-dontwarn com.badlogic.gdx.utils.XmlWriter
-keepclasseswithmembernames class * {
native <methods>;
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet, int);
}
-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
A: OK, I think I got to the root of the issue/confusion.
One of the things proguard does is in-line some methods. Because of this, the entire contents of my setupContinue() function at the bottom of my constructor was added directly into the contents of my constructor. So now I have a bunch more code to review, and I do see some more possibilities for NPEs. I'm pretty sure I'll get to the bottom of my issue.
I figured this out by taking the obfuscated.jar that proguard produces, and running it through a decompiler. Its an interesting exercise as you get get little more insight into the inner workings of proguard. I highly recommend it for people wanting to better understand the impacts that proguard has on their code.
A: Your best bet would be to use the mapping.txt file and the retrace tool to find the exact location of the error.
From there it would be easier to understand if it's indeed Proguard or some other end-case you didn't think of.
To do this, you need to copy the stack trace from the developer's console to another file, let's assume it's called
c:\trace.txt
Now, in your project, you'll find a Proguard folder with 4 files.
Let's assume your project is in
c:\project
What you'll need to do is run the retrace tool (using the batch file for easier use) located at (change to the location of your Android Sdk folder) :
c:\android-sdk-windows\tools\proguard\bin\retrace.bat
Go to that folder and run:
retrace c:\project\proguard\mapping.txt c:\trace.txt
From there on, it would be much easier to figure our the exact line of the exception and to probably find the error.
From my experience, the only things that could get messed up are third party libraries. Normal Android code, for all my projects, was never harmed from obfuscation.
A: Sorry I can't post comments yet (I'm new to SO).
This could be another problem I've encountered myself. On some phones there was a problem at some point with missing Android libraries like a JSon library.
I'd recommend you take a closer look at what phones that actually get the NPE - there might be some similarities.
In my case it was the HTC Desire Z, that was missing the JSon library and so the app force closed every time the JSon part was called. The problem was fixed by HTC later on with a hotfix to the Desire Z's rom.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to get CODE from formatResult in an Autocomplete plugin? I have this:
var objects_list = [{
"code": "44",
"name": "Privilegios de cuenta",
"alias": "account-privileges",
"typename": "Opci\u00f3n",
"typealias": "object",
"description": null
}, {
"code": "104",
"name": "Asignar aplicaciones",
"alias": "add-application-to-user",
"typename": "Opci\u00f3n",
"typealias": "object",
"description": "Permite asignar aplicaciones a las cuentas"
}];
$('#find_object').autocomplete(objects_list, {
minChars: 0,
width: 310,
matchContains: "word",
autoFill: false,
formatItem: function(row, i, max) {
return "<b>" + row.name + "</b>" + " (" + row.description + ")";
},
formatMatch: function(row, i, max) {
return row.name + " " + row.alias + " " + row.description + " " + row.typename + " " + row.typealias;
},
formatResult: function(row) {
$('#code_to_use').val( row.code );
return row.name + " (" + row.description + ") ";
}
});
This code works well, but I can't understand the code very clearly. In the formatResult function, the line $('#code_to_use').val( row.code ) is never executed or did I get it wrong?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Learning Java public static main method I am learning java and I have come across the following problem: write the code for a single file that implements a public static void main(String[]) method when called with any array of strings, can anyone explain how I do this, it to used with an immutable abstract data type of a list of string?
Thanks
A: The args[] array contains a list of command line parameters given to your program. So:
java SomeClass runInBackground debugModeOn
would result in the args array:
["runInBackground", "debugModeOn"]
A: public class FirstMain {
public static void main(String [] args) {
for (String arg : args) {
System.out.println(arg);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-8"
} |
Q: Error with a SQL statement What I am trying to do is create a view that selects empno, ename, deptno renames the columns empno to Employee_ID, ename to Employee, Deptno to Department_ID
Any ideas to why I have these problems?
SQL> create view DEPT20 AS
2 select empno,ename,deptno (employee_id, employee, Department_ID) from emp
3 where deptno = 20
4 with check option constraint emp_dept_20;
select empno,ename,deptno (employee_id, employee, Department_ID) from emp
*
ERROR at line 2:
ORA-00904: "DEPTNO": invalid identifier
I know its there so why do I get the error?
SQL> select empno, ename, deptno from emp;
EMPNO ENAME DEPTNO
---------- ---------- ----------
7839 KING 10
7698 BLAKE 30
7782 CLARK 10
7566 JONES 20
7654 MARTIN 30
7499 ALLEN 30
7844 TURNER 30
7900 JAMES 30
7521 WARD 30
7902 FORD 20
7369 SMITH 20
EMPNO ENAME DEPTNO
---------- ---------- ----------
7788 SCOTT 20
7876 ADAMS 20
7934 MILLER 10
8888 Stuttle 40
15 rows selected.
SQL>
A: It looks like you're trying to rename the columns. I think you need to do it like the following
select empno as employee_id, ename as employee,deptno as department_id from emp
A: Maybe it helps, if you try this one:
SELECT
empno as employee_id,
ename as employee,
deptno as Department_ID
FROM emp ...
A: why don't you try like this -
... select empno as employee_id, ename as employee, deptno as Department_ID
from emp where Department_ID = 20 ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Preformance issue AutomationID attached property I have question about performance issue with AutomationID attached property. Is it using as much of Cpu and RAM as Name attribute, which is generally not recommended to supply if not needed?
A: This is a classic DependencyProperty and the cost is not that great IMO.
I personally recommend to put it only on the key controls of your application which will be the target of ui tests.
Maybe you'll find this post useful too: http://www.jonathanantoine.com/2011/11/03/coded-ui-tests-automationid-or-how-to-find-the-chose-one-control/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: J2ME Canvas fill background in for loop Im developing a small app with J2ME Midlet and i know canvas is very strong in low level to create GUI. I try some code to create GUI but i got stuck when i try to fill and draw it!
I dont know how can i draw it in loop look like this picture below:
I wanna fill background like this picture gray and black in loop
http://fc03.deviantart.net/fs70/i/2011/028/2/1/music_player_tutorial_by_app_juice-d388pcq.jpg
I mean if i have a vector or a int variable
int value = 10
for(int i = 0; i< value; i++){
if(i % 2 ==0){
Fill gray
}else{
Fill black
}
what should i do in this loop?
}
i dont know how to identify coordinate X and Y when use for loop
i need expert help me
Thank you!!
A: You can use this, or at least you can check how he did it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java Sending Email "Client Server" Trying to create a email client server through using JAVA and I have implemented the following but got stuck where to go next.. appreciate the help
I am trying to create a socket and set up the input and the output streams. We Take user's request, call up the appropriate method (doSend or doRead), close the link and then ask if the user wants to do another read/send.
Email.java:
import java.io.*;
import java.net.*;
import java.util.*;
public class Email {
private static InetAddress host;
private static final int PORT = 21;
private static String name;
private static Scanner networkInput, userEntry;
private static PrintWriter networkOutput;
public static void main(String[] args) throws IOException {
try {
host = InetAddress.getLocalHost();
} catch (UnknownHostException uhEx) {
System.out.println("Host ID not found!");
System.exit(1);
}
userEntry = new Scanner(System.in);
do {
System.out.print("\nEnter name ('Mike' or 'Jack'): ");
name = userEntry.nextLine();
} while (!name.equals("Mike") && !name.equals("Jack"));
talkToServer();
}
private static void talkToServer() throws IOException {
String option, message, response;
do {
/*******************************************************
* I am trying to cREATE A SOCKET and SET UP the INPUT and the OUTPUT
* STREAMS. We Take USER'S REQUEST, CALL UP THE APPROPRIATE METHOD
* (doSend or doRead), CLOSE THE LINK AND THEN ASK IF USER WANTS TO DO
* ANOTHER READ/SEND.
*******************************************************/
} while (!option.equals("n"));
}
private static void doSend() {
System.out.println("\nEnter 1-line message: ");
String message = userEntry.nextLine();
networkOutput.println(name);
networkOutput.println("send");
networkOutput.println(message);
}
private static void doRead() throws IOException {
/*********************************
* I am trying to full the read method
*********************************/
}
}
A: Take a look at this JavaMail API tutorial.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to get the jquery last state Hi I am using the jquery image slider from http://www.gmarwaha.com/jquery/jcarousellite/. this works perfectly but after postback the slider starts from 0. how to remember the last state after postbacks? here is the live demo http://sampath.ind.in
$(document).ready(function () {
$("#slidebox").jCarouselLite({
vertical: false,
hoverPause: true,
btnPrev: ".previous",
btnNext: ".next",
visible: 3,
circular: false,
start: 0,
scroll: 1,
speed: 300
});
});
A: You can use the afterEnd callback to store the current state in a cookie or local storage and start from there if this key is present.
This should set a cookie (lastPosition), that you can use later:
$(...).jCarouselLite({
...
afterEnd:function(e){$.cookie('lastPosition', e.first().index());}
...
});
To start with a predefined position you would do something like this:
$(...).jCarouselLite({
...
start: parseInt($.cookie('lastPosition'),10) || 0
...
});
To set/retrieve cookies you can use this library: https://github.com/carhartl/jquery-cookie. This is not tested code, but it should give you a basic idea.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I make my TCP listening app safer? I’m looking for advice on writing a very safe C/C++ app that will listen to a tcp port. I'd like to peek at what others are trying to do to my machine, but I’d rather not install an elaborate honeypot app if I can do what I need with a very short program. With my goal being simple and safe, I want to make sure I handle at least the following:
1) The client should not be able to send an unlimited amount of data,
2) The client(s) should not be able to overload the server with too many connections and
3) The client should not be able to keep a connection open indefinitely.
Because my current app is small and functional, a third party library doesn't seem warranted for this project. However, a small library that would simplify the app further would be interesting. Also, I expect the C++ standard library may help in simplifying my code.
Below are some key functions from my initial attempt. This code compiles on Windows, OSX and Linux.
How can I make the app safer, or simpler?
void SafeClose(SOCKET s)
{
if (s == INVALID_SOCKET)
return;
shutdown(s, SHUT_RDWR);
closesocket(s);
}
void ProcessConnection(SOCKET sock, sockaddr_in *sockAddr)
{
time_t time1;
char szTime[TIME_BUF_SIZE];
char readBuf[READ_BUF_SIZE];
time(&time1);
strftime(szTime, TIME_BUF_SIZE-1, "%Y/%m/%d %H:%M:%S", localtime(&time1));
printf("%s - %s\n", szTime, inet_ntoa(sockAddr->sin_addr));
usleep(1000000); // Wait 1 second for client to send something
int actualReadCount = recv(sock, readBuf, READ_BUF_SIZE-1, 0);
if (actualReadCount < 0 || actualReadCount >= READ_BUF_SIZE){
actualReadCount = 0;
strcpy(readBuf, "(Nothing)");
} else {
CleanString(readBuf, actualReadCount); // Replace non-printable characters
readBuf[actualReadCount] = 0;
}
printf("%s\n\n", readBuf);
SafeClose(sock);
}
int main(int argc, char* argv[])
{
int port = 80;
char cmd[CMD_BUF_SIZE] = {0};
sockaddr_in newSockAddr;
sockaddr_in localSockAddr;
if(argc < 2){
printf("Usage: safelisten PORT\n\n");
return error_code;
}
error_code++;
port = atoi(argv[1]);
BuildCleanAsciiMap(); // Used to replace non-printable characters
localSockAddr.sin_family = AF_INET;
localSockAddr.sin_addr.s_addr = INADDR_ANY;
localSockAddr.sin_port = htons(port);
sizeNewSockAddr = sizeof newSockAddr;
CHK( listenSocket = socket(AF_INET, SOCK_STREAM, 0));
CHK( setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)));
CHK( bind(listenSocket, (sockaddr*)&localSockAddr, sizeof localSockAddr));
CHK( listen(listenSocket, BACKLOG));
CHK( SetNonBlocking(listenSocket));
CHK( SetNonBlocking(0)); // Set STDIN to nonblocking for linux
printf ("Listening on port: %d\nEnter q to quit.\n\n", port);
while(strcmp(cmd, "q")) // While the user has not entered q ...
{
newSocket = accept(listenSocket, (sockaddr*)&newSockAddr, &sizeNewSockAddr);
ReadCmd(cmd, CMD_BUF_SIZE);
if(newSocket == INVALID_SOCKET) {
// accept() would have blocked, thus we wait and try again
usleep(10000);
continue;
}
// Set to nonblocking because we don't want the client to dictate how
// long we are connected.
CHK( SetNonBlocking(newSocket));
ProcessConnection(newSocket, &newSockAddr);
}
SafeClose(listenSocket);
return 0;
}
A:
2) The client(s) should not be able to overload the server with too
many connections...
Your best options is letting the router limit how many connections an IP address makes, as, by the time your program gets the connection info there are system resources already allocated.
1) The client should not be able to send an unlimited amount of data,
The best option is to have some reasonable max that can be sent, and just keep track of how much you have read, and once you reach the max limit, close the connection.
3) The client should not be able to keep a connection open indefinitely.
For this, you can just create a thread that will start a countdown, so when a connection has been open for a specific amount of time, it can timeout and you can just close the connection.
There are other, more complicated, solutions, but I think this would be a good starting point.
If you want to do something about (2), keep a hashmap in memory and just increment how many connections have been made, but you may also want to keep track of time. You want the data structure to be very fast, so you can decide if you need to disconnect the connection early.
For example, if you had two longs in the hashmap, then you could put the time (in unixtime or ticks) of the first connection, and increment, and if you get 10 connections in less than one minute, start to close the excess until a minute has passed. Then remove that element if it has had connections long enough that you trust it was not attacking you.
Also, make certain you validate all the parameters being passed to you, and have reasonable max values for any strings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using Minitest in Rails Recently, I've read quite a few articles about Minitest. I really like the idea of a super lightweight test framework. I decided to replace rspec with it in a recent project and have had no luck getting it all to work. My problems are
a) getting named routes in my acceptance/integration tests (rspec and test::unit seem to automatically include them but no go with minitest),
b) and the overall lack of adoption in rails makes me uneasy (everyone seems to be using rspec though it's used more with gems/libraries).
Is it worth using minitest when rspec has the main dominance with testing rails applications?
A: I did some work last days to make testing Rails with minitest much straightforward. Please look at http://rawonrails.blogspot.com/2012/01/better-way-of-testing-rails-application.html to find more.
A: The minitest-rails gem makes this easy.
A: I'm the author of minitest-rails. Things have changed a lot from the time you originally asked this to now. My answer assumes you're using minitest-rails.
Named Routes
If you are using minitest-rails this just works (now). You can use the generators to create these tests, or write them yourself. All the named routes are available in your acceptance/integration tests.
require "minitest_helper"
describe "Homepage Acceptance Test" do
it "must load successfully" do
get root_path
assert_response :success
end
end
Adoption
I think we will continue to see increased attention on using Minitest with Rails as we get closer to Rails 4.
Worth it?
I think starting with Minitest now is totally worth it. There is tremendous activity going on in Minitest right now. It aligns nicely with the recent focus on fast tests as well. But it really depends on your app and team dynamics.
A: I recently switched an application from Rspec to Minitest & it was well worth it. Tests run much faster, the syntax encourages smarter, leaner code, & somehow I just have more confidence in the suite now (less magic at work).
The improvement extends to integration/acceptance testing, I find Minitest with Capybara much more readable & straightforward than Cucumber (& much less brittle).
Below is a helper file that should be all you need to get unit, functional & integration tests running with Minitest using spec syntax. This was based on a gist by @tenderlove & a lot of reading/experimentation. Notes & caveats below.
ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rubygems'
gem 'minitest'
require 'minitest/autorun'
require 'action_controller/test_case'
require 'miniskirt'
require 'capybara/rails'
require 'mocha'
require 'turn'
# Support files
Dir["#{File.expand_path(File.dirname(__FILE__))}/support/*.rb"].each do |file|
require file
end
class MiniTest::Spec
include ActiveSupport::Testing::SetupAndTeardown
alias :method_name :__name__ if defined? :__name__
end
class ControllerSpec < MiniTest::Spec
include Rails.application.routes.url_helpers
include ActionController::TestCase::Behavior
before do
@routes = Rails.application.routes
end
end
# Test subjects ending with 'Controller' are treated as functional tests
# e.g. describe TestController do ...
MiniTest::Spec.register_spec_type( /Controller$/, ControllerSpec )
class AcceptanceSpec < MiniTest::Spec
include Rails.application.routes.url_helpers
include Capybara::DSL
before do
@routes = Rails.application.routes
end
end
# Test subjects ending with 'Integration' are treated as acceptance/integration tests
# e.g. describe 'Test system Integration' do ...
MiniTest::Spec.register_spec_type( /Integration$/, AcceptanceSpec )
Turn.config do |c|
# use one of output formats:
# :outline - turn's original case/test outline mode [default]
# :progress - indicates progress with progress bar
# :dotted - test/unit's traditional dot-progress mode
# :pretty - new pretty reporter
# :marshal - dump output as YAML (normal run mode only)
# :cue - interactive testing
c.format = :cue
# turn on invoke/execute tracing, enable full backtrace
c.trace = true
# use humanized test names (works only with :outline format)
c.natural = true
end
Notes
*
*Geared for use in Rails 3.1 or 3.2. Haven't tried below that.
*gem 'minitest' is necessary to get some more advanced Minitest functionality (let blocks, etc.)
*This uses mocha (fuller mocks/stubs), miniskirt (factory_girl lite), & the new turn runner. None of these are dependencies.
*As of Rails 3.2, nested describe blocks in controller tests throw an error
A: Coding Ningja's "MiniTest::Spec setup with Capybara in Rails 3.1" helped a lot with integrating Minitest with Rails.
http://code-ningja.posterous.com/73460416
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: How to internationalize data that came from Database? I have a ASP.NET MVC Website that relys on resource files for UI internationalization.
Some data in the database will be generated by useres (in their language), but some data is generated by me and users shouldn't edit it. For that system data, I would need to store just a "token" in database and translate it at the moment of diplay it to the user in his language.
I really don't like the idea of having the translation in the database, and join every text column with the translation tables.
What are my alternatives to accomplish this?
May be an hybrid of DB and resources?
EDIT: The number of languages is indeterminated, for now we are working with 3 languages, but I hope we could need many other.
EDIT 2: This is mainly for Catalog data... some catalogs have system and user data in the same table. System data needs translation as is not editable by the user.
A: You could actually store just the identifiers in the database and resolve them to language content from Resource Files (regular *.resx) at runtime.
Although in such case it quite does not make sense to store this in the database at all (just using resource files would suffice). And of course maintaining this would be a nightmare (you would need to actually synchronize contents of the database with resource files).
Other than that, you could actually create your own Resource Manager to read the contents from the database, and put translations along with identifiers - in such case, your primary key would need to be defined on both resource identifier and language (I think it is called compound key, isn't it?):
---------------------------------------------------------
| Id | Locale | Translation |
---------------------------------------------------------
| 1 | en-US | Something happened on the way to heaven |
| 1 | pl | Coś się stało na drodze do nieba |
---------------------------------------------------------
But it would require modifying Database Schema...
A: I'm not clear reading your post whether you are maintaining user-generated content together with your own localizable content in the same DB table. If that's the case, it sounds like you should consider separating them.
If your own content is stable (i.e. you won't be adding new content or changing it between deployments of updates of your app), then it should live in your localizable resources rather than in the database and you should treat it just like your localized UI.
If on the other hand it is dynamic content, then there seems to be no alternative to storing it in the DB. You would need to store a content ID as well as a language ID for each (the compound key Paweł Dyda refers to) in a separate localization table that provides the translated versions of each content. Or perhaps you could rely on a multilingual CMS to manage this multilingual content (see for example the WPML plug-in for WordPress)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: YouTube Grid Gallery: How can I get the player to appear in a popup? I'm using the following code:
<head>
<script type="text/javascript" src="http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js"></script>
<script type="text/javascript">
function loadVideo(playerUrl, autoplay) {
swfobject.embedSWF(
playerUrl + '&rel=1&border=0&fs=1&autoplay=' +
(autoplay?1:0), 'player', '290', '250', '9.0.0', false,
false, {allowfullscreen: 'true'});
}
function showMyVideos2(data) {
var feed = data.feed;
var entries = feed.entry || [];
var html = ['<ul class="videos">'];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var title = entry.title.$t.substr(0, 15);
var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url;
var playerUrl = entries[i].media$group.media$content[0].url;
html.push('<li onclick="loadVideo(\'', playerUrl, '\', true)">',
'<span class="titlec">', title, '...</span><br /><img src="',
thumbnailUrl, '" width="130" height="97"/>', '</span></li>');
}
html.push('</ul><br style="clear: left;"/>');
document.getElementById('videos2').innerHTML = html.join('');
if (entries.length > 0) {
loadVideo(entries[0].media$group.media$content[0].url, false);
}
}
</script>
</head>
<body>
<div id="playerContainer" style="width: 20em; height: 180px; float: left;">
<object id="player"></object>
</div>
<div id="videos2"></div>
<script
type="text/javascript"
src="http://gdata.youtube.com/feeds/users/yerface/uploads?alt=json-in-script&callback=showMyVideos2&max-results=9">
</script>
</body>
</html>
which is found here:http://groups.google.com/group/youtube-api-gdata/browse_thread/thread/f3994f8078d20fe6.
What is the easiest way to have the player appear in a popup? I've been playing around with CSS options, using visible and display, but I can't seem to get it correct. Any tips for a newbie would be greatly appreciated, thanks!
A: If you want the player to be displayed on top of your content you could use position: absolute; in your CSS which takes it out of the document content flow. Then you use the top and left rules to place it where you like. Since you already know the dimensions of your popup, you can center it using javascript to calculate the top and left positions.
Good luck,
Per Flitig
Netlight Consulting
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: On a web server, when is it worth it to do asychronous I/O? I'm working on a web site that is expected attract a large number of users within a short time, and we want to minimize the number of servers required on the farm. Handling requests can involve local I/O, sql server requests to a single db server, and http requests to an external website. My first thought was that we definitely need to implement all I/O asynchronously, but after some more reading I'm not as certain.
I understand that asynchronous calls to a sql server can simply move the bottleneck to the db server. Since our db requests should be fast anyway, it might be better to keep them synchronous so that requests queue up across multiple web servers instead of the single db server.
For accessing the local file system, I suspect the same thing might also be true (just moving the bottleneck further down into the OS.) Would there be a good reason to do local file I/O asynchronously for reading/writing one or two files that are 25K-150K in size per web request?
Accessing external websites is the one case where asynchronous requests might still make sense. The external service is not likely to become a bottleneck (it is much more scalable than our site needs to be), and will introduce longer delays (compared to db and local files) since the connection is across the Internet. This should also be a relatively rare situation, maybe 5 percent of all requests.
I don't have enough experience to have a good "gut feeling" on these issues, and while we will need to do some performance testing, we don't have time to extensively test all the possible implementations.
It probably doesn't make a difference, but the software stack in this case is ASP.Net MVC 3 and Sql Server.
For a sense of the scope, we need to be ready for around 10 million users over two weeks, probably with an early spike. The site involves uploading and returning files of around 150K, and maintaining some simple records in a db. We're hosting it behind a CDN, but my concern is mostly with the file and db I/O, and the calls to an external website.
Any thoughts on where asynchronous calls would actually help in this application?
A: Async helps if you wait for a long time. E.g. you start a request via http or socket to a service and wait 15 seconds for response. In this case it makes no sense to block a thread for waiting as more threads are required which costs context switches and cost a lot of memory.
in the case of databases async makes sense for writing statistic records, where you have a fire and forget and dont wait for the response. In any other case i would analyze why the db is too slow that you think you require async.
normally i would say, async stuff heavily increases complexity, and in my personal experience it was in many cases not worth the effort. I would optimize everywhere else, using caching etc before going async.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Error: The navigation property of type 'MVCApp.Models.Order' is not a single implementation of 'System.Collections.Generic.ICollection`1[T]' Q: How can I access the following OrderStatusType within my Order object (both in my controller and razor view...using mvc3/ef4.1/.edmx)? The following code throws the error specified in the Title.
-- Controller Code (errors):
public ViewResult Details(int id)
{
Order o = db.Orders.Find(id);
OrderStatusType os = o.OrderStatusType; // <= This is throwing!
return View(o);
}
-- Model:
public class Order
{
public int OrderId { get; set; }
public int Desc { get; set; }
public int OrderStatusTypeId { get; set; }
public virtual OrderStatusType OrderStatusType { get; set; } // Order contains an OrderSTatusType
}
public class OrderStatusType
{
public int OrderStatusTypeId { get; set; }
public int Name { get; set; }
}
-- Razor (errors):
<div class="display-field">
@Model.OrderStatusType.Name @* This throws the same error as well *@
</div>
A: Try dropping the Order and OrderStatusType tables from your edmx file, then re-adding them.
A: I think you are missing the following in your OrderStatusType class:
public virtual ICollection<Order> Order {get;set;}
I have called the property Order but it should be called in the same way as that end on the relationship
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: implementing apt in MobileSafari Does anyone know how to use APT on a website, so respringing, installing/uninstalling .debs, etc work like Cydia, but just on a web browser?
A: There isn't really any App Store like package manager for the web. There is Webmin though, which has a built-in package manager frontend to apt.
https://doxfer.webmin.com/Webmin/Software_Packages
Edit: look into https://github.com/linuxappstore/linuxappstore as it might be what you are looking for.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Accessing youtube services from php I am completely new to php. I am trying to build a system to upload videos to youtube and preserve their URL. Another flash application later combines them. I am clearing the target so that i can be assured that the library can perform these tasks.
1) upload on a default channel
2) get video url
3) download video for offline viewing
I found the zend library which is used with php by googling. But facing a lot problem. I am using WAMP. I copied the zend library folder to "C:\wamp\www\zend" and changed the php.ini here
; Windows: "\path1;\path2"
include_path = ".;C:\wamp\www\zend\library;c:\php\includes"
feeling no change. So I am trying to test the library with this code.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_include_path('C:/wamp/library/zend/library' . PATH_SEPARATOR . get_include_path());
require_once 'zend/library/Zend/Gdata/YouTube.php';
require_once 'zend/library/Zend/Gdata/ClientLogin.php';
require_once 'zend/library/Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
$authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';
$httpClient =
Zend_Gdata_ClientLogin::getHttpClient(
$username = '[email protected]',
$password = '***',
$service = 'youtube',
$client = null,
$source = 'testphp',
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
$developerKey = 'AI3....w';
$applicationId = 'Student Collaborative Video System';
$clientId = 'Student Collaborative Video System';
$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);
$yt->setMajorProtocolVersion(2);
$videoFeed = $yt->getVideoFeed(Zend_Gdata_YouTube::VIDEO_URI);
printVideoFeed($videoFeed);
var_dump($videoFeed);
?>
THe error i currently see is
1 0.0023 375392 {main}( ) ..\testphp.php:0
2 0.0086 560192 require_once( 'C:\wamp\www\zend\library\Zend\Gdata\YouTube.php' ) ..\testphp.php:7
A: Your code worked fine for me, I just had to adjust the include path from \zend\library to X:/zend/framework/library which was where I put it on my PC. Make sure to use the full path to the framework when setting up the include path.
Then I needed to specifically include the Zend_Gdata files we would be using. Here is code that worked.
<?php
set_include_path('X:/zend/framework/library' . PATH_SEPARATOR . get_include_path());
// we must manually require these since we didn't set up the autoloader
require_once 'Zend/Gdata/YouTube.php';
require_once 'Zend/Gdata/ClientLogin.php';
$authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';
$httpClient =
Zend_Gdata_ClientLogin::getHttpClient(
$username = '[email protected]',
$password = 'mypass',
$service = 'youtube',
$client = null,
$source = 'MySource', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
$developerKey = 'myprodkey';
$applicationId = 'TestProduct';
$clientId = 'Student Collaborative Video System';
$yt = new Zend_Gdata_YouTube($httpClient, $applicationId, $clientId, $developerKey);
$yt->setMajorProtocolVersion(2);
$videoFeed = $yt->getVideoFeed(Zend_Gdata_YouTube::VIDEO_URI);
//printVideoFeed($videoFeed);
var_dump($videoFeed); // worked, printed out a list of videos in my app
A: replace
require_once 'Zend\Loader.php';
with
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trouble with OAuth 2.0 in my Facebook application evertything was running fine in my facebook application until I upgraded it to OAuth 2.0, and im not sure if im doing everything right.
The thing is that I already made the OAuth dialog to work and when the user authorizes the app, it renders my app into the iFrame, but I am having trouble with my $_GETs[], let me explain:
Here's my index.php, which I use as the main page, while i just include() some file in a div called content, depending on the $_GET['section']:
$app_id = "xxx";
$application_secret = 'xxx';
$canvas_page = "xxx";
$auth_url = "http://www.facebook.com/dialog/oauth?client_id=".$app_id. "&redirect_uri=".urlencode($canvas_page)."&scope=publish_stream,offline_access";
//OAuth 2.0
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
//
$data = parse_signed_request($_REQUEST["signed_request"],$application_secret);
if (empty($data["user_id"])) {
echo("<script> top.location.href='" . $auth_url . "'</script>");
} else {
$_SESSION['on'] = 1;
include ('src/facebook.php');
$files = array();
$files['RE'] = 'xxx.php';
$files['RC'] = 'yyy.php';
$files['DP'] = 'zzz.php';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $application_secret,
'cookie' => true,
'perms' => 'publish_stream, offline_access',
));
$_SESSION["access_token"] = $data["oauth_token"];
$me = $facebook->api('/me?oauth_token='.$_SESSION["access_token"]);
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" xmlns:fb="https://www.facebook.com/2008/fbml">
<link rel="stylesheet" href="css/style.css" type="text/css">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />
</head>
<body>
<div class="wrapper">
<?php include("inc/app_header.php");?>
<div class="content">
<?php
if(isset($_GET['section']))
{
$file_to_include = 'inc/'.$files[$_GET['section']];
}
else
{
$file_to_include = 'inc/section_restaurantes.php';
}
include($file_to_include);
?>
<div class="content_bottom_space"></div>
</div>
<div class="footer">
</div>
</div>
</body>
</html>
<?php } ?>
and the code for section_restaurantes is:
<div class="section_restaurantes">
<div class="restaurantes_container">
<div class="restaurantes"><a href="index.php?section=DP"></a></div>
<div class="restaurantes"><a href="index.php?section=PH"></a></div>
</div>
</div>
The thing is that when I click in those divs all my browser is reloaded, the ?code= parameter in the url changes twice and it reloads again on section_restaurantes.php, instead of loading the DP section, I hope I'm clear.
I think because its reloading twice i loose the $_GET['section'] parameter and then it loads the default which is "inc/section_restaurantes.php"
I need help please, I've tried to find solutions on the internet but I found nothing.
A: You don't need to parse the signed_request if you are using the PHP-SDK as it'll take care of that for you. You just need to retrieve the user (getUser()) and if no user, redirect to the login url (refer to the example file).
Here is a better code:
<?php
include ('src/facebook.php');
$app_id = "xxx";
$application_secret = 'xxx';
$canvas_page = "xxx";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $application_secret
));
$user = $facebook->getUser();
if(!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'redirect_uri' => $canvas_page,
'scope' => 'publish_stream,offline_access'
));
echo("<script> top.location.href='" . $loginUrl . "'</script>");
exit;
}
$_SESSION['on'] = 1;
$files = array();
$files['RE'] = 'xxx.php';
$files['RC'] = 'yyy.php';
$files['DP'] = 'zzz.php';
try {
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" xmlns:fb="https://www.facebook.com/2008/fbml">
<link rel="stylesheet" href="css/style.css" type="text/css">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />
</head>
<body>
<div class="wrapper">
<?php include("inc/app_header.php");?>
<div class="content">
<?php
if(isset($_GET['section']))
{
$file_to_include = 'inc/'.$files[$_GET['section']];
}
else
{
$file_to_include = 'inc/section_restaurantes.php';
}
include($file_to_include);
?>
<div class="content_bottom_space"></div>
</div>
<div class="footer">
</div>
</div>
</body>
</html>
Now for your restaurant section, I would link to the parent document:
<div class="section_restaurantes">
<div class="restaurantes_container">
<div class="restaurantes"><a href="<?php echo $canvas_page; ?>?section=DP" target="_top"></a></div>
<div class="restaurantes"><a href="<?php echo $canvas_page; ?>?section=PH" target="_top"></a></div>
</div>
</div>
Assuming your $canvas_page is the intended destination.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Eclipse: The declared package does not match the expected package I have a problem importing an external project. I go File -> Import... -> Existing Projects into Workspace, choose the folder where the project is located and everything is imported - but the package names of the project don't seem to be what Eclipse expects. The package names all have a prefix:
prefix.packagename1
prefix.packagename2
etc.
But Eclipse expects
src.prefix1.prefix.packagename1
src.prefix1.prefix.packagename2
etc. because the directory is src/prefix1/prefix/package1
I don't really want to mess around with external code. How do I tell Eclipse to ignore the directory "src/prefix1"? Or what else can I do?
A: I just ran into this problem, and since Mr. Skeet's solution did not work for me, I'll share how I solved this problem.
It turns out that I opened the java file under the 'src' before declaring it a source directory.
After right clicking on the 'src' directory in eclipse, selecting 'build path', and then 'Use as Source Folder'
Close and reopen the already opened java file (F5 refreshing it did not work).
Provided the path to the java file from "prefix1" onwards lines up with the package in the file (example from the requester's question prefix1.prefix.packagename2). This should work
Eclipse should no longer complain about 'src.'
A: If you have imported an existing project, then just remove your source folders and then add them again to build path, and restart eclipse. Most of the times eclipse will keep showing the error till you restart.
A: The only thing that worked for me is deleting the project and then importing it again. Works like a charm :)
A: Move your problem *.java files to other folder.
Click 'src' item and press "F5".
Red crosses will dissaperar.
Return your *.java files to "package path", click 'src' item and press "F5".
All should be ok.
A: Just go into the build path and change the source path to be src/prefix1 instead of src.
It may be easiest to right-click on the src directory and select "Build Path / Remove from build path", then find the src/prefix1 directory, right-click it and select "Build Path / Use as source folder".
A: Happens for me after failed builds run outside of the IDE. If cleaning your workspace doesn't work, try: 1) Delete all projects 2) Close and restart STS/eclipse, 3) Re-import the projects
A: Suppose your project has a package like
package name1.name2.name3.name4 (declared package)
Your package explorer shows
package top level named name1.name2
sub packages named name3.name4
You will have errors because Eclipse extracts the package name from the file directory structure on disk starting at the point you import from.
My case was a bit more involved, perhaps because I was using a symbolic link to a folder outside my workspace.
I first tried Build Path.Java Build Path.Source Tab.Link Source Button.Browse to the folder before name1 in your package.Folder-name as you like (i think). But had issues.
Then I removed the folder from the build path and tried File > Import... > General > File System > click Next > From Directory > Browse... to folder above name1 > click Advanced button > check Create links in workspace > click Finish button.
A: I get this problem in Eclipse sometimes when importing an Android project that does not have a .classpath file. The one that Eclipse creates is not exactly the same one that Android expects. But, the Android .classpath files are usually all relative, so I just copy a correct .classpath file from another project over the incorrect .classpath. I've created a video that shows how I do this: https://www.youtube.com/watch?v=IVIhgeahS1Ynto
A: Go to src folder of the project and copy all the code from it to some temporary location and build the project. And now copy the actual code from temporary location to project src. And run the build again. Problem will be resolved.
Note: This is specific to eclipse.
A: I happened to have the same problem just now. However, the first few answers don't work for me.I propose a solution:change the .classpath file.For example,you can define the classpathentry node's path like this: path="src/prefix1/java"
or path="src/prefix1/resources".
Hope it can help.
A: For me the issue was that I was converting an existing project to maven, created the folder structures according to the documentation and it was showing the 'main' folder as part of the package. I followed the instructions similar to Jon Skeet / JWoodchuck and went into the Java build path, removed all broken build paths, and then added my build path to be 'src/main/java' and 'src/test/java', as well as the resources folders for each, and it resolved the issue.
A: The build path should contain the path 'till before' that of the package name.
For eg, if the folder structure is: src/main/java/com/example/dao
If the class containing the import statement'package com.example.dao' complains of the incorrect package error, then, the build path should include:src/main/java
This should solve the issue.
A: *
*Right click on the external folder which is having package
src.prefix1.prefix.packagename1
src.prefix1.prefix.packagename2
*Click Build path --> Remove from build path.
*Now go the folder prefix1 in the folder section of your project.
*Right click on it --> Build path --> Use as source folder.
*Done. The package folder wont show any error now. If it still shows, just restart the project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "89"
} |
Q: Get item of ListActivity ListActivity always has corresponding ListView element, right? So, has it any method to get list item by index or I have to get ListView instance manually using findViewById and get item from it?
EDIT:
I want to change text of list item in code.
A: The way to go about this is a little different than what you might expect. Rather than trying to get the view and change its text, you should retrieve the data from your adapter and update it. After that, you may need to reset the adapter that your ListActivity uses.
To get the adapter, you need to first call ListActivity.getListAdapter. Once you have the Adapter, you can call Adapter.getItem to get the data at a specific position.
A: Obviously depending on your adapter you'd use different casting etc, but as an example with a ListView in an ListActivity:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new String[] { "One", "Two", "Three" });
// One, two, three
setListAdapter(adapter);
// Display "Two" (specified by index with `getItem`).
Toast.makeText(this, "Element two is: " + (String)getListAdapter().getItem(1), Toast.LENGTH_SHORT).show();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Apple Movie Player sample resize I'm using Movie Player to see video streaming in my ipod. But the video is always bigger than the screen. How I can resize the video view? I have tried to put frame size in a lot of places, but without sucess..
I appreciate all of tips and helps.
A: try this
MPMoviePlayerViewController * moviePlayerVC = [[MPMoviePlayerViewController alloc]initWithContentURL:Video URL String];
moviePlayerVC.moviePlayer.allowsAirPlay = YES;
moviePlayerVC.view.frame = CGRectMake(10, 50, 300, 300);
moviePlayerVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self.view addSubview:moviePlayerVC.view];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery Mobile: Getting ID of previous page I basically need a custom function to be used only when, for example, the #reviews page is clicked on from the home page.
Here is the current code I am using:
$(document).bind("mobileinit", function(){
$('#reviews').live('pagebeforeshow',function(event){
var cpage = $.mobile.activePage.attr('id');
if (cpage == 'home') {
addPages();
}
});
});
The problem is, even though it is using 'pagebeforeshow' it is using the id of the page it is about to transition to as the active page, in this case 'reviews' rather than home, thus causing the if statement to fail.
So my question is, in this example, how would i get the id of the previous page, to make sure it is in fact coming from the #home page?
A: pagebeforeshow event handler actually gets 2 params: event and ui. You can access the previous page from the ui. This is an example from jquery-mobile event docs:
$('div').live('pageshow', function(event, ui){
alert( 'This page was just hidden: '+ ui.prevPage);
});
Those params are the same for all 4 page show/hide events.
A: To complete the answer: you will get a jQuery object back, so to get the ID of the page do this:
$("#page-id").live('pagebeforeshow', function(event, data) {
console.log("the previous page was: " + data.prevPage.attr('id'));
});
data.prevPage is getting the previous page as jQuery object,
.attr('id') is getting the id from that jQuery object.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Hidden Markov Model predicting next observation I have a sequence of 500 observations of the movements of a bird. I want to predict what the 501st movement of the bird would be. I searched the web and I guess this can be done by using HMM, however I do not have any experience on that subject. Can anyone explain the steps of an algorithm used to solve this problem?
A: x1-x2-x3-x4-x5......x500-x501
| | | | | |
y1 y2 y3 y4 y5 y500
x - actual state
y - observations
P(y_i|x_i) - how you think the observation depends on the actual state
P(x_i|x_(i-1)) - how you think the actual state evolves
for i = 1,2,3...,501:
write down best-guess of x_i based on y_i* and x_(i-1)**
you have your solution, since you only care about the last state
* missing in step 1
** missing in step 501
The above is known as the forward-backward algorithm ( http://en.wikipedia.org/wiki/Forward-backward_algorithm ) and is a special case of the sum-product algorithm (on Bayesian network trees and Markov network trees) on this particular kind of tree (a simple chain with nodes hanging off). You can ignore the "backwards" step because you don't need it, since you only care about the last state.
If the transition probabilities in your HMM are unknown, you must either:
*
*perform a learning algorithm, such as EM (known as Baum-Welch when performed on HMMs)
*take a naive guess based on domain knowledge (e.g. if your hidden states is DNA you can count the frequencies of transition events given the previous state by manually labeling the transitions on DNA data and computing the frequencies)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Content Rotator With Content Management I am developing a website that will have content rotator in one of the pages. The only dynamic part of the website will be the news part. I want to add a content management page for the news. The news items will be edited by the user and will be published. The rest of the website wont be affected.
There are many free content sliders but unfortunately none of the ones i found has a content management system. I am developing the website in asp .net. I dont want to use a very big content management system for such a small job. Is there any free or commercial with a small price product that can fullfil my requirements ?
Thanks
A: Yes, you can find via my profile link that I made for programmers. There are other great ones too like Page Lime which is great for designers. You could try some open source ones for ASP.NET like Orchard CMS or DotNetNuke. It all depends on your comfort level. I do prefer the cloud ones myself but I'm a bit impartial as I hate installing things and having to learn frameworks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Alternate way to retrieve data from core data database - ios I am having performance issues while retrieving data from the database.
Right now, this is how I do it.
+(NSMutableArray *) searchObjectsInContext: (NSString*) entityName : (NSPredicate *) predicate : (NSString*) sortKey : (BOOL) sortAscending
{
i3EAppDelegate *appDelegate = (i3EAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
[request setEntity:entity];
[request setFetchBatchSize:5];
//[request setFetchLimit:10];
[request setReturnsObjectsAsFaults:NO];
// If a predicate was passed, pass it to the query
if(predicate != nil)
{
[request setPredicate:predicate];
}
// If a sort key was passed, use it for sorting.
if(sortKey != nil)
{
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
}
NSError *error;
NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
// NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
exit(-1); // Fail
}
[request release];
//[context release];
appDelegate = nil;
return [mutableFetchResults autorelease];
}
Is there any other way to perform the same operation but in a faster way?
If so, it would be great if someone could help me out in this.
A: Ask yourself a couple of questions about your data requirements.
Do you need access to all the results at once? If you only need a small number at a time you could retrieve only the NSManagedObjectID's:
[request setResultType:NSManagedObjectIDResultType];
This will be very quick and give you a sorted list, but you'll have to retrieve the actual data as required.
If you need the data a bit faster you could retrieve faulted NSManagedObject's
[request setIncludesPropertyValues:NO];
This will allocate the objects in advance, but won't fetch the actual data until you request it.
Alternatively do you need to perform the sort as part of the fetch, or if could you somehow do it quicker once the objects are in memory?
It is worth creating yourself a test harness and trying the various options to see which are most suitable for your application.
A: There are a few issues:
*
*You do not have a predicate. Therefore you are retrieving the entire table. That is probably your single biggest issue.
*You are loading all of the full objects on retrieval. This is going to slow things down considerably. If you do not need the entire objects realized then I would suggest turning -setReturnsObjectsAsFaults: back on.
*The setting of -setFetchBatchSize: is probably not having the effect you are expecting. If you want to limit the number of results returned use -setFetchLimit:
*Making a -mutableCopy of the NSArray results has no value. I suspect you got that from a book and recommend you stop doing it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use two dialogs within a single preference selection I want to create a sound preference that works like the sound selection in the alarm and timer application. In short, the preference starts with a standard list preference, but once the music or ring tone selection is made, another dialog is displayed allowing the audio to be chosen.
Is my only option to create a custom preference handler ? Can I capture the initial list preference change and then present the handler for the audio ?
A: Here's my solution. I extended ListPreference with my own class. When the dialog is closed, I then call a chooser for the audio list. When the choose completes, the custom, parent PreferenceActivity is called.
Relevant code bits:
public class AlertBehaviorPreference extends ListPreference {
...
public void onDialogClosed(boolean positiveResult)
{
super.onDialogClosed(positiveResult);
if(positiveResult)
{
String s = this.getValue();
if(s != null && s.equals(SONG_ALARM_ACTION)) // play song
{
// Get the parent activity.
// This activity will be notified when the audio has been selected
PreferenceActivity pActivity = (PreferenceActivity)this.getContext();
// Select a recording
Intent i = new Intent(pActivity, pActivity.getClass());
i.setAction(Intent.ACTION_GET_CONTENT);
i.setType("audio/*");
pActivity.startActivityForResult(Intent.createChooser(i, "Select song"), 1);
Log.d(TAG, "Started audio activity chooser");
}
public class MyPreferenceActivity extends PreferenceActivity {
...
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Call back into the preference to save data
// Where the result can be validated and settings can be
// be reset if the user cancelled the request.
((AlertBehaviorPreference)(findPreference("alertBehaviorPreference"))).onSongActivitySelectionComplete(data);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Information from local DB and external source in one view Situation:
The simplified situation is this: consider a blog that is build as an MVC project. The YII blog-example is fine for this, but the question is not framework specific: It is nothing special; you have a table with posts and a page build from:
*
*a model (YII will give you a basic active-record setup)
*a controller that for instance builds the index (list of all posts)
*a view (or some views) that build the actual HTML in the end.
Now I have a working blog, but I also have an external source of information that I want to introduce to this same page: for example an RSS feed.
How do I add this new datasource?
Possible sollutions
To clarify what I am struggling with, here are some things I am considering
*
*Make a new model that gets its information from both sources
*
*Feels like the way of least resistance/work
*It would need to sort the blogposts and RSS items by date
*It might need to give some sort of flag about what kind of item it is (An RSS item might not have an author, but it does have a source).
*The fact that above flag feels neccessairy makes me believe these should be 2 models.
*Make a new model for the RSS and make a controller that combines the two sources and feeds it to a view that can handle both types of post
*Something more complicated (maybe more framework specific), but the current view of a post is just one view for one post, and it gets repeated. Instead of one view that handles both types you might want not only a model, but also a view for your RSS, and a controller(?) that does all the mixing and matching?
Framework notes:
I'm using YII, but it's not really about YII. Ofcourse if something complicated is to be done I will have to implement it in YII, but it's about the design and the MVC pattern, not about where to put the ; ;D
A: If i had to do it, i would make a new controller for the view, and use two models.
*
*I am very new to the mvc pattern, however from what i have gathered till now, it feels like any model should limit itself to only one data source. Also in addition to the CRUD operations, the "business logic" (if any) , should be included within that model. Business logic here would mean logic that applies to the data source pertaining to the web app, i.e the things that you have mentioned, like sorting RSS by date.
*Create a controller that accesses these two models, to populate your view(s).
*Finally the best way to organize these components/modules/parts of the mvc, with respect to Yii, depends on your app requirements, and ux.
Now, i think you should put this question in the programmers site also.
Hope this helps!
Edit: Not too sure where to put the sorting, controller or view.
A: u can hve something like this (I too use yii so the following code follows yii framework)
class XyzController extends CController
{
.
.
.
public function actionAbc()
{
.
.
.
$this->render('viewname',array(
'model1'=>$model1,//for posts frm table
'model2'=>$model2 //for rss feed
));
}
}
for better understanding try to render two separate views for each type of post inside the parent view "viewname"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Incorrect subscription when using two delegates with single event Hello guys I'm getting some troubles using delegates to subscript to same event trought two forms (parent and child), this is my code :
public delegate void SplitDelegate(object s, ControllerEventArgs e);
public delegate void SetBatchDelegate(object s, ControllerEventArgs e);
public class ControllerEventArgs : EventArgs
{
public string sp1;
public int ip1;
public int ip2;
public ControllerEventArgs(string sp1)
{
this.sp1 = sp1;
}
public ControllerEventArgs(int p1, int p2)
{
this.ip1 = p1;
this.ip2 = p2;
}
public ControllerEventArgs(string sp1, int p1, int p2)
{
this.sp1 = sp1;
this.ip1 = p1;
this.ip2 = p2;
}
}
public interface IController
{
event SplitDelegate splitRowEvent;
event SetBatchDelegate setSmallBatchEvent;
void InvokeControllerEvent(string p1);
void InvokeControllerEvent(int p1, int p2);
void InvokeControllerEvent(string sp1, int p1, int p2);
}
public class Controller : IController
{
public event SplitDelegate splitRowEvent;
public event SetBatchDelegate setSmallBatchEvent;
public void InvokeControllerEvent(string p1)
{
this.OnControllerEvent(new ControllerEventArgs(p1));
}
public void InvokeControllerEvent(int p1, int p2)
{
this.OnControllerEvent(new ControllerEventArgs(p1, p2));
}
public void InvokeControllerEvent(string sp1, int p1, int p2)
{
this.OnControllerEvent(new ControllerEventArgs(sp1, p1, p2));
}
protected virtual void OnControllerEvent(ControllerEventArgs e)
{
if (this.splitRowEvent != null)
{
this.splitRowEvent.Invoke(this.splitRowEvent, e);
}
if (this.setSmallBatchEvent != null)
{
this.setSmallBatchEvent.Invoke(this.setSmallBatchEvent, e);
}
}
}
For example, when I call in Form A :
frmFormB.controller.InvokeControllerEvent("ugPER");
Both invokations are processed when I just want to use the first one SplitRowEvent
Is there a way to remake my code using the correct syntax for get the correct callback?
Added for best explanation :
button1_click :
SmallBatchSplitSetRows frmModal = new SmallBatchSplitSetRows(this.controller);
frmModal.controller.InvokeControllerEvent("ugFAB");
frmModal.ShowDialog();
button2_click :
SmallBatchSplitInput frmModal = new SmallBatchSplitInput(this.controller);
frmModal.controller.InvokeControllerEvent("ugPER");
frmModal.ShowDialog();
A: Your OnControllerEvent method explicitly calls uses splitRowEvent and setSmallBatchEvent. If you don't want it to, just change the contents of the method.
Ultimately it's not clear why you've got two different events but only one way of invoking them, via three overloads. Are the three overloads meant to do different things? Is each one meant to call a different set of event handlers? This is where using descriptive names instead of overloading would be really helpful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: seek in http connection when downloading with python I have actually two questions in one. Firstly, does http protocol allows seeking. If the wording is incorrect, what I mean is this: for example, there is file accessible through http request in some server. File's size is 2 gb. Can I retrieve only last 1 gb of this file using http. If this can be done, how to do it in Python. I am asking this, because I am considering writing a Python script to download same file with paralel connections, and combining the outcome.
A: The http protocol defines a way for a client to request part of the resource see http://www.w3.org/Protocols/rfc2616/
Since all HTTP entities are represented in HTTP messages as sequences
of bytes, the concept of a byte range is meaningful for any HTTP
entity. (However, not all clients and servers need to support byte-
range operations.)
Therefore in theory, you could specify a range header to specify which part of the file you want, however the server might just ignore the request. Therefore you need to configure the server to supports byte range.
Sorry cant provide you with a code sample, I have never worked in python but this information should be sufficient to get you started. If you need further help, please ask.
A: HTTP lets you request a "range" of bytes of a resource, this is specified in the HTTP/1.1. RFC. Not every server and not every resource might support range retrieval and may ignore the headers. The answer to this question has some example code you could look at.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sort NSDictionaries in NSMutableArray by NSDate I have a NSMutableArray with dictionaries, all of the dict's contain a NSDate is form of NSString with key 'Date'. I want to sort the NSDictionaries by the Dates. So for example i have the following state of the array:
Dict
Date
20.06.1996 23:30
Dict
Date
04.10.2011 19:00
Dict
Date
20.06.1956 23:39
And I want to sort it, so that it looks like this:
Dict
Date
20.06.1956 23:39
Dict
Date
20.06.1996 23:30
Dict
Date
04.10.2011 19:00
I have already experimented with NSSortDescriptor, but without success...
Update:
I have managed to sort the dates, but I came to this problem: In the dicts there is not only dates, also other objects, and what my code does is it only switches the date values between the dicts, instead of switching the complete dicts around. With this, the other values in the dicts get assigned a wrong date, which is very bad. Can anybody help me? Heres my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"savedData.daf"];
NSMutableArray *d = [NSMutableArray arrayWithContentsOfFile:path];
for (int ii = 0; ii < [d count]; ii++) {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
if (is24h) {
[dateFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
}
else {
[dateFormatter setDateFormat:@"dd.MM.yyyy hh:mm a"];
}
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *dat = [dateFormatter dateFromString:[[d valueForKey:@"Date"] objectAtIndex:ii]];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[d objectAtIndex:ii];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:dat forKey:@"Date"];
[d replaceObjectAtIndex:ii withObject:newDict];
[newDict release];
}
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"Date" ascending:YES];
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];
[sorter release];
NSMutableArray *sorted = [NSMutableArray arrayWithArray:[d sortedArrayUsingDescriptors:sorters]];
[sorters release];
NSLog(@"%@",sorted);
for (int ii = 0; ii < [sorted count]; ii++) {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
if (is24h) {
[dateFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
}
else {
[dateFormatter setDateFormat:@"dd.MM.yyyy hh:mm a"];
}
[dateFormatter setLocale:[NSLocale currentLocale]];
NSString *sr = [dateFormatter stringFromDate:[[sorted valueForKey:@"Date"] objectAtIndex:ii]];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[d objectAtIndex:ii];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:sr forKey:@"Date"];
[sorted replaceObjectAtIndex:ii withObject:newDict];
[newDict release];
}
NSLog(@"before: %@"
""
"after: %@",d,sorted);
[sorted writeToFile:path atomically:YES];
A: There are many ways to do this, one would be to use NSDate objects instead of NSStrings (or NSStrings formatted according to ISO 8601, so that the lexicographic sort would match the desired sorting). Then you could do:
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"Date"
ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];
Or, if you can't (or don't want to) change your data, you can always sort using a block:
[array sortUsingComparator:^(id dict1, id dict2) {
NSDate *date1 = // create NSDate from dict1's Date;
NSDate *date2 = // create NSDate from dict2's Date;
return [date1 compare:date2];
}];
Of course this would probably be slower than the first approach since you'll usually end up creating more than n NSDate objects.
A: There are a couple of options, one is to put NSDate objects in the dictionary.
One problem with comparing the strings is that you can 't just do a string compare because the year is not in the most significant potion of the string.
So, you will need to write a comparison method to use with:
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr
or perhaps:
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context
The comparator will need to handle the dd.mm.yyyy hh:mm string format.
Other options include adding another dictionary key with an NSDate representation and sorting on that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: getFont() method I just wanted to ask a question about the getFont() method, which is in java.awt.Font. I don't understand why the getStyle() is undefined for type string, although it actually should work with strings. In API it says it takes an integer as argument.
import java.awt.Font;
//import java.util.*;
public class NotEqual
{
public static void main(String[] args)
{
//Scanner input = new Scanner(System.in);
//System.out.println("Write something ");
String sentence = "The sentence";
//int x = 2;
//System.out.println(sentence.getFont());
//System.out.println(sentence.getSize());
//System.out.println(sentence.getStyle());
System.out.println(sentence.getFont());
}
}
A: Style is a integer, defined by the constants Font.PLAIN, Font.BOLD, or Font.ITALIC.
From the docs:
Returns the style of this Font. The style can be PLAIN, BOLD, ITALIC, or BOLD+ITALIC.
It is never a string. A string is not one of the accepted values. (It never has been.)
A: Your code won't work because Strings don't have fonts. Period. All they are are lists of chars with supporting methods and properties, but no font. To see what methods you can call on String, look at the API as that is the final arbitrator of what you can and cannot do with them. In fact, if you search the text of the String API, you won't even find the word "font" present anywhere.
I still don't understand the part about it "In API it says it takes an integer as argument" though.
A: One reason might be that the int return value is easier to interpret than either BOLD+ITALIC or ITALIC+BOLD (same style, same int, different String).
Noting also that arguments can be overloaded but return types cannot, it could be argued that the int is the better value to return.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to show compass on Screen? I am new to iOS development. My objective is to show a compass on Screen. I have a latitude and longitude of a certain location. I have gotten my current latitude and longitude by using CLLocation.
I have calculated the distance between two points using an API, but now I want to know the correct direction of my phone N/S/E/W and something like according to correct north pole... I am not sure.
Is there some concept of iPhone north pole and actual north pole?
I want show a line pointing towards the particular longitude and latitude, even if my phone is rotating or moving; the line points towards that point only.
Please help me, where i should proceed now?
Any guidance or links/tut will be great.
A: This is called the "heading" of a CLLocation.
See the CLLocationManager doc part to configure heading for you app and call startUpdatingHeading to be notified with your heading changes, namely when your iPhone is pointing toward another point.
Then use the standard CLLocationManagerDelegate methods to be informed of heading changes and redraw your line accordingly.
Read the Location Awareness Programming Guide for more info about Location Services and heading, especially this part that even contains sample code.
PS: About the two different north, there is no concept of "iPhone North Pole", that's nothing related the the iPhone itself. In Geographic systems, there are two north references to consider: the Magnetic North Pole, which is defined according to the earth magnetic field, and the True North Pole, which is defined according the rotational axis of the earth.
That's also explained in details in the Location Awareness Programming Guide too (like quite everything; always read Programming Guides which are great and very complete resources in general):
Heading values can be reported relative either to magnetic north or true north on the map. Magnetic north represents the point on the Earth’s surface from which the planet’s magnetic field emanates. This location is not the same as the North Pole, which represents true north. Depending on the location of the device, magnetic north may be good enough for many purposes, but the closer to the poles you get, the less useful this value becomes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can I diagnose and fix this 'uninitialized constant' error? I have a working Redmine 0.8.0 site that I'm trying to upgrade to 1.2.1 (most recent stable). I have met all listed requirements and followed their upgrade directions as far as I can, but I'm stuck at the final step before clean up - migration. Based on the evidence below, I'm guessing that part of my infrastructure (Ruby, RubyGems, or one of my gems) is not at the right version, but I can't figure out who's at fault. How can I determine the next step to fix this issue?
The upgrade directions state:
If you have installed any plugins, you should also run their database migrations. If you are upgrading from Redmine 0.8.x as part of this migration, you need to upgrade the plugin migrations first:
rake db:migrate:upgrade_plugin_migrations RAILS_ENV=production
rake db:migrate_plugins RAILS_ENV=production
running
$sudo rake --trace db:migrate:upgrade_plugin_migrations RAILS_ENV=production
gives the following error:
(in /var/www/html/redmine-1.2.1)
** Invoke db:migrate:upgrade_plugin_migrations (first_time)
** Invoke environment (first_time)
** Execute environment
rake aborted!
uninitialized constant Rails::Plugin::Dependencies
/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.11/lib/active_support/dependencies.rb:131:in `const_missing'
/var/www/html/redmine-1.2.1/vendor/plugins/redmine_google_calendar/init.rb:47:in `reloadable!'
/var/www/html/redmine-1.2.1/vendor/plugins/redmine_google_calendar/init.rb:47:in `each'
/var/www/html/redmine-1.2.1/vendor/plugins/redmine_google_calendar/init.rb:47:in `reloadable!'
/var/www/html/redmine-1.2.1/vendor/plugins/redmine_google_calendar/init.rb:51:in `evaluate_init_rb'
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/rails/plugin.rb:158:in `evaluate_init_rb'
/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.11/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/rails/plugin.rb:154:in `evaluate_init_rb'
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/rails/plugin.rb:48:in `load'
/var/www/html/redmine-1.2.1/config/../vendor/plugins/engines/lib/engines/plugin.rb:44:in `load'
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/rails/plugin/loader.rb:38:in `load_plugins'
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/rails/plugin/loader.rb:37:in `each'
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/rails/plugin/loader.rb:37:in `load_plugins'
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/initializer.rb:369:in `load_plugins'
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/initializer.rb:165:in `process'
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/initializer.rb:113:in `send'
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/initializer.rb:113:in `run'
/var/www/html/redmine-1.2.1/config/environment.rb:20
/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.11/lib/active_support/dependencies.rb:182:in `require'
/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.11/lib/active_support/dependencies.rb:547:in `new_constants_in'
/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.11/lib/active_support/dependencies.rb:182:in `require'
/usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/tasks/misc.rake:4
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:636:in `call'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:636:in `execute'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:631:in `each'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:631:in `execute'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:597:in `invoke_with_call_chain'
/usr/local/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:607:in `invoke_prerequisites'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:604:in `each'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:604:in `invoke_prerequisites'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:596:in `invoke_with_call_chain'
/usr/local/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:583:in `invoke'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2051:in `invoke_task'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `each'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2023:in `top_level'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2001:in `run'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
/home/selfsimilar/.gem/ruby/1.8/gems/rake-0.8.7/bin/rake:31
/usr/local/bin/rake:19:in `load'
/usr/local/bin/rake:19
script/about fails similarly:
$ RAILS_ENV=production script/about
/usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.11/lib/active_support/dependencies.rb:131:in `const_missing': uninitialized constant Rails::Plugin::Dependencies (NameError)
from /var/www/html/redmine-1.2.1/vendor/plugins/redmine_google_calendar/init.rb:47:in `reloadable!'
from /var/www/html/redmine-1.2.1/vendor/plugins/redmine_google_calendar/init.rb:47:in `each'
from /var/www/html/redmine-1.2.1/vendor/plugins/redmine_google_calendar/init.rb:47:in `reloadable!'
from /var/www/html/redmine-1.2.1/vendor/plugins/redmine_google_calendar/init.rb:51:in `evaluate_init_rb'
from /usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/rails/plugin.rb:158:in `evaluate_init_rb'
from /usr/local/lib/ruby/gems/1.8/gems/activesupport-2.3.11/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'
from /usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/rails/plugin.rb:154:in `evaluate_init_rb'
from /usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/rails/plugin.rb:48:in `load'
... 11 levels...
from /usr/local/lib/ruby/gems/1.8/gems/rails-2.3.11/lib/commands/about.rb:1
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from script/about:4
here's details of my environment, which, as I read the requirements page, are within spec for running Redmine 1.2.1.
$ ruby -v
ruby 1.8.6 (2008-08-11 patchlevel 287) [i686-linux]
$ gem -v
1.3.7
$ gem list --local
*** LOCAL GEMS ***
actionmailer (2.3.11)
actionpack (2.3.11)
activerecord (2.3.11)
activeresource (2.3.11)
activesupport (2.3.11)
arrayfields (4.7.0)
fastthread (1.0.1)
fattr (1.0.3)
git-rails (0.2.1)
hoe (1.8.3)
i18n (0.4.2)
main (2.8.3)
passenger (2.0.6)
rack (1.1.1)
rails (2.3.11)
rake (0.8.7)
rubyforge (1.0.2)
rubygems-update (1.5.0)
tzinfo (0.3.12)
A: The gem you are using is incompatible with your version of Rails, probably because the gem is out of date. Look around for a more up-to-date version or patch it yourself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: STI and virtual attribute inheritance (Rails 2.3) Say I have an STI relationship, where Commentable is the super class, and NewsComment is the subclass. In Commentable I have:
attr_accessor :opinionated
def after_initialize
self.opinionated = true
end
And in NewsComment:
attr_accessor :headliner
def after_initialize
self.headliner = true
end
When instantiate NewsComment, the VA self.opinionated is not inherited. Why is that? And how can you "force" NewsComment to inherit from Commentable?
A: How are you instantiating the NewsComment object? The after_initialize callback is only executed when an object is instantiated by the finder. Also, the way you are defining the method may be overriding its behavior. What if you use the DSL style method?:...
class Commentable
attr_accessor :opinionated
after_initialize do
self.opinionated = true
end
end
class NewsComment < Commentable
attr_accessor :headliner
after_initialize do
self.headliner = true
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MongoDB - How to Handle Relationship I just start learning about nosql database, specially MongoDB (no specific reason for mongodb). I browse few tutorial sites, but still cant figure out, how it handle relationship between two documents/entity
Lets say for example:
1. One Employee works in one department
2. One Employee works in many department
I dont know the term 'relationship' make sense for mongodb or not.
Can somebody please give something about joins, relationship.
A: The short answer: with "nosql" you wouldn't do it that way.
What you'd do instead of a join or a relationship is add the departments the user is in to the user object.
You could also add the user to a field in the "department" object, if you needed to see users from that direction.
Denormalized data like this is typical in a "nosql" database.
See this very closely related question: How do I perform the SQL Join equivalent in MongoDB?
A: in general, you want to denormalize your data in your collections (=tables). Your collections should be optimized so that you don't need to do joins (joins are not possible in NoSQL).
In MongoDB you can either reference other collections (=tables), or you can embed them into each other -- whatever makes more sense in your domain. There are size limits to entries in a collection, so you can't just embed the encyclopedia britannica ;-)
It's probably best if you look for API documentation and examples for the programming language of your choice.
For Ruby, I'd recommend the Mondoid library: http://mongoid.org/docs/relations.html
A: There are some instances in which you want/need to keep the documents separate in which case you would take the _id from the one object and add it as a value in your other object.
For Example:
db.authors
{
_id:ObjectId(21EC2020-3AEA-1069-A2DD-08002B30309D)
name:'George R.R. Martin'
}
db.books
{
name:'A Dance with Dragons'
authorId:ObjectId(21EC2020-3AEA-1069-A2DD-08002B30309D)
}
There is no official relationship between books and authors its just a copy of the _id from authors into the authorId value in books.
Hope that helps.
A: Generally, if you decided to learn about NoSql databases you should follow the "NoSql way", i.e. learn the principles beyond the movement and the approach to design and not simply try to map RDBMS to your first NoSql project.
Simply put - you should learn how to embed and denormalize data (like Will above suggested), and not simply copy the id to simulate foreign keys.
If you do this the "foreign _id way", next step is to search for transactions to ensure that two "rows" are consistently inserted/updated. Few steps after Oracle/MySql is waiting. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: RestKit handling different HTTP status codes I've just started to try out RestKit for an iOS app i'm building. I normally use ASIHttpRequest, but I want to test out RestKit mostly for its object mapping between JSON and CoreData. There are some great things about RestKit, but I've run into an issue that really makes it feel deficient, unless I'm doing something wrong or have missed something. I hope someone here can guide me on that.
I'm using RKObjectLoader to make async & sync calls to a REST API. My service is designed to send back proper HTTP status codes, along with some sort of description, a 401 being an example of when the API needs an authenticated user.
My problem is that RestKit stops acting normally if i get a 401 error back. The RKResponse object has a status code of 0, even though it has a payload in it. I'm pretty sure this comes down to NSURLConnection's poor handling of HTTP statuses, but I would expect RestKit to wrap around this somehow. Especially since the RKResponse class has quite a few wrapper functions to determine the status code of the response (isOK, isCreated, isForbidden, isUnauthorized, etc.).
In comparison, ASIHttpRequest doesn't use NSURLConnection, but instead uses the lower level CFNetwork code. ASIHttpRequest allows me to see exactly what came back over HTTP without sending out errors left & right.
Question is, am I doing something wrong, or is this the expected behavior out of RestKit? Has anyone successfully been able to make a calls to [RKResponse isAuthenticated]? Although its inconclusive to me, is there any difference between running in async and sync mode in this regard. I did read somewhere that NSURLConnection run in sync mode will act a bit differently, even though the underlying code is just calling the async operations. Does this have more to do with me using RKObjectLoader as opposed to just RKRequest? Perhaps the fact that the payload can't map to a model causes anger, but it seems that the code is breaking earlier within RKRequest.sendSynchronously, prior to when mapping actually takes place.
Bottom line is my code needs to be able to freely read HTTP status codes. Any guidance would be most appreciated.
Haider
A: The common way for RestKit 0.20.x is to subclass RKObjectRequestOperation.
I wrote a blog article about this problem which can be found here:
http://blog.higgsboson.tk/2013/09/03/global-request-management-with-restkit/
A: See http://groups.google.com/group/restkit/msg/839b84452f4b3e26
"... when authentication fails, the authentication challenge gets cancelled and that effectively voids the request."
UPDATE:
RestKit already includes a delegate method for this:
(void)request:(RKRequest *)request didFailAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
Triggers before
(void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError *)error
When HTTP Basic authentication fails, so we can use this instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CSS Hover to change other elements I have this navigation bar which I have done in CSS, I would like it so when I hover over one of the 3 navigation icons it will change the main image background position.
I've tried a few ways but not managed to get them to work properly.
CSS
/* Nav Button 1 */
.nav1 {
float:left;
padding-top:20px;
border:none;
outline:none;
}
#nav1
{
display: block;
width: 92px;
height: 107px;
background: url("images/triangle.png") no-repeat 0 0;
}
#nav1:hover
{
background-position: 0 -107px;
}
/* Nav Button 2 */
.nav2 {
float:left;
padding-top:20px;
border:none;
outline:none;
padding-right: 0px;
}
#nav2
{
display: block;
width: 92px;
height: 107px;
background: url("images/triangle.png") no-repeat 0 0;
}
#nav2:hover
{
background-position: 0 -107px;
}
/* Nav Button 3 */
.nav3 {
float:left;
padding-top:20px;
border:none;
outline:none;
padding-right: 0px;
}
#nav3
{
display: block;
width: 92px;
height: 107px;
background: url("images/triangle.png") no-repeat 0 0;
}
#nav3:hover
{
background-position: 0 -107px;
}
/* Nav Name */
.navname {
float:left;
padding-top:20px;
border:none;
outline:none;
padding-right: 0px;
}
#navname
{
display: block;
width: 228px;
height: 81px;
background: url("images/blank.png") no-repeat 0 0;
}
HTML
<div id="navigation">
<div class="nav1">
<a id="nav1" href="#"></a>
</div>
<div class="nav2">
<a id="nav2" href="#"></a>
</div>
<div class="nav3">
<a id="nav3" href="#"></a>
</div>
<div class="navname"><a id="navname" href="#"></a>
</div>
</div>
Any ideas how this can be done? The 'navname' element is background position I want to change when hovering over either nav1, nav2, nav3.
Thanks :D
A: This is quite simple using jQuery:
$('element-to-initiate-change').hover(function(){
//this will happen when your mouse moves over the object
$('element-to-change').css({
"property":"value",
"property":"value",
});
},function(){
//this is what will happen when you take your mouse off the object
$('element-to-change').css({
"property":"value",
"property":"value",
});
});
Here is an example: http://jsfiddle.net/dLbDF/258/
If you made a jsfiddle using your code, I would've done this to your code so you could see clearer. Always use jsfiddle or some other kind of example when asking a question.
A: Old question but here's a possible CSS-only solution for others who come across it.
https://jsfiddle.net/Hastig/ancwqda3/
html
<div id="navigation">
<a class="nav n1" href="#"></a>
<a class="nav n2" href="#"></a>
<a class="nav n3" href="#"></a>
<a class="title t0" href="#"></a>
<a class="title t1" href="#">one</a>
<a class="title t2" href="#">two</a>
<a class="title t3" href="#">three</a>
</div>
css
.nav {
display: inline-block;
float: left;
padding-top: 0px;
width: 92px;
height: 107px;
background: url("http://dl.dropbox.com/u/693779/triangle.png") no-repeat 0 0;
}
.nav:hover {
background-position: 0 -107px;
}
.title {
width: 228px;
height: 107px;
background: url("http://dl.dropbox.com/u/693779/blank.png") no-repeat 0 0;
color: red; font-weight: bold;
text-decoration: none;
font-size: 40px; line-height: 107px;
text-align: center;
}
.t0 {
display: inline-block;
}
.t1, .t2, .t3 {
display: none;
}
.nav:hover ~ .t0 {
display: none;
}
.n1:hover ~ .t1, .n2:hover ~ .t2, .n3:hover ~ .t3 {
display: inline-block;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting the cursor location in Visual Studio to clipboard Often when describing an issue in code, I need to reference it by line/column/function.
Is there a macro/add-in for Visual Studio that copies that information for me?
It would be perfect if it could copy to clipboard: File, Line, column, function name
But I'd take any combination :).
Thanks!
A: I ended up doing a macro. Unfortunately I was unable to access the clipboard from the macro so I had to use NirCmd for that part. Other than that, it works great!
Public Sub CopyLocation()
Dim fileName = DTE.ActiveDocument.Name
Dim line = ""
Dim column = ""
Dim functionName = ""
Dim className = ""
Dim textDocument = TryCast(DTE.ActiveDocument.Object, TextDocument)
If textDocument IsNot Nothing Then
Dim activePoint = textDocument.Selection.ActivePoint
column = activePoint.DisplayColumn
line = activePoint.Line
Dim codeElement As CodeElement
codeElement = activePoint.CodeElement(vsCMElement.vsCMElementFunction)
If codeElement IsNot Nothing Then
functionName = codeElement.Name
End If
codeElement = activePoint.CodeElement(vsCMElement.vsCMElementClass)
If codeElement IsNot Nothing Then
className = codeElement.Name
End If
End If
Dim output As String = String.Format("File: {0} ", fileName)
If (String.IsNullOrEmpty(line) = False) Then output = output & String.Format("Line: {0} ", line)
If (String.IsNullOrEmpty(column) = False) Then output = output & String.Format("Column: {0} ", column)
If (String.IsNullOrEmpty(className) = False) Then output = output & String.Format("at {0}", className)
If (String.IsNullOrEmpty(functionName) = False) Then output = output & String.Format(".{0}", functionName)
Dim process As System.Diagnostics.Process
process.Start("c:\NoInstall files\nircmd.exe", String.Format("clipboard set ""{0}""", output))
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I sort columns in a multidimensional array? I would like to sort a multidimensional array in php like you sort columns in a spreadsheet.
I need to be able to select a start and stop column, and optionally, if the "children" of a column get sorted. I'm not sure how I should explain this properly so I try with an example.
Can I do this with standard PHP functions, or do I need write my own? In case of the latter, I would appreciate some help on now to do it.
-------------0------1-------2--- (dimensions)
$someArray[$col1][$col22][$col3];
col1 col2 col3:
a 1 w
c 5 x
b 2 y
d 3 z
unknownSortFunction($someArray, 0, 1, $link=0) // Sort col1 first and then col2 leave col3 (and any "childs") "linked" to column 2.
expected results:
col1 col2 col3
a 1 w
b 2 y
c 3 z
d 5 x
Optionally I would like to be able to sort without keeping col3 "linked" to col2, ex:
col1 col2 col3
a 1 w
b 2 x
c 3 y
d 5 z
A: Multi-dimensions arrays sort is resolved by this function in php:
Array Multisort:
http://www.php.net/manual/en/function.array-multisort.php
As advanced tip, you can extend its using by setting witch dimensions you want to sort, leaving the other out. Using the output more as a index to search your data.
The manual can provide enough info to try out this function on our needs. But, if this is not the result you expect, instead you need to create your own sorting method of sorting. Then you can use the:
Usort:
http://www.php.net/manual/en/function.usort.php
Witch let you create your own method of sorting. You can even extend the multi sort this way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: pass values from 2 tables to a view codeigniter im having function that will display both buy and sell listings. Im trying to display both of these in one page.
im getting the values from 2 different tables and i wanr to pass both the values into the same template
Can someone please suggest how to do it?
controller
function leads(){
$this->load->model('listings');
$data['mylists']=$this->member_functions->mine();
$data['mylists2']=$this->member_functions->mine();
$data['heading']='headings/heading_view';
$data['body']='listbody';
$data['nav']='right';
$this->load->view('includes/template',$data);
}
Model
function mine(){
$mylists=$this->db->get('buy');
if ($mylists->num_rows()>0){
foreach ($mylists->result() as $a)
{
$data[]=$a;
}
return $data;
}
$mylists2=$this->db->get('sell');
if ($mylists2->num_rows>0)
{
foreach ($mylists->result() as $b)
{
$data[]=$b;
}
return $data;
}
}
View
<h2>Buy leads</h2>
<?php foreach ($mylists as $mylist):?>
<p><?php echo "$mylist->type1 in $mylist->country as $mylist->buyid" ?></p>
<?php endforeach;?>
</div>
<br />
<h2>Sell leads</h2>
<?php foreach ($mylists2 as $mylist2):?>
<p><?php echo "$mylist2->type1 in $mylist2->country" ?></p>
<?php endforeach;?>
A: You cannot use 2 return statements within the same function, since whenever the first is encountered...well, the function returns, and stops there. Try returning a single array with the 2 results instead, such as:
Model:
function mine(){
$mylists=$this->db->get('buy');
if ($mylists->num_rows()>0){
foreach ($mylists->result() as $a)
{
$data['res1'][]=$a;
}
}
$mylists2=$this->db->get('sell');
if ($mylists2->num_rows>0)
{
foreach ($mylists->result() as $b)
{
$data['res2'][]=$b;
}
}
return $data;
}
Controller:
$data['lists']=$this->member_functions->mine();
In your view, this array should be called like $lists['res1'] adn $lists['res2']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to control the Appearance of UIPickerView Can anyone point me in the right direction here.
Im trying to use a UIPickerView that is displaying images.
The images are too big for the default pickerview setup so I was wondering how I could control how big the rows in the UIPickerView are and how wide the translucent selection bar is to accomodate for their custom size.
Can anyone provide some guidelines as to how big I should make the row images or where a good tutorial / book chapter is on this?
Thanks!
A: Why not use the UIImagePickerController instead of trying to customize a UIPickerView? It is designed to enable you to allow the user to pick from their library of images if you use the sourceType of UIImagePickerControllerSourceTypePhotoLibrary.
There is sample code on how to use this controller at http://zcentric.com/2008/08/28/using-a-uiimagepickercontroller/
If the images are not from the user's library, then I would suggest you scale the images down to fit the constraints of the UIPickerView, or use a tabelView with the images laid out in it for the user to select.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: table cell content my goal is to make a javascript that i will run using my browser (on someone elses site, not mine) that will take a number from thar site and wait some time depending on the number on the site before clicking a button.
the number is kind of hard to find: in this site there is a table in this table there is a table cell, i got the ID from the cell (for now lets call it "tCell") inside this cell there is another table this does not have an ID, in this table there is a row (once again no ID) in this row there is two cells, and the number is the only content of this cell.
now how do i go from that cell i have an ID on to the content i want?
(how to find the content of a cell then go to the right row of the table among this content)
i guess i will have to use something like this:
var something = document.getElementById('tCell');
and then what...
A: var something = document.getElementById('tCell');
var table = something.firstChild;
var tbody = table.firstChild;
var row = tbody.firstChild;
var firstTd = row.firstChild;
var secondTd = firstTd.nextSibling;
var textNode = secondTd.firstChild;
var textNodeValue = textNode.nodeValue;
A: document.getElementById('tCell').getElementsByTagName("table")[0].getElementsByTagName("tr")[0].getElementsByTagName("td")[1].innerHTML
Will provide you with the number, in string format.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: finding nearest positive semi-definite correlation matrix Is there an R function or DLL that calculates a nearest positive semi-definite correlation matrix?
Finding the nearest positive semi-definite matrix is a well-documented common problem in portfolio construction.
NAGS includes a function but the library requires a license.
A: I think nearcor in the sfsmisc package uses the same algorithm as that NAG routine you link to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android & jar file compatibility How does one find out if a jar is Android compatible, meaning it does not contain imports from class not contained in Android.jar?
I'm trying to build a app that uses the MySQL J connector thingy (and YES, I know about SQLite's existence, but i need the MySQL thingy to work - for remote querying) and when i add the external jar, i get:
Conversion to Dalvik format failed with error 1
I've done my Googling and found this article:
http://bimbim.in/post/2010/09/24/Reason-of-Conversion-to-dalvik-format-failed-with-error-1.aspx
which states, as most answers given on stackoverflow on similar problems that i should: remove all jars, clean project, fix-project-properties.
Did this, but problem persist so I'm assuming that somewhere in this jar there is a class that uses an import that android.jar's java doesn't contain... but i could be wrong, i usually am.
So... Anyone?
A: The source code is included with the MySQL J connector download. Is it possible to use the source and build and compile java code for Android?
A: Try building the project from the command line.
(assuming you have ant, and the android tool that comes with the sdk is in your path)
android update project -p . -t android-10
ant debug
(use whatever android target level your project needs, for the -t option)
If this succeeds, then your problem has something to do with eclipse, not a problem with the jar you are using. And if it fails, it will likely give you a more helpful message than "Conversion to Dalvik format failed".
A: It is not possible to use the MySQL connector in Android. You need to create a layer on the server that is hosting your MySQL.
I read about the reason why Android and MySQL can't directly talk to each other, but of course I can't find the post, so you'll have to do with my answer :P
Check out this tutorial out on how to use a php script to process MySQL tables to JSon:
http://www.helloandroid.com/tutorials/connecting-mysql-database
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: save as PDF: recommend a server solution to receive raw data from client and send back PDF to client? My project requires me to add a "SaveAs PDF" feature. I was looking for a pure JavaScript solution which does this just in client end, however, was told that it's not implementable, at least for now.
jsPDF currently is still a limited version, not support graph and others. So now I am looking for a stable open-srouce free solution to set up a server web service, that receive data from client-end and send back the produced PDF file or a link for user to save to their disk.
The data from client is determined by client user, which means, not the whole page. User can choose to save a map, a table, or all of them into PDF file.
Any recommendations?
PS: in Windows environment
A: You might check out the ReportLab Toolkit - it includes an Open Source Python library for creating PDFs. (You didn't specify what server-side language you wanted, but Python is pretty widely supported.)
If you need something that can be coded in Javascript, one option might be PhantomJS. This tool allows you to run a headless Webkit browser from the command line, and among other things it can render and save webpages as PDFs. Slippy uses this approach, so you might be able to get example code from that project. Scripting the PDF creation would probably be much faster in PhantomJS than in Python, but it's likely to be much slower (it has to fire up a Webkit instance) and server installation might be complicated.
A: I've create this function in javascript which send on iframe to the server:
function download(url, datas){
if(url && datas){
var inputs = '', value,
iframe = '<iframe name="iframeDownload" id="iframeDownload" width=0 height=0></iframe>';
$(iframe).appendTo('body');
datas.forEach(function(data){
name = encodeURI(data.get('name'));
value = encodeURI(data.get('value'));
inputs+='<input name="'+name+'" value="'+value+'"/>';
});
$('<form action="'+url+'" method="post" target="iframeDownload">'+inputs+'</form>').appendTo('body').submit().remove(); // .appendTo and remove() are needed for firefox
$(iframe).remove();
};
};
I'm encoding the input name and value to be able to send data.
On my server, I'm using php, so to decode this, you need: rawurldecode. If you define the name of the inputs as "fileName" and "file" you can write this:
$fileName = rawurldecode($_POST['fileName']);
$file = rawurldecode($_POST['file']);
After than, to force the download, you need to send the corrects header. I'm using this function:
function download($filename, $file) {
header('Content-disposition: attachment; filename="'.$filename.'"');
header('Content-Type: application/force-download');
header('Content-Length: '. filesize($file));
readfile($file);
}
If you don't need to send the file from javascript because it's created on the server side, just add the path of your file to the download function.
If you're using PHP, You can use fpdf to generate the pdf.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Linux Bluetooth l2ping with signal strength (without connecting?) For any Linux BlueZ/BT experts here:
I'm looking for a way to "ping" known BT devices (known BDADDR) and if they are in range I'd like to know the approximate signal strength.
I know that I could first run l2ping, then establish a connection to the device and finally check the rssi or link quality if the connection worked without pairing first.
However what I'm looking for is a way of getting the signal strength without connecting to the device first. Perfect would be a signal strength measurement from the l2ping reply packet, but I don't know if that info is available at all and passed along the stack.
A: You can obtain RSSI during inquiry scan, without connecting to devices. Here's an example using pybluez. You could also do the same thing directly from C using Bluez on linux.
inquiry-with-rssi.py
A: I'm using this code with my iPhone 7 and Raspberry Pi and it works great.
#!/bin/bash
sudo hcitool cc AA:BB:CC:DD:EE:FF 2> /dev/null
while true
do
bt=$(hcitool rssi AA:BB:CC:DD:EE:FF 2> /dev/null)
if [ "$bt" == "" ]; then
sudo hcitool cc AA:BB:CC:DD:EE:FF 2> /dev/null
bt=$(hcitool rssi AA:BB:CC:DD:EE:FF 2> /dev/null)
fi
echo "$bt"
done
A: Very old question, but someone might be still interested in.
The previous answers talk about the RSSI during an inquiry scan. It's correct but not always doable, i.e. undiscoverable devices.
For this class of devices you can establish a connection and eventually ask for the connection RSSI. Connection RSSI can be obtained using BlueZ command hcitool rssi <MAC:ADDRESS>.
Blend l2ping and hcitool rssi do the trick.
For this reason, I created this repository: [https://github.com/edoardesd/myBluez]
Output:
44 bytes from XX:XX:XX:XX:XX:XX id 8 time 8.23ms with RSSI -9
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Portable lightbox for use in userscripts I have tried to implement various lightboxes into my userscripts, but I have never gotten them to work. The most common problem is some of them require's you to modify a css/js file, setting where various image files located. If this is not the case, the image must be located on a specific location on the current server. This is of source not possible, when I don't own the servers I wish to modify.
The lighbox should be able to:
*
*Display one image at once with forward/back arrows.
Not required, but would be nice:
*
*A numbering of the images at the bottom of the lightbox, allowing to jump to a specific image number.
Please provide an example of it being implemented in an userscript. The script may use the // @require and // @resource fields.
A: Lightbox2, coincidentally the first Google result for "lightbox", doesn't mention the need to edit any CSS / JS files or do anything besides include their scripts on the page, and wrapping the thumbnails with a link to the full sized images. If you've tried this, was there any specific problem with it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: RVM Gemset - Bundler & Capistrano in Production I'm deploying a rails app to a VPS with capistrano, bundler and rvm.
Here is part of my deploy.rb
$:.unshift(File.expand_path('./lib', ENV['rvm_path']))
require "rvm/capistrano"
require "bundler/capistrano" # Load RVM's capistrano plugin.
set :rvm_type, :system
set :rvm_ruby_string, '1.9.2@gemset_name'
my .rvmrc
rvm --create use 1.9.2@gemset_name
When I logged into the server I noticed that the rvm gemset was created, however all the gems were installed in /shared/bundle/ruby/1.9.1/gems --not in the gemset(/usr/local/rvm/gemset)
I use RVM in development and I think it's great but when is time to deploy to production. what are the best practices? Is there a way to tell bundler to install the gems in the gemset?
Do I even need a gemset at all? (seems like bundler is already isolating gemsets), Am I missing something?
Please help me understand!
Thank you very much
A: I use RVM in development and production as well. However, while I use gemsets in development to separate gems between my rails projects, I only use RVM to install rubies on my production VPS and let Bundler handle the versions of my gems.
Using the bundler integration via require "bundler/capistrano" automatically sets some things up for bundler. You can see the code behind this in Bundlers Github page. The basic settings are so that bundle executes this command:
bundle install --gemfile Gemfile --path shared/bundle --deployment --quiet --without development test
As you can see, the --deployment and --path flags are given, which tells Bundler to bundle your gems with your application in the shared/bundle directory, and only use the versions specified in your Gemfile.lock (i.e. the versions that are working in development). Since the bundle directory is shared between deployments, I find it comparable to using RVM gemsets for each application, just easier.
If you still want to put gems in separate gemsets I'd recommend this tutorial from Darcy Laycock for further reading.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Thread restart after computer standby I have an application running in the Windows system tray and it seem like after I put the computer in stand-by (not shutdown!) when I turn the system back on, a Thread I have running in the application does not continue running. How would I either A) keep the Thread running, or B) determine the system has come back from stand-by and restart the Thread?
A: You don't need to resume threads after the system resumes. That happens automatically. If your thread or process doesn't resume operation properly it is probably mis-handling the standby or hibernate.
A: Maybe the application is not 100% thread-safe and/or the thread died by an uncaught exception while the system is going stand-by or back from it. Set up an UncaughtExceptionHandler for your thread which logs the uncaught exceptions to a file.
FindBugs and PMD are also useful for hints.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I expect an error but I dont get what I would think I create a view
SQL> create view DEPT20 AS
2 select empno AS Employee_ID_ID,ename AS Employee, deptno as Department_ID from emp
3 where deptno = 20
4 with check option constraint emp_dept_20;
View created.
I expect to get this error
ORA-01402: view WITH CHECK OPTION where-clause violation
But I dont get an error I get
SQL> update dept20
2 set department_ID=30
3 where Employee='Smith';
0 rows updated.
SQL>
Normally I like no errors but in this one I want the error when someone tries to go outside the allowed.
A: What happens if you run this SQL?
update dept20
set department_ID=30
where Employee='SMITH';
If you're using the canonical EMP table, all the employees' names are in uppercase.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Better practice: saving count result into field or not? I'm devloping a music streaming site where I have two major tables: 'activity' and 'music'. Activity saves, among other things, every song reproduction into a new record.
Every time I select from music I need to fetch the number of reproductions of every song. So, what would be the better practice
SELECT music.song, music.artist, COUNT (activity.id) AS reproductions
FROM music LEFT JOIN activity USING (song_id) WHERE music.song_id = XX
GROUP BY music.song_id
Or would it be better to save the number of reproductions into a new field in the music table and query this:
SELECT song, artist, reproductions FROM music WHERE music.song_id = XX
This last query is, of course, much easier. But to use it, every time I play a soundfile I should make two querys: one INSERT in the activity table, and one UPDATE on the reproductions field on music table.
What would be the better practice in this scenario?
A: Well this depends on the response times these two queries will have in time.
After tables will become huge (hypothetically) sql nr 2 will be better.
You have to think that in time even insert might be costly...you you might think on some data warehousing if you will have ..millions of rows in DB.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why can't I use GcHandle.Alloc to pin an array of enums I want to do the following:
public enum Blah
{
A,B
}
[Test,Explicit]
public void TestEnumGcHandle()
{
var ea = new Blah[10];
GCHandle.Alloc(ea, GCHandleType.Pinned);
}
but I get:
System.ArgumentException : Object contains non-primitive or non-blittable data.
Are .net Enums blittable types? (Marshalling) claims that Enums are blittable, but I can't pin an array of them. Could this be a bug in GcHandle.Alloc? I'm using .NET 3.5.
A: It is a little heavy-handed in my book but enums are not primitive (typeof(Blah).IsPrimitive is false) and not blittable. It is missing from the list of blittable types. The linked SO question is wrong about that. Problem is that there's no way to find out what the size of the underlying integral type for the native enum might be. Heavy handed, I think, because there certainly is a way to specify it in the managed enum type. Well, can't do it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Run code when new page is created in MediaWiki I want every page on my wiki to end with a <comments /> tag. How do I automatically add this tag to the end of every page?
NOTE: comments tag comes from ArticleComments extension.
Do I have to write my own extension? How do I go about this?
A: You could take a look at something like the Preloader extension or the MultiBoilerplate extension at the mediawiki home page see if it matches what you need
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Facebook tab application - application controlled icons / tab translations? Is it possible to control a tab icon?
*
*over tab settings?
*over an API?
Why I'm asking: I'm trying to implement top company information into tabs. It's just one application. I can manually change the icon if I create a new application for each tab.
Is it possible to create one application that controls loaded iframe URL and change the icon from tab settings?
A: I don't think this is possible. Have a look at the tabs section in the page document, you can only update three parameters: position, custom_name and is_non_connection_landing_tab
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: C++ - Undefined reference to an object Compiler: MinGW
IDE: Code::Blocks
Platform: Windows XP
External libraries: SDL, SDL_image
What I'm trying to do: Cap the framerate at 60 frames per second using a timer that resets after each loop.
Just a warning, I AM inexperienced with C++, but I've done research and I can't find this kind of error anywhere else. I'm sure it has to do with scope, but I'm not sure how to resolve it.
Compiler output:
In function ZN4data6OnLoopEv':|'C:\Documents and Settings\Evan\My Documents\Programming Projects\Roguelike SDLtest 2\OnLoop.cpp|5|undefined reference to 'fps'
C:\Documents and Settings\Evan\My Documents\Programming Projects\Roguelike SDLtest 2\OnLoop.cpp|7|undefined reference to 'fps'
C:\Documents and Settings\Evan\My Documents\Programming Projects\Roguelike SDLtest 2\OnLoop.cpp|9|undefined reference to 'fps'
Main.cpp:
#include "data.h"
bool data::OnExecute()
{
if (OnInit() == false)
{
data::log("Initialization failure.");
return 1;
}
SDL_Event Event;
while(running == true)
{
fps.start();
while(SDL_PollEvent(&Event))
{
OnEvent(&Event);
}
OnRender();
OnLoop();
log(convertInt(1000/fps.get_ticks()));
}
OnCleanup();
data::log("Program exited successfully.");
return 0;
}
data.h:
#ifndef _DATA_H_
#define _DATA_H_
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <string>
#include <fstream>
#include <sstream>
#include "globals.h"
class timer
{
private:
int startTicks; //Clock time at timer start
bool started; //Timer status
int frame;
public:
void Timer(); //Set timer variables
//Clock actions
void start();
void stop();
//Get timer status
int get_ticks();
bool is_started(); //Checks timer status
void incframe();
};
class data
{
private:
timer fps;
bool running;
SDL_Surface* display;
SDL_Surface* tileset; //The tileset
SDL_Rect clip[255];
int spritewidth;
int spriteheight;
bool mapfloor[80][24]; //Contains the locations of the floor and walls
int mapplayer[80][24]; //Contains the location of the player
SDL_Rect playersprite; //Clip value of the sprite that represents the player
std::string tilesetdsk; //Location of the tileset on disk
std::string debugfile;
int FRAMES_PER_SECOND; //Max FPS
public:
data();
bool OnExecute();
bool OnInit();
void OnEvent(SDL_Event* Event);
void OnLoop();
void OnRender();
void OnCleanup();
static SDL_Surface* load_image(std::string filename);
static void apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip);
void LoadSprite(); //Determines what sprite is where in the tileset
bool levelgen(); //Generates a level
void log(std::string); //**DEBUG** function for logging to file
void setvars();
std::string convertInt(int number);
};
#endif
OnLoop.cpp:
#include "data.h"
void data::OnLoop()
{
if(fps.get_ticks() < 1000/FRAMES_PER_SECOND)
{
SDL_Delay((1000/FRAMES_PER_SECOND) - fps.get_ticks());
}
fps.incframe();
}
A: fps is a variable of type timer, declared in data::OnExecute().
However, you also reference fps in another method data::OnLoop(), where fps is out of scope.
To fix this, I recommend making fps a member-variable of class data. Then fps will always be available inside all the methods of data.
Do this by declaring fps right with your other member-variables(in the private: section of class data)
Remove the declaration in data::OnExecute().
A: You must move the fps variable declaration to the header file. The fps variable is only defined in the data::OnExecute function scope. If you move it to be a class member, all the methods in the class can access it.
So:
1. Remove the "timer fps;" line from data::OnExecute.
2. Add "timer fps;" below the "private:" in data.h
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: If i close and open my app several times i eventually get Out of Memory Error, does it mean i have memory leak? I have an app which let users to pick an image from sd card and then app process the image. I am downsizing images to 1/5 of avialable vm memory and i do call recycle() for every bitmap in onDestroy() call and i still get out of memory error if i close and open my app multiple times.
A: There are various memory leak scenarios in Android. One way to track them down is to use the Traceview tool http://developer.android.com/guide/developing/debugging/debugging-tracing.html.
For more info on common Android memory leak problems see http://android-developers.blogspot.co.uk/2009/01/avoiding-memory-leaks.html
A: Note that when you finish the last Activity of the app the Java process of your app may (in most cases will) be alive meaning all static stuff is still alive when you "start" the app again. Do you store any heavy objects in static fields?
Also note that according to the Activity life-cycle the onDestroy() is not guaranteed to be called. However I don't think this is related, because when you (versus the OS) close the Activity (either by pressing 'Back' button or by calling finish() from the code) then OS always calls onDestroy().
In general, without seeing the code it is difficult to say what happens.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I create identical cron jobs for staging and production with the whenever gem? I have one job in schedule.rb:
set :output, File.expand_path('../log/whenever.log', __FILE__)
set :job_template, "bash -l -c 'source ~/.bashrc ; :job'"
every 1.day, :at => '12:01 am' do
runner "MyModel.do_something"
end
In my staging deployment (bash) script I have this line to write to cron:
ssh $SERVER "cd $DEPLOY_TO && whenever --set environment=staging -w"
And this line in the production deployment script:
ssh $SERVER "cd $DEPLOY_TO && whenever --set environment=production -w"
This works fine and creates the job when I deploy either environment. The problem is that whenever sees them both as one job so it gets overwritten by whichever environment was last deployed:
# Begin Whenever generated tasks for: /Users/simon/apps/myapp/staging/config/schedule.rb
1 0 * * * bash -l -c 'source ~/.bashrc ; cd /Users/simon/apps/myapp/staging && script/rails runner -e staging 'MyModel.do_something' >> /Users/simon/apps/myapp/staging/log/whenever.log 2>&1'
# End Whenever generated tasks for: /Users/simon/apps/myapp/staging/config/schedule.rb
and...
# Begin Whenever generated tasks for: /Users/simon/apps/myapp/production/config/schedule.rb
1 0 * * * bash -l -c 'source ~/.bashrc ; cd /Users/simon/apps/myapp/production && script/rails runner -e production 'MyModel.do_something' >> /Users/simon/apps/myapp/production/log/whenever.log 2>&1'
# End Whenever generated tasks for: /Users/simon/apps/myapp/production/config/schedule.rb
What's a sensible way to add the same cron job for two separate environments on the same server?
A: You can namespace your whenever tasks by using something similar to the following:
# Whenever
set :whenever_environment, defer { stage }
set :whenever_identifier, defer { "#{application}-#{stage}" }
require "whenever/capistrano"
In the above example, stage is the variable that contains the environment. Change it to whatever you are using.
The Capistrano integration section at https://github.com/javan/whenever goes into a bit more detail if you need it.
A: For capistrano-v3-integration add require "whenever/capistrano" to Capfile and set set :whenever_identifier, ->{ "#{fetch(:application)}_#{fetch(:stage)}" } to config/deploy.rb
*
*capistrano-v3-integration
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Structure with formulas My problem is that the correct value that is suppose to be stored in the data[i].Px isn't stored and the same with the data[i].Py.
My formula in the do-while is faulty or must be.
The formula should calculate the 'position' of a projectile.
Vx and Vy is the initial velocities/values and Px and Py is the positions (in the x and y directions)
typedef struct
{
float t, Vx, Vy, Px, Py;
}datapoint;
steps = 100
data[0].Vx = (20*(cos(30))); //in my program 30 is in radians
data[0].Vy = (20*(sin(30));
data[0].Px = 0;
data[0].Py = 0;
do
{
i=1;
printf("Time: %.2f\t",i*q5);
//X
data[i].Vx = data[i-1].Vx;
data[i].Px = ((data[i-1].Px) + ((data[i].Vx) * i));
printf("X = %.2f\t",data[i].Px);
//Y
data[i].Vy= data[i-1].Vy - (9.81)*i;
data[i].Py= data[i-1].Py + (data[i].Vy * i);
printf("Y = %.2f\t", data[i].Py);
printf("\n");
i++;
}while(**(data[i].Py >0)** && (i<=steps));
A: In the while condition of the do while loop, do you want to have
while((data[i].Py > 0) && (i <= steps));
Oh just saw a flaw. Why are you initializing i=1 inside the loop! Its value will never go beyond 2.
(I just skimmed through your question, so if this doesn't work I will check it thoroughly).
A: Judging from the notation used (since the declaration is not shown), data is an array of datapoint. Then data->Px is equivalent to data[0].Px.
You don't show how data[0] is initialized.
i never gets beyond 2. Unless steps is 2, the loop won't terminate because of the i <= steps condition. Since the value in data[0].Py (aka data->Py) is not modified in the loop, you have an infinite loop unless data[0].Py is negative or zero on entry to the loop.
You should look askance at a do { ... } while (...); loop. They aren't automatically wrong; but they are used far less often than while or for loops.
Generally, you will get better answers on StackOverflow if you produce a minimal compilable and runnable program (or a minimal non-compilable program that illustrates the syntax error if you are having problems making the program compilable). And 'minimal' means that nothing can be removed without altering the behaviour.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pyramid and Chameleon ZPT Repetition I am trying to loop through a list and get an output like this:
Python:
items=['item1', 'item2', 'item3']
return dict(items=items)
HTML:
<ul>
<li><a href="/item1>item1</a></li>
<li><a href="/item1>item2</a></li>
<li><a href="/item1>item3</a></li>
</ul>
I can get the list part right but adding it to the anchor is not going so well.
A: How about (supposing 'items' is a namespace passed from your code to your template):
<ul>
<tal:block repeat="item items">
<li><a href="" tal:attributes="href item" tal:content="item">item</a></li>
</tal:block>
</ul>
You can put tal:repeat on the li element, but I personally like to use a dedicated tag using an element in the tal namespace (idiomatic choice is tal:block).
Also see: http://drdobbs.com/web-development/184404974
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Set a parameter in select statement I am trying to set a parameter in the select statement and then pass it to a user defined function in the same statement. Is this possible? If yes, where is my mistake? If no, then I guess I will have to write a cursor and some temporary tables which I want to avoid.
declare @param varchar(1000)
select Pincode, Name,( @param = AlternateName) as AlternateName
,(select Top(1) part from SDF_SplitString (@param,',')) as NewName from PinCodeTable
A: You can either get all of the fields out as variables, or get the usual set of rows, but you can't mix and match in a single SELECT. Variables are limited to queries that return no more than one row. (Why do I feel like I'm about to learn something frightening?)
If you are writing a stored procedure and doing something like header/trailer rowsets, you can always return a rowset built from variables:
SELECT @Foo = Foo, @Bar = Bar, ... from Headers where Id = 42
SELECT @Foo as Foo -- Return the first rowset.
SELECT Size, Weight, Color from Trailers where Bar = @Bar -- Return second rowset.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Mysql design for a user with several items of data I want to store notes, bookmarks, videos and images that belong to a user:
The simplified user table is as follows:
user: id, email, password_hash
A note contains a title and content, whereas a bookmark contains a title and a url
note: id, title, content, (user_id)
bookmark: id, title, uri
video: id, title, uri
images: id, title, uri
I could create a table for all these, however If I wanted to add something else, for example tasks, I would have to create another table for this. How do you suggest I design the tables?
Is mysql the best db for this, Or would something like mongodb be better?
A: As JamWaffles suggests you could have one table for content and one for content types, i.e.:
content: id, title, uri, content_type_id, user_id
content_type: id, name
EDIT: The content table could look like this:
-------------------------------------------------------------
| id | title | uri | content_type_id | user_id |
-------------------------------------------------------------
| 1 | 'My note' | '/note?id=1' | 4 | 56 |
-------------------------------------------------------------
And the content type table:
---------------
| id | name |
---------------
| 4 | 'note' |
---------------
I haven't actually used MongoDB but I guess you could use the following structure:
{
"id": "...",
"email": "...",
"password_hash": "...",
"notes": {
"id": "...",
"title": "...",
"uri": "..."
}
"bookmarks": {
...
}
}
MongoDB like other NoSQL databases have their advantages as well as disadvantages. You would have to evaluate your specific needs in order to determine which better suite yours. Personally I don't see why you couldn't use mysql for your proprosed database structure.
I hope this helps,
Per Flitig
Netlight Consulting
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: '__e3_' is null or not an object - google maps Message: '_e3' is null or not an object
Line: 19
Char: 1068
Code: 0
URI: http://maps.gstatic.com/intl/en_us/mapfiles/api-3/6/6/main.js
I really have no clue on javascript and this is someone elses code, but does anyone know why it causes the above error in internet explorer?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Marker Animations</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var stockholm = new google.maps.LatLng(59.32522, 18.07002);
var parliament = new google.maps.LatLng(59.327383, 18.06747);
var marker;
var map;
google.maps.event.addListener(marker, 'drag', function(event){
document.getElementById("latbox").value = event.latLng.lat();
document.getElementById("lngbox").value = event.latLng.lng();
});
function initialize() {
var mapOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: stockholm
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
marker = new google.maps.Marker({
map:map,
draggable:true,
animation: google.maps.Animation.DROP,
position: parliament
});
google.maps.event.addListener(marker, 'drag', toggleBounce);
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
document.getElementById("latbox").value=marker.getPosition().lat();
document.getElementById("lngbox").value=marker.getPosition().lng();
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 500px; height: 400px;">map div</div>
Lat:<input type="text" id="latbox" name="latbox" style="width:100px;" >
<br>
Long:<input type="text" id="lngbox" name="lngbox" style="width:100px;" >
</body>
</html>
A: If you open IE's developer tools, change to the script tag, and start debugging, then when the page refreshes and the error occurs, the developer tools will show a call stack headed by your call to add a listener to the drag event of a marker, and the __e3_ being referenced is a property of the marker, but you have not created the marker.
Move the addListener(marker ... call to within the initialize() function, after you've created the marker.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't connect to MongoDB on remote host via php I have such network configuration (see link - http://s58.radikal.ru/i160/1110/4c/1c2c5d74edd0.jpg)
Where:
Notebook - contain Apache+php+mongodb+php drivers for mongodb+web project on Zend (Windows)
router - virtual station (nat on 192.168.5.23 interface + ipfw)
natd.conf:
interface le0
same_ports
use_sockets
redirect_port tcp 192.168.5.23:27017 27017
redirect_port tcp 192.168.5.23:27017 27017
ipfw:
allow from any to any
virtual station 2 - contain ONLY mongodb (no php, apache, or mongodb php drivers )
1 - ping from notebook to mongodb host and backward - works.
2 - shell on virtual mongodb host: mongo 192.168.5.20:27017 - connected to notebook's mongodb successfully
3 - attempt to connect from notebook to virtual host cause such error:
C:\mongodb1.8.2\bin>mongo 192.168.9.21:27017
MongoDB shell version: 1.8.2
connecting to: 192.168.9.21:27017/test
Sun Oct 02 22:31:14 Error: couldn't connect to server 192.168.9.21:27017 shell/mongo.js:81
exception: connect failed
4 - attempt to use remote host with DB in php project (www.vm.lcl):
an exception occured while bootstrapping
connecting to vm-db1.lcl failed: Unknown error
Stack Trace:
#0 C:\www\vm-db1.lcl\library\Zirrk\Database\MongoConnection.php(16): Mongo->__construct('vm-db1.lcl')
Please, give me advise - in what direction should I search my mistakes!
Thank a lot!
A: I've solve this problem by changing rule in natd.conf
redirect_port tcp 192.168.5.23:27017 27017
to
redirect_port tcp 192.168.5.23:27017 192.168.9.21:27017
Before understanding how to fix it, I've create in virtual network (192.168.9.0/24) web-server (192.168.9.11) with apache+php+mongo-php-driver (mongodb - was not installed), and tried to connect to 192.168.9.21
$m = new Mongo("mongodb://192.168.9.21:27017");
This was no sense. I've spent whole day in brainstorm and googling information, but still nothing. (Error was in timeout while connection to server). Then I rest for few hours, and understand, that in my case, all traffic goes through Freebsd-gateway host and add to natd.conf
redirect_port tcp 192.168.9.11:27017 192.168.9.21:27017
reboot gate-way server, and it come to work!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JavaScript on third party website I am working on building a Chrome extension that injects bits and pieces of JavaScript onto websites, a bit like AdBlock does.
What is the best way to develop/test my JavaScript code on third-party websites? I want to have my custom JavaScript loaded as if it was JavaScript from the original website.
A: You can use Chrome's developer console. Right click, go to inspect element, and go to console. Alternatively, press ctrl+shift+j.
You should write the code in notepad++ or a similar text editor and then copy it into the console and run it to test it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Manipulating Strings and Arrays in Ruby I've got:
@fruit = ["Apples, Oranges, Bananas", "Apples", "Bananas, Pears", "Bananas, Apples, Pears", "Pears"]
I want to do two different things with this, first turn it into a pure array with only one instance of each:
["Apples", "Oranges", "Bananas", "Pears"]
Secondly I want to be able to determine how many of a given instance there are in the array:
@fruit.count("Apples") = 3
Thirdly, is it possible to order the array by the number of instances:
@fruit.sort = ["Apples", "Apples", "Apples", "Bananas", "Bananas", "Bananas", "Pears", "Pears", "Pears", "Oranges"]
What array/string functions would I have to use to do this?
A: arr = ["Apples, Oranges, Bananas", "Apples", "Bananas, Pears", "Bananas, Apples, Pears", "Pears"]
hsh = Hash.new { |h, k| h[k] = 0 }
arr.each do |str|
fruits = str.split(/, /)
fruits.each do |fruit|
hsh[fruit] += 1
end
end
p hsh.keys
# => ["Apples", "Oranges", "Bananas", "Pears"]
hsh.keys.each { |fruit| puts "#{fruit}: #{hsh[fruit]}" }
# => Apples: 3
# => Oranges: 1
# => Bananas: 3
# => Pears: 3
A: @fruit = ["Apples, Oranges, Bananas", "Apples", "Bananas, Pears", "Bananas, Apples, Pears", "Pears"]
@fruits = @fruit.map{|f| f.split(", ")}.flatten
#=>["Apples", "Oranges", "Bananas", "Apples", "Bananas", "Pears", "Bananas", "Apples", "Pears", "Pears"]
@fruits.uniq
#=> ["Apples", "Oranges", "Bananas", "Pears"]
@fruits.count{|f| f=="Apples"}
#=>3
A: A hash is the better data structure to do this:
@fruit = ["Apples, Oranges, Bananas", "Apples", "Bananas, Pears", "Bananas, Apples, Pears", "Pears"]
h = Hash.new
@fruit.each do |str|
str.split(/,/).each do |f|
f.strip!
h[f] ||= 0
h[f] += 1
end
end
h.keys
=> ["Apples", "Oranges", "Bananas", "Pears"]
h
=> {"Apples"=>3, "Oranges"=>1, "Bananas"=>3, "Pears"=>3}
h["Apples"]
=> 3
you can then process the accumulated data in the hash to print out a sorted array if you need one.
A: @fruit = ["Apples, Oranges, Bananas", "Apples", "Bananas, Pears", "Bananas, Apples, Pears", "Pears"]
p @fruit.map{|f| f.split(', ') }.flatten.uniq
#=> ["Apples", "Oranges", "Bananas", "Pears"]
p @fruit.count{|f| f.include?("Apples")}
#=> 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When using Parallel BeginInvoke is working while Invoke is not - c# 4.0 When i use invoke inside AddListBoxItem function as seen below software become unreponsive and frozen but if i use BeginInvoke it works. Why is that happening ?
visual studio 2010 , C# 4.0
private void button2_Click(object sender, EventArgs e)
{
var watch = Stopwatch.StartNew();
Parallel.For(2, 20, (i) =>
{
var result = SumRootN(i);
AddListBoxItem("root " + i + " : " + result);
});
AddListBoxItem(watch.ElapsedMilliseconds.ToString());
}
private delegate void AddListBoxItemDelegate(object item);
private void AddListBoxItem(object item)
{
if (this.listBox1.InvokeRequired)
{
this.listBox1.Invoke(new AddListBoxItemDelegate(this.AddListBoxItem), item);
}
else
{
this.listBox1.Items.Add(item);
}
}
A: Your UI thread will wait for Parallel.For to complete before it continues. That means it can't process any further UI messages until it's completed.
Now when the worker threads call Invoke, they wait until the UI thread processes the delegate before they continue. So they're waiting for the UI thread to get free, basically.
Hence, you have a deadlock - the UI thread is waiting for the tasks, which are waiting for the UI thread... BeginInvoke works because then the task threads don't wait for the delegates to be processed in the UI thread.
I would suggest that you don't call Parallel.For in the UI thread to start with. You'll block the UI until it completes anyway, which isn't a good idea. Do the whole thing in a background thread - then you can still use Invoke if you want, and while it's doing the computation the UI will still be responsive.
A: It sounds like you are deadlocking the UI thread. This makes perfect sense, as your button2_Click doesn't exit until For completes, and in particular, no message-loop events can be processed until button2_Click has completed. If you are on a different thread, Invoke uses a message-loop event, and does not return until that item is processed - so nothing will ever be done - and For / button2_Click will never complete.
By using BeginInvoke you simply queue this work - BeginInvoke returns immediately. This means that the For can complete, which lets button2_Click complete, which then allows the message-loop events to be processed (updating the UI).
A: I think it's because auf the Mainthread beeing blocked in the above Click event, waiting to finish AddListBoxItem, which is waiting the buttion2_click event to return.
You shouldn't have Controller logic in your UI, so the main problem that the Click isn't calling back a logic in a different thread. After Implementing an thread for your logic, your GUI wouldn't block and would refresh easy in any situation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: C++ Vs PHP - Object oriented questions: I've been working in PHP lately and while I find the language pretty simple coming from C++/C#/python, etc, I have been running into some strange differences (maybe) when it comes to its OO representations. If anyone could answer a few short questions I would be very appreciative :)
*
*Can a constructor return a result value in PHP?
*When a member function within a class calls another member function within
a class, do I have to use the self:: scoping or is that just a hint?
*Why is there self:: and $this-> and what's the difference?
*Is there any need to delete an object created with new, or will
going out of scope remove it? I'm not sure if its truly dynamic, or
if there's garbage collection like in C#.
I know the questions are a little simple, and I keep seeing code that uses all these things - but I haven't seen anything concrete enough and I don't have a good php book at home :) So thank you in advance for answers!
A:
1. Can a constructor return a result value in PHP?
No. (This was possible, but the issue has been fixed - in case you see code that suggests something else.)
2. When a member function within a class calls another member function within a class, do I have to use the self:: scoping or is that just a hint?
This normally technically works, please don't do so. Inside object instances use $this to access own properties and methods.
3. Why is there self:: and $this-> and what's the difference?
It's not the full answer, but for the intro: self:: is for static function calls and member access. See PHP: self vs. $this.
4. Is there any need to delete an object created with new, or will going out of scope remove it? I'm not sure if its truly dynamic, or if there's garbage collection like in C#.
You don't need to delete objects, there is a garbage collector. When objects leave scope they are deleted (the zval's container reference count is one). Keep in mind that everything is deleted at the end of the request in PHP. Your application normally only runs for a fraction of a second, then the process's memory is cleared anyway as the script (and PHP) terminated.
A: *
*No, it automatically returns an instance of $this (unless an exception is thrown)
*Using self:: is required when accessing static members
*self:: is for accessing static members, $this-> is for instance members
*No, the object will be garbage collected when all references to it are gone
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7628803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Subsets and Splits