text stringlengths 8 267k | meta dict |
|---|---|
Q: Why http authentication with htaccess get slow when password incorrect? I don't know why but when i type a wrong password it always take alot of time to come back with authentication dialog.
but when i type a correct password it always go fast.
htaccess:
AuthUserFile c:/senha1
AuthName "Bem vindo"
AuthType Basic
require valid-user
I created this 'senha1' file with htpasswd.
Thanks.
A: That's a simple measure to slow down brute force attacks.
Correctly authenticated requests are handled instantly, while incorrect authentication attempts are delayed by a second or so -- this doesn't bother a regular user that just made a typo, but it sure does slow down attackers that want to rapidly try thousands of passwords.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jQuery 1.7 "unifying bind/live/delegate" The jQuery 1.7 release will "unify bind/live/delegate". What does this mean in term of the jQuery source? What are the consequences for my jQuery code?
A: *
*Corresponding ticket
*Google Doc explaining the changes
Short summary:
Currently we have three different event API pairs: bind/unbind, live/die, and delegate/undelegate. Since they all use the same event lists and events under the covers, exposing the APIs separately can lead to incorrect expectations. Introduction of jQuery.fn.on. Bind/Delegate/Live will stay as shorthand methods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can I turn a string into a list in Python? How can I turn a string (like 'hello') into a list (like [h,e,l,l,o])?
A: The list() function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Need to change @src of a parent iframe from within child iframe I have the following HTML markup (don't ask....)
- document //main site
- <iframe> //my site
- <iframe> //site within my site
- <frame>
- <a onclick="JavaScript:parent.parent.location.href='http://bla.com;return false;'">
Basically, main site is calling my site in an iframe. I, in turn, also have an iframe on my site where I'm calling 3rd site. The third site has a frameset with a frame in it that has a link. When clicking on this link, it has to change the url of my site. My site and my child site are on the same domain. When I'm running my site as "stand-alone" (not in iframe) the above code works fine in all browsers.
Once I open my site in an iframe of the main site, it looks like the above code is trying to change the source of the main site. In FireFox I get a console message "Access to property denied". In IE it opens up a new window with my site not in the main site anymore.
What is the correct JavaScript to change the @src attribute on my site when I'm within an iframe?
A: You are banging your head against the wall that is the same origin policy here. This is XSS country and strictly forbidden, no way around it, unless both domains agree to talk together.
You can read more about cross domain communication using iframes, but again, unless the different domain agree to talk together, you are out of luck.
Although this might seem frustrating, be glad of this rule next time you use homebanking ;)
A: Can you try something like this
<document> //main site
<iframe id="my_iframe"> //your site
<iframe> //site within your site
<frame>
<a onclick="JavaScript:Top.document.getElementById('my_iframe').location.href='http://bla.com;return false;'">
Top refers to the main window, and then getElementById('my_iframe') will give you your iframe element.
A: I believe that you're trying to do communication between different pages.
You may take a look this API: HTML5 Cross Document Messaging
Basically, if you want to tell the parent iframe to navigate to a certain url, you can do this:
In the site within my site html:
// onclick of your anchor, post message (an event) with an expected origin
window.postMessage("http://bla.com", "www.sitewithinmysite.com");
In my site html:
// listen to the event "message"
window.addEventListener("message", messageHandler, true);
function messageHandler(e) {
// only recognize message from this origin
if (e.origin === "www.sitewithinmysite.com") {
// then you can navigate your page with the link passed in
window.location = e.data;
}
}
A: You might want to have the pages communicate using AJAX. Have the site that needs to change its URL listen by long polling to to a node.js server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Configuring an Autofac delegate factory that's defined on an abstract class I'm working on a C# project. I'm trying to get rid of a Factory class that has a large switch statement.
I want to configure Autofac to be able to construct a dependency based on a parameter, thereby allowing Autofac to take the place of the Factory.
I've looked at the DelegateFactories page of the Autofac wiki, but I can't figure out how to apply the pattern to an abstract class. Here's some code showing the situation:
public enum WidgetType
{
Sprocket,
Whizbang
}
public class SprocketWidget : Widget
{
}
public class WhizbangWidget : Widget
{
}
public abstract class Widget
{
public delegate Widget Factory(WidgetType widgetType);
}
public class WidgetWrangler
{
public Widget Widget { get; private set; }
public WidgetWrangler(IComponentContext context, WidgetType widgetType)
{
var widgetFactory = context.Resolve<Widget.Factory>();
Widget = widgetFactory(widgetType);
}
}
I'd like it if I were to say new WidgetWrangler(context, WidgetType.Sprocket), its Widget property would be a SpocketWidget.
When I try this, I get errors stating that Widget.Factory is not registered. Does this delegate factory pattern not work with abstract classes, and if so, is there another way to accomplish this?
A: What you're looking for is the IIndex<,> Relationship Type.
If you register your sub-classes with .Keyed<>(...) you can key a registration to a value (object).
For example:
builder.RegisterType<SprocketWidget>()
.Keyed<Widget>(WidgetType.Sproket)
.InstancePerDependency();
builder.RegisterType<WhizbangWidget>()
.Keyed<Widget>(WidgetType.Whizbang)
.InstancePerDependency();
Then you only require a dependency of IIndex<WidgetType,Widget> to mimic factory behaviour.
public class SomethingThatUsesWidgets
{
private readonly IIndex<WidgetType,Widget> _widgetFactory;
public SomethingThatUsesWidgets(IIndex<WidgetType,Widget> widgetFactory)
{
if (widgetFactory == null) throw ArgumentNullException("widgetFactory");
_widgetFactory = widgetFactory;
}
public void DoSomething()
{
// Simple usage:
Widget widget = widgetFactory[WidgetType.Whizbang];
// Safe Usage:
Widget widget2 = null;
if(widgetFactory.TryGetValue(WidgetType.Sprocket, out widget2))
{
// do stuff
}
}
}
That's using Dependency Injection approach, if you just want to resolve the factory:
var factory = Container.Resolve<IIndex<WidgetType,Widget>>();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: replacing backslash string in php I need to replace \b with \\b in php in order to insert into mysql table.
Therefore \bhello\b becomes \\bhello\\b then inserted into mysql where it is converted back to \bhello\b.
But I can't seem to figure out how. Tried preg_replace and str_replace and I always end up with an error or what I started with.
A: Sounds like you need to use the correct escaping mechanism for your database.
For the record, this is definitely not addslashes().
If using mysql_*(), then use mysql_real_escape_string().
If using PDO, use bound parameters with prepared statements.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails 3.1 asset pipeline outside view I am trying to set CarrierWave's default url inside of the CarrierWave uploader. To do this, I would like to use the asset pipeline to do the following in uploaders/image_uploader.rb:
def default_url
image_path('question_mark.png')
end
But it fails because: undefined methodimage_path' for :ImageUploader`
Then I tried to add include ActionView::Helpers::AssetTagHelper to uploaders/image_uploader.rb but got this error: undefined local variable or methodconfig' for :ImageUploader`
Any idea how I can get the image_path helper to work outside the view?
A: I asked a similar question here and concluded there is no way to get any *_path or *_url helpers working in models. I knew that it definitely shouldn't be done (violating MVC and so forth) but it seems it cannot be done at all...
My problem was setting the default_url for a Paperclip attachment and I ended up setting it to the path I would give to image_tag (simply 'image.png' if image.png is located in app/assets/images or public/images) and then using image_path when accessing it. Would that work for you as well?
A: Not sure exactly what I was trying to do here, ended up working around it but in case anyone comes here wanting to add the _path or _url helpers in their model, do this:
class Post < ActiveRecord :: Base
include Rails.application.routes.url_helpers
# This is so you can use _url params
# you'll need to define the host in your config for it to work though
default_url_options[:host] = Rails.configuration.host
# ...
end
A: I had a similar problem and I resolved it by doing the following in Rails 3.2.
I declared the following module:
module MyApp::AssetHelper
def config
@config ||= ActionController::Base.config
@config.asset_host = 'http://whereveryouhostyour.assets' #not needed if you have this defined in your environment file
@config
end
def controller
ActionController::Base
end
end
I included the following helpers into the model where I wanted to use the asset_tag helpers
include Sprockets::Helpers::RailsHelper
include MyApp::AssetHelper
This allowed me to call the asset_tag helpers where I needed it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Highcharts won't show line through my dots This is my full code:
$(document).ready(function()
{
var options =
{
chart: { renderTo: 'zb' },
title: { text: 'Test' },
tooltip:
{
enabled: true,
formatter: function()
{
return '<b>' + this.x + ' ' + this.series.name + '</b><br/>' + this.y;
}
},
xAxis: { categories: [] },
yAxis: { title: { text: 'Visits Num' } },
series: [],
plotOptions:{ line: { lineWidth : 2 } }
};
var tpo;
$.ajax({url: 'utils/request2.php', success: function(data)
{
var lines = data.split('\n');
var series =
{
type: 'line',
name: 'Visits',
data: [],
marker: { enabled: true, radius : 3 }
};
var cats = [];
$.each(lines, function(lineNo, line)
{
var line_data = line.split(',');
series.data.push(parseInt(line_data[1]));
});
options.series.push(series);
var chart = new Highcharts.Chart(options);
}});
});
It calls to the request2.php file that have data (saved in UTF8 without BOM if it matters) separated with comma, 2 values per row
When I'm showing the data without the parseInt it's showing the line, but the numbers are wrong because it's string - like showing 1500 as 20
Anyone have an idea why?
Thanks alot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ListenableFutureTask / ExecutorService I've Guava in my Classpath and want to use ListenableFutures, but currently I don't know how to submit ListenableFutures or is it currently only possible to use them without an executor in the calling thread? I've read that a decorator is available in r10 which isn't out?
I've found Futures.makeListenable(Future<V> future) but I'm not sure if that's currently the only way how to use ListenableFutures.
kind regards,
Johannes
A: We improved the ListenableFuture Javadoc for the forthcoming r10, including adding information about how to obtain an instance of the class. You can see the HEAD version here: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/ListenableFuture.html
The decorator method you're interested in is MoreExecutors.listeningDecorator
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Any reason for this call to Activator.CreateInstance? I'm maintaining someone else's code and they have this section in a method:
object ReportCriteriaInstance =
Activator.CreateInstance(
typeof(MyCompany.Utils.ReportStructure.ReportSearchCriteria));
//ReportCriteria is passed in as a method parameter
ReportCriteriaInstance = ReportCriteria;
I don't know why they're setting ReportCriteriaInstace to a different value one line after instantiating it with CreateInstance().
Aside from that,
because we're passing in a known type to CreateInstance (MyCompany.Utils.ReportStructure.ReportSearchCriteria) is there any reason not to use new() instead? Some default, parameterless constructor reason I'm not getting maybe?
A: This seems like an abandoned effort to implement poor man's DI container. Later on the object was just passed in, so the code can be safely removed (unless there is a default ReportSearchCriteria constructor that has some potential side effects).
A: You can easily convert code to the following, avoiding side effects of the refactorings entirely:
var ReportSearchCriteriaInstance = new MyCompany.Utils.ReportStructure.ReportSearchCriteria();
object ReportCriteriaInstance = ReportCriteria;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Solr CapitalizationFilterFactory not working I am a complete noob when it comes to solr, this is my first configuration and I am having issues getting solr data to be filtered properly. We are using solr 4.0, the 09-21-2011 snapshot. What I want is to capitalize the first letter of each word in various fields. The data we index will have data like 'name' = 'STAR WARS'. What i want is when I query the data that the name should come back as 'Star Wars' but is comes back as 'STAR WARS'
Here is my setup
<fieldType name="text_capital" class="solr.TextField" positionIncrementGap="100">
<analyzer type="index">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0" splitOnCaseChange="1"/>
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.CapitalizationFilterFactory" onlyFirstWord="false" okPrefix="CVS"/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
</analyzer>
<analyzer type="query">
<tokenizer class="solr.WhitespaceTokenizerFactory"/>
<filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="0" catenateNumbers="0" catenateAll="0" splitOnCaseChange="1"/>
<filter class="solr.LowerCaseFilterFactory"/>
<filter class="solr.CapitalizationFilterFactory" onlyFirstWord="false" okPrefix="CVS"/>
<filter class="solr.RemoveDuplicatesTokenFilterFactory"/>
</analyzer>
</fieldType>
And here is the field mapping
<field name="name" type="text_capital" indexed="true" stored="true" />
Now when i look at the analyzer everything looks fine for both query and index it hits the tokenizer and all the filters properly, but when i run a query results come back with the name as all caps. I feel like i am missing something obvious here.
Thanks,
-zach
A: The value you refer as "coming back" is the stored value which is always the verbatim value you fed to Solr when indexing. Tokenizers, filters, etc, affect the indexed value which is used when searching (and the query terms). It's up to you to transform the stored value you get back into the form you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiple strings matching performance I have an artists table with over 100,000 records that I use to match against an array (between 1 and several thousands) of artists submitted by the user. My current query looks like this:
SELECT id from artists WHERE lower(name) IN(downcase_artists)
This does the job fine, but I'm wondering whether it could be made faster. Query time varies between a few hundred ms to sometimes 10 whole seconds when it's matching thousands of artists. The name column is indexed. (does that even make a difference on string columns?)
I was thinking maybe something like Redis would speed this up? By keeping a key-value store of the artist name and its corresponding id?
Is there any other option that I'm missing that would speed this up?
EDIT: as James suggested, I tried implementing some kind of all_artists cached method (using the memcache add-on on heroku) and use it to match my strings against it:
artist_ids = self.all_cached.select{|a| downcase_array.include?(a.name)}.collect(&:id)
I gained very small db query time but total request time increased drastically:
Before: Completed 200 OK in 1853ms (Views: 164.2ms | ActiveRecord: 1476.3ms)
After: Completed 200 OK in 12262ms (Views: 169.2ms | ActiveRecord: 1200.6ms)
I'm getting similar results when I run it locally:
Before: Completed 200 OK in 405ms (Views: 75.6ms | ActiveRecord: 135.4ms)
After: Completed 200 OK in 3205ms (Views: 245.1ms | ActiveRecord: 126.5ms)
Putting the ActiveRecord times aside, it looks like taking the string matching off the query worsened my issue (and that's with as few as 100 strings). Or am I missing something?
I also had a look at full-text search engines such as Sphinx but they definitely sound overkill, since I'm only searching through 1 single column...
EDIT 2: I finally managed to decrease request time down to
Before: Completed 200 OK in 1853ms (Views: 164.2ms | ActiveRecord: 1476.3ms)
Now: Completed 200 OK in 226ms (Views: 127.2ms | ActiveRecord: 48.7ms)
using a redis store of json strings (see full answer)
A: The usage of IN can be quite costly, if I remember right. How about this:
caches_action :find_all_artists
def gather_artist_ids
@all_artists = Artist.all(:select => "id,name)
end
then, wherever you want the query:
@downcase_artists = "Joe Schmo, Sally Sue, ..."
@requested_artists = @all_artists.select{|a| @downcase_artists.include?(a)}.collect(&:id)
You could do a cache_action on the :gather_artist_ids and have your sweeper only triggered after_create, after_update, and after_destroy.
MongoDB:
I use MongoDB via Mongoid and have 1.51 million records in it and a regex search /usersinput/i takes less than 100ms with an index where needed. It's exceptionally fast.
A: Since you're storing the artists' names in lower case, and you're searching for the full artist name, then this should work for you. I will state the Redis commands, you should easily find the corresponding API call in your client (Use redis-cli first, it will clear things up for you).
I will suppose your table Artists has 3 records: 'The Reign of Kindo', 'Dream Theater' and 'A.C.T', corresponding ids 1, 2, 3.
The basic idea is load that table in a sorted set. Each member's score will be the id of the artist, and the member string will be the artist's name:
Loading phase, filling up the sorted set with all artists (note the lower case):
ZADD artists 1 "the reign of kindo"
ZADD artists 2 "dream theater"
ZADD artists 3 "a.c.t"
Now I will query Redis for the first two bands. The idea is to build this time a temporary sorted set (query:10), which will be intersected with the artists sorted set.
Why not just use query as a key ? I am assigning each query an (arbitrarily) id, so there is no collision between concurrent user searches! Also, we can refer to the id later when caching the result set for a period (more on that below).
The use of : as a delimiter is a recommended convention (look here).
Query phase, filling up the query sorted set.
ZADD query:10 0 "the reign of kindo"
ZADD query:10 0 "dream theater"
ZINTERSTORE result_query:10 2 artists query:10 WEIGHTS 1 0
EXPIRE result_query:10 600
The score for the query sorted set doesn't matter, so it can be 0.
With ZINTERSTORE, we store in result_query:10 the intersection of 2 keys, artists and query:10. But there is a catch! How are scores from both keys combined into the final sorted set ?
Answer: Redis by default sums them.
Now, we can use the WEIGHTS attribute to zero the scores we don't want. So WEIGHTS 1 0 is saying that only the score for artists will be summed.
Now we have the matching artists in result_query:10, which EXPIRE makes it last for 10 minutes. You can figure out a smart way to use this cache =)
Getting the result set
So doing all of the above, you can get the desired result with ZRANGE:
redis> zrange result_query:10 0 -1 withscores
1) "the reign of kindo"
2) "1"
3) "dream theater"
4) "2"
The interval 0 -1 means get all members, and withscores attribute makes ZRANGE returns the ids (scores) of each member, together with their strings.
Hope that all makes sense. It's only the tip of the iceberg for Redis. Good benchmarking and see ya!
A: I'd consider a full-text search engine (Sphinx, Ferret, Lucene, etc.), some of which end up giving you more interesting search capabilities. Unless you'll always just want to search on artist name etc.
Then I'd consider just keeping a wad of memory available to perma-cache the names and hit that instead of the DB.
A: Remove the function "lower(..)" from the query.
A: I ended up using Redis to store not only artist ids and names but the whole json response I return to the user. My Redis hash looks like this:
{"all_artists" => ["artistname1" => "json_response1", "artistname2" => "json_response2"...]}
I do the matching using the following (redis-rb gem):
REDIS.hmget("all_artists", *downcase_array)
That returns all the json strings (including the artist id, name, and upcoming concerts) for the corresponding artists without ever hitting the db. I'm obviously updating the Redis hash every time artists or concerts are updated.
And the resulting time difference (for 100 artists):
Before: Completed 200 OK in 1853ms (Views: 164.2ms | ActiveRecord: 1476.3ms)
Now: Completed 200 OK in 226ms (Views: 127.2ms | ActiveRecord: 48.7ms)
There is still some optimization left to be done but the string matching is definitely out of the way now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to stay on current window when the link opens in new tab? When a user clicks on a link
<a href="http://www.stackoverflow.com" target="_blank">click</a>
is there a way to stay on the current window instead of going to the tab ?
A: <a href="www.stackoverflow.com" onclick="window.open('#','_blank');window.open(this.href,'_self');">
This will load the current web page in a new tab which the browser will focus on, and then load the href in the current tab
A: I guess target="_blank" would open new tab/Windows but will switch the tab as well, and no way I can find them stuff in html,
Yes but when we click in link pressing control key it opens the link in new background tab,
Using javascript we can stimulate same
Here is code I found
function openNewBackgroundTab(){
var a = document.createElement("a");
a.href = "http://www.google.com/";
var evt = document.createEvent("MouseEvents");
//the tenth parameter of initMouseEvent sets ctrl key
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,true, false, false, false, 0, null);
a.dispatchEvent(evt);
}
A: No, this is controlled by the browser.
A: Try this (I found it useful for playing audio files in the background without distracting the user from the current page or using script.)
<a href="first.mp3" target="yourframename"> First Song </a>
<a href="second.mp3" target="yourframename"> Second Song </a>
The first time a user clicks on the link, the target window will be on top. Any subsequent clicks leave the current window on top. Essentially, the links open in the background window because there is no <frame> or <iframe> specified.
Only works on Opera, Mozilla and IE (the versions on my computer). Doesn't work for Chrome and Safari.
A: You could open the current page in a new tab, as this new tab gets focused it would seem you are on the same page, and then change the page where you were before to the new url.
window.open(window.location.href)
window.location.href = new_url
A: It can be done easily using javascript to intercept all clicks through a delegate function and then calling preventDefault() on the event. After that it is a matter of creating a pop-under window just like a nasty ad ;)
That said, don't do this unless you plan on pissing your users off :P
A: There isn't a way to currently control this.
If you want to remove the existing behaviour:
Is there a way to stay on the current window instead of going to the tab [when the link has target="_blank"] ?
Only if you do something like this first...
$('a[target="_blank"]').removeAttr('target');
A: it opens on new tab or window
target="_blank"
stay on your current tab or window
target="_self"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
} |
Q: Word Play Question I created a function that takes a word and a string of 'forbidden' letters, and returns True if the word doesn't use any of the letter.
def avoids(word,forbidden):
for letter in word:
if letter in forbidden:
return False
else:
return True
I want to modify this so instead of using 'forbidden' as the letters to avoid, the user will be prompted to place a couple of letters and print the number of words that don't contain any of them. I also have a .txt document that contain these words to make it interesting.
This is what I've came up with which is wrong. I would like some assistance and education if possible since my 'online' teacher is never around to assist. Please Help :)
def word_no_forbidden():
forbidden = input('pick 5 letters')
fin = open('words1.txt')
no_forbidden_word = 0
for line in fin:
word = line.strip()
for letter in word:
if forbidden in word:
continue
print word
This is the error I get and I understand it but, I'm not sure how else to approach this...
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
word_no_forbidden()
File "C:/Python27/test.py", line 9, in word_no_forbidden
if forbidden in word:
TypeError: 'in <string>' requires string as left operand, not tuple
A: My guess...
You are python 2.x
When you ran the program you typed in:
'a','b','c','d'
On python 2.x, you want to use raw_input not input. That'll give a string of exactly what you type in. As it is python will try to interpret whatever you right as a python expression which is dangerous and generally a bad idea.
Your second problem is that you've reversed your line of code from the first example, letter in forbidden, so that it becomes forbidden in word Not the same thing.
A: def word_no_forbidden():
forbidden = raw_input('pick 5 letters')
fin = open('words1.txt')
no_forbidden_word = 0
for line in fin:
word = line.strip()
for letter in list(word):
if letter in forbidden:
break
else:
print word
NOTE:
1> As winston said use raw_input
2> In case you want to traverse a string use list(your_string) to get a list of characters
3> the else here executes only when our for letter in list(word) loop completes without ever going to break( in other words, none of the letters are in forbidden)
A: To read in a string from the user, you should use raw_input, not input. input tries to actually evaluate the string the user types as Python code, and can result in you getting a datatype you don't expect (or other, worse things).
In contrast, raw_input always returns a string.
(Note: this applies for Python 2.x only. Starting with Python 3, raw_input is renamed to input, and there's no function that does what input used to do.)
A: In this part of the code
for letter in word:
if forbidden in word:
You should be doing
for letter in forbidden:
if letter in word:
What you want to do is check, for every letter in the ones the users entered, if it is in the word read from the file, skip the word and go to the next one. There are more pythonic ways of doing this but I think this is clear and easy to understand.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android - Problems with tcpdump when in ad-hoc mode Currently I'm working on a project that demands using Android and tcpdump.
A short description of what I do:
I want sniff packets using android. I have built an android application which does this using by "tcpdump".
Basically the application initiate tcpdump, which dumps the captured packet in a file (in the sdcard). Then I process the captured packets just by opening the file.
The problem :
When the wifi is in managed mode, everything works fine. But, when I put the wifi device in "ad-hoc" the wireless device stops working.
I'm using "Samsung Captivated S" (SGH - I897), and in order support "overhearing" (promiscuous mode) and ad-hoc I installed the latest "Cyanogen 7" rom ( cm_galaxysmtd_full-126.zip, from: http://download.cyanogenmod.com/?type=nightly&device=galaxysmtd)
I don't know how to solve this and I would really need your help. I suspect
that "wpa_supplicat" is to blame for that, but most probably I wrong.
Thanks in advance,
Ps: I should also mention that I start an adhoc network using my laptop. Then two android devices join the adhoc network. The android devices (SGH-I897) join the network without a problem. All the devices can ping each other.
A: only solution for this is described here.
http://www.44actions.com/?p=273
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Android: How do you hide Tabs in the ActionBar? I need to temporarily hide the Tab objects I've defined for my ActionBar. There is no setVisibility method on Tab objects, so I'm at a loss as to how to accomplish this.
A: I'd try setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD), to move back to the non-tab rendition. It's possible that, when you later call setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) that you will need to re-establish your tabs, though.
UPDATE: Note that action bar tabs are deprecated in the "L" Developer Preview and should remain deprecated in future production Android releases. Consider using something else for tabs: ViewPager with a tabbed indicator, FragmentTabHost, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Send parameters to a running application in C# I am trying to send parameters to an application which is already in the processor. I am using Mutex to find if the application is running or not already. I need to send any command line parameter and that text is added to the listbox. But the parameter is going in but the values are not getting added to the listbox. Application's name is "MYAPPLICATION" and the function which adds the value to listbox is parameters()
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 Frm1 = new Form1();
bool createdNew = true;
using (Mutex mutex = new Mutex(true, "MYAPPLICATION", out createdNew)) //Finding if application is running or not
{
if (createdNew)
{
//foreach (string abc in Environment.GetCommandLineArgs())
//{
// MessageBox.Show(abc);
//}
Application.Run(Frm1);
}
else
{
Process current = Process.GetCurrentProcess();
foreach (Process process in Process.GetProcessesByName(current.ProcessName))
{
if (process.Id != current.Id)
{
SetForegroundWindow(process.MainWindowHandle);
Frm1.parameters(Environment.GetCommandLineArgs());
break;
}
}
}
}
}
A: the easiest and for me the most reliable way to send other applications a message... is to use the WM_COPY event. You can get to this with some old school API calls.
Still valid in Windows 7 We implemented this same thing in a recent application and it works flawlessly on all windows platforms. (tested back to windows xp, but have use the same api in windows 98)
Here is a link to codeproject.
http://www.codeproject.com/KB/cs/ipc_wmcopy.aspx
Essentially register a window in the applications and send messages to that window. Then you can filter it down to the applications.
Pretty cool, and quite efficient. With a little tooling you can make an unlimited amount of application instances communicate with each other.
A: A message queue is a common pattern to communicate between processes. Volure's version of that is cool. A more common approach is to use MSMQ (Microsoft Message Queueing).
Check it out here
http://msdn.microsoft.com/en-us/library/ms978430.aspx
http://en.wikipedia.org/wiki/Microsoft_Message_Queuing
http://blog.goyello.com/2009/09/08/why-msmq-is-excelent-for-net-developers/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Jquery Datatables - Make whole row a link This maybe simple, but cant seem to figure it out. Using jquery datatables how can I make each row clickable to just link to a normal page? So if someone moused over any of the row the whole row will hightlight and be clickable and link to whatever url I would want it to link to when clicked.
A: You can also use the DataTables plugins api which allows you to create custom renderers.
A: I've use the fnDrawCallback parameter of the jQuery Datatables plugin to make it work. Here is my solution :
fnDrawCallback: function () {
$('#datatable tbody tr').click(function () {
// get position of the selected row
var position = table.fnGetPosition(this)
// value of the first column (can be hidden)
var id = table.fnGetData(position)[0]
// redirect
document.location.href = '?q=node/6?id=' + id
})
}
Hope this will help.
A: This did it for me using the row callback.
fnRowCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
responsiveHelper.createExpandIcon(nRow);
$(nRow).click(function() {
document.location.href = 'www.google.com';
});
},
A: $('#myTable').on( 'click', 'tbody tr', function () {
window.location.href = $(this).data('href');
});
where #myTable is the ID of the table, and you need put the href in the tr, like that:
<tr data-href="page.php?id=1">
<th>Student ID</th>
<th>Fullname</th>
<th>Email</th>
<th>Phone</th>
<th>Active</th>
</tr>
A: It's simple enough to do this with a vanilla <table>, but I don't see why this wouldn't work with a jQuery DataTables one either.
$('#myTableId').on('click', 'tbody > tr > td', function ()
{
// 'this' refers to the current <td>, if you need information out of it
window.open('http://example.com');
});
You'll probably want some hover event handling there as well, to give users visual feedback before they click a row.
A: Very cool: JS addon here
And using the fnDrawCallback
fnDrawCallback: function() {
this.rowlink();
},
A: You can do that to make row clickable :
<script type="text/javascript">
var oTable;
$(document).ready(function() {
oTable = $('#myTable').dataTable({
"ajax" : "getTable.json",
"fnInitComplete": function ( oSettings ) {
//On click in row, redirect to page Product of ID
$(oTable.fnGetNodes()).click( function () {
var iPos = oTable.fnGetPosition( this );
var aData = oSettings.aoData[ iPos ]._aData;
//redirect
document.location.href = "product?id=" + aData.id;
} );
},
"columns" : [ {
"data" : "id"
}, {
"data" : "date"
}, {
"data" : "status"
}]
});
});
</script>
<table id="myTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>#</th>
<th>Date</th>
<th>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>
A: I think it will be like that
$('#invoice-table').dataTable({
"fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
var slug = $(nRow).data("slug");
$(nRow).attr("href", "/invoices/" + slug + "/");
$(nRow).css( 'cursor', 'pointer' );
$(nRow).click(function(){
window.location = $(this).attr('href');
return false;
});
}
});
And the table row like that
<tr class="invoice_row" data-slug="{{ invoice.slug }}">
<td>{{ invoice.ref }}</td>
<td>{{ invoice.campaign.name }}</td>
<td>{{ invoice.due_date|date:'d-m-Y' }}</td>
<td>{{ invoice.cost }}</td>
<td>
<span class="label label-danger">Suspended</span>
</td>
</tr>
This worked fine with me
A: **I have used a simple solution for this. Add onclick on tr and you are done. Tested with jquery datatable **
<tr onclick="link(<?php echo $id; ?>)">
function link(id){
location.href = '<?php echo $url ?>'+'/'+id;
}
A: Recently I had to deal with clicking a row in datatables.
$(document).ready(function() {
$("#datatable tbody tr").live( 'click',function() {
window.open('http://www.example.com');
} );
} );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Compressing (Gzip or Deflate) Shows, Lists and views in Couchdb It seems that couchdb automatically compress all its _attachments when requested with the correct header. But unfortunately this doesn't happen for views, show or lists.
Is there any way to achieve a compression before returning the result to the client?
Is using a third party library like deflatejs (didn't test it yet) a bad approach?
Thanks
A: You can certainly use js-deflate in show and list functions, but you cannot do it in view functions. I also suspect it would be inefficient (just a guess, test it if you want numbers).
Until CouchDB does not support gzip encoding, the easiest solution is to put a reverse proxy in front of CouchDB to do the compression. For example you can use nginx with the HttpGzipModule.
A: The Couchbase distribution of CouchDB (Couchbase Single Server) supports Google's snappy compression for the JSON files on disk. I believe the same goes for the views, but I'll have to defer to someone better qualified.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Log Fiddler Requests to Database Real-time Is there any way to log all requests ongoing to a database or can you only log snapshots to a database?
A: The following example relies upon OLEDB 4.0 which is not available for 64bit processes. You can either select another data provider (e.g. SQLServer) or you can force Fiddler to run in 32bit mode.
Add the following to the Rules file to create a new menu item.
// Log the currently selected sessions in the list to a database.
// Note: The DB must already exist and you must have permissions to write to it.
public static ToolsAction("Log Selected Sessions")
function DoLogSessions(oSessions: Fiddler.Session[]){
if (null == oSessions || oSessions.Length < 1){
MessageBox.Show("Please select some sessions first!");
return;
}
var strMDB = "C:\\log.mdb";
var cnn = null;
var sdr = null;
var cmd = null;
try
{
cnn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strMDB);
cnn.Open();
cmd = new OleDbCommand();
cmd.Connection = cnn;
for (var x = 0; x < oSessions.Length; x++){
var strSQL = "INSERT into tblSessions ([ResponseCode],[URL]) Values (" +
oSessions[x].responseCode + ", '" + oSessions[x].url + "')";
cmd.CommandText = strSQL;
cmd.ExecuteNonQuery();
}
}
catch (ex){
MessageBox.Show(ex);
}
finally
{
if (cnn != null ){
cnn.Close();
}
}
}
Note: To use the Database Objects in Fiddler 2.3.9 and below, you'll need to add system.data to the References list inside Tools | Fiddler Options | Extensions | Scripting. In 2.3.9.1 and later, this reference will occur automatically.
Then, list the new import at the top of your rules script:
import System.Data.OleDb;
see FiddlerScript CookBook
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Codeigniter: how can I send a foreach statement to the view? Controller:
$categorys = array(
'1234' => array('Car Audio','Car Subwoofers'),
'12' => array('Car Stereos')
)
$category_id = $this->input->get('category_id');
$product_id = $this->input->get('modelNumber');
if (array_key_exists($category_id,$categorys))
{
foreach($categorys[$category_id] as $key => $value)
{
echo $value;
}
}
How can I echo the $value outputted from the foreach statement in my view file?
A: You can pass the whole array to the view and run the foreach directly in the view, e.g.:
$data['array'] = array(/* etc. */);
$this->load->view('view', $data);
And in the view:
<?php foreach($array as $key => $value): ?>
<p>The key is <?php echo $key; ?><br>
The value is <?php echo $value; ?></p>
<?php endforeach; ?>
A: Controller
if (array_key_exists($category_id,$categorys))
{
$query['cats'] = $categorys[$category_id];
}
View
foreach($cats as $key => $value)
{
echo $value;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Serving download after form submit w/ validation I have created together a pretty simple Download Code redeemer in .php (thanks to help from here) and am having a hard time trying to figure out what the best way to serve a download is if the validation is successful. Basically -
User enters invalid code -> Page is refreshed with error message.
User enters valid code -> Give download 'Save as' -> refresh page.
At the minute I'm using http://www.zubrag.com/scripts/download.php to serve the file but once it has started downloading, my form refreshes the page but only half loads the content?!
This is the form with the PHP script I did.
<div class="dcrForm">
<p>Have a physical copy of this release? Claim your digital download by entering your Download Code below.</p>
<form action="index.php" method="post">
<input type="text" name="code" class="dcrInput" value="">
<input type="submit" name="harrisSubmit" class="dcrSubmit" value="Submit">
</form>
<?php
include("scripts/dcr_config.php");
$code="";
$log="";
if (isset($_POST['harrisSubmit']))
{
$code=$_POST['code'];
$link = mysql_connect($hostname, $dbusername, $dbpassword);
mysql_select_db("$databasename");
$query = "select count from $harris where code='$code'";
if ($q=mysql_query($query))
if ($r=mysql_fetch_array($q)){
if ($r[0]<3)
{
$subquery="update $tbname set count='".($r[0]+1)."' where code='$code'";
mysql_query($subquery);
?><script>window.location.href="download.php?f=test.txt";</script><?php
}
}
$log="<p>Invalid code. Try Again.</p>";
}
echo $log."";
?>
</div>
Does anyone have an ideas on what the best way to serve the download would be? I know that currently anyone who had the file location could download the file but I'm not sure how I could go about protecting i
A: I am glad you have made it this far!
If you are going to redirect the user to a download script, that script would need to have some sort of token attached to it as to prevent unauthorized downloads, basically re-verifying the code or token given.
In the above script, instead of outputting the javascript to redirect to the download script you could do this:
<?php
include "scripts/dcr_config.php";
$code = "";
$log = "";
if (isset($_POST['harrisSubmit'])) {
$code = trim($_POST['code']);
$link = mysql_connect ( $hostname, $dbusername, $dbpassword );
mysql_select_db ( "$databasename" );
$code = mysql_real_escape_string($code); // very important! protects against exploits
$query = "select count from $harris where code='$code'";
if ($q = mysql_query ( $query )) {
if ($r = mysql_fetch_array ( $q )) {
if ($r [0] < 3) {
$subquery = "update $tbname set count='" . ($r [0] + 1) . "' where code='$code'";
mysql_query ( $subquery );
$file = '/path/to/protecteddownload.txt';
// send file to browser as a download dialog
// no content can be output prior to these header() calls
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="file.txt"');
header('Content-Length: ' . filesize($file));
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
echo file_get_contents($file);
exit; // terminate script
} else {
$log = 'Sorry, this code has already been redeemed.';
}
} else {
$log = 'Invalid download code. Try again.';
}
} else {
// query failed
$log = 'An error occurred validating your code, please try again later.';
}
$log = "<p>Invalid code. Try Again.</p>";
}
?>
<?php if (isset($log) && $log != ''): ?>
<strong class="error"><?php echo $log ?></strong>
<?php endif; ?>
<div class="dcrForm">
<p>Have a physical copy of this release? Claim your digital download by
entering your Download Code below.</p>
<form action="index.php" method="post"><input type="text" name="code"
class="dcrInput" value=""> <input type="submit" name="harrisSubmit"
class="dcrSubmit" value="Submit"></form>
</div>
The download script is probably similar to some of what I have above.
The key thing about this example is that the file you are serving with file_get_contents, is not accessible from the web. You only send it when a valid code is entered.
A: I have just 1 quick question, how big is this file? Could this be a case that the php timeout is being experienced while reading the file to the browser?
You could play around with the php settings to confirm this (http://php.net/manual/en/function.set-time-limit.php).
Just my 2 cents
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: PSEXEC not redirecting 7zip output I'm trying to use PSEXEC to uncompress a self extracting file (a console exe created with 7zip) in a remote machine and view the results on my screen.
The remote command executes just fine, but I don't see it's output locally.
This is the command I'm using:
PSEXEC.exe \MACHINE_NAME -u USER_NAME -p PASSWORD -w "\JCOLIN\TWClient" cmd /c "\JCOLIN\TWClient\TW1.17.19.exe" -y
I also have tried:
PSEXEC.exe \MACHINE_NAME -u USER_NAME -p PASSWORD -w "\JCOLIN\TWClient" cmd /c "\JCOLIN\TWClient\TW1.17.19.exe" -y > "\JCOLIN\TWClient\TW1.17.19.exe.log"
in order to save the results in a log file and then retrieve the contents using the TYPE command but even if the log file is create it is always empty
I also have tried:
PSEXEC.exe \MACHINE_NAME -u USER_NAME -p PASSWORD -w "\JCOLIN\TWClient" cmd /c "\JCOLIN\TWClient\TW1.17.19.exe" -y 2> "\JCOLIN\TWClient\TW1.17.19.exe.log"
but in this case the PSEXEC output is saved to the file, not TW1.17.19.exe's output.
By the way, I also tried with a console SFX created with WinRAR with the same problem. I just do not understand why PSEXEC can redirect output from some programs and not others.
Do you have any idea on how to get the desired output on my screen?
Thank you in advance for any help.
A: You might try putting an escape character, "^", before the redirection symbol (^> instead of just >):
PSEXEC.exe \MACHINE_NAME -u USER_NAME -p PASSWORD -w "\JCOLIN\TWClient" cmd /c "\JCOLIN\TWClient\TW1.17.19.exe" -y ^> "\JCOLIN\TWClient\TW1.17.19.exe.log"
This should cause the redirection to occur on the remote machine, not the local machine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jquery ajax not working? i have a jquery ajax post that for some reasons doesn't work:
<script>
var callback = function(data) {
if (data['order_id']) {
$.ajax({
type: 'POST',
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { myid: 123456 },
success: function(data) {
alert("Transaction Completed!");
}
});
}}
</script>
<?php if ($_POST['myid']) { echo $_POST['myid']; } ?>
the 'callback' functions works fine(i test it), just that it stops at the ajax post
and i cant see my echo's
any ideas on what i am doing wrong?
thanks
edit:
i edited the script a bit at the point where the ajax is posting successfully but i cant get the php to echo anything
A: If the AJAX - Call is succeeding now, you can't just echo anything with PHP. The data is sent to the client, but PHP is interpreted at the server. You're not sending an HTTP - Request anymore (which is pretty much the point of an AJAX-Call), so PHP is not going to do anything at this point.
You have to add your new content to the DOM with JavaScript. Try this and see if you get the message shown on your page. I append it to the body, because I don't know how your Markup and your returned data looks like:
$.ajax({
type: 'POST',
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { myid: 123456 },
success: function(data) {
alert("Transaction Completed!");
$('body').prepend('<p>Successful AJAX - Call</p>');
}
});
Then you can take a look at your data-variable with console.log(data), access the returned data and modify the DOM via JavaScript.
A: ok, for a start.
writeback("Transaction Completed!";
fix it to:
writeback("Transaction Completed!");
A: *
*you have a trailing comma after 123456
data: { myid: 123456, },
*you're missing a closing } to your callback function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cisco switch and router programming using Arduino? So, this topic is very similar to this Cisco Switch/Router programming using Arduino?.
I have an Arduino ATmega2560 and Ethernet Shield plus a Cisco 1751 router. I want to configure the router via the console or AUX port using Arduino.
Fast search gave the following results: you could connect to the router using RJ45 to Serial or RJ45 to RJ45 connectors; the protocol is very similar to Telnet (actually works like serial port with text-based commands).
So the main question is - am I able to control the router via a console or AUX port using Ethernet Shield (and an Ethernet library) or do I have to use a serial port connection using something like RS-232?
Update: I've noticed one thing - the DB9 port is just an option for easy communicating with a PC so it seems that my idea is not so bad:) See Cabling and Adapter Setups that Work.
A: As you have pointed out the console and aux ports on Cisco devices are serial ports not network ports so you need to connect to them using RS232, this is an entirely different type of interface from Ethernet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: mysqldump column type 'text'
*
*I am planning to move a mysql database to a different host using mysqldump. Some of the tables have columns of type 'text'. Wanted to find out if there are any issues I need to be aware of (eg. text being truncated etc.) since I haven't done this before.
*Also here are the steps for migration, can you confirm:
On the original database host:-
mysql> FLUSH TABLES WITH READ LOCK;
mysql> SET GLOBAL read_only = ON; (leave session open)
mysqldump --all-databases --lock-all-tables --routines --triggers --events --log-error=/tmp/dump_error.log > /tmp/dbdump.sql -p -u root
mysql> SET GLOBAL read_only = OFF;
mysql> UNLOCK TABLES;
On the new host
mysql -p -u root < /tmp/dbdump.sql
FLUSH PRIVILEGES;
3. I am planning to increase the max_connections from 150 to 300 on the new host, is this fine for this configuration (8 cpu, 16gb ram)
A: No you're gonna be fine with this approach, although I always used 'UNLOCK TABLES', but that's aside the point.
I do want to point out, if you have a massive database you are better off simply copying the physical files, rather than doing a dump. It's going to save you a TON of time. (still lock all the tables though).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UiViewController - Pop doesn't pop I'm displaying UIControllerView subclass when a button is pressed from a another UIViewController like this:
- (IBAction)openNextLevelViewController
{
NSLog(@"openNextlevelViewController");
[self.navigationController pushViewController:nextLevelViewController animated:YES];
}
And the app will return from that view on a button push which trigger this method:
-(IBAction) returnToStart {
NSLog(@"returnToStart method called");
[self.navigationController popViewControllerAnimated:YES];
}
The problem is that the displayed view not getting destroyed/deallocated on the pop. As a result, when it gets pushed, it's not executing the viewDidLoad, which initiates some variables. This may be causing a related problem where, the second time through, when the user presses the return button, the "pop" no longer causes a return to the previous controller.
What's the best way to deal with this? I could move the initialization code to the "willAppear" method, but it seems as if that could be called almost randomly.
A: Well, its not getting released because nextLevelViewController is still being retained somewhere else. Most likely in your nextLevelViewController variable.
- (IBAction)openNextLevelViewController
{
NSLog(@"openNextlevelViewController");
// assuming you have nib already set up
UIViewController *nextLevelViewController = [[NextLevelViewController alloc] init];
// RETAIN COUNT = 1
// navigationController retains your controller
[self.navigationController pushViewController:nextLevelViewController animated:YES];
// RETAIN COUNT = 2
// Don't need it any more let navigation controller handle it.
[nextLevelViewController release]
// RETAIN COUNT = 1 (by NavigationController)
}
Further On
-(IBAction) returnToStart {
[self.navigationController popViewControllerAnimated:YES];
// RETAIN COUNT = 0, dealloc will be called on your viewController, make sure to release all your retained objects.
}
Now when your controller gets popped, it SHOULD get released (shouldn't have been retained anywhere else). And next time you call openNExtLevelViewController, it'll be initializing a new instance of your viewController anyway.
I'm a fan of releasing viewController when it is no longer needed (displayed), instead of holding it in memory. Let navigationController and TabBarController handle viewControllers whenever possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: android black screen on device test I'm using a honeycomb device to test my app and for whatever reason the app runs like it doesn't have any content layout set. It used to run fine and it all of a sudden started showing just black. Other apps run fine and even new test apps from eclipse run fine.
Logcat on run:
09-22 23:07:07.955: DEBUG/AndroidRuntime(16269): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
09-22 23:07:07.955: DEBUG/AndroidRuntime(16269): CheckJNI is ON
09-22 23:07:08.203: DEBUG/AndroidRuntime(16269): Calling main entry com.android.commands.pm.Pm
09-22 23:07:08.251: DEBUG/dalvikvm(1633): GC_EXPLICIT freed 10K, 16% free 2666K/3139K, paused 1ms+1ms
09-22 23:07:08.251: WARN/ActivityManager(164): No content provider found for:
09-22 23:07:08.343: WARN/ActivityManager(164): No content provider found for:
09-22 23:07:08.347: DEBUG/PackageParser(164): Scanning package: /data/app/vmdl503116950.tmp
09-22 23:07:08.423: INFO/PackageManager(164): Removing non-system package:com.test.tv
09-22 23:07:08.423: INFO/Process(164): Sending signal. PID: 16153 SIG: 9
09-22 23:07:08.423: INFO/ActivityManager(164): Force stopping package com.test.tv uid=10026
09-22 23:07:08.471: DEBUG/dalvikvm(284): GC_EXPLICIT freed 13K, 24% free 3540K/4615K, paused 2ms+2ms
09-22 23:07:08.559: DEBUG/dalvikvm(611): GC_EXPLICIT freed <1K, 19% free 5940K/7303K, paused 20ms+7ms
09-22 23:07:08.583: DEBUG/dalvikvm(465): GC_EXPLICIT freed 4K, 60% free 5733K/14087K, paused 50ms+6ms
09-22 23:07:08.723: DEBUG/dalvikvm(164): GC_CONCURRENT freed 1557K, 55% free 9969K/21831K, paused 2ms+6ms
09-22 23:07:08.759: DEBUG/PackageManager(164): Scanning package com.test.tv
09-22 23:07:08.759: INFO/PackageManager(164): Package com.test.tv codePath changed from /data/app/com.test.tv-1.apk to /data/app/com.test.tv-2.apk; Retaining data and using new
09-22 23:07:08.759: INFO/PackageManager(164): Unpacking native libraries for /data/app/com.test.tv-2.apk
09-22 23:07:08.775: DEBUG/installd(116): DexInv: --- BEGIN '/data/app/com.test.tv-2.apk' ---
09-22 23:07:08.879: DEBUG/dalvikvm(16278): DexOpt: load 5ms, verify+opt 53ms
09-22 23:07:08.891: DEBUG/installd(116): DexInv: --- END '/data/app/com.test.tv-2.apk' (success) ---
09-22 23:07:08.891: DEBUG/PackageManager(164): Activities: com.test.tv.TestActivity com.test.tv.FullscreenActivity
09-22 23:07:08.891: INFO/ActivityManager(164): Force stopping package com.test.tv uid=10026
09-22 23:07:08.891: WARN/PackageManager(164): Code path for pkg : com.test.tv changing from /data/app/com.test.tv-1.apk to /data/app/com.test.tv-2.apk
09-22 23:07:08.891: WARN/PackageManager(164): Resource path for pkg : com.test.tv changing from /data/app/com.test.tv-1.apk to /data/app/com.test.tv-2.apk
09-22 23:07:08.951: INFO/installd(116): move /data/dalvik-cache/data@app@com.test.tv-2.apk@classes.dex -> /data/dalvik-cache/data@app@com.test.tv-2.apk@classes.dex
09-22 23:07:08.951: DEBUG/PackageManager(164): New package installed in /data/app/com.test.tv-2.apk
09-22 23:07:09.011: INFO/ActivityManager(164): Force stopping package com.test.tv uid=10026
09-22 23:07:09.075: DEBUG/dalvikvm(360): GC_EXPLICIT freed 72K, 16% free 2883K/3399K, paused 1ms+1ms
09-22 23:07:09.099: DEBUG/dalvikvm(236): GC_EXPLICIT freed 25K, 32% free 10096K/14727K, paused 2ms+3ms
09-22 23:07:09.111: DEBUG/PackageManager(164): generateServicesMap(android.accounts.AccountAuthenticator): 1 services unchanged
09-22 23:07:09.119: DEBUG/PackageManager(164): generateServicesMap(android.content.SyncAdapter): 1 services unchanged
09-22 23:07:09.131: DEBUG/PackageManager(164): generateServicesMap(android.accounts.AccountAuthenticator): 1 services unchanged
09-22 23:07:09.131: DEBUG/PackageManager(164): generateServicesMap(android.content.SyncAdapter): 1 services unchanged
09-22 23:07:09.143: DEBUG/GTalkService(284): [GTalkService.1] handlePackageInstalled: re-initialize providers
09-22 23:07:09.143: DEBUG/GTalkService(284): [RawStanzaProvidersMgr] ##### searchProvidersFromIntent
09-22 23:07:09.147: DEBUG/GTalkService(284): [RawStanzaProvidersMgr] no intent receivers found
09-22 23:07:09.159: WARN/RecognitionManagerService(164): no available voice recognition services found
09-22 23:07:09.271: DEBUG/dalvikvm(164): GC_EXPLICIT freed 681K, 56% free 9810K/21831K, paused 2ms+5ms
09-22 23:07:09.275: INFO/installd(116): unlink /data/dalvik-cache/data@app@com.test.tv-1.apk@classes.dex
09-22 23:07:09.279: DEBUG/AndroidRuntime(16269): Shutting down VM
09-22 23:07:09.295: INFO/AndroidRuntime(16269): NOTE: attach of thread 'Binder Thread #3' failed
09-22 23:07:09.295: DEBUG/dalvikvm(16269): GC_CONCURRENT freed 98K, 87% free 338K/2560K, paused 1ms+1ms
09-22 23:07:09.295: DEBUG/jdwp(16269): Got wake-up signal, bailing out of select
09-22 23:07:09.295: DEBUG/dalvikvm(16269): Debugger has detached; object registry had 1 entries
09-22 23:07:09.531: DEBUG/AndroidRuntime(16285): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
09-22 23:07:09.531: DEBUG/AndroidRuntime(16285): CheckJNI is ON
09-22 23:07:09.699: DEBUG/AndroidRuntime(16285): Calling main entry com.android.commands.am.Am
09-22 23:07:09.711: INFO/ActivityManager(164): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.test.tv/.TestActivity } from pid 16285
09-22 23:07:09.727: INFO/ActivityManager(164): Start proc com.test.tv for activity com.test.tv/.TestActivity: pid=16292 uid=10026 gids={3003}
09-22 23:07:09.735: DEBUG/AndroidRuntime(16285): Shutting down VM
09-22 23:07:09.743: INFO/AndroidRuntime(16285): NOTE: attach of thread 'Binder Thread #3' failed
09-22 23:07:09.751: DEBUG/dalvikvm(16285): GC_CONCURRENT freed 99K, 86% free 365K/2560K, paused 0ms+1ms
09-22 23:07:09.751: DEBUG/jdwp(16285): Got wake-up signal, bailing out of select
09-22 23:07:09.751: DEBUG/dalvikvm(16285): Debugger has detached; object registry had 1 entries
09-22 23:07:09.787: ERROR/jdwp(16292): Failed sending reply to debugger: Broken pipe
09-22 23:07:09.787: DEBUG/dalvikvm(16292): Debugger has detached; object registry had 1 entries
09-22 23:07:10.151: INFO/ActivityManager(164): Displayed com.test.tv/.TestActivity: +425ms
09-22 23:07:10.271: DEBUG/dalvikvm(236): GC_EXPLICIT freed 264K, 31% free 10199K/14727K, paused 3ms+4ms
Manifest:
<application android:icon="@drawable/logo" android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" android:label="@string/app_name">
<activity android:name=".TestActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="FullscreenActivity">
<intent-filter>
<action android:name="com.test.tv" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
** edit FOUND PROBLEM **
The problem was in the onCreate for the Default Activity (in my case - TestActivity). Eclipse had added too many parameters to the onCreate function and that apparently stopped the function from running, but there was no error in the logs at all. Once those extra params were removed, everything went back to normal.
A: The problem was in the onCreate for the Default Activity (in my case - TestActivity). Eclipse had added too many parameters to the onCreate function and that apparently stopped the function from running, but there was no error in the logs at all. Once those extra params were removed, everything went back to normal.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I prevent clipped portions of subviews from still taking touch events? I'm currently clipping some UIViews within a parent view like in the illustration below:
The problem is that the clipped portions (the invisible portions) of the subviews are still receiving touch events that, intuitively, should be going to the other views visible there.
Is there something else I should be doing to achieve this behavior, or is this not actually an easy thing to do?
A: This was happening because the parent view in this case had a custom implementation of
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event,
and it wasn't performing this bounds test (which I now assume is part of the default implementation).
Adding:
if ([self pointInside:point withEvent:event]) {
....
}
around the code in that implementation solved the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Scope Problem with Visual Assert I'm trying to use Visual Assert for testing. Visual Studio says the method I want to test which is defined inside main.cpp is undefined in the Test Fixture.
MyFunctionTest.cpp:
#include <cfixcc.h>
class ExampleTest : public cfixcc::TestFixture
{
private:
public:
void Test()
{
CFIXCC_ASSERT_EQUALS(4, MyFunction(2,2));
}
};
CFIXCC_BEGIN_CLASS(ExampleTest)
CFIXCC_METHOD(Test)
CFIXCC_END_CLASS()
I didn't make a separate project for tests so the two files are a part of the same project. How can I have MyFunction visible for Visual Assert to work properly?
A: #include the header that declares MyFunction()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: convert x and y vector to meshgrid I have an x, y, and z vector that I am currently using to create a 3-D scatter plot. Is it possible to create a mesh plot using these three vectors? I would prefer to only use these vectors and not alter any of my previous code.
A: I'm a bit confused by your terminology, but I'm assuming that you have unstructured surface data - z is the surface height for a set of positions x, y.
If you want to form a "mesh" for this data you could triangulate (via a Delauany triangulation of the positions):
t = delaunayn([x, y]);
If you want to visualise the "meshed" surface you can use trimesh/trisurf:
figure;
trimesh(t, x, y, z);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jCrop: Set a square selection (centred) of an uploaded image of any dimensions I would like to offer my users the ability to crop their uploaded image via jCrop. The result should be a square format. The selection should appear centred in the image, with about a 10% gap either side along the shortest dimension. Current code:
jcrop_api = $.Jcrop('#imgCrop', {
onSelect: storeCoords,
onChange: storeCoords,
aspectRatio: 1
setSelect: [20, 20, 280, 280]
});
so rather than hardcoded values I need a way to set the x1, y1, x2, y2 values to the correct positions.
A: Use the coordinates from your preview method as parameters for the array:
jcrop_api = $.Jcrop('#imgCrop', {
onSelect: storeCoords,
onChange: storeCoords,
aspectRatio: 1
setSelect: [ ($('#imgCrop').attr('width') / 2) - 10,
($('#imgCrop').attr('height') / 2) - 10,
($('#imgCrop').attr('width') / 2) + 10,
($('#imgCrop').attr('height') / 2) + 10
]
});
It will take some trial and error to find the pattern and get it to work consistently.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: After an attractive non-flash PHP charting solution I've been using XML/SWF Charts (maani.us) for ages, but now want to move my charts to a non-flash setup.
On the charts I have at the moment, I have lots of mouseovers, so for instance if you put the mouse over a data point you get a little pop up with more details.
I've recently discovered pChart which looks fantastic, except I don't think that sort of interaction will be possible with it, as they're rendered bitmaps.
Is there something out there that brings together the best of both worlds, using HTML5/SVG/canvas/etc? I don't know much about these newer technologies, but am eager to learn!
This will be a lot of work to port everything over, so I want to make sure I pick the "right" charting solution.
Needs to be:
*
*Very customizable
*Able to generate pretty, appealing graphs that users will want to play with
*Be interactive. Tooltip mouseovers at the very least, and possibly more.
Doesn't have to be free, though that's obviously a bonus. Happy to spend up to $200 say, for the right solution. The intended use is a commercial website that I own & run.
Many thanks!
edit:
OK, so I have a shortlist now:
*
*pChart (no dynamic, but very pretty...)
*Raphael
*Highcharts
*Google charts
*amCharts
Now just need to make sure I pick the "right" one. Please post below if you know of a good solution that I've not listed!
A: http://g.raphaeljs.com/
Uses canvas I think.
Edit: The basic Raphael functions should work well too, example
A: I would recommend Highcharts - a javascript charting library.
A: ExtJS is offered by Sencha in both GPL and commercial licenses.
Chart examples available at: http://www.sencha.com/products/extjs/examples/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hide element only if javascript is enabled I have a view that displays a textbox as follows:
@Html.TextBoxFor(m => m.CodeGuest, new {style = "display: none"})
it is displayed via javascript (so the user clicks a checkbox).
If javascript is not enabled, I must remove this line (style = "display: none") so that the textbox is displayed by default.
A: I typed this as a comment because it seemed so obvious I figured somebody else could grab some upvotes, but:
<noscript>
<div>
Hello YOU HAVE JAVASCRIPT TURNED OFF YOU BIG SILLY
</div>
</noscript>
The content of a <noscript> tag is shown only when JavaScript is disabled.
A: You can use client side logic for this, have it visible as default and hide it with javascript on page load.
If you use jQuery it will be something like this:
$(function() {
$('[name="CodeGuest"]').hide();
});
And remove the display: none from the Razor logic.
Another solution is to wrap the textbox element in <noscript>-tags.
For example:
<noscript>
@Html.TextBoxFor(m => m.CodeGuest)
</noscript>
A: The way I generally handle this is by hiding the elements initially WITH javascript when the Dom loads... This way, no javascript = no hiding...
A: The way I generally prefer to do this, to avoid the flashing of the content on long pages when using the JS hiding solution, is to add something like this to the CSS:
html.jsEnabled #CodeGuest {display: none;}
and then in the JS, just add this:
document.getElementsByTagName('html')[0].className += ' jsEnabled';
The advantage is that you can run that bit of code even before the DOM is Ready, since the HTML tag will already be available. Plus I can use that class for any other progressive enhancements I might have in mind.
A: I like Pointy's answer, but here's a simple script option:
<script type="text/javascript">
document.write('<style type="text/css">#hideMe {display:none;}<\/style>');
</script>
While a noscript element is elegant, it is not consistent with the principles of feature and capability detection and graceful degredation. A better strategy is to decide whether to show the element or not only if the browser is capable of running the associated script.
The above suggestion has the same drawback.
A: You can just hide the element with JavaScript, so the element is displayed by default.
Only if JavaScript is executed, the element is hidden.
I don't know what markup your given code generates, but with JavaScript you could do something like this (for a simple-case example, when the element gets an id):
elem = document.getElementById(id);
elem.style.display = 'none';
So it will get hidden, when JavaScript is enabled. Be sure to wait, until the DOM is fully loaded, before you execute your script, otherwise this could end up doing nothing.
For DOM-Manipulation, I tend to use jQuery, it has a good DOM-ready Listener and easy element-selection.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can I use WordPress as a login provider in my application? I already have a website running WordPress and I have an additional service, which however isn't built on WordPress. The problem is, that the service will be used only by registered users on the WordPress website.
What I would like to do, is use WordPress authentication, as if users were logging in via OpenID, Google, Facebook connect or anything in that manner. Is that even possible to do with WordPress?
A: I do believe that you can. http://wordpress.org/extend/plugins/openid/ is a SSO (Single Sign On) provider.
Or try http://wordpress.org/extend/plugins/wp-userlogin/ (work with versions up to 3.0.5)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jquery form field custom messages in an effort to improve my jquery skills i've decided to create a form and validate it. everything is working fine, but when i submit my form i only get one of the error messages that i've created. i should get all the error messages if i try to submit a blank form, why does it stop after it displays the first error message? this is the first question i've ever asked on here so please excuse any mangled code that gets posted on this one.
html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript" src="js/styles.js"></script>
<title>Form Submit Test</title>
</head>
<body>
<div id="wrapper">
<div class="form_errors">
</div><!--close form_errors-->
<form action="confirmation.html" method="post">
<table border="0" cellspacing="10" cellpadding="10" align="center" bgcolor="">
<tbody>
<tr>
<td width="100" style="" align="left">
User Name
</td>
<td width="170" style="" align="left">
<input type="text" name="first_name" value="First" id="first_name"/>
</td>
</tr>
<td colspan="1" style="" align="left"></td>
<td colspan="1" style="" align="left">
<input type="text" name="last_name" value="Last" id="last_name"/>
</td>
</tr>
<tr>
<td colspan="1" style="" align="left">
Car Make
</td>
<td colspan="1" style="" align="left">
<select name="car_make" id="car_make">
<option>Choose a make</option>
<option value="ford">Ford</option>
<option value="mercury">Mercury</option>
<option value="lincoln">Lincoln</option>
<option value="oldsmobile">Oldsmobile</option>
<option value="toyota">Toyota</option>
<option value="honda">Honda</option>
<option value="lexus">Lexus</option>
</select>
</td>
</tr>
<tr>
<td colspan="1" style="" align="left">
Year
</td>
<td colspan="1" style="">
<select name="car_year" id="car_year">
<option>Choose a year</option>
<option value="1990">1990</option>
<option value="1991">1991</option>
<option value="1992">1992</option>
<option value="1993">1993</option>
<option value="1994">1994</option>
<option value="1995">1995</option>
<option value="1996">1996</option>
<option value="1997">1997</option>
<option value="1998">1998</option>
<option value="1999">1999</option>
<option value="2000">2000</option>
<option value="2001">2001</option>
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
</select>
</td>
</tr>
<tr>
<td colspan="1">
Select Service
</td>
<td colspan="1">
<input type="radio" name="service[]" value="quote" class="radio"/> Quote
</td>
</tr>
<tr>
<td colspan="1"></td>
<td colspan="1">
<input type="radio" name="service[]" value="pick-up" class="radio"/> Pick Up Car
</td>
</tr>
<tr>
<td colspan="1"></td>
<td colspan="1">
<input type="radio" name="service[]" value="drop-off" class="radio"/> Drop Off Car
</td>
</tr>
<tr>
<td colspan="1"></td>
<td colspan="1">
<input type="submit" value="Submit" id="submit"/>
<input type="reset" value="Reset" id="reset"/>
</td>
</tr>
<!--close tbody-->
</tbody>
<!--close table-->
</table>
</form>
</div>
<!--close wrapper-->
</body>
</html>
jquery:
$(document).ready(function(){
//custom input toggle function
jQuery.fn.inputtoggle = function(){
$(this).each(function(index){
var myvalue = $(this).attr("value");
$(this).focusin(function(){
if($(this).val() == myvalue)
$(this).val("");
});
$(this).focusout(function(){
if($(this).val() === "")
$(this).val(myvalue);
});
});
};
//use custom function on inputs
$("input[type=text]").inputtoggle();
//style first td in ever tr and add 'td-style' class
$("form table td:first-child").addClass('td-style');
//hide .form_errors div by default
$(".form_errors").hide();
$("#reset").click(function(){
$(".form_errors").empty().hide();
});
$("form").submit(function(e){
/*RADIO BUTTON VALIDATION*/
//check to see if radio buttons have been checked
if($("input[type=radio]:checked").val()){
//if valid, removes content from .form_errors div in case the radio button was previously invalid
$(".form_errors").empty().hide();
//prevents div content from flickering and disappearing.
//the default action for the input is to submit and post to the next page
//http://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false
} else{
$(".form_errors").show().append('<p>Radio button is NOT checked.</p>');
return false;
}
/*FIRST NAME VALIDATION*/
if($("#first_name").val() == 'First'){
$(".form_errors").show().append('<p>Please enter your first name.</p>');
return false;
}
var firstName = $("#first_name").val();
var validName = /[A-Za-z]/;
if(!validName.test(firstName)){
$(".form_errors").show().append('<p>You may only enter letters.</p>');
return false;
}
/*FIRST NAME VALIDATION*/
if($("#last_name").val() == 'Last'){
$(".form_errors").show().append('<p>Please enter your last name.</p>');
return false;
}
var lastName = $("#last_name").val();
var validName = /[A-Za-z]/;
if(!validName.test(lastName)){
$(".form_errors").show().append('<p>You may only enter letters.</p>');
return false;
}
//close form submit
});
//close jquery
});
A: It stop after the first error message because you "return false". The "return" stop the execution of the current function
A: In short, if you have a look at your if statements, you are using "return false" after each check. This way the form prevents itself from submitting itself but this also stops the flow of execution and gets out of the whole method straight from the condition-satisfying "if" block. That's why only the first check, whichever is triggered in the order of how its organized in your code, is executing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Remap a key press in javascript / jquery Is there an "easy" way to map a keystroke to another key when on a page?
Background:
We are using a custom javascript grid for handling keyboard entry in a web application. Normally, the [enter] key allows the user to move to the next line, and the [tab] key allows the users to move to the right. The grid handles the keystrokes, and has some rather complicated logic when one is pressed.
Our users are requesting that we map the Plus Key [+] on the numeric keypad to [tab] so that they don't need to use two hands while keying. This seems logical (the are keying thousands of numbers in a row while holding papers with their other hand), but I can't figure out to do it.
A: Well you could do something like this:
$(document).keydown(function(e){
if(e.keyCode == 107) { // + key on num keyboard on my keyboard, test your clients to be sure
e.preventDefault();
//trigger tab functionality here
}
});
To trigger the tab functionality, i'd use focus() called on elements which have tabindex="0" set so they fall into the natural taborder of the page and are focusable - if it is formelements they are already focusable and there is no need for the tabindex attribute.
A: You can trigger a keypress event on an element when the + or - keys are press on an element by doing this:
$("body").keypress(function(e){
if ( e.which === 43 || e.which === 45 ) {
$(e.target).trigger({
type: "keypress",
which: 13
});
e.preventDefault();
}
});
This triggers the enter key on both - and +. You should be able to trigger the tab event too, however it will not cause the default browser behavior of going to the next element.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Help with back reference regex in Vim I am trying to write a regular expression in vi to match any whitespace character followed by any digit. Then, at each match, insert a dollar sign between the whitespace and the digit. Here is an example:
A1234 12 14 B1234
B1256 A2 14 C1245
C1234 34 D1 1234K
The correct regex would produce this:
A1234 $12 $14 B1234
B1256 A2 14 C1245
C1234 $34 D1 $1234K
I realize I need to use a back reference, but I can't quite seem to write the correct regex. Here is my attempt:
:'<,'>/(\s\d)/\s\1\$/g
Also, I have Vim's default regex mode turned off (vnoremap / /\v).
Thanks for the help.
A: You need to escape the parentheses to make them work as groupings rather than as actual matches in the text, and not escape the $. Like so:
:%s/\(\s\)\(\d\)/\1$\2/g
This worked for me in vim (using standard magic setting).
Edit: just realized that your non-standard regex settings cause you having the escape 'the other way around'. But still, the trick, I think, is to use two groups. With your settings, this should work:
:%s/(\s)(\d)/\1$\2/g
A: Using a back reference is not inevitable. One can make a pattern to match
zero-width text between a whitespace character and a digit, and replace that
empty interval with $ sign.
:'<,'>s/\s\zs\ze\d/$/g
(See :help /\zs and :help /\ze for details about the atoms changing the
borders of a match.)
A: My first thought is:
:%s/(\b\d)/$\1/g
with \b is for word boundary. But it turns out that \b doesn't mean word boundary in Vim regex, rather \< and \> for the start and end of the word. So the right answer would be:
:%s/\(\<\d\)/$\1/g
(Making sure to escape the capturing parenthesis.)
Sorry that my correction came so late.
A: Not sure abt the exact vim syntax, but regEx syntax should be this:
search expr - "(\s)([\d])"
replacement expr - "\1 $\2"
so something like:
/(\s)([\d])/\1 $\2/g
A: This will do the job for you (without using groups):
:%s/\s\@<=\d\@=/$/g
Explanation:
*
*%: On every line...
*s: Substitute...
*/: Start of pattern
*\s: Whitespace
*\@<=: Match behind (zero-width)
*\d: Digit
*\@=: Require match (zero-width)
*/: End of pattern, start of replacement
*$: What you asked for!
*/: End of replacement
*g: Replace all occurrences in the line.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Buddypress Unread message count - live update? I am using the following code to display the logged in users unread message count in a template.
<?php if (messages_get_unread_count() != 0) { ?>
<div id="message_count">
<div class="countspan">
<?php echo messages_get_unread_count(); ?>
</div>
</div>
<?php } ?>
This works great however it requires a page refresh to update. Since I am making heavy use of ajax driven navigation throughout the site and the custom apps within it this is not a satisfactory solution.
How can make the counter update automatically?
I have played around with the 'lvive notifications' plugin which polls the srver every 10 seconds to provide live notifications but of course this does not interact with my custom unread message counter.
Any ideas guys? I could really use the help.
A: I've worked it out...
It turns out buddypress has built in ajax functions for a lot of this stuff...
So for anyone else wanting to do the same thing.... It is a simple case of putting the 'count' inside an a link with the following id.
<a id="user-messages">
<span><?php echo messages_get_unread_count(); ?></span>
</a>
Buddypress' javascript then does the rest for you. Simple!
Mana thanks for your suggestion though.
A: You could use setTimeout to periodically fire a request to the server which invokes your messages_get_unread_count() and returns a value.
Then based on the value returned, you could show or hide your <div id="message_count"> with the updated count.
A: You can do it with jQuery that calls a seperate php file like so.
jQuery.post('call.php',{ action: "get"}, function (data) {
jQuery('#content').append(data);
});
This tutorial walks you through it http://vavumi.com/?p=257
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Interpolating an angle counter clockwise? Right now 'm using linear bezier to interpolate angles:
float CardAnimation::valueAt( float valueA, float valueB, float t ) const
{
return (1.0f - t) * valueA + t * valueB;
}
....
if(m_startCard.m_angle != m_endCard.m_angle)
{
m_targetCard->m_angle =
valueAt(m_startCard.m_angle, m_endCard.m_angle,m_interval);
}
This works as expected. But here is my problem. If your start angle is 0.5f and you want to go to 6.0f (in radians) then it will go clockwise from 0.5f to 6.0f when really since 6.0f - 0.5f > 3.14f it would be much smarter to go counter clockwise from 0.5f to 6.0f (resulting in moving only 0.78 radians rather than 5.5). What should I do to interpolate counter clockwise if abs(endAngle - startAngle > PI) ?
Thanks
A: Maybe something like this:
*
*Normalize all angles to lie in [0, 2Pi) by adding or subtracting 2Pi repeatedly.
*Shift by min(a, b) so that your new endpoints are 0 and c.
*You either want your range to be c or by 2Pi - c, whichever is smaller, and you have to figure out the sign depending on what you did at (2). Then you want to interpolate between your original start point, and the startpoint plus the range.
A: If abs(endAngle - startAngle) > PI, then subtract 2*PI from endAngle. Then instead of going from 0.5 to 6.0, you go from 0.5 to -0.28.
Edit:
This actually assumes 0 <= startAngle < endAngle <= 2*Pi.
If 0 <= endAngle < startAngle <= 2*Pi and startAngle - endAngle > PI, then add 2*PI to endAngle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery with .Net So I have a very simple .Net page that uses JQuery. When I place the code directly on the page the script executes fine, but when I call from an external js page it fails.
$(document).ready(function () {
$("#MainContent_Button1").click(function () {
alert("Hello world!");
});
});
(jQuery)
<asp:Button ID="Button1" CssClass="Button1" runat="server" Text="CLICK ME FOO" />
When I link like so:
<script type="text/javascript" src="menu.js"></script>.
It doesn't work, but if I place on the page it works fine.
A: It's supposed to be src="" in the script tag.
<script type="text/javascript" src="menu.js"></script>
A: Most likely the javascript file you are referencing externally is not loading. Use chrome to make sure you are getting a 200 message for that file and not a 404. Also, make sure in your external javascript file you are including the jquery document load method exactly like you have above. You have to ensure the button has been placed in the DOM before you can bind any events to it. Also I would recommending using ClientIDMode="static" so you can reference the button with the actual id of button in the jQuery selector.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Porting GCC app, Windows cursor stays on IDC_APPSTARTING I'm porting an application (which makes use of a launcher stub) to Windows (using MinGW GCC).
Here's a minimal example that I will use as reference to demonstrate the issue.
#include <process.h>
int main(int argc, char *argv[])
{
chdir("C:\appdir");
spawnl(P_WAIT, "C:\appdir\app.exe", "C:\appdir\app.exe", NULL);
return 0;
}
This launcher stub is compiled as follows:
gcc -O3 -o launcher.o -c launcher.c
gcc -mwindows -o launcher.exe launcher.o
When launcher.exe is run, it correctly executes app.exe and then waits for it to terminate before terminating itself.
The unexpected side effect of this is that the Windows cursor goes into arrow+hourglass mode for about 5 seconds after launch.exe is spawned.
This does not happen when app.exe is run directly (through the command prompt or by double-clicking it.)
I have already tried adding the following to the app above, with no success (cursor still behaves exactly as before):
#include <windows.h>
SetCursor(LoadCursor(NULL, IDC_ARROW));
Interestingly, running launcher.exe from the command prompt (instead of double-clicking in Explorer), causes the cursor to act normally. I.e., it merely flashes to the hourglass and almost instantly returns to normal.
How can the busy cursor be suppressed? Or at least changed back reliably, without having to block?
A: The SetCursor trick won't work because it will change immediately to the IDC_APPSTARTING, as the system is responding to the WM_SETCURSOR messages.
The APPSTARTING cursor in Windows is more or less documented in the STARTUPINFO struct page (see explanation on STARTF_FORCEONFEEDBACK).
There it says that you can call GetMessage() to get rid of the feedback cursor, but you appear to know that already. Why is that you don't want to use it?
About the different behavior when calling from a console window, it makes sense. Think of when a program is "input idle":
*
*If the program is a Windows one: When the first window is created and ready (called GetMessage).
*If the program is a Console one:
*
*If running from double-click: as soon as it creates the console window.
*If running from another console: immediate.
Update: Try adding the following at the very beginning of main:
PostMessage(0, 0, 0, 0);
MSG msg;
GetMessage(&msg, 0, 0, 0);
A: This is pretty simple and Rodrigo pointed you in the right direction.
Windows displays this cursor to indicate that an app is starting and turns it off when the app begins it's message loop. Your launcher application never starts a message loop so Windows never turns off the cursor.
So, here is what you need:
#include <process.h>
#include <Windows.h>
void turn_off_the_starting_cursor()
{
PostQuitMessage( 0 );
MSG msg;
BOOL bRet;
while( (bRet = GetMessage( &msg, 0, 0, 0 )) != 0)
{
if (bRet != -1)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
}
int main(int argc, char *argv[])
{
turn_off_the_starting_cursor();
chdir("C:\appdir");
spawnl(P_WAIT, "C:\appdir\app.exe", "C:\appdir\app.exe", NULL);
return 0;
}
This posts a quit message to the message queue and then runs the loop which quits immediately. Windows thinks the app is ready to go.
*
*Geoffrey
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Reasoning behind using a rules engines This is more of a generic question. But I am trying to understand a concept of using a tool and why one would need this tool. I keep going round and round.
q)Why do we need rule engines?
I have been reading up on Drools and ILOG rule engines and am still not clear on the concept of what benefit an organization can have using these tools.
q)Is it just to give the business users a way to fire queries ( which are being referred to as rules ) to the database ( repository ) ?
Doesn't this extra piece of s/w just result more money spent on licences and support in comparison to the benefit achieved?
We anyways have a all the applications doing the same thing.
Example:
If sales < $ 5000000 then order shipment = No
Above is example of a business logic. This is easily implemented in the program. So what is the benefit of going via a rules engine?
Any input would be great!
Thank you.
A: Did you have a look at this doc : Why should I use a rule engine ?
It's pretty clear when to use and not use a rule engine.
Have a closer look at these 2 paragrpahs :
1.2.5. Strong and Loose Coupling
No doubt you have heard terms like "tight coupling" and "loose
coupling" in systems design. Generally people assert that "loose" or
"weak" coupling is preferable in design terms, due to the added
flexibility it affords. Similarly, you can have "strongly coupled" and
"weakly coupled" rules. Strongly coupled in this sense means that one
rule "firing" will clearly result in another rule firing, and so on;
in other words, there is a clear (probably obvious) chain of logic. If
your rules are all strongly coupled, the chances are that the will
turn out to be inflexible, and, more significantly, that a rule engine
is an overkill. A clear chain can be hard coded, or implemented using
a Decision Tree. This is not to say that strong coupling is inherently
bad, but it is a point to keep in mind when considering a rule engine
and the way you capture the rules. "Loosely" coupled rules should
result in a system that allows rules to be changed, removed and added
without requiring changes to other, unrelated rules.
and
It seems to me that in the excitement of working with rules engines,
that people forget that a rules engine is only one piece of a complex
application or solution. Rules engines are not really intended to
handle workflow or process executions nor are workflow engines or
process management tools designed to do rules. Use the right tool for
the job. Sure, a pair of pliers can be used as a hammering tool in a
pinch, but that's not what it's designed for.
--Dave Hamu
Hope it helps
A: There are a lot of advantages of using a business rule engine or a business rule management suite. When you start to decoupling the business logic from your application using a declarative approach you end up having your business knowledge expressed in those rules. This fact is extremely valuable for a company that can have all their knowledge in a centralized repository and all their applications can re-use.
The declarative power is also a key concept in my perspective. The idea of letting the engine to pick the rules that are needed for a specific situation is great. Rules engines are optimized for that purpose and makes a really good job when you have tons of rules that must be evaluated.
Hope it helps :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: try throw exception handling I'm having a little trouble with making the following piece of code work. I cannot write a throw exception so I don't know what else could I do.
case 't': // Top of Stack
try
{
cout << "Top() -- " << sPtr->Top() << endl; //this should run if the stack is not empty.
}
catch (StackEmpty)
{
cout << "Top() -- Failed Empty Stack" << endl; // this should run if the stack is empty.
}
break;
the sPtr points to Top() Function in a Class name Stack here is the code for that function:
int Stack::Top() const // Returns value of top integer on stack WITHOUT modifying the stack
{ cout << "*Top Start" << endl;
if(!IsEmpty())
return topPtr->data;
cout << "*Top End" << endl;
}
if I remove the if statement it causes a segmentation fault problem.
A: Why "can't" you throw an exception? Note that if you don't return anything from Top() (when your stack is empty) you are asking for trouble to happen. It should be a precondition to Top() that the stack is not empty, so if you can't throw an exception an assert would be acceptable, even preferable at least to me.
By the way, exceptions are thrown like this:
throw StackEmpty();
A: You're not actually throwing anything on failure, and in the case when the stack is empty you're just running off the end of the function without returning anything. Also your final log statement is only hit when the stack is empty.
You need something more like this:
int Stack::Top() const // Returns value of top integer on stack WITHOUT modifying the stack
{
cout << "*Top Start" << endl;
if(!IsEmpty())
{
cout << "*Top End" << endl;
return topPtr->data;
}
cout << "*Top End" << endl;
throw StackEmpty();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Select rows which depend on conditions on n other rows - mysql I'm not sure how to correctly articulate the title, so please correct it if giving the wrong idea.
Here's an example table named table1:
id name1 number1 name2 number2
... ... ... ... ...
341 A 12 T 10
342 C 17 A 21
343 H 15 G 3
344 C 10 A 11
345 T 15 G 16
... ... ... ... ...
Here is what I'd like to select, for n=3:
id name1 number1 name2 number2 number3
... ... ... ... ... ...
341 A 12 T 10 ...
342 C 17 A 21 ...
344 C 10 A 11 11-10+21-17+12-10
351 D 9 A 5 5-9+11-10+21-17
360 A 18 C 10 18-10+5-9+11-10
503 A 21 K 16 9
... ... ... ... .... based on last 3 where name1 or name2=A
As you can see number_i belongs to name_i, i=1,2
Conditions:
- name1 or name2 must be A
- number3 depends on last 3 number_i entries (current included) where name_i=A, i=1,2
A: Following should get you started.
Note that there is much room for improvement but because of my lacking knowledge regarding MySQL, I have taken the safe route that should work on every DBMS.
SQL Statement
SELECT id
, name1
, number1
, name2
, number2
, r1number1 - r1number2 + r2number1 - r2number2 + r3number1 - r3number2
FROM (
SELECT r1.id
, r1.name1
, r1.number1
, r1.name2
, r1.number2
, r1number1 = CASE WHEN r1.name1 = 'A' THEN r1.number1 ELSE r1.number2 END
, r1number2 = CASE WHEN r1.name1 = 'A' THEN r1.number2 ELSE r1.number1 END
, r2number1 = CASE WHEN r2.name1 = 'A' THEN r2.number1 ELSE r2.number2 END
, r2number2 = CASE WHEN r2.name1 = 'A' THEN r2.number2 ELSE r2.number1 END
, r3number1 = CASE WHEN r3.name1 = 'A' THEN r3.number1 ELSE r3.number2 END
, r3number2 = CASE WHEN r3.name1 = 'A' THEN r3.number2 ELSE r3.number1 END
FROM (
SELECT r1id = r1.id, r2id = MAX(r2.id), r3id = MAX(r3.id)
FROM (SELECT * FROM q WHERE name1 = 'A' OR name2 = 'A') r1
LEFT OUTER JOIN (SELECT * FROM q WHERE name1 = 'A' OR name2 = 'A') r2 ON r2.id < r1.id
LEFT OUTER JOIN (SELECT * FROM q WHERE name1 = 'A' OR name2 = 'A') r3 ON r3.id < r2.id
GROUP BY
r1.id
) rid
INNER JOIN (SELECT * FROM q WHERE name1 = 'A' OR name2 = 'A') r1 ON r1.id = rid.r1id
LEFT OUTER JOIN (SELECT * FROM q WHERE name1 = 'A' OR name2 = 'A') r2 ON r2.id = rid.r2id
LEFT OUTER JOIN (SELECT * FROM q WHERE name1 = 'A' OR name2 = 'A') r3 ON r3.id = rid.r3id
) r
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: RewriteRule and Wordpress Page Parameters I want to send custom parameters to my wordpress page.
and have this rule.
RewriteRule ^mypage/(.+)$ index.php/mypage/?url=myparameter [L]
The funny thing is it works great on my local box but does not work on my online server.
Rewrite is enabled and if i rewrite it to load image it works great but if i use this rule wp returns 404.
I really have no idea what to do.
here is the complete htaccess file.
the only difference is the rewritebase parameter locally
RewriteBase /mysite/
RewriteRule . /mysite/index.php [L]
online
RewriteBase /
RewriteRule . /index.php [L]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /mysite/
RewriteRule RewriteRule ^mypage/(.+)$ index.php/mypage/?url=myparameter [L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /mysite/index.php [L]
</IfModule>
# END WordPress
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I check if a command exists in a shell script? I am writing my first shell script. In my script I would like to check if a certain command exists, and if not, install the executable. How would I check if this command exists?
if # Check that foobar command doesnt exist
then
# Now install foobar
fi
A: Five ways, 4 for bash and 1 addition for zsh:
*
*type foobar &> /dev/null
*hash foobar &> /dev/null
*command -v foobar &> /dev/null
*which foobar &> /dev/null
*(( $+commands[foobar] )) (zsh only)
You can put any of them to your if clause. According to my tests (https://www.topbug.net/blog/2016/10/11/speed-test-check-the-existence-of-a-command-in-bash-and-zsh/), the 1st and 3rd method are recommended in bash and the 5th method is recommended in zsh in terms of speed.
A: Try using type:
type foobar
For example:
$ type ls
ls is aliased to `ls --color=auto'
$ type foobar
-bash: type: foobar: not found
This is preferable to which for a few reasons:
*
*The default which implementations only support the -a option that shows all options, so you have to find an alternative version to support aliases
*type will tell you exactly what you are looking at (be it a Bash function or an alias or a proper binary).
*type doesn't require a subprocess
*type cannot be masked by a binary (for example, on a Linux box, if you create a program called which which appears in path before the real which, things hit the fan. type, on the other hand, is a shell built-in (yes, a subordinate inadvertently did this once).
A: In general, that depends on your shell, but if you use bash, zsh, ksh or sh (as provided by dash), the following should work:
if ! type "$foobar_command_name" > /dev/null; then
# install foobar here
fi
For a real installation script, you'd probably want to be sure that type doesn't return successfully in the case when there is an alias foobar. In bash you could do something like this:
if ! foobar_loc="$(type -p "$foobar_command_name")" || [[ -z $foobar_loc ]]; then
# install foobar here
fi
A: A function which works in both bash and zsh:
# Return the first pathname in $PATH for name in $1
function cmd_path () {
if [[ $ZSH_VERSION ]]; then
whence -cp "$1" 2> /dev/null
else # bash
type -P "$1" # No output if not in $PATH
fi
}
Non-zero is returned if the command is not found in $PATH.
A: The question doesn't specify a shell, so for those using fish (friendly interactive shell):
if command -v foo > /dev/null
echo exists
else
echo does not exist
end
For basic POSIX compatibility, we use the -v flag which is an alias for --search or -s.
A: Check if a program exists from a Bash script covers this very well. In any shell script, you're best off running command -v $command_name for testing if $command_name can be run. In bash you can use hash $command_name, which also hashes the result of any path lookup, or type -P $binary_name if you only want to see binaries (not functions etc.)
A: A function I have in an install script made for exactly this
function assertInstalled() {
for var in "$@"; do
if ! which $var &> /dev/null; then
echo "Install $var!"
exit 1
fi
done
}
example call:
assertInstalled zsh vim wget python pip git cmake fc-cache
A: which <cmd>
also see options which supports for aliases if applicable to your case.
Example
$ which foobar
which: no foobar in (/usr/local/bin:/usr/bin:/cygdrive/c/Program Files (x86)/PC Connectivity Solution:/cygdrive/c/Windows/system32/System32/WindowsPowerShell/v1.0:/cygdrive/d/Program Files (x86)/Graphviz 2.28/bin:/cygdrive/d/Program Files (x86)/GNU/GnuPG
$ if [ $? -eq 0 ]; then echo "foobar is found in PATH"; else echo "foobar is NOT found in PATH, of course it does not mean it is not installed."; fi
foobar is NOT found in PATH, of course it does not mean it is not installed.
$
PS: Note that not everything that's installed may be in PATH. Usually to check whether something is "installed" or not one would use installation related commands relevant to the OS. E.g. rpm -qa | grep -i "foobar" for RHEL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "207"
} |
Q: What triggers a knockout.js template to update? I'm using knockout (awesome library), but I've run into a problem with templates: the DOM only changes for some of my observable objects, but not others. The behavior is kind of weird -- it's left me wondering what triggers a DOM update for a templated object in knockout.
Details: I'm building a simple survey editor. My model is an observableArray of questions, which is rendered through a jquery tmpl template. Users can edit the survey model using inputs that are bound on the page.
Here's (a stripped-down version of) the model:
var surveyModel = {
questions: ko.observableArray([
{header_text:ko.observable("What is the first answer?"), answer_array:ko.observableArray(["Yes","Maybe","No"])},
{header_text:ko.observable("What is the second answer?"), answer_array:ko.observableArray(["Yes","No"])}
])
};
The template itself:
<div class="questionBox">
<div class="headerText">{{html header_text}}</div>
{{each(i,v) answer_array}}
<div class="answerText"><input type="radio" value="${i+1}">{{html v}}</input></div>
{{/each}}
The template binding:
<div id="codebookMain"
data-bind="template: {name:'questionTemplate',
foreach:questions,
afterRender:addCodebookStyles}">
</div>
A binding for header_text:
<textarea data-bind="value: questions()[2].header_text"></textarea>
Bindings and update function for answer_array:
<textarea data-bind="event: {change: function(event){codebookModel.updateAnswerArray('2',event);}}" >
</textarea>
With this code:
updateAnswerArray: function( i, event ){
T = event.target;
this.questions()[i].answer_array = ko.observableArray(event.target.value.split('\n'));
}
Everything works great until I try to update an answer_array. I'm certain the changes are being made in the model, but they aren't getting pushed to the DOM.
The weird thing about this is that changing the html-only header_text variable works perfectly. It's only the answer_array part of the template that doesn't update.
Any ideas on why this is happening, and how to fix it?
A: You are setting answer_array equal to a new observableArray that is not bound to anything. To set the value of an observableArray equal to a new array, you want to do:
myObservableArray(myNewArray);
In your case that would be:
this.questions()[i].answer_array(event.target.value.split('\n'));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: switch/case within a switch/case The following appears in my WinProc:
if(message == WM_CREATE)
{
//Do WM_CREATE stuff
}
else
{
switch(message)
{
case WM_KEYDOWN:
{
switch(wParam)
{
case VK_LEFT:
{
//declare new variable here
D2D1_RECT_F bounds;
HRESULT hr = pDemoApp->mpGeometryGroup->GetBounds(pDemoApp->mTransform, &bounds);
}
}
}
}
}
Is there any problem with declaring and using variables this way?
I set up a breakpoint after I declare and use bounds (still within the scope) but I can't seem to find it in the 'Locals' window in the debugger. What is wrong?
I didn't want to spam the post with a bunch of unrelated code, but here is the full WinProc.
LRESULT CALLBACK DemoApp::WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT result = 0;
if (message == WM_CREATE)
{
LPCREATESTRUCT pcs = (LPCREATESTRUCT)lParam;
DemoApp *pDemoApp = (DemoApp *)pcs->lpCreateParams;
::SetWindowLongPtrW(
hwnd,
GWLP_USERDATA,
PtrToUlong(pDemoApp)
);
result = 1;
}
else
{
DemoApp *pDemoApp = reinterpret_cast<DemoApp *>(static_cast<LONG_PTR>(
::GetWindowLongPtrW(
hwnd,
GWLP_USERDATA
)));
bool wasHandled = false;
if (pDemoApp)
{
switch (message)
{
case WM_SIZE:
{
UINT width = LOWORD(lParam);
UINT height = HIWORD(lParam);
pDemoApp->OnResize(width, height);
}
result = 0;
wasHandled = true;
break;
case WM_DISPLAYCHANGE:
{
InvalidateRect(hwnd, NULL, FALSE);
}
result = 0;
wasHandled = true;
break;
case WM_PAINT:
{
pDemoApp->OnRender();
ValidateRect(hwnd, NULL);
}
result = 0;
wasHandled = true;
break;
case WM_KEYDOWN:
{
D2D1_SIZE_F rtSize = pDemoApp->mpRenderTarget->GetSize();
static float angle = 0.0f;
switch(wParam)
{
case VK_LEFT:
{
angle -= 90;
if(angle < -360)
angle = 0;
D2D1_RECT_F bounds;
HRESULT hr = pDemoApp->mpGeometryGroup->GetBounds(pDemoApp->mTransform, &bounds);
pDemoApp->mTransform = D2D1::Matrix3x2F::Rotation(
angle,
D2D1::Point2F((bounds.right + bounds.left)/2, (bounds.bottom + bounds.top)/2)
);
hr = hr;
InvalidateRect(hwnd, NULL, FALSE);
break;
}
case VK_RIGHT:
{
angle += 90;
if(angle > 360)
angle = 0;
D2D1_RECT_F bounds;
pDemoApp->mpGeometryGroup->GetBounds(pDemoApp->mTransform, &bounds);
pDemoApp->mTransform = D2D1::Matrix3x2F::Rotation(
angle,
D2D1::Point2F((bounds.right + bounds.left)/2, (bounds.bottom + bounds.top)/2)
);
InvalidateRect(hwnd, NULL, FALSE);
break;
}
case VK_DOWN:
{
pDemoApp->mTransform = pDemoApp->mTransform * D2D1::Matrix3x2F::Translation(
0.0f,
5.0f);
InvalidateRect(hwnd, NULL, FALSE);
break;
}
}
}
result = 0;
wasHandled = true;
break;
case WM_LBUTTONDOWN:
{
FLOAT xPos, yPos;
xPos = LOWORD(lParam);
yPos = HIWORD(lParam);
BOOL contains = false;
pDemoApp->mpGeometryGroup->FillContainsPoint(
D2D1::Point2F(xPos, yPos),
pDemoApp->mTransform,
&contains);
if(contains)
MessageBoxA(hwnd, "Hooray!", NULL, NULL);
D2D1_GEOMETRY_RELATION relation;
pDemoApp->mpGeometryGroup->CompareWithGeometry(
pDemoApp->mpSecondGeometryGroup,
pDemoApp->mTransform,
0.001f,
&relation);
if(relation == D2D1_GEOMETRY_RELATION_CONTAINS ||
relation == D2D1_GEOMETRY_RELATION_IS_CONTAINED ||
relation == D2D1_GEOMETRY_RELATION_OVERLAP)
{
MessageBoxA(hwnd, "overlap or contains.", 0, 0);
}
}
result = 0;
wasHandled = true;
break;
case WM_DESTROY:
{
PostQuitMessage(0);
}
result = 1;
wasHandled = true;
break;
}
}
if (!wasHandled)
{
result = DefWindowProc(hwnd, message, wParam, lParam);
}
}
return result;
}
A: There is no problem in declaring variables that way, since you have specified a new scope for the VK_LEFT case. If you weren't declaring a separated scope, then variables would be visible yet possibly non-initialized which would be a problem. Note that you missed a few breaks by the way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Django Multiple Caches - How to choose which cache the session goes in? I have a Django app set up to use multiple caches (I hope). Is there a way to set the session to use a specific cache, or is it stuck on 'default'?
Here's what i have now:
CACHES = {
'default': {
'BACKEND': 'util.backends.SmartMemcachedCache',
'LOCATION': '127.0.0.1:11211',
'TIMEOUT': 300,
'ANONYMOUS_ONLY': True
},
'some_other_cache': {
'BACKEND': 'util.backends.SmartMemcachedCache',
'LOCATION': '127.0.0.1:11211',
'TIMEOUT': 300,
'ANONYMOUS_ONLY': True,
'PREFIX': 'something'
},
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
A: The cached_db and cache backends don't support it, but it's easy to create your own:
from django.contrib.sessions.backends.cache import SessionStore as CachedSessionStore
from django.core.cache import get_cache
from django.conf import settings
class SessionStore(CachedSessionStore):
"""
A cache-based session store.
"""
def __init__(self, session_key=None):
self._cache = get_cache(settings.SESSION_CACHE_ALIAS)
super(SessionStore, self).__init__(session_key)
No need for a cached_db backend since Redis is persistent anyway :)
When using Memcached and cached_db, its a bit more complex because of how that SessionStore is implemented. We just replace it completely:
from django.conf import settings
from django.contrib.sessions.backends.db import SessionStore as DBStore
from django.core.cache import get_cache
class SessionStore(DBStore):
"""
Implements cached, database backed sessions. Now with control over the cache!
"""
def __init__(self, session_key=None):
super(SessionStore, self).__init__(session_key)
self.cache = get_cache(getattr(settings, 'SESSION_CACHE_ALIAS', 'default'))
def load(self):
data = self.cache.get(self.session_key, None)
if data is None:
data = super(SessionStore, self).load()
self.cache.set(self.session_key, data, settings.SESSION_COOKIE_AGE)
return data
def exists(self, session_key):
return super(SessionStore, self).exists(session_key)
def save(self, must_create=False):
super(SessionStore, self).save(must_create)
self.cache.set(self.session_key, self._session, settings.SESSION_COOKIE_AGE)
def delete(self, session_key=None):
super(SessionStore, self).delete(session_key)
self.cache.delete(session_key or self.session_key)
def flush(self):
"""
Removes the current session data from the database and regenerates the
key.
"""
self.clear()
self.delete(self.session_key)
self.create()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jekyll blog on heroku I'm trying to setup a jekyll blog on heroku. This is my dir structure
.
├── Gemfile
├── Gemfile.lock
├── _layouts
│ └── default.html
├── _posts
├── _site
│ ├── Gemfile
│ ├── Gemfile.lock
│ ├── config.ru
│ └── index.html
├── config.ru
└── index.html
My Gemfile has
source "http://rubygems.org"
gem 'jekyll'
and only other file with anything in it is index.html with
Hello world!
If I run jekyll --server it runs fine locally. But if I git push heroku master (after checking everything in) I get this error in my heroku logs
!! Unexpected error while processing request: undefined method `[]' for nil:NilClass
How can I get my jekyll blog to work on Heroku?
A: I agree with phsr's answer. Static websites might be better served using amazon CDN or something similar. However to answer your question:
*
*Check your static files into your git repo. E.g. into a directory like "public".
*Set up a config.ru file to use a middleware like rack-static-if-present and point it towards the public directory.
A: Jekyll generates static HTML files, so there is no need to use Heroku. It would be a better idea to host it on S3. See this Amazon blog post on hosting a static site on S3. With the AWS Free tier, your site would be completely free for the first year (as long as it's under 5 GB in size), and would cost pennies a month after that
A: I had a lot of problems getting a jekyll blog running on Heroku, but managed it in the end.
If this is still relevant, you can see the full code here on github: https://github.com/ramijames/Blueverve_public
You can clone and push to a heroku app and fiddle with the actual setup there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What am i doing wrong? create xml using php I am following this tutorial step by step http://code.google.com/apis/maps/articles/phpsqlajax.html . Actually I copy pasted the code and created the database, added the data to the table, downloaded the provided php and html files but when i actually try to run the page that will create the xml file i get this error. Can anyone guess what is wrong? I am using XAMPP
1.7.4
[PHP: 5.3.5]
(The google tutorial suggests 3 ways to generate the xml file. I tried all 3 of them and the same error appears on the first 2 and an "error on line 10" (which is the line that php script begins) appears when i try the 3rd suggested way. I am thinking if this wont work to use mysqldump command in order to export the xml file i need.)
A: You have two root elements in your XHTML: html and markers. This is why your browser correctly considers it to be invalid.
The problem with blindly copying/pasting code is that when you come across a problem it's very difficult to solve, because you don't understand what the code is doing. I suggest you read through the code closely. When you understand it, you'll be able to fix it.
Essentially you'll want to remove all of the output up until the <markers> tag. Perhaps the HTML file you're using is incorrect.
A: -EDIT-
Problem was in the connection to the database, value for $host and/or $user and/or $pass was incorrect or not provided.
If you use version 2 (phpsqlajax_genxml2), edit the file at line 15 replacing localhost with 'localhost'.
If you use version 3 (phpsqlajax_genxml3), edit the file at line 13replacing localhost with 'localhost'.
Then try again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the difference between lazy loading and lazy evaluation? Is there a difference between "lazy loading" and "lazy evaluation" (both of which are tags on Stack Overflow), or are they synonymous?
Response to comment: The tag wikis (which I'd looked at before asking the question) has the former referring to deferring of initialization, and the other talked about deferring of evaluation. Is it possible to initialize something without evaluating it?
A: lazy evaluation refers to how expressions are evaluated. For example:
f(x) && g(x)
g(x) will not be called unless f(x) is true.
Lazy loading refers to initializing objects only when they are needed
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Counting in a FOR loop using Windows Batch script Can anyone explain this? I am able to count in a loop using the Windows command prompt, using this method:
SET /A XCOUNT=0
:loop
SET /A XCOUNT+=1
echo %XCOUNT%
IF "%XCOUNT%" == "4" (
GOTO end
) ELSE (
GOTO loop
)
:end
But this method does not work (it prints out "1" for each line in the file). It acts like the variable is out of scope:
SET /A COUNT=1
FOR /F "tokens=*" %%A IN (config.properties) DO (
SET /A COUNT+=1
ECHO %COUNT%
)
A: It's not working because the entire for loop (from the for to the final closing parenthesis, including the commands between those) is being evaluated when it's encountered, before it begins executing.
In other words, %count% is replaced with its value 1 before running the loop.
What you need is something like:
setlocal enableextensions enabledelayedexpansion
set /a count = 1
for /f "tokens=*" %%a in (config.properties) do (
set /a count += 1
echo !count!
)
endlocal
Delayed expansion using ! instead of % will give you the expected behaviour. See also here.
Also keep in mind that setlocal/endlocal actually limit scope of things changed inside so that they don't leak out. If you want to use count after the endlocal, you have to use a "trick" made possible by the very problem you're having:
endlocal && set count=%count%
Let's say count has become 7 within the inner scope. Because the entire command is interpreted before execution, it effectively becomes:
endlocal && set count=7
Then, when it's executed, the inner scope is closed off, returning count to it's original value. But, since the setting of count to seven happens in the outer scope, it's effectively leaking the information you need.
You can string together multiple sub-commands to leak as much information as you need:
endlocal && set count=%count% && set something_else=%something_else%
A: for a = 1 to 100 step 1
Command line in Windows . Please use %%a if running in Batch file.
for /L %a in (1,1,100) Do echo %a
A: Here is a batch file that generates all 10.x.x.x addresses
@echo off
SET /A X=0
SET /A Y=0
SET /A Z=0
:loop
SET /A X+=1
echo 10.%X%.%Y%.%Z%
IF "%X%" == "256" (
GOTO end
) ELSE (
GOTO loop2
GOTO loop
)
:loop2
SET /A Y+=1
echo 10.%X%.%Y%.%Z%
IF "%Y%" == "256" (
SET /A Y=0
GOTO loop
) ELSE (
GOTO loop3
GOTO loop2
)
:loop3
SET /A Z+=1
echo 10.%X%.%Y%.%Z%
IF "%Z%" == "255" (
SET /A Z=0
GOTO loop2
) ELSE (
GOTO loop3
)
:end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: error: expected specifier-qualifier-list before "File" I wrote this header file for a another main program. This file declares a struct_buffer struct that is used by the main function (somewhere else).
What I am trying to do is that when someone initialises a buffer with the buffer_init function, a pointer to the buffer is returned. The buffer would contain, an array of pointers, the current number of pointer in the buffer(size), and the file-pointer to a file to which the pointers stored in the buffer will be dumped.
The main program will call the add_to_buffer() function to add pointers to the buffer. This in turn calls the buffer_dump() function to dump the pointers in a file specified by the buffer->fp. At the end, I will call buffer_close() to close the file. However compiling it gives me several errors that I am unable to understand and get rid of.
The following is a code of header file in C, that I am trying to compile and it is giving me errors that I can't understand.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PTRS 1000
struct struct_buffer
{
int size;
File *fp;
unsigned long long ptrs[MAX_PTRS];
};
//The struct_buffer contains the size which is the number of pointers in ptrs, fp is the file pointer to the file that buffer will write
struct struct_buffer*
buffer_init(char *name)
{
struct struct_buffer *buf = malloc(sizeof(struct struct_buffer));
buf->size = 0;
buf->fp = fopen(name,"w");
return buf;
}
//This function dumps the ptrs to the file.
void
buffer_dump (struct struct_buffer *buf)
{
int ctr=0;
for(ctr=0; ctr < buf->size ; ctr++)
{
fprintf(buf->fp, "%llx\n",buf->ptrs[ctr]);
}
}
//this function adds a pointer to the buffer
void
add_to_buffer (struct struct_buffer *buf, void *ptr)
{
if(buf->size >= MAX_PTRS)
{
buffer_dump(buf);
buf->size=0;
}
buf->ptrs[(buf->size)++] = (unsigned long long)ptr;
}
//this functions closes the file pointer
void
buffer_close (struct struct_buffer *buf)
{
fclose(buf->fp);
}
The above code on compilation gives me the following errors. I could not understand the problem. Please explain to me what the trouble is.
buffer.h:10: error: expected specifier-qualifier-list before 'File'
buffer.h: In function 'buffer_init':
buffer.h:19: error: 'struct struct_buffer' has no member named 'fp'
buffer.h: In function 'buffer_dump':
buffer.h:29: error: 'struct struct_buffer' has no member named 'fp'
buffer.h:29: error: 'struct struct_buffer' has no member named 'ptrs'
buffer.h: In function 'add_to_buffer':
buffer.h:40: error: 'struct struct_buffer' has no member named 'ptrs'
buffer.h: In function 'buffer_close':
buffer.h:46: error: 'struct struct_buffer' has no member named 'fp'
A: File is not defined. The correct type you are looking for is FILE.
struct struct_buffer
{
int size;
FILE *fp; // <---------
unsigned long long ptrs[MAX_PTRS];
};
The rest of your errors appear to be a product of this error, so this should be your only fix.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to print out ascii characters from 0 to 255 in C, displayed in a webpage through Django? I'm working on a C assignment for school. Here's the exact wording of the assignment:
"Write a program that prints a list of the integers 0 through 255 and the corresponding ASCII character. "
The actual code was simple enough:
#include <stdio.h>
int main() {
int i;
for (i = 0; i <= 256; i++) {
printf("%d --> %c\n", i, i);
}
return 0;
}
However, I need to display this output in a webpage with Django. I compiled this code with gcc (with the -std=C99 option enabled), and it outputs fine. However, within the webpage, this does not output anything. Our Django view is using popen2 to open the executable with this code:
if os.path.isfile(file_sh):
output = popen2.popen2(file_sh)[0].read()
and the page has been tested to function with all other C code for this class. I've added a print statement within the view to verify that the output of the code is being sent to the browser correctly, and it gets displayed correctly in the terminal but not the browser. In fact, it's not being displayed at all in the browser. Upon further inspection, there is absolutely nothing within the tag this page would normally display the output of the code. I'm guessing this has something to do with character encoding. Any ideas?
EDIT: I forgot to mention that in my template, I specified the character encoding to be utf-8 with the meta tag.
EDIT 2: A friend of mine has a version that displays the contents of a text file saved on Windows as utf-8 at http://geekingreen.dyndns.org/week02/Assignment-5, but if he tries to display that page with output from an executable, he gets the same problem as me.
A: Ha, found a way for it to at least render it to the page, the characters don't display correctly but at least it renders something to the page.
The code is simply this:
mystring = unicode(mystring, errors='replace')
EDIT: Found an even better way
import chardet
chartype = chardet.detect(mystring)
# perhaps you may want to check the confidence that it is that encoding first?
# if chartype['confidence'] > 0.5 or something
mystring = mystring.decode(chartype['encoding']).encode('utf-8')
Works like a charm, although some characters still seem to be missing it shows more than the previous method.
A: raw bytes with values 128..255 are not valid utf-8 characters, so that is probably your problem. Specify a Ascii encoding rather than utf-8, as that's what you're doing
A: Chances are that character encodings are not the issue. Although Django uses Unicode strings exclusively and Python uses ASCII strings by default, the UTF-8 character set is backwards-compatible with ASCII.
It's more likely that you are accidentally not including the variable in the page at all. If your function looks like:
def view_function(request):
output = ''
if os.path.isfile(file_sh):
proc = subprocess.Popen(file_sh, stdout=subprocess.PIPE)
stdout, stderr = proc.communicate()
output = stdout
return render_to_response('template.html', {'output': output})
and your template looks like:
<!DOCTYPE html>
<html>
<head>...</head>
<body>
<p>
{{ output }}
</p>
</body>
</html>
then you should see the characters on the page. The text won't break across the same lines as the terminal output, but at least you will see something. On the other hand, if you change the inclusion tag to {{ ouptut }}, the wrong spelling will cause nothing to be embedded in the page.
Just make sure you don't have autoescaping turned off - if you do, the "-->" string will look like the end of a comment and will break the HTML structure of the page.
One other suggestion: use subprocess rather than popen2. The Python docs mark popen2 as deprecated.
A: As others have tried to say, you just need to use the correct encoding.
output = popen2.popen2(file_sh)[0].read().decode('cp1252')
A: Hint: Think of this ÿ (& # 254;), ÿ (& # 255;) or μ (& # 956;). Just remove spaces to get the characters.
You can do pretty easy counting:
for i in range(256):
print '&#%s;<br/>\n' % i
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can't get JQuery to work in MVC3 application at ALL? This is driving me crazy, at the moment I can't get what seems a very simple piece of JQuery to work in my asp.net MVC3 application. I'm just starting to learn JQuery, I have created a new MVC 3 internet application and have added the following JQuery code to the top of index.cshtml:
<script type="text/javascript">
$(document).ready()(function() {
$("#box").hide();
});
</script>
I have also added the following html to the index.cshtml page:
<div id="box">
blah
</div>
But when I load the page the div is not hidden, when I try debugging using firebug it seems like my script isn't even called. I've looked at god know how many tutorials tonight and I can't see what I'm missing, I'm sure it will be something simple. If anyone could spare some time to point it out it would be very much appreciated.
Cheers
A: You have a syntax error. The anonymous function is an argument to the ready method.
$(document).ready(function() {
$("#box").hide();
});
You can also use the ready handler shorcut if you'd like.
$(function() {
$("#box").hide();
});
A: Your script is broken at the document ready, here is a fixed version:
$(document).ready(function() {
$("#box").hide();
});
A: try this: (like rfvgyhn said, you pass the entire function to the ready() method, it might help to look at it this way.
<script type="text/javascript">
$(document).ready(
function()
{
$("#box").hide();
}
);
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: create XML nodes based on XPath in java I have a configuration file may or may not contain a certain element whose XPath is:
/configuration/server/address
when I write the configuration I have to create the node if it doesn't exist.
Node n = (Node)xp.evaluate("/configuration/server/address", configDocument, XPathConstants.NODE);
but, no surprise, node is null if the node doesn't exist in the real file.
QUESTION
Ok. My idea is have something like File: i can define a path that doesn't exist:
File f = new File("myInexistentDir/myInexistentSubdir");
then, i call f.mkdirs() and the path is replicated in the real world.
Is it possible with java implementation of XPath?
Possible objection. It's obvious that not all XPath expressions are "creatable nodes".
Where create the "//anywhere" element?
I would say that "//anywhere" expression doesn't is a "path" in a strict sense, it's more similar to a query.
A: Nothing like this exists that I've ever seen. A quick glance at the JavaDocs of some of the alternative parsers didn't find anything either. XOM returns a Nodes object from it's XPath engine, which does allow inserts. That might get you close to what you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Disabling default drag behavior on links in iOS Safari I am developing a web app. I am trying to disable most of the default iOS Safari behavior on links so I set the "-webkit-touch-callout" CSS property on the links to "none". However, I still notice that if I hold my finger on a link for a second or so, then drag it, then let go of it, the link will open in a new window. I don't want this behavior. I would like it to either open in the same window, or do nothing at all. Does anyone know how to make this happen?
EDIT: I am using jQuery so it is OK to use jQuery's event-handling functions if that will simplify things.
EDIT 2: For some links, I am using handlers to override their default behavior. For example:
$(".categoryList a").live("click", function(e) {
e.preventDefault();
$.get(
"someOtherUrl",
{someVariable: "someValue"},
function(result) {
$(".result").html(render(result));
}
);
});
My actual code is more complicated than this but my point is that I am overriding the default click action on some links and whatever solution I use to fix this problem should not interfere with these handlers. Sanooj's solution does not work for my purposes because the "window.location" assignment always redirects the browser regardless of whether I have any handlers to prevent this behavior. Maybe I arguably shouldn't use links for this purpose but this is how the app was before I started working on it and changing this would be a big project. I am wondering if there is an easier and simpler way to fix this.
A: please check this
$('a').live('click', function (event) {
event.preventDefault();
window.location = $(this).attr("href");
});
A: I know you said you already tried it, but you might be running into a specificity issue. You can try something like this.
* {
-webkit-touch-callout: none !important;
}
Hope this helps.
If this doesn't solve your problem, try here
A: Set a timeout before loading the ajax content and detect finger movements:
function setupAnchorClicks() {
var timer = null;
$(".categoryList a").live("click", function(e) {
e.preventDefault();
timer = setTimeout(function() {
// ...
}, 1000);
}).live("touchmove", function() {
clearTimeout(timer);
});
}
setupAnchorClicks();
This probably doesn't work out of the box because I'm a terrible javascript coder, but you get the idea :)
A: This worked for me:
a {
-webkit-user-drag: none;
}
A: I don't know if this will work, but on default webkit (chrome/safari) you set the attribute ondragstart="return false;" to disable default drag behavior.
A: To resolve your issue with Sanooj's solution have you tried calling your own functions from within his suggested code? For example:
$('a').live('click', function(event)
{
if($(this).hasClass('categoryList'))
categoryListSpecificFunction();
event.preventDefault();
window.location = $(this).attr("href");
});
I can't test this with a Web App at the moment but it works for me in a normal browser, i.e. it prevents the normal behaviour but also allows me to call specific functions based on classes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Why doesn't Windows Azure Diagnostics reliably log? We are having problems getting Windows Azure Diagnostics to reliably log. It seems hit-or-miss and we don't understand why.
Here's our code that sometimes works, sometimes doesn't:
public class WorkerRole : RoleEntryPoint
{
public override void Run()
{
Trace.WriteLine("Run() beginning.", LogLevel.Information.ToString());
try
{
var logic = new WorkerAgent();
logic.Go(false);
}
catch (Exception err)
{
Trace.WriteLine(err.ToString(), LogLevel.Critical.ToString());
Run();
}
}
public override bool OnStart()
{
// Initialize our Cloud Storage Configuration.
AzureStorageObject.Initialize(AzureConfigurationLocation.AzureProjectConfiguration);
// Initialize Azure Diagnostics
try
{
//get the storage account using the default Diag connection string
var cs = CloudStorageAccount.FromConfigurationSetting("Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString");
//get the diag manager
var dm = cs.CreateRoleInstanceDiagnosticManager(RoleEnvironment.DeploymentId,
RoleEnvironment.CurrentRoleInstance.Role.Name,
RoleEnvironment.CurrentRoleInstance.Id);
//get the current configuration but if that failed, get the values from config file
var dc = dm.GetCurrentConfiguration() ?? DiagnosticMonitor.GetDefaultInitialConfiguration();
//Windows Azure Logs
dc.Logs.BufferQuotaInMB = 25;
dc.Logs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;
dc.Logs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
//Windows Event Logs
dc.WindowsEventLog.BufferQuotaInMB = 25;
dc.WindowsEventLog.DataSources.Add("System!*");
dc.WindowsEventLog.DataSources.Add("Application!*");
dc.WindowsEventLog.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
////Performance Counters
//dc.PerformanceCounters.BufferQuotaInMB = 25;
//var perfConfig = new PerformanceCounterConfiguration
// {
// CounterSpecifier = @"\Processor(_Total)\% Processor Time",
// SampleRate = TimeSpan.FromSeconds(60)
// };
//dc.PerformanceCounters.DataSources.Add(perfConfig);
//dc.PerformanceCounters.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
//Failed Request Logs
dc.Directories.BufferQuotaInMB = 25;
dc.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
////Infrastructure Logs
//dc.DiagnosticInfrastructureLogs.BufferQuotaInMB = 25;
//dc.DiagnosticInfrastructureLogs.ScheduledTransferLogLevelFilter = LogLevel.Verbose;
//dc.DiagnosticInfrastructureLogs.ScheduledTransferPeriod = TimeSpan.FromMinutes(1);
//Crash Dumps
CrashDumps.EnableCollection(true);
//overall quota; must be larger than the sum of all items
dc.OverallQuotaInMB = 5000;
//save the configuration
dm.SetCurrentConfiguration(dc);
}
catch (Exception ex)
{
Trace.Write(ex.Message, LogLevel.Critical.ToString());
}
// give logging time to register itself and load up.
Thread.Sleep(10000);
Trace.WriteLine("Completed diagnostics initialization.", LogLevel.Information.ToString());
return base.OnStart();
}
}
Note that our AzureStorageObject.Initialize method replaces the standard CloudStorageAccount.SetConfigurationSettingPublisher method.
Using this code with absolutely no code changes or configuration changes, we can run it over and over and over in the emulator or deploy it over and over and over to Azure with equally unreliable results. Notice that what's SUPPOSED to happen is 1) setup WAD 2) sleep 10 seconds to give it time to finish (I was really grasping for straws when I added this) 3) log that WAD init is done 4) we log that Run() is called and then we go do all of our work (WorkerAgent has our while(true) loop in it). Sometimes this is what happenes. Sometimes, we don't get the logged message in 3) but we do get it in 4). Sometimes we don't get it in 3 or 4). Again, NOTHING changes in code or configuration and all of this points to Azure storage (not emulator storage).
Why isn't this reliably logging every time we call Trace.Write?
A: This question
TraceSource.TraceEvent() fails logging when Exception message contains non-printable characters
reports an issue when logging silently fails as a consequence of an exception being thrown while logging. Specifically in this case the log message can't be serialized.
The fix for this situation is to use HttpUtility.HtmlEncode to encode the exception text before it's logged in Azure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: What Is -[NSURL _fastCharacterContents]:? So I'm calling this in a method:
-(id)initWithContentURL:(NSString *)url {
if (self = [super init]) {
NSLog(@"xSheetMusicViewController - %@",url);
// Casting an NSString object pointer to a CFStringRef:
CFStringRef cfString = (CFStringRef)url;
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), cfString, NULL, NULL);
pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
}
return self;
}
Which crashes right at the NSLog at the line marked:
CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), cfString, NULL, NULL);
with this wonderful little error I've never seen before. Here's the crash log:
SheetMuse[83550:b603] -[NSURL _fastCharacterContents]: unrecognized selector sent to instance 0x4ec35f0
2011-09-22 17:36:22.921 SheetMuse[83550:b603] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURL _fastCharacterContents]: unrecognized selector sent to instance 0x4ec35f0'
*** Call stack at first throw:
(
0 CoreFoundation 0x011be5a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x01312313 objc_exception_throw + 44
2 CoreFoundation 0x011c00bb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x0112f966 ___forwarding___ + 966
4 CoreFoundation 0x0112f522 _CF_forwarding_prep_0 + 50
5 CoreFoundation 0x010d2857 CFStringGetCharactersPtr + 135
6 CoreFoundation 0x010d6c93 CFStringGetFileSystemRepresentation + 35
7 CoreFoundation 0x01110811 _CFFindBundleResources + 289
8 CoreFoundation 0x0110d961 CFBundleCopyResourceURL + 305
9 SheetMuse 0x00005b19 -[xSheetMusicViewController initWithContentURL:] + 153
10 SheetMuse 0x00009724 -[ExamplesViewController tableView:didSelectRowAtIndexPath:] + 708
11 UIKit 0x00487b68 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1140
12 UIKit 0x0047db05 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 219
13 Foundation 0x00b9779e __NSFireDelayedPerform + 441
14 CoreFoundation 0x0119f8c3 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 19
15 CoreFoundation 0x011a0e74 __CFRunLoopDoTimer + 1220
16 CoreFoundation 0x010fd2c9 __CFRunLoopRun + 1817
17 CoreFoundation 0x010fc840 CFRunLoopRunSpecific + 208
18 CoreFoundation 0x010fc761 CFRunLoopRunInMode + 97
19 GraphicsServices 0x028a31c4 GSEventRunModal + 217
20 GraphicsServices 0x028a3289 GSEventRun + 115
21 UIKit 0x0041ec93 UIApplicationMain + 1160
22 SheetMuse 0x000028a9 main + 121
23 SheetMuse 0x00002825 start + 53
)
terminate called throwing an exceptionsharedlibrary apply-load-rules all
So, what is this error, and how do I fix it?
EDIT: This question has been solved. Thank you everyone who answered, I was banging my head on the wall trying to figure this out. If you would like, I can give you a mention in the app, seeing as I would like to release it in a few weeks, and your help has ironed out the biggest bug in the code. Again THANK YOU!
A: -_fastCharacterContents: is a private method of NSString. The error you get indicates that the corresponding message was being sent to an NSURL instance, hence the crash. It looks like the url parameter that’s being passed to -initWithContentURL: is an NSURL, not an NSString.
Placing
NSLog(@"url is of type %@", [url class]);
at the beginning of the method should tell you the exact class of url.
I suggest you change your method signature to:
- (void)initWithContentPath:(NSString *)path
in order to make it clear that the method expects a string representing a (relative) path. There are other classes in Cocoa Touch that declare -initWithContentURL: to receive an NSURL * argument.
A: In most cases this sort of error is due to passing the wrong type of object on a call.
A: How are you calling initWithContentURL? It looks like you might be passing an NSURL that has been (improperly) cast to an NSString.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: MediaRecorder crashes when record a second audio clip I am trying to record audio clips with MediaRecorder, but I keep getting these errors in my Logcat when I start, stop, and start again; the activity would also close:
INFO/DEBUG(1285): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
INFO/DEBUG(1285): Build fingerprint: 'LGE/thunderg/thunderg/thunderg:2.2.1/FRG83/eng.nikech.choi.20110126.134422:user/release-keys'
INFO/DEBUG(1285): signal 11 (SIGSEGV), fault addr 00000010
INFO/DEBUG(1285): r0 00000000 r1 00000000 r2 a930cc98 r3 00000001
……
INFO/DEBUG(1285): #00 pc 00033c28 /system/lib/libmedia.so
INFO/DEBUG(1285): #01 pc 0000780e /system/lib/libmedia_jni.so
……
INFO/DEBUG(1285): code around pc:
INFO/DEBUG(1285): a9033c08 2001e001 1c1861a0 46c0bd70 00029a58
……
INFO/DEBUG(1285): code around lr:
INFO/DEBUG(1285): a93077f0 f7ffb510 bd10ffcf b082b570 ae011c05
……
INFO/DEBUG(1285): stack:
INFO/DEBUG(1285): bef054d0 00000001
……
An audio clip is recorded and can be played on the computer, but if I want to record another one, the above happens. I have already asked for permission in the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
I used this code from Ben McCann:
import java.io.File;
import java.io.IOException;
import android.media.MediaRecorder;
import android.os.Environment;
/**
* @author <a href="http://www.benmccann.com">Ben McCann</a>
*/
public class AudioRecorder {
final MediaRecorder recorder = new MediaRecorder();
final String path;
/**
* Creates a new audio recording at the given path (relative to root of SD card).
*/
public AudioRecorder(String path) {
this.path = sanitizePath(path);
}
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
if (!path.contains(".")) {
path += ".3gp";
}
return Environment.getExternalStorageDirectory().getAbsolutePath() + path;
}
/**
* Starts a new recording.
*/
public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state + ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
recorder.reset();
System.out.println("reset");
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
System.out.println("setAudioSource");
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
System.out.println("setOutputFormat");
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
System.out.println("setAudioEncoder");
recorder.setOutputFile(path);
System.out.println("setOutputFile");
recorder.prepare();
System.out.println("prepare");
recorder.start();
System.out.println("start");
}
/**
* Stops a recording that has been previously started.
*/
public void stop() throws IOException {
recorder.stop();
System.out.println("stopped");
recorder.release();
System.out.println("released");
}
}
My code:
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class TestActivity extends Activity implements OnClickListener {
private final String TAG = TestActivity.class.getSimpleName();
Button startRecord;
Button stopRecord;
boolean recordStarted = false;
private static String fileName = "/Recordings/event.3gp";
AudioRecorder audioRecorder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.record);
startRecord = (Button)findViewById(R.id.buttonStartRecord);
stopRecord = (Button)findViewById(R.id.buttonStopRecord);
startRecord.setOnClickListener(this);
stopRecord.setOnClickListener(this);
audioRecorder = new AudioRecorder(fileName);
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "resumed");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "paused");
}
@Override
public void onClick(View v) {
if (v == startRecord){
try {
audioRecorder.start();
Toast.makeText(this, R.string.msgRecordSuccessful,
Toast.LENGTH_SHORT).show();
recordStarted = true;
Log.e(TAG, String.format("recording: %s", recordStarted));
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, R.string.msgRecordFail, Toast.LENGTH_SHORT).show();
}
} else if (v == stopRecord){
if (recordStarted == true) {
try {
audioRecorder.stop();
recordStarted = false;
Log.e(TAG, String.format("recording: %s", recordStarted));
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, R.string.msgNotRecording, Toast.LENGTH_SHORT).show();
}
}
} // end onClick
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="start"
android:id="@+id/buttonStartRecord"></Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/buttonStopRecord"
android:text="Stop"></Button>
</LinearLayout>
Strings:
<string name="msgReset">reset</string>
<string name="msgSetAudioSource">setAudioSource</string>
<string name="msgSetOutputFormat">setOutputFormat</string>
<string name="msgSetAudioEncoder">setAudioEncoder</string>
<string name="msgSetOutputFile">setOutputFile</string>
<string name="msgPrepare">prepare</string>
<string name="msgStart">start</string>
I don't have a lot of programming experience and I have no idea what this means or how to even search for this problem in Google... if anybody can point me in a general direction that would be really nice :D
Thank you!!
------------ updates ---------------
@ Tim
the few lines after the debug block from logcat:
INFO/ActivityManager(1362): Process com.bcit.chairlogger (pid 26461) has died.
INFO/WindowManager(1362): WIN DEATH: Window{44f04e20 com.bcit.chairlogger/com.bcit.chairlogger.TestActivity paused=false}
INFO/ActivityManager(1362): Displayed activity com.bcit.chairlogger/.TestActivity: 106629 ms (total 106629 ms)
INFO/UsageStats(1362): Unexpected resume of com.lge.launcher while already resumed in com.bcit.chairlogger
WARN/Flex(1456): getString FLEX_OPERATOR_CODE TLS
WARN/Flex(1456): getString FLEX_OPERATOR_CODE TLS
INFO/#LGIME(1442): #### onStartInput: restarting=false, fieldId=-1
WARN/InputManagerService(1362): Got RemoteException sending setActive(false) notification to pid 26461 uid 10071
A: i had same error, solution that worked for me "And MediaRecorder recorder = new MediaRecorder(); at the beginning of start()" (Several audio recording in Android)
A: I solved this issue by adding the recorder in stop functionality.
You need to add this 4 line code inside stop() then only you can start the second audio clip:
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
Refer below code:
public void stop(View view) {
try {
myRecorder.stop();
myRecorder.reset();
myRecorder.release();
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
startBtn.setEnabled(true);
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
A: Turns out it was due to the AudioRecorder class. Since the new MediaRecorder object is created at the beginning of the class rather than in the "start" method, the object is released every time in the "stop" method, rendering it useless.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: are there character set restrictions or autoconversion oddities for location.hash? i want to store and retrieve data via the url hash. the user is able to make some dropdown settings on the page, which should get written into the url via the location.replace function*.
for simplicity’s sake, it now works like this: initially, the user is on test.com. after changing two settings, the url looks like this: http://test.com#fruit→banana#color→light blue.
another almost as simple way would be http://test.com#fruit=banana, color=light blue. the only characters the settings and options contain are (as regular expression) [A-Za-z &]
as far as i can tell, this works fine, although firefox url-escapes everything on copying, and chrome doesn’t. after pasting and pressing enter, the url bar shows the unescaped hash, fetching location.hash per javascript also gives the unescaped unicode string.
my question: are there any probblems, inconsistencies, or other quirks i don’t know about?
*FYI: location.replace("#hash") works just like one would expect :D
A: As i already noted in the comment, forget
location.hash
and use
location.href.replace(/^[^#]+/,'');
instead.
It will save you a whole heap of trouble.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to access a non static member from a static method in java? I have a situation where i have to access a non static member from inside a static method. I can access it with new instance, but current state will be lost as non static member will be re-initialized. How to achieve this without losing data?
A: Maybe you want a singleton. Then you could get the (only) instance of the class from within a static method and access its members.
The basic idea is
public class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
and then in some static method:
public static someMethod() {
Singleton s = Singleton.getInstance();
//do something with s
}
A: What you are asking for doesn't really make sense. Just make your method non-static because your static method cannot be tied to an instance.
A: Static methods do not apply to a particular instance/object, they're a class-level thing. Because of that, they're not given an instance reference. So, no you cannot do this.
If you can work out which instance reference to use another way, you could access the non-static methods of it.
Or, alternatively, re-architect your classes so that it's a non-static method.
A: You can't. A static method is not associated with any particular state (aka any non-static members). In other words, they operate independently of any particular instance of the class so they cannot depend on non-static members.
A: A non static member variable "is state". It's the state of a specific instance of that class.
When you say you want to access a non-static member variable, it's as good as saying "want to access a non-static member variable of a specific instance of class XXX", I mean the bolded part is implicit.
So it doesn't make sense to say "I can access it with new instance".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use FormsAuthentication with logins stored in SQL Server DB table? I am making a new web application in ASP.NET (in C#) using FormsAuthentication for the login. A standard FormsAuthentication setup is in place currently, with usernames and passwords specified in the web.config as usual, and this setup is working great. However,
I would like to link this login setup to an SQL Server table in the database. This table stores user account information for each user, including username and password. Basically, I would like to find a way so that the following line of code will look for a username and password in this DB table, rather than in the web.config as it normally does:
FormsAuthentication.Authenticate(txt_username.Text, txt_password.Text);
But I'm at a loss as to how to do this exactly.
I've been reading about Membership.ValidateUser, but I still cannot find how to use that to link to the usernames and passwords in the users table in the database.
Any help will be highly appreciated!
(Btw, this is my first post, so please feel free to point out any noob mistakes I may have made).
A: You need to implement a custom MembershipProvider.
The MembershipProvider is the mechanism that your application will use to authenticate users as well as handle user-related functionality (change password, unlock users, etc). A custom MembershipProvider is nothing more than a class which extends the MembershipProvider abstract class. This is where you'll write custom logic to interface with your database to perform the required membership actions (validate credentials, create user, change password, etc).
Have a look at this tutorial:
http://www.asp.net/general/videos/how-do-i-create-a-custom-membership-provider
This is a good resource if you are unfamiliar with ASP.NET Membership.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails 3.1 is very slow in development-mode because of assets, what to do? After I added Sprockets, Rails is loading very slow in development mode, what should I do to speed it up?
A: Take a look at https://github.com/wavii/rails-dev-tweaks.
Rails is running all of the to_prepare hooks on every Sprockets asset request in development mode. This includes things like auto-(re)loading your code, and various gems sneak work in there too.
rails-dev-tweaks disables to_prepare & reloading on any asset request (and a few others - read the first part of its README). Speeds up your dev environment by a huge amount for any decently sized project. It's also configurable to do this for any additional requests you like
A: After referring to several Google results regarding this issue, I've nailed down where the DNS issue resides.
The problem is: Rails is doing reverse lookups. So, if you request from a direct IP, or a hostname in the /etc/hosts of only the machine with the browser, which i do often because i run everything in thrown together VM's, and that IP doesn't resolve to something quickly in the dev server, Rails will wait, for each, and every request.
Moral of the story? Include a /etc/hosts entry for every IP related to your development on the dev server (i.e. the server running rails). This means to go ahead and make a hosts entry for every fake/virtual/etc... IP on the dev server you expect to be involved in rails testing, because when it logs requests and whatnot, it will do a reverse lookup, and you want that to be speedy.
A: Weird solution that worked for me. I normally navigated to my app on development via myapp.local:3000, which was set in my hosts file. Assets were loading ridiculously slow.
By navigating to my app via 127.0.0.1:3000, the assets loaded quickly, and further, after using the local ip one time, I could then navigation using myapp.local:3000 and the assets were loading super fast now.
Wish I could tell you why, but I hope it helps someone out there. I'm on OSX 10.7.5.
A: Have you looked at how quickly it runs in production? The development environment behaves differently than testing and production, and takes more performance hits because of it. Without more information, we can't provide you with a better answer.
A: Also check out Turbo Sprokets here - https://github.com/ndbroadbent/turbo-sprockets-rails3
It looks promising.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
} |
Q: Restructuring Default MVC3 Project Directories And NuGet I once watched a TekPub video on MVC2 that suggested renaming Content folder as Public, Adding Scripts to this folder etc.
A couple of developers I am showing MVC preferred this structure and tried it. However with the inclusion of NuGet it seems to expect the folders to be in the standard locations. E.g. JQuery I think just puts itself in \Scripts folder. Guess that is convention over configuration.
Is there anyway to restructure the default folders but explain to NuGet where to put things? Is it just a bad idea to change the default layout?
A: The issue is that currently, when you create a package, you specify in the .nuspec file the path that the file will ultimately end up at. So right now, things are pretty much hard-coded to go to /Content.
We've actually discussed adding the ability to specify virtual folders or placeholders in your .nuspec file. Then the end-user can define a mapping to say all $scripts files go to /public/js, etc.
You can see the discussion here http://nuget.codeplex.com/discussions/256542
We can create an issue for this and get people to vote it up.
A: There is no way for Nuget to know where you randomly decided to put stuff. It can't read your mind, and without some kind of configuration, which Nuget doesn't really have for this sort of thing, it simply isn't possible.
This is why you should stick to conventions, because doing so saves you a lot of work if you are ever going to need to utilize third party tools.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Order navigation properties when using Include and/or Select methods with EF 4.1 Code-First? This is the second step of a question explained here: EF 4.1 code-first: How to load related data (parent-child-grandchild)?.
With @Slauma's guidance, I have successfully retrieved data with this approach:
var model = DbContext.SitePages
.Where(p => p.ParentId == null && p.Level == 1)
.OrderBy(p => p.Order) // ordering parent
.ToList();
foreach (var child in model) { // loading children
DbContext.Entry(child)
.Collection(t => t.Children)
.Query()
.OrderBy(t => t.Order) // ordering children
.Load();
foreach (var grand in child.Children) { // loading grandchildren
DbContext.Entry(grand)
.Collection(t => t.Children)
.Query()
.OrderBy(t => t.Order) // ordering grandchildren
.Load();
}
}
Though this approach works, it sends many queries to the database and I am searching for a way to do this all in just one query. With @Slauma's guidance (explained in the answer at the above link), I have changed the query to this one:
var model2 = DbContext.SitePages
.Where(p => p.ParentId == null && p.Level == 1)
.OrderBy(p => p.Order)
.Include(p => p.Children // Children: how to order theme???
.Select(c => c.Children) // Grandchildren: how to order them???
).ToList();
Now, how can I order children (and grandchildren) when selecting them (such as shown in the first code example above)?
A: Unfortunately eager loading (Include) doesn't support any filtering or sorting of loaded child collections. There are three options to achieve what you want:
*
*Multiple roundtrips to the database with explicite sorted loading. That's the first code snippet in your question. Be aware that multiple roundtrips are not necessarily bad and that Include and nested Include can lead to huge multiplication of transfered data between database and client.
*Use eager loading with Include or Include(....Select(....)) and sort the data in memory after they are loaded:
var model2 = DbContext.SitePages
.Where(p => p.ParentId == null && p.Level == 1)
.OrderBy(p => p.Order)
.Include(p => p.Children.Select(c => c.Children))
.ToList();
foreach (var parent in model2)
{
parent.Children = parent.Children.OrderBy(c => c.Order).ToList();
foreach (var child in parent.Children)
child.Children = child.Children.OrderBy(cc => cc.Order).ToList();
}
*Use a projection:
var model2 = DbContext.SitePages
.Where(p => p.ParentId == null && p.Level == 1)
.OrderBy(p => p.Order)
.Select(p => new
{
Parent = p,
Children = p.Children.OrderBy(c => c.Order)
.Select(c => new
{
Child = c,
Children = c.Children.OrderBy(cc => cc.Order)
})
})
.ToList() // don't remove that!
.Select(a => a.Parent)
.ToList();
This is only a single roundtrip and works if you don't disable change tracking (don't use .AsNoTracking() in this query). All objects in this projection must be loaded into the context (the reason why the first ToList() is necessary) and the context will tie the navigation properties correctly together (which is a feature called "Relationship span").
A: Have you try following?
...
Select(from ch in c.children
orderby ch.property desending
select ch)
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How can I size/match a record component while reading in its data from a Stream in Ada? Very specific question but we have some good Ada people here so I would like to hear thoughts. I’m reading data from a file used for embedded systems. The data chunks I’m working with always have a predicable header format …but there’s one problem…the data payload length is given as part of the format right before the payload occurs. So I don’t know the payload size until I read a certain byte at a known position in the header. The chunks occur one after the other.
Literally the format is ([ ] used for readability):
[2byte TAG] [1byte length of payload (LSB)] [1byte length of payload (MSB)] [PAYLOAD]
The payload is human-readable configuration text. The next TAG will be the next two bytes after the previous payload and so on until I don’t see any matching a known TAG after the last payload. Then I know I’m done.
I am reading this out of a file using a direct_IO stream but I might switch to a more general stream and just start performing conversions.
I’d like to store all of this in a simple record at the end of the day
I’m looking for a technique where I can read in the data and reading the 3rd byte I now know the payload size and can size the array or String component to hold the data right at that moment while the record is already acting as the read buffer. That is I need to read the TAG and length data in, so I’d like to store them immediately in a record. I want to store the payload in that same record if I can. I could consider using an access type and dynamically creating the payload storage but that means I have to stop the read after 3 bytes, the do work, and then continue. Plus that means writing will have the same problem since the object's representation no longer matches the expect chunk format.
I was thinking about trying to use a record to hold all this with a discriminant for the payload size and use a representation clause on that record to mimic the exact above described format. With the discriminant being the third byte in both the record and the data chunk I might be able to do a conversation and simply "lay" the data into the object…but I don’t have a way to size the component when I instantiate the record without already reading the TAG and length. I assume I cannot read AND create the object at the same time, so to create the object I need a length. While I could keep fiddling with the file position and read what I need, then go back to the beginning and then create and consume the entire chunk I know there has got to be a better “Ada” way.
Is there a way that I can use the representation clause to fill the header into the record and when the discriminant is filled with a value from the data the record array or String Payload component size would be set?
Also this isn’t just for reading, I need to find a nice way of outputting this exact format into the file when the configuration changes. So I was hoping to use a representation clause to match the underlying format so I could literally “write” the object out to the file and it would be the correct format. I was hoping to do the same for reads.
All the Ada read examples I’m so far seen are with records of know length (or known max length) where the record reads in a static sized data chunk.
Does someone have an example or can point me in the right direction of how I might use this approach in dealing with this variably size payload?
Thanks for any help you can provide,
-Josh
A: Essentially the way this is done is to do a partial read, enough to get the number of bytes, then read the rest of the data into a discriminated record.
Something like the following in pseudo-Ada:
type Payloads is array (Payload_Sizes range <>) of Your_One_Byte_Payload_Type;
type Data (Payload_Length : Payload_Sizes) is
record
Tag : Tag_Type;
Payload : Payloads(1 .. Payload_Length);
end record;
for Data use record
Tag at 0 range 0 .. 15;
Payload_Length at 2 range 0 .. 15;
-- Omit a rep spec for Payload
end record;
Typically the compiler will locate the Payload data immediately following the last rep-spec'ed field, but you'll need to verify this with the vendor, or do some test programs. (There may be a more explicit way to specify this, and I'm open to having this answer updated if someone provides a workable approach.)
And do not provide a default for the Payload_Length discriminant, that would cause instances of the record to always reserve the maximum amount of storage needed for the largest value.
Then, in your data reading code, something along the lines of:
loop
Get(Data_File, Tag);
Get(Data_File, Payload_Length)
declare
Data_Item : Data(Payload_Length);
begin
Data_Item.Tag := Tag;
Get(Data_File, Data_Item.Payload);
Process_Data(Data_Item);
end;
...
exit when Whatever;
end loop;
(You'll need to work out your exit criteria.)
Data_Item will then be dynamically sized for the Payload_Length. Beware, though, if that length is odd, as padding may occur...
A: This situation is precisely what the attribute 'input is in the language for.
If you also own the code that writes that data out to the stream in the first place, then this is easy. Just use
Myobject : Discriminated_Record := Discriminated_Record'input (Some_Stream'access);
(and of course use 'output when writing).
If you must instead read in someone else's formatted data, it gets a wee bit more complicated. You will have to implement your own 'input routine.
function Discriminated_Record_Input
(Stream : access Ada.Streams.Root_Stream_Type'class)
return Discriminated_Record;
for Discriminated_Record'input use Discriminated_Record_Input;
In your implementation of Discriminated_Record_Input, you can get around the discriminant issue by doing everything in the declaration section, or using a local declare block.
(warning: uncompiled code)
function Discriminated_Record_Input
(Stream : access Ada.Streams.Root_Stream_Type'class)
return Discriminated_Record is
Size : constant Natural := Natural'input(Stream);
Data : constant Discriminated_Record_Input
:= (Size, (others => Byte_Type'input(Stream));
begin
return Data;
end Discriminated_Record_Input;
The main drawback to this is that your data may get copied twice (once into the local constant, then once again from there into MyObject). A good optimizer might fix this, as would adding lvalue references to the language (but I don't know if that's being contemplated).
A: Building on Marc Cs & TEDs answers, a couple of points to consider:
*
*As you have mentioned that this is an embedded system, i would also
read the project requirements regarding dynamic memory allocation,
as many embedded systems explicitly forbid dynamic memory
allocation/deallocation. (check your implementation of ada.streams)
*The format you have described is reminiscent of Satellite Payload
formats, am i correct? If so read the spec carefully as those
'sizes' are often more correctly termed 'maximum indexable offset
from this point starting from 0', aka size -1.
*A Discriminent record is probably the way to go, but you may have to
make it an immutable record with a length field (not the
discriminant) to guarantee that your program will not allocate too
much memory. Fix it to your 'reasonable max'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Where on a web server is the best place to store a folder containing resume files? Inside web root or outside? What's safest? Suppose that I have this filepath going /www.mywebsite.com/content/ and that 'content' is my webroot. Should I store these resume files inside a folder in the webroot like so:
/www.mywebsite.com/content/resumes/
and is this safe? I noticed that anyone could link to anyfile externally (without clicking on a proper link that I've created) to any of the files and I don't want this.
E.g.
http://mywebsite.com/resumes/bobs-resume.doc
would give them access Bob's resume even though they can't see what's in:
http://mywebsite.com/resumes/
Or should I just put the resumes folder outside of the webroot like so?
/www.mywebsite.com/resumes/
I know it kinda sounds obvious but I'd like to know if there's any caveats to storing files outside of the webroot. For example, how would I be able to create links to any of those files so that the right (authenticated and authorized) people can download them?
If it helps I'm also working on an Apache, PHP, MySQL stack so if anyone has any PHP specific solutions for this they would be most helpful.
Thank you in advanced for your help.
A: If you are working with Apache, you could add a .htaccess file to /resumes/ that contains deny from all which will prevent anyone from viewing the contents of that directory. Still I don't always recommend this because if the .htaccess file is removed, or not copied, then the directory is no longer secure. This happens easily when moving from one server to another. Also, that only works with apache and you would have to change your method for another server.
I would just as soon store them in a completely non web-accessible location such as /www.mywebsite.com/resumes/ as you suggested.
A: If you put the files outside the website root they will definitely be safe from accidental browsing - inaccessible unless somebody hacks into the server itself. You can then write a script that reads the file content from there and sends it to the browser - after authenticating the visitor (username/password, I guess).
Another possibility is to put the stuff in a site subfolder and require authentication to access that folder, i.e. password-protect the directory with .htaccess; you can send the password to the intended recipient, allow reasonable time to fetch the files and then change the password. A variation would be to compress the files in a ZIP file and set a password on it (or even encrypt the stuff with PGP).
A: Typically when I need to do stuff like this I put it in a dot folder (for example, /var/www/.resumes): this way it is in the web root and you can trivially access it but by default Apache won't serve any files from within a dot folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ModelState.IsValid with custom view result I've created a custom view result that inherits from ViewResult. In my controller I check if ModelState.IsValid and then return my custom view. I'm finding that the errors don't seem to be making it to the view. Here's my view result:
public class EnrichedViewResult<T> : ViewResult
{
public EnrichedViewResult(string viewName, T model)
{
this.ViewName = viewName;
this.ViewData.Model = model;
}
public override void ExecuteResult(ControllerContext context)
{
base.ExecuteResult(context);
}
}
And the method I'm calling on my controller:
public EnrichedViewResult<T> EnrichedView<T>(string viewName, T model){
return new EnrichedViewResult<T>(viewName, model);
}
When I inspect ControllerContext.Controller.ViewData.ModelState in ExecuteResult the ModelState contains errors as I would expect.
[Update]
@Andras was spot on. I needed to pass the ViewData from my controller rather than just a model. Easiest way was to grab my base controller's ViewData property (same as what ASP.NET MVC use for the ViewResult helper methods. I changed my custom ViewResult to accept a ViewDataDictionary and my helper methods to below:
public EnrichedViewResult<T> EnrichedView<T>(string viewName, T model){
if (model != null) {
ViewData.Model = model;
}
return new EnrichedViewResult<T>(viewName, ViewData);
}
A: I think you should be passing in a ViewData object to your result; since that is the container of ModelState; not simply the Model. Typically you then shortcut the creation/passing of the ViewData by using the Controller's ViuewData as a starting point, writing in the model (check out the base controller).
From this code it doesn't there's any way ModelState could make it to the view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Lucene query using GetFieldQuery not getting back results? I am not sure why this is not pulling back documents:
The documents being added:
document.Add(new Field("project.id", projectId.ToString(), Field.Store.YES, Field.Index.NO));
document.Add(new Field("contact.id", entity.Id.ToString(), Field.Store.YES, Field.Index.NO));
document.Add(new Field("contact.businesspartnerid", entity.BusinessPartnerId.ToString(), Field.Store.YES, Field.Index.NO));
document.Add(new Field("contact.businesspartner.name", entity.BusinessPartner.Name, Field.Store.YES, Field.Index.ANALYZED));
document.Add(new Field("contact.emailaddress", entity.EmailAddress, Field.Store.YES, Field.Index.ANALYZED));
document.Add(new Field("contact.firstname", entity.FirstName, Field.Store.YES, Field.Index.ANALYZED));
document.Add(new Field("contact.lastname", entity.LastName, Field.Store.YES, Field.Index.ANALYZED));
document.Add(new Field("contact.fullname", entity.FirstName + " " + entity.LastName, Field.Store.YES, Field.Index.ANALYZED));
The Query in Lucene.Net:
var prefix = "dan";
var fields = new {"contact.emailaddress"};
var filterFields = new Dictionary<string,string>();
filterFields.add("project.id","123456");
var parser = new MultiFieldQueryParser(Version.LUCENE_29, fields, new KeywordAnalyzer());
var query = new BooleanQuery();
query.Add(parser.Parse(prefix + "*"), BooleanClause.Occur.MUST);
if (filterFields != null)
{
foreach (var field in filterFields)
{
query.Add(parser.GetFieldQuery(field.Key, field.Value), BooleanClause.Occur.MUST);
}
}
The query being passed to Lucene:
query.Query = {+(contact.emailaddress:dan* ) +project.id:123456}
if I remove the parser.GetFieldQuery it works great. When I physically look into the index file there is an entry with the project.id and an entry that starts with "dan".
Should I be doing something else to facet the search by project.id?
A: I ended up changing the way Lucene was storing the project.id:
document.Add(new Field("project.id", projectId.ToString(), Field.Store.NO, Field.Index.ANALYZED));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to work with date_select form helper without a model in Rails? I have a variable @the_date and a date_select form helper without an associated model.
How to use date_select to display the appropriate HTML?
The following does not work:
<%= date_select "the_date", @the_date %>
A: You can do:
<% @the_date = Time.now %>
<%= date_select("my_date", "my_date", :default => @the_date) %>
A: Here's what finally worked:
<% @the_date = Date.strptime(@the_date_string, "%Y-%m-%d") %>
<%= date_select("the_date_string", "", :default => @the_date) %>
I am storing the date as a string. So, it needs to be converted to a date object before displaying in the HTML form, and converted back to a string before saving in the database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How does one use a WPF/SL Grid and GridSplitter as a bindable SplitContainer? Suppose you want to allow a user to re-size a WPF/SL Grid containing two columns. But you also want to allow the user to hide one column (a "panel") or the other column. When both columns (panels) are shown, the GridSplitter should be also be shown; otherwise not. You also want to use MVVM-style bindings without code-behind. And maybe you want to persist the settings between sessions. You have these properties in your view-model:
bool IsPanelOneVisible
bool IsPanelTwoVisible
GridLength SplitPosition
So how can I wire this up using only bindings?
Note that a grid column's width (set either via binding or to Auto) gets overridden when the user drags the GridSplitter.
None of the posts that I've perused (which also include a couple of SplitContainer implementations) address this scenario head on. One could wire this up using code-behind (in response to events) or additional properties on the view-model. But I was hoping for a more elegant solution.
Any ideas? Thanks!
A: We hit the same problem and the binding solutions were so messy we would up creating a user control to do all the above (splitter and toggle of panes on/off).
The problem is that the 1st column size changes from pixel sized (resizable by the splitter) to autosize and back again. The visibility of the splitter may also change depending on how you want it to function.
Once you create a user control to do the lot you will stop worrying about MVVM on the inside (code-behind is not evil for user controls, only at an application level) and only worry about exposing MVVM friendly properties like IsPanelOneVisible etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Selecting SVG and path elements with JavaScript I would like to select the last path in an SVG and remove it. I've tried a variety of methods, in pure javascript and in jquery and I don't seem to be able to access the SVG properly or its paths.
HTML:
<div id="thesvgwrapper">
<svg id="thesvg"...><path ....></path><path ...></svg>
</div>
I CAN clear the SVG using:
$('svg#thesvg').empty();
I CAN see the SVG's contents using:
var svgwrapper = $('#svgwrapper');
var svgcontents = $(svgwrapper).html();
alert(svgcontents);
However, I CANNOT similarly select the SVG and see it's path contents...
my goal is something like
$('#thesvg path:last').remove();
thanks a million for any help
A: Here's executable code in pure JavaScript:
var paths = svgDoc.getElementsByTagName("path");
var last_path = paths[paths.length - 1];
last_path.parentNode.removeChild(last_path);
A: I'm assuming that you're using an SVG compatible browser, such as Firefox.
It's been a while since I tried to manipulate SVG via jQuery. I remember that I was reluctant to use an SVG jQuery plugin, but without one I was having some problems accessing the elements in the DOM. Including the jQuery SVG plugin allowed me to access the elements so including it might help with the problems that you're having.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: how to find users roles stored using bitwise technique in sql? I would like to run a simple query to get all users of a particular role, the problem is user roles are stored in bitwise numbers using power of 2 pattern.
For example the roles table is.
1 role one
2 role two...
4
8
16
In a user table we have
username other columns roles
billy .... 192949
I'm not sure how to query for a role like that...
A: For a single role:
DECLARE @RoleOne = 1
SELECT * FROM Users
WHERE (roles & @RoleOne) > 0
Or a member of all multiple roles
DECLARE @MultipleRoles = 1 + 4 + 64
SELECT * FROM Users
WHERE (roles & @MultipleRoles) = @MultipleRoles
(I'm assuming SQL Server but will be very similar for other flavours)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FreeFontPath: FPE "unix/:7100" refcount is 2, should be 1; fixing I tried to run Xvfb in my Centos 5.7 machine to get thumbnails of websites.
I follow this Xvfb + Firefox site and install Xvfb, firefox on my Gnome Centos 5.7.
No problem at all for installation, yet when I try to run
DISPLAY=:1 firefox-remote http://www.google.com/
I kept getting this error message
FreeFontPath: FPE "unix/:7100" refcount is 2, should be 1; fixing.
and I can not proceed with anything else now. Hours of hours spent and still have no clue, please help me out here.
A: This fixed it for me:
http://corpocrat.com/2008/08/18/fix-freefontpath-fpe-unix7100-refcount-is-2-should-be-1-fixing/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Problems submitting form after using .getJSON to submit to another site I have a form that's being validated using jQuery Validate and then submitted to a third-party subscription site.
I'm trying to get the submission posted elsewhere, too.
Here's my form:
<form class="" action="http://www.fakelink.com/forms/userSubmit.jsp" method="post" id="providerDemoForm" accept-charset="UTF-8">
<fieldset>
<ul class="undecorated group">
<li>
<label for="fld_1_fn">First Name*</label>
<input type="text" name="First Name" id="fld_1_fn" class="required" onFocus="clearMsg();" />
</li>
</fieldet>
</form>
Here's my validation script:
<script type="text/javascript">
function postCMFields() {
$.getJSON(
"http://sample.createsend.com/x/x/x/fmill/?callback=?",
$('#providerDemoForm').serialize()
);
}
$(document).ready(function() {
$("#providerDemoForm")[0].reset();
$("#providerDemoForm").validate({
errorClass: "fieldWithErrors",
validClass: "valid",
highlight: function(element, errorClass, validClass) {
$(element).parent("li").addClass(errorClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).parent("li").removeClass(errorClass);
},
errorContainer: "#formErrorMsg",
errorLabelContainer: "#messageBox",
wrapper: "li", debug:false,
submitHandler: function(form) {
$('#formErrorMsg').hide();
postCMFields();
form.submit();
},
invalidHandler: function(form, validator) {
$('#formErrorMsg').show();
}
});
});
</script>
Everything submits if I don't have that getJSON part (form submits the action url). If I add in the function to post the contents with JSON to my campaignmonitor url, though, it doesn't work. Furthermore, if I comment out "form.submit()", the data DOES get posted to campaignmonitor.
Is there something I'm missing? Thanks!
A: I'm not certain why my code wasn't working, but I think it was because my MIME type wasn't set correctly. I was able to get things working by updating my postCMFields function to use .ajax:
var cmdata = $('#providerDemoForm').serialize();
$.ajax({
type: "GET",
data: cmdata,
url: "http://fake.createsend.com/x/x/x/fmill/?callback=?",
async: false,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
form.submit();
}
});
A: The URL seems fictitious. http://sample.createsend.com/x/x/x/fmill/?callback=? looks like a get URL that you bind variables to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is this cursor not working? Do you know why this cursor is not working? When I click on "More Results" no other results are displayed. Thanks.
if n==1:
query = Main.all()
query.filter("tag_list", s[0])
query.order("-date")
cursor = self.request.get("cursor")
if cursor: query.with_cursor(cursor)
items = query.fetch(2)
cursor = query.cursor()
for item in items:
main_id = item.key().id()
self.response.out.write("""<p>
<a href="%s" target="_blank"><span id=large>%s</span></a>
<a href="/comment?main_id=%s"><span id="small">comments</span></a><br />
%s <a href="/edit?main_id=%s&url_path=/searchhandler?search_string=%s"><span id="small">edit</span></a>
</p>
""" %
(item.url, item.title, main_id,
f1.truncate_at_space(item.pitch), main_id, search_string))
self.response.out.write('<a href="/searchhandler?cursor=%s">More Results</a>' % cursor)
Edit
As Dave W. Smith's answer the problem was with s which changed after cursor is called. I paste below the code with log info.
class SearchHandler(webapp.RequestHandler):
def get(self):
...
#-------search form--------#
self.response.out.write("""
<form name="search_form" action="/searchhandler" method="get"><br />
<input type="text" name="search_string" size=40>
<input type="submit" value="search tags">
</form> """)
search_string = self.request.get("search_string")
s = filter(None, f1.striplist(self.request.get("search_string").split(" ")))
logging.info("""((((((s1: %s))))))""" % s)
# before cursor --> ((((((s1: [u'python']))))))
# after cursor --> ((((((s1: []))))))
n = len(s)
if n==1:
query = Main.all()
query.filter("tag_list", s[0])
query.order("-date")
logging.info("""((((((s2: %s))))))""" % s)
#-->((((((s2: [u'python']))))))
cursor = self.request.get("cursor")
if cursor: query.with_cursor(cursor)
items = query.fetch(2)
cursor = query.cursor()
related_tags = []
if items:
logging.info("""((((((s3: %s))))))""" % s)
#-->((((((s3: [u'python']))))))
for item in items:
for tag in item.tag_list:
related_tags.append(tag)
unique_tags = sorted(f1.f2(related_tags))
for tag in unique_tags:
self.response.out.write("""
<a href="/rt?rt=%s">%s</a> | """ %
(tag, tag))
self.response.out.write("""<br />""")
for item in items:
main_id = item.key().id()
self.response.out.write("""<p>
<a href="%s" target="_blank"><span id=large>%s</span></a>
<a href="/comment?main_id=%s"><span id="small">comments</span></a><br />
%s <a href="/edit?main_id=%s&url_path=/searchhandler?search_string=%s"><span id="small">edit</span></a>
</p>
""" %
(item.url, item.title, main_id,
f1.truncate_at_space(item.pitch), main_id, search_string))
self.response.out.write("""<a href="/searchhandler?cursor=%s">More Results</a>""" % cursor)
logging.info("""((((((s4: %s))))))""" % s)
# --> ((((((s4: [u'python']))))))
self.response.out.write("""<br /><br />""")
else:
self.redirect("/nomatch")
Edit 2
Problem solved as suggested by Dave Smith:
class SearchHandler(webapp.RequestHandler):
def get(self):
...
search_string = self.request.get("search_string")
if search_string:
s = filter(None, f1.striplist(self.request.get("search_string").split(" ")))
self.response.out.write("""
<form name="search_form" action="/searchhandler" method="get"><br />
<input type="text" name="search_string" size=40 value="%s">
<input type="submit" value="search tags">
</form> """ % search_string)
else:
ss = self.request.get("ss")
s = filter(None, f1.striplist(self.request.get("ss").split(" ")))
self.response.out.write("""
<form name="search_form" action="/searchhandler" method="get"><br />
<input type="text" name="search_string" size=40 value="%s">
<input type="submit" value="search tags">
</form> """ % ss)
n = len(s)
if n==1:
query = Main.all()
query.filter("tag_list", s[0])
query.order("-date")
cursor = self.request.get("cursor")
if cursor: query.with_cursor(cursor)
items = query.fetch(7)
cursor = query.cursor()
...
self.response.out.write("""<a href="/searchhandler?cursor=%s&ss=%s">More Results</a>""" % tuple([cursor, search_string]))
...
A: Assuming that code is in a handler, is s[0] the same on each invocation? Cursors only work on identically declared queries. If s[0] changes, the query changes, and the previously-saved cursor won't work with it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: URL rewriting....what am I doing wrong? please help me with this one... I am really new to this subject.
I have placed this in my .htaccess file.
RewriteEngine On
RewriteRule ^gallery/([0-9]+)/?$ viewgallery.php?cid=1 [NC,L]
To make the link
http://www.123456.com/viewgallery.php?cid=1
look like this...
http://www.123456.com/viewgallery/1/
What I am doing wrong... ? It is not working...
Any help is appreciated! Thank you very much....
A: You're rewriting "gallery/1/" instead of viewgallery.
RewriteRule ^viewgallery/([0-9]+)/?$ viewgallery.php?cid=$1 [NC,L]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: tsql query to create new table from a combination of two tables I have a table as follows:
table 1
temp_id node_name variable_1 variable_2 variable_3
1 ab a b y
2 sdd a a a
3 u a s s
and another table as follows:
table 2
temp_id node_name variable_1 variable_2 variable_3
1 ab as sb y
2 sdd a a a
3 u a s s
I want to fetch all the records from table 1 where variable_1, variable_2 and variable_3 of table 1 doesnot match with table 2.
How can I do that in TSQL?
A: Try this:
INSERT INTO new_table
SELECT t1.* FROM table1 AS t1
LEFT JOIN table2 AS t2
ON t1.temp_id = t2.temp_id AND
t1.node_name = t2.node_name
WHERE t1.variable_1 <> t2.variable_1 AND
t1.variable_2 <> t2.variable_2 AND
t1.variable_3 <> t2.variable_3
A: SELECT * FROM [table 1] t1
WHERE NOT EXISTS (
SELECT * FROM [table 2] t2
WHERE
t1.variable_1 = t2.variable_1
AND t1.variable_2 = t2.variable_2
AND t1.variable_3 = t2.variable_3
)
---EDIT---
The above will "fetch all the records from table 1 where variable_1, variable_2 and variable_3 of table 1 doesnot match with table 2", as you asked.
However, it seems that you want to match the specific rows from table 2 not just any rows (BTW, you should have specified that in your question). If that is the case, Marco's answer looks good.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: cvQueryFrame() returns NULL before end of file I'm trying to process large AVI files (approx. 61000 frames, 505MB) with
OpenCV, using cvCaptureFromAVI() and cvQueryFrame().
However, cvQueryFrame() returns a NULL pointer before it reaches the last frame
of the avi.
long int numframe = 6000;
while (numframe < 67000)
{
frame = cvQueryFrame( capture );
if (! frame)
{
fprintf(stderr, "could not query the frame %ld.\n", numframe);
break;
}
char namefile[250];
sprintf( namefile, "/media/6E86F8CB03A4DFA4/image-sequence/%ld.jpg", numframe );
cvSaveImage( namefile, frame ); // save frame as a image
numframe++;
}
Has anyone else has had the same problem and found a way around it?
Is there something that I can do?
A: Most probably you are experienced one of the FFMPEG integration bugs. This bugreport looks very similar to your problem.
What version of OpenCV are you using?
Any way I recommend you:
*
*Try another version of OpenCV
*Try to build OpenCV without FFMPEG. Probably OpenCV will be able to read your file with VfW or GStreamer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the purpose of the implicit grant authorization type in OAuth 2? I don't know if I just have some kind of blind spot or what, but I've read the OAuth 2 spec many times over and perused the mailing list archives, and I have yet to find a good explanation of why the Implicit Grant flow for obtaining access tokens has been developed. Compared to the Authorization Code Grant, it seems to just give up on client authentication for no very compelling reason. How is this "optimized for clients implemented in a browser using a scripting language" (to quote the specification)?
Both flows start out the same (source: https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-22):
*
*The client initiates the flow by directing the resource owner's user-agent to the authorization endpoint.
*The authorization server authenticates the resource owner (via the user-agent) and establishes whether the resource owner grants or denies the client's access request.
*Assuming the resource owner grants access, the authorization server redirects the user-agent back to the client using the redirection URI provided earlier (in the request or during client registration).
*
*The redirection URI includes an authorization code (Authorization code flow)
*The redirection URI includes the access token in the URI fragment (Implicit flow)
Here's where the flows split. In both cases the redirection URI at this point is to some endpoint hosted by the client:
*
*In the Authorization code flow, when the user agent hits that endpoint with the Authorization code in the URI, code at that endpoint exchanges the authorization code along with its client credentials for an access token which it can then use as needed. It could, for example, write it into a web page that a script on the page could access.
*The Implicit flow skips this client authentication step altogether and just loads up a web page with client script. There's a cute trick here with the URL fragment that keeps the access token from being passed around too much, but the end result is essentially the same: the client-hosted site serves up a page with some script in it that can grab the access token.
Hence my question: what has been gained here by skipping the client authentication step?
A: The usual explanation is that the Implicit grant is easier to implement when you're using a JavaScript client. But I think this is the wrong way to look at it. If you're using a JavaScript client that requests protected resources directly via XMLHttpRequest, the Implicit grant is your only option, although it's less secure.*
The Authorization Code grant provides additional security, but it only works when you have a web server requesting the protected resources. Since the web server can store the access token, you run less risk of the access token being exposed to the Internet, and you can issue a token that lasts a long time. And since the web server is trusted, it can be given a "refresh token", so it can get a new access token when the old one expires.
But -- and this is a point that's easy to miss -- the security of the Authorization code flow works only if the web server is protected with a session, which is established with user authentication (login). Without a session, an untrusted user could just make requests to the web server, using the client_id, and it would be the same as if the user had the access token. Adding a session means that only an authenticated user can access the protected resources. The client_id is just the "identity" of the JS webapp, not authentication of said webapp.
It also means that you can end the session before the OAuth token expires. There's no standard way to invalidate an access token. But if your session expires, the access token is useless, since nobody knows it but the web server. If an untrusted user gained access to your session key, they would only be able to access the protected resources for as long as the session was valid.
If there's no web server, you have to use the Implicit grant. But this means that the access token is exposed to the Internet. If an untrusted user gains access to it, they can use it until it expires. This means they'll have access to it for longer than with an Authorization Code grant. So you may want to consider making the token expire sooner, and avoid giving access to more sensitive resources.
*EDIT: More recently, people are recommending that you avoid using the Implicit grant, even on web apps without a server. Instead you can use the Authorization Code grant configured with an empty secret, along with PKCE. The auth-code grant avoids storing the access token in your browser history, and PKCE avoids exposing it if someone hijacks the redirect URL to steal the auth code. In this case you would need the server to avoid returning a refresh token, since your client probably can't store it securely. And it should issue an access token with the same limitations mentioned above.
A: In the implicit flow if the user's browser is corrupted (evil extension / virus ) then the corruption gets access to the user's resources and can do the bad stuff.
In the auth flow the corruption can't because it doesn't know the client secret.
A: in addition to the other answers it is also important to realize that the Implicit profile allows for a front-channel only flow as opposed to the Authorization Code flow that requires a call back to the Authorization Server; this becomes evident in OpenID Connect which is an SSO protocol built on top of Auth 2.0 where the Implicit flow resembles the pretty popular SAML POST binding and the Authorization Code flow resembles the less widely deployed SAML Artifact binding
A: https://www.rfc-editor.org/rfc/rfc6749#page-8
Implicit
The implicit grant is a simplified authorization code flow
optimized for clients implemented in a browser using a scripting
language such as JavaScript. In the implicit flow, instead of
issuing the client an authorization code, the client is issued an
access token directly (as the result of the resource owner
authorization). The grant type is implicit, as no intermediate
credentials (such as an authorization code) are issued (and later
used to obtain an access token).
When issuing an access token during the implicit grant flow, the
authorization server does not authenticate the client. In some
cases, the client identity can be verified via the redirection URI
used to deliver the access token to the client. The access token may
be exposed to the resource owner or other applications with access to
the resource owner's user-agent.
Implicit grants improve the responsiveness and efficiency of some
clients (such as a client implemented as an in-browser application),
since it reduces the number of round trips required to obtain an
access token.
A: It boils down to: If a user is running a browser-based, or "public", (JavaScript) web app with no server side component, then the user implicitly trusts the app (and the browser where it runs, potentially with other browser-based apps...).
There is no 3rd-party remote server, only the resource server. There is no benefit to an authorization code, because there is no other agent besides the browser acting on behalf of the user. There is no benefit to client credentials for the same reason. (Any client can attempt to use this flow.)
The security implications, however, are significant. From https://www.rfc-editor.org/rfc/rfc6749#section-10.3:
When using the implicit grant type, the access token is transmitted in
the URI fragment, which can expose it to unauthorized parties.
From https://www.rfc-editor.org/rfc/rfc6749#section-10.16:
A resource owner may willingly delegate access to a resource by
granting an access token to an attacker's malicious client. This may
be due to phishing or some other pretext...
A: Here are my thoughts:
The purpose of auth code + token in authorization code flow is that token and client secret will never be exposed to resource owner because they travel server-to-server.
On the other side, implicit grant flow is for clients that are implemented entirely using javascript and are running in resource owner's browser. You do not need any server side code to use this flow. Then, if everything happens in resource owner's browser it makes no sense to issue auth code & client secret anymore, because token & client secret will still be shared with resource owner. Including auth code & client secret just makes the flow more complex without adding any more real security.
So the answer on "what has been gained?" is "simplicity".
A: I think Will Cain answered this when he said " There is no benefit to client credentials for the same reason. (Any client can attempt to use this flow.)" Also consider that the redirect_uri for implicit flow maybe "localhost"--no callback is made from the Authorization Server for the implicit flow. As there is no way to pre-trust the client, the user would have to approve the release of user claims.
A: The Implicit Grant allows for obtaining tokens from Authorization Endpoint with a GET. This means the authorization server does not have to support CORS.
If that is not a concern and there are no other issues related to the authorization server been inflexible (e.g. refresh tokens are not optional, for some reason) then authorization code flow is the preferred one, even for public clients, according to recent industry trends and to at least this (current) instance of an official draft.
Historically there were other reasons to implement the implicit flow but it seems they are currently outweighed by security advantages the authorization code grant provides, including:
*
*option to deliver and use the tokens over a back-channel for confidential clients
*not exposing tokens in the browser history for public clients
*interrupting an unauthorized flow before tokens are issued - with PKCE, for "all kinds of OAuth clients"
A: I'm not sure that I understand correctly the answer and Dan's comment. It seems to me that the answer has stated some facts correct but it does point out exactly what OP asked. If I understand correctly, the major advantage of the implicit grant flow is that a client like JS app (e.g Chrome extension) doesn't have to expose the client secret.
Dan Taflin said:
...in the authorization code flow the resource owner never needs to see the access token, whereas in javascript clients that's unavoidable. Client secret could still be kept from javascript clients using authorization code flow, however..
Perhaps I misunderstood you, but the client (JS app in this case) must pass the client credential (client key and secret) to the resource server in the authorization code flow, right ? The client secret cannot be "kept from JS".
A: It's there for security reasons, not for simplicity.
You should consider the difference between the user agent and the client:
The user-agent is the software whereby the user ("resource owner") communicates with other parts of the system (authentication server and resource server).
The client is the software which wants to access the resources of the user on the resource server.
In the case of decoupled user-agent and client the Authorization Code Grant makes sense. E.g. the user uses a web-browser (user-agent) to login with his Facebook account on Kickstarter. In this case the client is one of the Kickstarter's servers, which handles the user logins. This server gets the access token and the refresh token from Facebook. Thus this type of client considered to be "secure", due to restricted access, the tokens can be saved and Kickstarter can access the users' resources and even refresh the access tokens without user interaction.
If the user-agent and the client are coupled (e.g. native mobile application, javascript application), the Implicit Authorization Workflow may be applied. It relies on the presence of the resource owner (for entering the credentials) and does not support refresh tokens. If this client stores the access token for later use, it will be a security issue, because the token can be easily extracted by other applications or users of the client. The absence of the refresh token is an additional hint, that this method is not designed for accessing the user resources in the absence of the user.
A: While Implicit Grant was designed to support apps that could not protect a client secret including client-side JavaScript apps, some providers are implementing an alternative using Authorization Code without a Client Secret instead. The OAuth 2.0 IETF RFC-6749 was published in 2012 and current recommendations some recent discussions are from 2017.
2017 discussion on the IETF OAuth mailing list is available from these implementers:
*
*Redhat: https://www.ietf.org/.../oauth/current/msg16966.html
*Deutsche Telekom: https://www.ietf.org/.../oauth/current/msg16968.html
*Smart Health IT: https://www.ietf.org/.../oauth/current/msg16967.html
Read more here:
*
*https://aaronparecki.com/oauth-2-simplified/
*https://aaronparecki.com/oauth-2-simplified/#single-page-apps
Implicit was previously recommended for clients without a secret, but has been superseded by using the Authorization Code grant with no secret.
...
Previously, it was recommended that browser-based apps use the "Implicit" flow, which returns an access token immediately and does not have a token exchange step. In the time since the spec was originally written, the industry best practice has changed to recommend that the authorization code flow be used without the client secret. This provides more opportunities to create a secure flow, such as using the state parameter. References: Redhat, Deutsche Telekom, Smart Health IT.
Moving to Auth Code without Client Secret from Implicit Grant is also mentioned for mobile apps here:
*
*https://aaronparecki.com/oauth-2-simplified/#mobile-apps
A: I've just faced with some article about OAuth 2.0. Author states that the reason behind the Implicit flow is that JS apps were very restricted in there requests:
if you wonder why the implicit type was included in OAuth 2.0, the
explanation is simple: Same Origin Policy. Back then, frontend
applications were not allowed to send requests to different hosts to
get the access token using code. Today we have CORS (Cross-Origin
Resource Sharing).
https://medium.com/securing/what-is-going-on-with-oauth-2-0-and-why-you-should-not-use-it-for-authentication-5f47597b2611
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "286"
} |
Q: How do you use a require_once header for items in a different folder? I use require_once("header.php"); for all pages of my website. Though, I feel like I can only use that code for files filed directly under the public_html folder. If I use the require_once("header.php"); code for any other files located in a directory (e.g. shirts) under public_html, such that you have public_html/shirts/example.php, the header.php doesn't load the images, links, or any other pages correctly.
I know to resolve this in the short term, I can make a new header just for that directory and add ../ to all the code, but I think there's an easier way. Does anyone know of a way I can just change the code of header.php, so I don't have to make separate headers?
Thanks.
A: You could add to your include_path.
Either add the current directory where header.php is, or create a folder called includes somewhere in your site and add that to the include path.
You can either update the include_path in php.ini (easiest) or do it programmatically like this:
set_include_path(implode(PATH_SEPARATOR, array(
'/path/to/your/includes',
get_include_path(),
)));
The programmatic method works well, but unless most of your files are served through a common script (i.e. front controller pattern) then you will need to copy that code to all of your files which is not ideal. Sometimes you can use .htaccess to set the include_path as well, but only if PHP is an Apache module.
As long as your structure is fairly static, there is nothing wrong with includes using ../ either.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Iteration Problem - appending beginning and ending html I'm trying to figure out how to only append the opening and close div and ul here. I don't know how to compare the next string to the current for the ParentName:
foreach (SList subList in parentList)
{
if (subList.SubList.Count < 1)
return string.Empty;
for(int i = 0; i < subList.SubList.Count; i++)
{
if (string.Compare(subList.PName, lastPName) != 0)
{
subListItemsToHtml.AppendFormat(@"<div id='{0}-test' class='dropdown'>", subList.SubList[i].PName);
subListItemsToHtml.Append("<ul>");
}
subListItemsToHtml.AppendFormat(@" <li><a href='{0}'>{1}</a></li>", subList.SubList[i].URL, subList.SubList[i].DisplayName);
lastPName = subList.SubList[i].PName;
if (i + 1 < subList.SubList.Count)
if(string.Compare(subList.SubList[i].PName, subList.SubList[i+1].PName) != 0)
subListItemsToHtml.Append("</ul></div>");
}
}
return subListItemsToHtml.ToString();
}
A: I don't know if the structure of your data matches the structure of the markup, but changing to this seems logical if it does match:
foreach (SList subList in parentList)
{
if (subList.SubList.Count < 1)
return string.Empty;
subListItemsToHtml.AppendFormat(@"<div id='{0}-test' class='dropdown'>", subList.SubList[i].PName);
subListItemsToHtml.Append("<ul>");
for(int i = 0; i < subList.SubList.Count; i++)
{
subListItemsToHtml.AppendFormat(@" <li><a href='{0}'>{1}</a></li>", subList.SubList[i].URL, subList.SubList[i].DisplayName);
lastPName = subList.SubList[i].PName;
}
subListItemsToHtml.Append("</ul></div>");
}
return subListItemsToHtml.ToString();
Personally, I'd approach this more like a projection of your data using LINQ and LINQ to XML instead. This will also avoid potential mal-formed HTML (you're build HTML through string concatenation without HTML-escaping your output):
var xhtml = new XDocument(
new XElement("div",
from subList in parentList
where subList.SubList.Count > 0
select new XElement("div",
new XAttribute("id", subList.SubList[0].PName + "-test"),
new XAttribute("class", "dropdown"),
new XElement("ul",
from child in subList
select new XElement("li",
new XElement("a",
new XAttribute("href", child.URL),
new XText(child.DisplayName)))))));
return xhtml.ToString();
A: Try to refacor the code as follows:
foreach (SList subList in parentList)
{
if (subList.SubList.Count < 1)
return string.Empty;
for(int i = 0; i < subList.SubList.Count; i++)
{
if (string.Compare(subList.PName, lastPName) != 0)
{
subListItemsToHtml.AppendFormat(@"<div id='{0}-test' class='dropdown'>", subList.SubList[i].PName);
subListItemsToHtml.Append("<ul>");
subListItemsToHtml.AppendFormat(@" <li><a href='{0}'>{1}</a></li>", subList.SubList[i].URL, subList.SubList[i].DisplayName);
subListItemsToHtml.Append("</ul></div>");
}
else
{
subListItemsToHtml.AppendFormat(@" <li><a href='{0}'>{1}</a></li>", subList.SubList[i].URL, subList.SubList[i].DisplayName);
}
lastPName = subList.SubList[i].PName;
}
}
A: One thing I'm not sure about with your question if it is right that there is a sublist of sublists?
It seems like your structure is this:
public class Parent : List<SList>
{ }
public class SList
{
public List<SList> SubList = new List<SList>();
public string PName;
public string URL;
public string DisplayName;
}
In your code you compare the top sublist's PName with each child's sublist's PName and that doesn't seem right to me. Perhaps you could explain your structure some more?
Nevertheless, if I can assume you can flatten your parentList data to just an IEnumerable<SList> then I have a solution for you.
First, I flatten the parentList data like so:
var sublists =
from subList in parentList
from subList2 in subList.SubList
select subList2;
Then I do the following:
var html = String.Join(Environment.NewLine,
sublists
.AdjacentBy(
sl => sl.PName,
sls => String.Format(@"<div id='{0}-test' class='dropdown'><ul>",
sls.First().PName),
sl => String.Format(@"<li><a href='{0}'>{1}</a></li>",
sl.URL,
sl.DisplayName),
sls => @"</ul></div>")
.SelectMany(x => x));
And that produces your html, which should is like the equivalent of this:
var html = @"<div id='foo1a-test' class='dropdown'><ul>
<li><a href='url1a'>bar1a</a></li>
</ul></div>
<div id='goo1b-test' class='dropdown'><ul>
<li><a href='url1b'>bar1b</a></li>
<li><a href='url2a'>bar2a</a></li>
</ul></div>
<div id='foo2b-test' class='dropdown'><ul>
<li><a href='url2b'>bar2b</a></li>
</ul></div>";
Now, I'm sure that you spotted the use of a new extension method AdjacentBy. This is where all the magic takes place.
I very much like to abstract away the kind of operation you are doing into a nice re-usable LINQ operator. Doing so means that your code that does the work of generating your HTML is tight and concise and separated away from the grunt work of iterating the list and grouping the results.
The signature for AdjacentBy looks like this:
IEnumerable<IEnumerable<V>> AdjacentBy<T, K, V>(
this IEnumerable<T> source,
Func<T, K> keySelector,
Func<IEnumerable<T>, V> headerSelector,
Func<T, V> valueSelector,
Func<IEnumerable<T>, V> footerSelector)
Its job is to take a list and make list of lists the whenever the value produced by the keySelector changes. The values in the list of lists comes from the valueSelector.
The headerSelector & footerSelector lambdas can be used to create a header value and footer value based on the items in the current list.
So, as an example, If I run this query:
var query = "CBBCCA"
.AdjacentBy(
c => c,
cs => cs.Count().ToString() + "x",
c => c.ToString(),
cs => ".")
.ToArray();
It will be the equivalent of:
var query = new []
{
new [] { "1x", "C", "." },
new [] { "2x", "B", "B", "." },
new [] { "2x", "C", "C", "." },
new [] { "1x", "A", "." },
};
Here's the full definition of AdjacentBy:
public static IEnumerable<IEnumerable<V>> AdjacentBy<T, K, V>(
this IEnumerable<T> source,
Func<T, K> keySelector,
Func<IEnumerable<T>, V> headerSelector,
Func<T, V> valueSelector,
Func<IEnumerable<T>, V> footerSelector)
{
var first = true;
var last = default(K);
var list = new List<T>();
var values = (IEnumerable<V>)null;
Func<List<T>, IEnumerable<V>> getValues = ts =>
{
var vs = (IEnumerable<V>)null;
if (ts.Count > 0)
{
IEnumerable<V> hs = headerSelector == null
? Enumerable.Empty<V>()
: new [] { headerSelector(ts) };
IEnumerable<V> fs = footerSelector == null
? Enumerable.Empty<V>()
: new [] { footerSelector(ts) };
vs = hs
.Concat(ts.Select(t => valueSelector(t)))
.Concat(fs)
.ToArray();
}
return vs;
};
foreach (var t in source)
{
var current = keySelector(t);
if (first || !current.Equals(last))
{
first = false;
values = getValues(list);
if (values != null)
{
yield return values;
}
list.Clear();
last = current;
}
list.Add(t);
}
values = getValues(list);
if (values != null)
{
yield return values;
}
}
I hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: dynamic container size in asp.net I am taking content from a text file to fill literal controls within my content placeholders. Sometimes there is more text than will fit in the container column. How can i make them dynamic, ie have scroll bars to see the unviewable content?
A: If you style the container with this CSS, then scrollbars will appear when content would overflow:
overflow: auto;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Site.css to Debug mode, site-min.css to release mode In my view like that in debug mode to view Site.css use her, and when compiled in release mode the view using CSS-min.css site.
Something like this:
# if (Debug)
/ / CSS
# elif (Release)
/ / CSS Min-
# endif
But in my view .cshtml
A: You can use Context.IsDebuggingEnabled. This boolean property is controlled by the debug attribute from the compilation section in web.config.
Here's a sample for your view.cshtml :
if (Context.IsDebuggingEnabled)
{
// use something.css
}
else
{
// use something.min.css
}
A: asp.net mvc - Razor view engine, how to enter preprocessor(#if debug) - Stack Overflow
How about this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Concise way to test if X is within the bounds of Y +/- small tolerance? Is there a concise way to test whether some number X is within the bounds of another number Y plus or minus some small tolerance?
A: The all.equal command allows for a tolerance parameter so that differences less than the tolerance value are ignored.
Personally, I am rather fond of all.equal as an alternative to identical, as it is far more informative. It is applicable to objects that are more general than just a single value (e.g. variable1 and variable2), such as data frames, lists, and more. So, although it will do the trick for your question, it is also more general for when you would like to consider whether two data frames are very nearly the same. This is quite useful when the differences are based on issues in numerical precision very close to the machine tolerance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Jquery not working with spring MVC project I am just trying to test jquery in one of my spring MVC project. I have added jquery-1.6.4.min.js file into WebContent/js/ folder. I am using jquery-1.6.4.min.js
Below is the code for my .jsp file. I don't understand where I am wrong. Is there anything else which I am not doing. I even have added the above .js file from windows->preferences-> javascript->include path->User Liberary
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring 3, MVC Examples</title>
<script type="text/javascript" src="/js/jquery-1.6.4.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$("#msgid").html("Hello ");
});
</script>
<div id="msgid">
</div>
Thanks in advance
A: I suspect your path is incorrect, relative and absolute path.
Can you change your source to http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js to isolate this.
A: Chin's suggestion to switch source to the online source is good: http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js
To troubleshoot your current version - if you create a war from your project, is your /js directory in the right place? If the path is wrong, then the jquery definitely won't load. You can use FireBug to see if there are any JS errors as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: contenteditable=false inside contenteditable=true block is still editable in IE8 I have the following HTML intending to make sure that the inner span isn't editable. This works in other browsers but not IE8.
<div contenteditable="true">
Luke, I am your father.
<span contenteditable="false">I'm your son?! Ewww!</span>
Don't speak back to me!
</div>
Here's a JSFiddle to illustrate the point (use IE8 to test it): http://jsfiddle.net/haxhia/uUKPA/3/ .
How do I make sure that IE8 treats this properly as well?
A: Okay, I already have discovered the answer much like how Penicillin was discovered.
You see, playing around with this code, I mistakenly set contenteditable to true for the span and voila! It worked!
So, to make a span NON-contenteditable inside a contenteditable div, you just set its contenteditable attribute to true!
<div contenteditable="true">
Luke, I am your father.
<span contenteditable="true">I'm your son?! Ewww!</span>
Don't speak back to me!
</div>
Here's the file to demonstrate (use IE8 to open it): https://codepen.io/hgezim/pen/qMppLg .
Lastly, I didn't post the question to get votes (although, they wouldn't hurt!), but since the solution was so ridiculous and I didn't find it here, I thought someone may find this tip time saving.
A: The problem with contenteditable="true" inside contenteditable="true" (to make it not editable) on IE is that double clicking on the inner element makes it editable
Solution
Grandparent tag as contenteditable true
Parent tag as contenteditable false
Child tag as contenteditable false
the contents of child tag will not be editable for sure
<ul contenteditable="true">
<li>By default, this content is editable via its
inherited parent elements value.</li>
<li contenteditable="false" ><span contenteditable="false">This content is
<b>not</b>
editable for sure</span></li>
</ul>
JSFiddle example
A: I was stuck with the same problem today and after trying for a while figured a solution that works for me on IE. Add a click event listener to the child contenteditable element. In the event handler do as below
document.querySelector('.simulated-icon').addEventListener('click', function(evt){
evt.stopPropogation;
evt.preventDefault;
return false;
});
<div class="simulated-icon"><span>Icon text</span></div>
As you can see here returning false on the click event listener for the child content editable tells IE to not allow the edit. This works if there is a click event on the parent node and we check if the target child node is clicked in the event listener. Good luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: iPhone :: Objective-C - Loading a list of Images from Restful Webservice into UITableView Hihi all,
I have implement a mechanism for the above (in the question title), this is how it works:
*
*Create an NSURLConnection and make a call to my json webservice to get a list of records with the image URL for each of the record.
*In the connectionDidFinishLoading delegate, I set the returned records to my NSArray and reload my UITableView with the NSArray, but I don't load the image at this point.
*In the same connectionDidFinishLoading delegate, for each of the retrieved record, I fire off separate connection to get the image data. Imagine I have 5 records returned from the previous json webservice, I will fire off 5 GET requests to get my image data for each of the records.
*Then this time round, in the connectionDidFinishLoading delegate, I will know this time it is fired from the request of getting image data, I will set the image data into my NSArray of my UITableView datasource and do a reloadData. For 5 records, the table will be reloaded 5 times.
*Everything seems working fine only if I do not reload the last 2 elements of my NSArray, otherwise, I will hit the exc_bad_access exception.
Appreciate your kind advice. This might be a foolish way of doing thing.
:)
A: The way you describe what you are doing seems OK. You could be using reloadRowsAtIndexPaths to just update each cell as its image is received rather than the whole table.
Here's a stack overflow question that may be helpful. Searching for lazy loading will get you plenty more examples.
I think using Core Data is the right way to do this because it lets you use a NSFetchedResultsController to handle all the table maintenance for you. Initially you load a table with objects that have a nil image path attribute so your cellForRowAtIndexPath can display a placeholder (or nothing). When you get a returned image (asynchronously) you write the image to local storage and update Core Data with the path for the image that should be displayed for that record. When you make a change to core data you do a performFetch on the fetched results controller and your table is displayed correctly. If you follow Apple's sample code you don't even need a reloadData on the table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Recording an AudioTrack to a sound file I am creating PCM data (from sine waves) and piping them to the speakers using AudioTrack.
I'd like to record this as a wav file (or a comparable format). I've looked at AudioRecord but it takes a source, and seems to want a microphone. Can I pipe my own PCM data into AudioRecord without a source so it saves my audio? Or is there another way to accomplish this.
Many thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: image manipulation in php or jquery? For a learn-as-I-code game that I'm designing, I have a pretty rudimentary map:
http://www.dixieandtheninjas.net/dynasties/images/dynasties_map_2.jpg
I want to allow manipulation of the map in some of the following ways:
*
*Have the code place a dot on the map where the player is located (sql
query to determine region number)
*Have the code recolor regions which
are hostile to the player (sql query)
While I think that this question might be far too broad for a succinct answer here, I wonder if someone can point me in the right direction.
Is there functionality built into either PHP or jquery to do this? Will I need additional libraries or resources or anything?
A: well. this indeed is really broad topic and I would suggest starting with something more trivial e.g. tic-tac-toe game.
here are some pointers:
1) if you are about to have visual effects in browser, you would like to checkout canvas and svg (html5)
2) you should understand that any client side "actions" will be generated by javascript (could use jQuery and jQuery)
3) "backend would be php/mysql whatever other server-side-scripting language you choose.
4) communication most likely would happen using AJAX (.get, .post, .ajax)
5) if game is for iOS devices, you might want to read more about touch events
but, each of points above are very very broad. so I suggest that you make it clear for yourself as to what you want to learn and achieve first. then make a proper plan of what technologies are involved, and then get to coding.
good luck
A: I would recommend that you concider of doing more work on the client side, jquery can add the dots and so on to the map if you send the coordinates to the client.
You will of course have to validate the clients actions in order to prevent cheating.
Wrote a quick little sample of a jQuery script that adds dots to your map: http://jsfiddle.net/yc2MC/1/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Network Status in C Right now I am able to retrieve the network status using the following code..
popen("netstat -i | grep '^e[a-z][a-z]*0[ \t]' | head -n1","r")
sscanf(line,"%32s %d %*s %*s %d %d %d %d",
name, &mtu,
&in_packets, &in_errors,
&out_packets, &out_errors);
I want to calculate packets per sec.. How can I do that?
Thanks
A: How to calculate packets/second
*
*Get the number of packets right now.
*Wait n seconds.
*Get the new number of packets.
Now subtract the first number from the second number and divide by n and you have your packets/second over a given interval.
A: you can use tcpstat e.g.
tcpstat -i eth0 -o '%b\n'
Output
16516.80 #bps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: php include() not working I'm making a simple program to interact with a database. I have taken a username variable from the user in a file called "connect_database.php" and called it $un. I then try to access that variable in another file where I have to submit the username to a database with a query. Every variable in the query has gone through except the username so I concluded it was due to my use of the include(). Any help?
include ("connect_database.php");
mysql_query("INSERT INTO `my_proj`. `inci` (
`type`, `date`, `time`, `reporter`, `ID`, `desc`)
VALUES ('$typeinc', CURDATE(), CURTIME(), '$un' ,NULL, '$text');"
) or die(mysql_error());
A: I would change the include() to a require(), since your program doesn't work without it. They are the same, however require will kill the execution if the file can't be included.
Then, once you're sure that the file is actually be included, double-check that the value is being set properly:
require("connect_database.php");
var_dump($un);
If that doesn't work, go back to the connect_database.php file and check your spelling.
A: require_once("connect_database.php");
Should fix your issue.
A: replace the include() with require_once(), look at the apache error log, it will show you the problem.
A: Where is $un declared? Globally or in a function? Is the query you are using where it does not show up in a function? If so the variable is not accessible from there. See variable scope.
Maybe you need global $un; somewhere or assign $un to $GLOBALS['un'] and reference it that way.
A: You might want to re-read the documentation on include and its brothers. They don't behave like you'd expect; instead of resolving the include path relative to the current file (the one you're looking at), they use the current working directory and the include path, which can be anything, depending on the OS, the web server, the PHP configuration files, and anything that has been executed before the include happens. Using require instead of include, like others have suggested, will not solve your problem, but it will tell you whether the include did infact fail.
You can solve your include problem through two means: Either control the current working directory and the include path and apply code discipline to make sure they don't change; or use absolute includes - the __FILE__ constant combined with dirname can be used to emulate the behavior which should have been the default.
On side note, the way you concatenate strings into queries is an SQL injection attack waiting to happen. You better step away from the mysql_XXXX() API now and use something that supports parametrized queries (PDO is great, mysqli also works).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Help resolving SyntaxError: Parse error I'm getting a SyntaxError: Parse Error when my browser runs the following code for an iPhone:
if (window.innerWidth && window.innerWidth <= 480) {
$(document).ready(function(){
$('#usernav ul').addClass('hide');
$('#usernav').append('<div class="leftButton"
onclick="toggleMenu()">Menu</div>');
});
function toggleMenu() {
$('#usernav ul').toggleClass('hide');
$('#usernav' .leftButton').toggleClass('pressed');
}
}
I'm new to all of this (programming, programming languages, etc.) but I'm wondering if this error is caused because I'm viewing my site in a browser.
I've noticed that when I drag my browser's window so the viewing width decreases, my styles degrade as the width decreases. Most sites (including SO it seems) don't allow this degradation in a browser, so I guess my questions are:
*
*What's the error in my JavaScript
*What are the best ways to stop my browser from degrading?
Hopefully that makes sense. Maybe the degradation isn't related to the JavaScript but since it's relevant I figured I'd ask.
EDIT: I've updated the code to close off the append but I'm still getting errors at the $('#usernav').append('<div class="leftButton" line. My IDE says "unterminated string literal".
A: Javascript can end lines with semicolons OR newlines. When you put in a new line, you ended your statement early. Put the statement on one whole line.
A: The problem is here:
$('#usernav').append('<div class="leftButton"
onclick="toggleMenu()">Menu</div>;
You're not closing .append('. You want this:
$('#usernav').append('<div class="leftButton" onclick="toggleMenu()">Menu</div>');
A: $('#usernav').append('<div class="leftButton" onclick="toggleMenu()">Menu</div>;');
I guess you forgot to close the function append() with the bracket and the semicolon. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Posting form data from an ASP.Net Website to a MVC Web Application I have two distinct web sites, one an ASP.Net website and the other a ASP.Net MVC web application. I want to be able to post form data (about 15 fields) from the ASP.Net website to the MVC web application.
Ideally I'd like to be able to create a complex object containing all the form data and post it from the website to the controller action but I'm unsure if this is possible.
What are your thoughts on the best way to do this?
A: There's really nothing to it.
On your ASP.NET web application, you build your form
<form action="http://your/mvc/app/controller/endpoint" method="POST">
<input type="text" name="property" />
<!-- Build your complex type properties here. Not sure how complex it is, but you may have to look up custom model binding -->
</form>
When that form is submitted it will post the data to your MVC controller who can pick it up and do something with it. And probably redirect to your ASP.NET application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python Interpreter Not Reading Indents Properly After Turning on VIM Auto-Indenting I'm not entirely sure what has happened.
I was debugging a script that worked "fine" (except for said intermittent bugs) and all of a sudden the module cannot be imported anymore. I undid all changes and still the problem exists.
Well, problemS. Plural.
Once I got an "unexpected indent" error, even though all the lines were perfectly indented. I fixed that one by deleting the line and retyping it.
Now in the following code, I get one of two errors:
class Lottery:
def __init__(self, session):
self.prizes = PrizeList()
self.session = session
self.players = self.session.listof.players.split(',')
self.pickWinner()
Most of the time, it gives me an error saying "session" is not defined. This is true. I'm just importing the module. It gets defined when the script calling it runs it. I experimented with just removing that line altogether, and then it told me that "self" was not defined.
All of that is the original code that was working 20 minutes ago. the bugs I was fixing are on a different part of this module altogether, and it was certainly importing without problems. Please help!
Traceback:
File "minecraft/mcAdmin.py", line 5, in <module>
from lottery.lottery import *
File "/home/tomthorogood/minecraft/lottery/lottery.py", line 36, in <module>
class Lottery:
File "/home/tomthorogood/minecraft/lottery/lottery.py", line 39, in Lottery
self.session = session
NameError: name 'session' is not defined
EDIT: SOLVED. Okay, somehow while editing, I did accidentally switch between tabs and spacing, which lead to the problem. I deleted and re-wrote that block of code exactly as pasted above and now it's working. There was a ghost indent problem.
DOUBLE EDIT: the core problem was that I only recently turned on auto-indenting in Vim. The configuration I am using is not using tabs as auto-indents, but I was using tabs in the past.
A: You've got an indentation problem.
The self.session = session line, and everything below, isn't inside your __init__ method, it's just inside the class body.
session isn't defined in the class body, only inside __init__, as you mention in your question, so you get the error.
IF you remove that line, the first thing that gets looked up is the self in self.players = self.session.listof.players.split(','), so you get the self is not defined error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: document.write in html/php doc writes to new page I'm trying to write a piece of text over an existing web page based on whether or not the cookie is set. The cookie part works fine, but the document.write causes the text to appear on a new blank page.
<script type="text/javascript">
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{
alert("Welcome again " + username);
}
else
{
username=prompt("Please enter your name:","");
document.write ("hello");
if (username!=null && username!="")
{
setCookie("username",username,7);
}
}
}
</script>
<body onload="checkCookie()">
</body>
I guess I need to use a z-index somehow, but can't seem to get it to work. If someone could explain how I get my 'document.write' line to appea on top of the stuff that already exists on the page, I would be really grateful. All of this is happening on a page on a joomla site, and the code is in the php file for one of the modules. Thanks all.
Rob.
A: document.write() should be avoided.
It has few (arguably) valid use cases, all of which must be used inline in a script element and executed as the page is loaded.
When you use it beyond the page load, it will implicitly call document.open() which will clear your page.
You should favour modern standardised DOM methods.
A: Assign the body an ID, such as 'body', then use the following:
document.getElementById('body').innerHTML = 'Text that you want to assign';
W3 Schools has a good example of it.
A: I think you should define a part in your Markup, where the message should be added.
<div id="wrapper">
<div id="message"></div>
<div id="content">
...
</div>
</div>
So you can just add your Message into the "message"-div:
document.getElementById('message').innerHTML = 'Hello '+username;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Authentication to a WCF service not maintained using SetAuthCookie and a full .net client but works with silverlight I've setup a site with forms authentication and AspNetCompatibility enabled. The actual client is a silverlight application, and works fine, however I want to unit test the application separately using normal .net to exercise the service (live system for methods without side-effects). However, when I stop using Silverlight and start using full .net it doesn't remain authenticated
In a web service I have:
[OperationContract]
public bool Login(string Username, string Password, bool isPersistent)
{
if (Membership.ValidateUser(Username, Password))
{
FormsAuthentication.SetAuthCookie(Username, isPersistent);
return true;
}
else
{
return false;
}
}
[OperationContract]
public bool IsLoggedIn()
{
return HttpContext.Current.User.Identity.IsAuthenticated;
}
Then in a test method on the client I call it like so:
Assert.IsTrue(Client.Login("MyUsername","MyPassword", true));
Assert.IsTrue(Client.IsLoggedIn());
The client is an instance of the automatically generated ServiceReference client for .net. The first assertion passes but the second one fails, i.e. from one method call to the next it stops being logged in. A similar method in the silverlight application would pass.
How can I make normal .net behave correctly as silverlight would? Is there just a better way of configuring client/service for full .net?
Aditional Info Requested
Service Config:
<services>
<service behaviorConfiguration="MyBehaviour" name="SSCCMembership.Web.Services.LoginService">
<endpoint address="" binding="customBinding" bindingConfiguration="customBindingBinary"
contract="SSCCMembership.Web.Services.LoginService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<bindings>
<customBinding>
<binding name="customBindingBinary">
<binaryMessageEncoding />
<httpTransport />
</binding>
</customBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="MyBehaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
Authentication Config:
<authentication mode="Forms" />
<membership defaultProvider="OdbcProvider">
<providers>
<clear />
<add name="OdbcProvider" type="SSCCMembership.Web.SimpleMembershipProvider" applicationName="/SSCCMembership" requiresUniqueEmail="false" connectionStringName="mainConn" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" writeExceptionsToEventLog="true" />
</providers>
</membership>
I then use the following to construct the client in WPF
public static T LoadService<T>(string URI, Func<CustomBinding, EndpointAddress, T> F)
{
try
{
Uri U = new Uri(new Uri(Root), URI);
BinaryMessageEncodingBindingElement binary = new BinaryMessageEncodingBindingElement();
HttpTransportBindingElement transport;
if (U.Scheme == "http")
transport = new HttpTransportBindingElement();
else if (U.Scheme == "https")
transport = new HttpsTransportBindingElement();
else
throw new Exception(U.Scheme + " is not a recognised URI scheme");
transport.MaxBufferSize = int.MaxValue;
transport.MaxReceivedMessageSize = transport.MaxBufferSize;
transport.AllowCookies = true;
CustomBinding binding;
binding = new CustomBinding(binary, transport);
EndpointAddress address = new EndpointAddress(U);
return F(binding, address);
}
catch (Exception)
{
return default(T);
}
}
Which I call like:
var Client = LoadService(ServiceLocation, (b,e)=>new LoginServiceClient(b,e));
A: I think the main problem you are having is due to the context that each application runs in.
A Silverlight application runs in the context of the web-page it's hosted in - and thus, can maintain session info, cookies, and all sorts of other things that you don't need to manually worry about.
As soon as you connect with an application running outside of the browser, your context (as far as asp.net is concerned) has changed. Have you tried enabling/installing the silverlight application out-of-browser to see if you have the same errors?
One way to work around this is to use the Silverlight Unit Test project and connect that to your web service for testing. (I have successfully done this with enterprise silverlight apps for the company I work for) The silverlight unit test project results in a silverlight app that can be hosted on a web page, and run from there - in the same context as any other silverlight app, as far as ASP.net is concerned, making your web-service calls much less likely to fail due to context.
Check out the Silverlight Unit Test Famework Homepage for more info...
A: Change your IsLoggedIn() method to reference the ServiceSecurityContext instead of HttpContext:
[OperationContract]
public bool IsLoggedIn()
{
return ServiceSecurityContext.Current.PrimaryIdentity.IsAuthenticated;
}
A: I had this same type of problem and ended up just implementing the WCF Authentication Services... The documentation was straight forward and it works great with the ASP.NET forms auth provider.
http://msdn.microsoft.com/en-us/library/bb386582.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7522882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.