text stringlengths 8 267k | meta dict |
|---|---|
Q: Combining 2 functions I am trying to combine two functions because A) I think I can and B) I think I should. When I use the functions separately the script works fine. When I combine them the "new" variable is an empty string vice what it should be. Any help would be appreciated. If you need the full script that could be arranged.
Function A:
def strip_domain_name(x):
global ns
l = x.find('@')
ns = x[0:l]
Function B:
def encode_user_name(x,y):
global new
for a in x:
if a in y:
new = new + y.get(a)
Function A+B:
def combined_above_script(x,y,z):
global ns
global new
l = x.find('@')
ns = x[0:l]
for a in y:
if a in z:
new = new + z.get(a)
Here is a simplified version of what I'm trying to do, with some modifications based on blender's suggestion. In the end if I print aa it should result in '0000000'. Which is not the case.
aa = ''
bb = ''
encode = {'a':'0'}
def strip_and_encode(x,y,z):
aa = ''
bb = x[0:x.find('@')]
for a in y:
if a in z:
aa += z.get(a)
s='aaaaaaa@aaa'
strip_and_encode(s,bb,encode)
print(aa)
A: I'd go easy with the globals:
def script(x, y, z):
new = ''
ns = x[:x.find('@')]
for a in y:
if a in z:
new += z.get(a)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET MVC - References a master/layout page from another project? Is it possible to include/reference a master (layout) page from another project? I have a "common" project that houses the look and feel that can be reusable (and able to override/customize) across many projects, but not sure what would be the approach?
Thank you.
A: You can compile your razor views .. look into
http://www.chrisvandesteeg.nl/2010/11/22/embedding-pre-compiled-razor-views-in-your-dll/
Then you can reference them into your project where you want to use it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to apply jQuery UI theme to my regular html? I use jQuery UI for the various widgets like dialogs, buttons, etc. I want to continue using the theme for my other webpage elements like error/alert notices and highlight styles. So I went to the themeroller page to view what they use for the css around, for example, an alert notice:
<div class="ui-widget">
<div style="padding: 0 .7em;" class="ui-state-error ui-corner-all">
<p><span style="float: left; margin-right: .3em;" class="ui-icon ui-icon-alert"></span>
<strong>Alert:</strong> Sample ui-state-error style.</p>
</div>
</div>
There's a wrapper div, span with background icon, etc. Do I just copy these or does the jQuery UI javascript create some for me? What's the proper way to apply themes to non-widget html?
A: Simply apply that to your own HTML. No Javascript needed (except for hover state).
When you're using jQueryUI's widget, the Javascript creates all of that HTML with those classes.
If you need the hover state, you'll have to toggle the ui-state-hover class. For that you'll need Javascript:
$('.ui-state-error').hover(function(){
$(this).toggleClass('ui-state-hover');
});
A: You can by default only use the themeroller pre-defined-elements on your site: buttons, icons, title bars etc. and all the jquery widgets like datepicker, dialogs, highlight/error - pretty much all the elemenst you see at http://jqueryui.com/themeroller/#themeGallery .
to archive this you have to copy the html and the appropriate classes for the html tags, and the browser will apply the styles from your included themeroller.css to it.
however, this also means that you are a bit limited with your layout. You can still include other, non-themeroller elements as long as you apply the right css classes (.ui-state-default, .ui-state-hover, .ui-state-disabled, icons etc.) to your html to be able to use the themeswitcher - see http://jqueryui.com/docs/Theming/API for the complete list of applicable classes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: eclim - cannot create new Projects I just set up eclim to be used inside (g)vim but it is not working. I can :PingEclim so there is no connection Problem but as soon as I try to set up a new Project via
:ProjectCreate /home/me/projectdir -n cpp" I get the strange error
org.eclipse.core.runtime.CoreException: Cannot create managed project with NULL configuration
I am (currently) using Kubuntu 11.04 and gvim.
A: According to eclim guide the fix looks pretty simple:
:ProjectCreate /home/me/projectdir -n c++
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: modification of code to bulk process in r After being recommended to use adehabitat to calculate volume of intersection I have stumbled into a slight (hopefully simple) problem. In this library I am using the kerneloverlap command because I need to calculate the volume of intersection. I was wondering if you could help me with some programming questions. i need to modify the script to make it "bulk" processing friendly. I know enough of R to get myself into trouble and to lose hair because I know certain things should be possible, but can't figure out how to get it to work.
The command is quite simple:
kerneloverlap(loc[,c("X","Y")], loc$year, lev = 90, grid=30, meth="VI", conditional=TRUE)
where it takes from the data file loc the x, y coordinates, by year, and calculates the volume of intersection with a grid cell size of 30 in a utilization distribution of 90.
The input file (see below for excerpt) is anid, X, Y, year, and seasons. For this example there is only 1 season(keep in mind I have 3 seasons). For this example I want to compare within 1 season between years for each individual volume of intersection. So the test data have 2 years and 1 seasons and 2 individuals. What I would like to be able to say is "the volume of Intersection for animal 1 during calving season between year 2003 and 2004 is 0.8 which indicates a high level of overlap and fidelity to a location".
I would also like to then compare between seasons. Such that the volume of intersection for animal 1 during its summer and wintering seasons in 2003 is 0.04 which indicates a low level of overlap and no fidelity to the location".
Some thing to keep in mind: Not all individuals are present each year or were alive for each season. Therefore some sort of droplevel might be necessary.
This is my R script thus far (it doesn't work). Notice that the output is not being joined well together either and I can't seem to get a compiled file. Id like it to tell me what year, individual or season it is comparing things with.
IDNames= levels(loc$anid)
Year = unique(loc$year)
for (i in 1:(length(IDNames))){
vi90 = kerneloverlap(loc[,c("X","Y")], loc$year, lev = 90, grid=30, meth="VI", conditional=TRUE)
}
colnames(vi)= c(paste(IDNames[i],Year[n], sep =""),paste(IDNames[i], Year[n], sep =""))
}
write.csv(vi,"VolInter_indiv.csv")
structure(list(anid = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L
), .Label = c("c_002", "c_104"), class = "factor"), X = c(276646.0514,
276485.0397, 278102.4193, 278045.4716, 278993.8807, 274834.5677,
278516.0218, 296741.8328, 299080.2451, 291874.5068, 168540.0024,
168360.8211, 169538.2299, 164538.2592, 157321.7524, 148090.3478,
140575.2442, 133369.7162, 134375.0805, 138763.5342, 232347.5137,
231989.4609, 231793.1066, 234923.4012, 233374.4531, 232256.4667,
233660.3445, 239317.3128, 246354.664, 145161.8922, 144148.7895,
145154.7652, 145399.3515, 144581.4836, 143646.7295, 145055.3165,
144613.1393, 145037.3035, 144701.2676), Y = c(2217588.648, 2216616.387,
2219879.777, 2220818.804, 2216908.127, 2220423.322, 2216589.91,
2234167.287, 2239351.696, 2232338.072, 2273737.333, 2273954.782,
2269418.423, 2271308.607, 2264694.484, 2263710.512, 2254030.274,
2253352.426, 2248644.946, 2262359.026, 2231404.821, 2229583.89,
2231700.485, 2231598.882, 2237122.967, 2233302.185, 2240092.997,
2237702.817, 2249213.958, 2261841.308, 2263064.156, 2262236.452,
2264147.03, 2263214.877, 2263336.363, 2261417.946, 2256289.995,
2256694.953, 2253352.576), year = c(2003L, 2003L, 2003L, 2003L,
2003L, 2003L, 2003L, 2003L, 2003L, 2003L, 2003L, 2003L, 2003L,
2003L, 2003L, 2003L, 2003L, 2003L, 2003L, 2003L, 2004L, 2004L,
2004L, 2004L, 2004L, 2004L, 2004L, 2004L, 2004L, 2004L, 2004L,
2004L, 2004L, 2004L, 2004L, 2004L, 2004L, 2004L, 2004L), season = structure(c(1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L), .Label = "calving", class = "factor")), .Names = c("anid",
"X", "Y", "year", "season"), class = "data.frame", row.names = c(NA,
-39L))
A: Ok, I'll bite.
Your code had some typos (I hope) that make it un-runnable. Let's throw it out and start over. The function kerneloverlap returns a matrix of overlap values for each pair of items specified in its second parameter. In your first example you're comparing years.
Let's start by imagining what we'd do with the data on just one animal, and write a function that outputs the values we want just for that simple case:
kernMod <- function(x){
#x is the data for a single animal
rs <- kerneloverlap(x[,c("X","Y")],
x$year,lev = 90,
grid = 30,
meth = "VI",
conditional = TRUE)
#Assumes we're only comparing two years
out <- data.frame(year = paste(colnames(rs),collapse="-"), val = rs[2,1])
out
}
Now we can apply this to each animal separately:
kernMod(subset(loc,anid == 'c_002'))
year val
1 2003-2004 0
> kernMod(subset(loc,anid == 'c_104'))
year val
1 2003-2004 0.06033966
or we can use ddply from the plyr package to apply it to each animal in turn:
ddply(loc,.(anid),.fun = kernMod)
anid year val
1 c_002 2003-2004 0.00000000
2 c_104 2003-2004 0.06033966
To include multiple seasons, you would simply add that to the list of variables to split over in ddply (untested):
ddply(loc,.(anid,season),.fun = kernMod)
To compare between seasons within year, you'll need to modify kernMod to pass x$season as the second argument and then call something like (untested):
ddply(loc,.(anid,year),.fun = kernMod)
If your full data has multiple years in it, kernMod will require some more modification, since kerneloverlap returns an n x n matrix, where n is the number of years in your data. Perhaps something like this (untested)
kernMod <- function(x){
#x is the data for a single animal
rs <- kerneloverlap(x[,c("X","Y")],
x$year,lev = 90,
grid = 30,
meth = "VI",
conditional = TRUE)
rs[lower.tri(rs,diag = TRUE)] <- NA
rs <- melt(rs)
rs <- subset(rs, !is.na(value))
out <- data.frame(year = paste(rs$X1,rs$X2,collapse="-"), val = rs$value)
out
}
This approach should handle "missing" animals by only calculating values for which you have data.
Ok. I'd love to get 3rd-4th author for this, but I'd settle for an acknowledgement. ;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Asynchronous CreateProcess? I have noticed that in my application, CreateProcessWithTokenW sometimes blocks for a very long time (up to 20 seconds) before returning. It is not acceptable to block my main thread for this long, so I'm considering moving the call onto a background thread. However, I'm wondering if there is a better, built-in way of doing an asynchronous CreateProcess, perhaps using overlapped operations or the like. Does anyone know whether such a thing exists?
A: CreateProcess and its variants are all you've got. If the blocking hurts you then a different thread is the only solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Does table size affect INSERT performance? This is a question just for the sake of asking:
Barring all intermediate to advanced topics or techniques (clustered indices, BULK INSERTS, export/import tricks, etc.), does an INSERT take longer the larger a table grows?
This assumes that there is only one auto-int column, ID [i.e., all new rows are INSERTED at the bottom, where no memory has to shuffled to accommodate a specific row positioning].
A link to a good "benchmarking MySQL" would be handy. I took Oracle in school, and so far the knowledge has done me little good on SO.
Thanks everyone.
A: Yes, but it's not the size of the table per se but the size of the indices that matter. Once index rewriting begins to thrash the disk, you'll notice a slowdown. A table with no indexes (of course, you'd never have such a thing in your database) should see no degradation. A table with minimal compact indexes can grow to a very relatively large size without seeing degradation. A table with many large indices will start to degrade sooner.
A: My experience has been that performance degrades if the dataset index no longer fits in memory. Once that happens, checks for duplicate indexes will have to hit disk and it will slow down considerably. Make a table with as much data as you think you'll have to deal with, and do some testing and tuning. It's really the best way to know what you'll run into.
A: I can only share my experience. hope it helps.
I am inserting lots of rows at the time, on huge database (several millions of entries). I have a script which prints the time before and after I execute the inserts. well I haven't seen any drop in performances.
Hope it gave you an idea, but I am on sqlite not on mysql.
A: The speed is not affected as long as MySQL can update the full index in memory, when it begins to swap out the index it becomes slower. This is what happens if you rebuild an enormous index instantly using ALTER TABLE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: SQL Server client-side alias is not working The legacy vb6 application uses hardcoded connection strings like
Provider=SQLOLEDB.1;User ID=USER_NAME;password=USER_PASSWORD;Initial Catalog=DB_NAME;Data Source=OLD_SERVER_NAME;Network Library=DBMSSOCN
The goal is to forward this application to the NEW_SERVER_NAME with specific port.
I've created alias but it is not working, application continues to use old server.
However if remove part Network Library=DBMSSOCN (I did it in test application)
everything works fine.
Is there any chance to make it work with original connection string?
A: The default TCP/IP port is 1433, but that's configurable. Here's a step-by-step that (hopefully) addresses at least that part of the problem you're facing.
http://msdn.microsoft.com/en-us/library/ms177440.aspx
As for your alias, you might make sure that you created it on the client, not sql-server. (Not saying you did anything wrong, but I see that mistake sometimes...)
http://support.microsoft.com/kb/289573
A: DBMSSOCN refers to the network library used for the connection. In this case, TCP/IP. Aliases can be configured for Named Pipes, TCP/IP, and VIA. When you remove the DBMSSOCN setting, it falls back to Named Pipes instead of TCP/IP. Make sure of two things (both in SQL Server Configuration Manager under the 32-bit and 64-bit SQL Native Client Configuration sections):
*
*Under Client Protocols, ensure TCP/IP is enabled.
*
*Under Aliases, make sure the alias you create is for the specific network library your connection string specifies. In your case, TCP/IP.
You may need to install the SQL Native Client 10.0 on the application server and change the connection string to use that version of the client before this will work. To install the new client, you'll need to install the SQL Server Tools from the installation of SQL Server 2008. The new connection string may look like the following (example is standard security from ConnectionStrings.com):
Provider=SQLNCLI10;Server=ServerAlias;Database=myDataBase;Uid=myUsername;Pwd=myPassword
A: cliconfg.exe which can be used to configure client alias when run on 64b machine only creates entry for 64b programs; if you don't have sql tools and want to create alias for both 32 and 64b programs create following entries in registry (below are contents of reg file with TCP alias):
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo]
"oldserver\\oldinstance"="DBMSSOCN,newserver\\newinstance"
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\MSSQLServer\Client\ConnectTo]
"oldserver\\oldinstance"="DBMSSOCN,newserver\\newinstance"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: method optimization - interface_si If I remove the html from the method arugments and put it into variables does this increase the memory overhead for the function as opposed to inserting it inline. Obviously the readabily is not as good with the html inserted inline. Which way is better?
Example 1
function interface_si()
{
var a=document.forms['f0'].elements,b='f0e';
check_empty(a,b,'Please enter your credentials')&&check_email(a[0],b,'Please contact <a class="d" href="mailto:support@archemarks.com">support</a> to reset your password')&&check_pass(a,b[1],'Please contact <a class="d" href="mailto:support@archemarks.com">support</a> to reset your password')&&s0('pi.php',serialize('f0')+'&a=0',s3,b);
}
Example 2
function i0_0()
{
var a=document.forms['f0'].elements,b='f0e';
var c='Please enter your credentials';
var d='Please contact <a class="d" href="mailto:support@archemarks.com">support</a> to reset your password';
var e='Please contact <a class="d" href="mailto:support@archemarks.com">support</a> to reset your password'
check_empty(a,b,c)&&check_email(a[0],b,d)&&check_pass(a,b[1],e)&&s0('pi.php',serialize('f0')+'&a=0',s3,b);
}
A: Going with readablity for now and pulling the arguments out into variables.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Django Template Inheritance Okay, this one is completely blowing my mind.
I have a very simple _base.html, whose code reads as follows:
<!DOCTYPE html />
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
{% load static %}
<title>Welcome!</title>
<!-- Includes jQuery UI -->
<script type='application/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'></script>
<script type='application/javascript' src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js'></script>
<link rel='stylesheet' href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/themes/cupertino/jquery-ui.css' type='text/css' media='screen' />
<!-- Includes Columnal -->
<link rel='stylesheet' href='{% get_static_prefix %}Columnal/columnal.css' type='text/css' media='screen' />
<!-- Custom CSS -->
<link rel='stylesheet' type='text/css' href='{% get_static_prefix %}Style.css' />
{% block head %}
{% endblock %}
</head>
<body>
<header>
<table width='100%'>
<tr>
{% if user.is_authenticated %}
<td>Welcome, {{user.username}}!</td>
<td align='right'><a href='logout/'>Logout</a></td>
{% else %}
<td><a href='login/'>Login / Register</a></td>
{% endif %}
</tr>
</table>
</header>
{% block content %}
{% endblock %}
</body>
</html>
Of course, while intended to be extended by a child template, this page does make sense by itself, and indeed, when rendered, I see what I would expect and what I had intended.
However, when I tried to extend this file with a child template, I was getting some unexpected results, so I tried cutting it down to the absolute bare minimum, namely:
{% extends '_base.html' %}
Just a single line of code. One would think that if I display this file, I get the exact same result that if I just displayed _base.html itself. However, THAT IS NOT THE CASE. For some reason, there is an extra white line of nothingness above the header when I use this trivial child template. What's even weirder is that, if I select view source for both pages (i.e., the page I get directly from _base.html and the one I get from the child template) IT SAYS THAT THE SOURCE CODE IS EXACTLY THE SAME (I'm using Chrome). How is it that two files, that should display the same page, give the same exact source code (according to the browser), but DISPLAY DIFFERENTLY.
This completely blows my mind and I have no idea what could be causing this. The way I understand it, Django does it's thing behind the scenes and feeds the browser a raw HTML file, so that the browser shouldn't care how I generated the HTML, as long as it's the same. How then could these two methods produce different results? Any help at all would be much appreciated as I have been stuck on this for the past two days.
P.S.: I am sorry that the code for _base.html is a bit long for a forum post. I probably could have chopped off a bit, but as I have no idea what's going on here, I don't really have an idea of what matters and what doesn't, so I didn't want to take the risk.
EDIT: As I mentioned before, (in Chrome) if I right-click and select 'View page source' for both pages, I get the exact same source code. However, if instead I select 'Inspect element', the source code is not the same. For some reason, when viewing the source code via 'Inspect element' using the child template version, I find all of the content in the <head> tag of _base.html located in the <body> tag of the source code I see. Any idea why that would happen?
A: Have you specified the correct path of the template directory in TEMPLATE_DIRS of settings.py. ?
Also have you tried to view the page clearing all the browsing data(cookies, cache, etc...) ?
May be the browser is caching data behind the scenes..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: File not deleting with if statement even if it is true, but is deleting without if statement Whenever I add the:
if(lines[0].equalsIgnoreCase("owner: " + sender.getName()))
The file does not delete, but yet this:
System.out.println("Deleted message successfully!");
still runs, meaning the if statement is true.
Whenever I delete the if statement above, it does delete the file.
Here is the code: (not the best)
String lines[], strLine;
int a = 0;
String fileLoc = currentDir + "//plugins//ExtendedSigns//" + c[1] + ".txt";
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(fileLoc)));
FileInputStream in = new FileInputStream(fileLoc);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
lnr.skip(Long.MAX_VALUE);
lines = new String[1 + lnr.getLineNumber()];
while ((strLine = br.readLine()) != null)
{
lines[a] = strLine;
a++;
}
if(lines[0].equalsIgnoreCase("owner: " + sender.getName()))
{
File del = new File(currentDir + "//plugins//ExtendedSigns//" + c[1] + ".txt");
del.delete();
System.out.println("Deleted message successfully!");
}
else
{
System.out.println("Deleted message unsuccessfully! You do not own it!");
}
A: Try this instead:
if(del.delete()) System.out.println("Deleted message successfully!");
else System.out.println("Deleted message unsuccessfully! You do not own it!");
A: Perhaps your file is not closed? Before comparison, call br.close() so that file gets closed (and linenumberreader should also get closed). Probably without your if/else statement, the JVM is closing the files or it is not locked anymore. May be something to do with sender.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to have multiple Display name pointing on the same Application Site URL? We need to localize the Display Name of our application in different lauguages, but we would like to have all names pointing to the same application in order not to split the stats (MAU and others).
Any ideas?
BTW, It's the same problem encountered by others. Refer to http://bugs.developers.facebook.net/show_bug.cgi?id=10501#c3
A: Yes, this is described in the Internationalization guide. You go to the translations tool and then select your application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: where is the RESOURCES folder in the new xCode4.2 I can't seem to find the Resources folder in the new xCode4.2 project navigator
where do i put the image resources for my app icon in this new xCode4.2?
Here is a screenshot:
A: It looks like many samples from Apple now use the Supporting Files folder instead. You can go ahead and create your own Resources folder, or go ahead and use Apple's Supporting Files folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7507997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: program closed unexpected when i try getConnectionInfo I'm in the process of learning the android api. However, when I try to get info about wifi my program is closing unexpectedly:
here is the code:
package com.example.helloandroid;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.content.BroadcastReceiver;
import android.content.Context;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
WifiManager wifi;
BroadcastReceiver receiver;
TextView textStatus;
Button buttonScan;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello, Android");
setContentView(tv);
wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
// WifiInfo info = wifi.getConnectionInfo();
// tv.append("\n\nWiFi Status: " + info.toString());
}
}
The code above runs, but as soon as I uncomment the line:
WifiInfo info = wifi.getConnectionInfo();
It says that my program has closed unexpectedly. I'm not sure what I'm doing wrong. Any help would be appreciated.
I am using the simulator.
Thanks
UPDATE: if I write out the wifi obj:
wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
tv.append(wifi.toString());
the app run and tv says:
android.net.wifi.
WifiManager@4051c960
UPDATE:
LogCat:
09-22 14:56:51.387: ERROR/AndroidRuntime(408): FATAL EXCEPTION: main
09-22 14:56:51.387: ERROR/AndroidRuntime(408): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.helloandroid/com.example.helloandroid.HelloAndroid}: java.lang.SecurityException: WifiService: Neither user 10034 nor current process has android.permission.ACCESS_WIFI_STATE.
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at android.os.Handler.dispatchMessage(Handler.java:99)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at android.os.Looper.loop(Looper.java:123)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at android.app.ActivityThread.main(ActivityThread.java:3683)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at java.lang.reflect.Method.invokeNative(Native Method)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at java.lang.reflect.Method.invoke(Method.java:507)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at dalvik.system.NativeStart.main(Native Method)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): Caused by: java.lang.SecurityException: WifiService: Neither user 10034 nor current process has android.permission.ACCESS_WIFI_STATE.
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at android.os.Parcel.readException(Parcel.java:1322)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at android.os.Parcel.readException(Parcel.java:1276)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at android.net.wifi.IWifiManager$Stub$Proxy.getConnectionInfo(IWifiManager.java:591)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at android.net.wifi.WifiManager.getConnectionInfo(WifiManager.java:605)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at com.example.helloandroid.HelloAndroid.onCreate(HelloAndroid.java:35)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
09-22 14:56:51.387: ERROR/AndroidRuntime(408): ... 11 more
A: Not certain if it's supported on emmulator but on a real device I think you would need to have the following permission in your manifest:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
If you were to look at the logcat output for errors when it closes you should see something to the effect of not having a permission...or maybe some other tidbit of info that would help others provide you some guidance. See: http://developer.android.com/guide/developing/tools/adb.html#logcat
A: I bet it's because you haven't set the permissions in the AndroidManifest.xml. See here. However, remember that it helps a ton if you post the actual exception message you are getting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Re-create an existing sql server database programatically? Is it possible to either copy and existing database, or generate the sql and then run it against a sql database to create a copy of an existing database?
I don't care about the data, just the schema.
I want to do this for unit testing. I know I can just use sqlite, but I am curious how this would work anyhow.
I don't have any stored procs or anything, simply tables and PK/FK etc.
I guess the best approach would be somehow to generate the sql schema, then just run it against the database.
Or if it is easier, copy the database and then truncate the tables.
Note: I want to know how this can be done programatically.
A: You can generate scripts by right clicking on database -> tasks -> generate scripts from sql management studio.
In wizard you can under advanced settings (depending on sql management tools version) choose whether you want schema, data, or both.
UPDATE
To create database programatically you can use generated sql and execute it via ADO.NET.
Or, if you use CodeFirst, it can do this automatically if you set CreateDatabaseIfNotExists initializer for context in your test class. You can create CodeFirst context from your database by reverse engineering existing application using Entity Framework Power Tools for Visual Studio. In that case you only need to specify connection string to non-existing database and CF will create it for you. You can also specify DropCreateDatabaseAlways to have your database refreshed each time when you run your test (same as executing sql query every time after you prepend drop for database in question to generated sql script)
If you use codefirst, then you do not need to generate sql scripts.
If you prefer any of these methods, I can provide you with more resources if you want?
A: You can do it programatically in nhibernate. Nhibernate creates all the tables
and the relations in database you only create The Database instance (name) in
any Database server like Oracle, MySQL, MsSQL...
You can look this for details.
A: You would use the objects in the SQL Server Management Objects Class library.
For instance, the Database class implements IScriptable. I'd use that as my starting point (but I haven't done this myself). It's possible that the script this generates might have too much that isn't relevant, in which case you might have to enumerate individual tables and generate scripts for them.
But SMO is always the answer (these days) to "how do I do management task X against SQL Server?".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: strtotime() doesn't warn of invalid dates I am using strtotime to parse a date that is like 10:24 AM 22-Sep I was then parseing this thru checkdate
$pickup_time = strtotime($pickupTime);
if (!checkdate(date(n,$pickup_time) ,date(j,$pickup_time), date(Y,$pickup_time)));
{
echo json_encode(array("msg"=>"Nice one, that date doesn't exist. Try again.","status"=>"false"));
break;
}
But strtotime converts bad dates to the next logical date it would seem. So 31st Sep becomes 1 October. Completely voiding the checkdate function. Should you be able to use strtotime() to check for valid dates?
A: strtotime() doesn't have built-in validation of dates, so if you need it - perform it manually
ps: it is wrong writing date(n,$pickup_time). As long as n is a string - put it within quotes: date('n', $pickup_time)
A: Should you be able to use strtotime() to check for valid dates?
No, the intent of strtotime()is to do the very best PHP can do in terms of interpreting what date you mean. From the short description on php.net:
Parse about any English textual datetime description into a Unix
timestamp
If your string makes no sense, strtotime() will still parse it. Sometimes it comes out garbage, but that's really on how you accept input from users.
A: You can convert the string to a date and then format it as a string that matches the format you've read in. If the strings don't match, then the date was invalid.
For example:
$str = '10:24 AM 22-Sep';
$d = new DateTime($str);
if ($d->format('H:i A j-M') != $str) {
echo 'Date is invalid';
}
You'd need to convert the code to use the non-object version date functions. However, this only works if you're expecting a certain format.
Sorry about the edits. This is my first post.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I show errors returned from the Javascript SDK I'm working on a script that combines both the PHP and Javascript SDKs.
It's a pretty basic script, and for the most part it works, but it's going to be used by others and I'm trying to make it a bit more bullet-proof.
The issue I have is that if anything like the URL, API Key or Secret are incorrect there is no message shown to the user to help them realise their problem.
If I watch the HTTP stream (with HttpFox) I can see that there is an error being returned. Something like...
<span>Given URL is not permitted...</span>
But nothing appears in the display. The span tags, make it seem like this response is intended for display, but I don't know where it should appear, or why it isn't.
Is there some specially named div element that I'm supposed to have on my page?
Any help appreciated!
A: The 'Dialogs API' has an optional 'show_error' parameter that you can add to request URLs to display some additional information about errors.
This works when calling dialogs via the Javascript SDK.
But for some other things from the SDK - yeah, sometimes it just says: "there was an error" and doesn't display anything else about it. It's annoying, but more often than not - it's something related to your facebook APP settings (i.e. incorrect app-id, incorrect domain-name, etc.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Returning from a function while continuing to execute I am working on a Django application where I would like to populate several fields within my model when an object is first created. Currently I am able to do this in the save() routine of my model like so:
def save(self, *args, **kwargs):
file = fileinfo.getfileinfo(self.file_path)
if not self.file_size:
self.file_size = file.FileSize
if not self.file_inode:
self.file_inode = file.FileInode
if not self.duration:
self.duration = file.Duration
if not self.frame_width:
self.frame_width = file.ImageWidth
if not self.frame_height:
self.frame_height = file.ImageHeight
if not self.frame_rate:
self.frame_rate = file.VideoFrameRate
super(SourceVideo, self).save(*args, **kwargs)
I created a function called getfileinfo within a separate module called fileinfo. This is what part of my function looks like:
def getfileinfo(source):
fstats = os.stat(source)
info = dict({
u'FileSize': fstats.st_size,
u'FileInode': fstats.st_ino
})
output = subprocess.Popen(
[exiftool, '-json', source], stdout=subprocess.PIPE)
info.update(
json.loads(output.communicate()[0], parse_float=decimal.Decimal)[0])
return DotDict(info)
Although all of this works, I would like to avoid blocking the save process should the retrieval process be delayed for some reason. The information is not needed at object creation time and could be populated shortly thereafter. My thought was that I would alter my function to accept both the file path in question as well as the primary key for the object. With this information, I could obtain the information and then update my object entry as a separate operation.
Something like:
def save(self, *args, **kwargs):
fileinfo.getfileinfo(self.file_path, self.id)
super(SourceVideo, self).save(*args, **kwargs)
What I would like help with is how to return from the function prior to the actual completion of it. I want to call the function and then have it return nothing as long as it was called correctly. The function should continue to run however and then update the object on its end once it is done. Please let me know if I need to clarify something. Also, is thing even something work doing?
Thanks
A: Your best bet in this case is to use celery.
This enables you to create tasks that will occur in the background, without blocking the current request.
In your case, you can .save(), create the task that updates the fields, push it to your celery queue, and then return the desired response to the user.
A: I don't know your requirements, but if this operation takes an unacceptable time on save but an acceptable one on access, I would consider treating FileSize, Duration, VideoFrameRate, etc, as lazy-loaded properties of the model, assuming that a longer initial load time is a decent trade-off for a shorter save time.
There are many ways you can do this: you could cache the frame rate, for instance, with the caching framework the first time it's accessed. If you prefer to make it something stored in the database, you could access the frame rate via a property, and calculate it (and other values, if appropriate), the first time it's accessed and then store them in the database. Theoretically, these are attributes of the file itself, and therefore your interface shouldn't allow them to be changed and hence made out of sync with the file they refer to. Along those lines, I might do something like this:
class MyMediaFile(models.Model):
file = models.FileField()
_file_size = models.IntegerField(null=True, editable=False)
_duration = models.IntegerField(null=True, editable=False)
<... etc ...>
@property
def file_size(self):
if self._file_size:
return self._file_size
else:
self.populate_file_info(self)
return self._file_size
def populate_file_info(self):
< ... do your thing here ... >
self._file_size = my_calcuated_file_size
< ... etc ... >
The logic of each property can easily be split into a general lazy-loading @property so the boilerplate doesn't need to be repeated for each one.
A: I don't know if your specific case will work like this, but what I would probably do is spawn a new thread pointing at your super.save, like so:
import threading
#other code here
def save(self, *args, **kwargs):
fileinfo.getfileinfo(self.file_path, self.id)
my_thread = threading.Thread(target=super(SourceVideo, self).save,
args=args, kwargs=kwargs)
my_thread.start()
This way save will run in the background while the rest of your code executes.
This will only work, however, if save doesn't block any data that might be needed elsewhere while the execution takes place.
A: What it sounds like you really want to do is return an object that represents the work that still needs to be done, and then attach a completion handler or observer to that returned object, which populates the model object with the results and then calls super.save().
Caveat being that I'm not sure how well this kind of approach fits into the Django application model.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Deprecation warning when using Cucumber with Rails 3.1: class_inheritable_attribute is deprecated This is a fresh project setup on Rails 3.1. When I run cucumber features I always get the same annoying deprecation warning twice. Any guidance would be appreciated.
DEPRECATION WARNING: class_inheritable_attribute is deprecated, please use class_attribute method instead. Notice their behavior are slightly different, so refer to class_attribute documentation first. (called from require at /Users/Mandingo/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:58)
A: The cucumber-rails guys are working on it as we talk :)
https://github.com/cucumber/cucumber-rails/issues/169
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: BrowserID without Javascript (preferably in Python) - is it possible? BrowserID currently uses a Javascript shim, while browsers are still (hopefully) developing support for it. Is it possible to use BrowserID for clients that don't run javascript?
I could read the 600 line JS shim, and figure out what navigator.id.getVerifiedEmail is meant to do, then replicate it on a server, but I was hoping there's an easier way. And even then, I don't think it would really work.
OK, digging a bit deeper, this seems to be peripheral to what BrowserID is meant to do, and might require some kind custom BrowserID validator, but I'm hoping there's an easier way.
A: "Server-side" BrowserID in python or whatever is impossible by its design. Read carefully the How BrowserID works page, especially pay attention to section 'Certificate Provisioning' and step 3 in the flow description. It does require support for BrowserID and javascript from the client's browser, because BrowserID technology requires some code to be run in the client browser during Certificate Provisioning step.
A: The Javascript shim exists to work around missing native support in browsers, so it will be required for the foreseeable future:
https://developer.mozilla.org/en-US/docs/Persona/FAQ#Why_does_Persona_require_JavaScript.3F
A: One solution, use OpenID or hand-rolled email verification, but then I have 2 problems. :(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to replace characters in a string with other characters? I want to replace certain characters in a string with other characters. I´ve did my research and found that the best way is to use regular expressions...
But, something doesn´t work ...
Here´s what i did so far...
var alphabet = {
'á':'a',
'é':'e',
'í':'i'
};
var word = $("input[name=phrase]").val();
alert(word); //output: ok!
var url = word.replace(/áéí|/g, function(s) {
return alphabet[s];
});
alert(url); //output: undefined,undefined,undefined...
A: Match any of those characters using [], and capture the match(es) using () instead of looking for a match of those consecutive characters.
var url = word.replace(/[áéí]/g, function(s) {
return alphabet[s];
});
DEMO: http://jsfiddle.net/5UmLV/1/
As noted by @Felix Kling the capture group was unnecessary. Updated to reflect that improvement.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: gIntersects TopologyException in rgeos R I have a shapefile that represents ecoregions of the world. I am trying to determine which ecoregions are intersected by the distributions of my species of interest. I am using the latest version of R and the rgdal and rgeos packages.
I load in a list of species ranges called 'rangelist'.
I load in my ecoregions shapefile (eco), and create a list called 'regions', which contains a SpatialPolygonsDataFrame object for every ecoregion:
readOGR(ecofile,gsub(".shp","",ecofile))->eco
regions<-list()
for (i in 1:length(unique(eco$ECO_NAME))){
print(unique(eco$ECO_NAME)[i])
eco[eco$ECO_NAME==unique(eco$ECO_NAME)[i],]->regions[[i]]
}
names(regions)<-as.character(unique(eco$ECO_NAME))
I then run a loop function that checks each range from 'rangelist' against each of these ecoregions from 'regions'. This works fine until:
> gIntersects(rangelist[[49]],regions[[23]])
Error in RGEOSBinPredFunc(spgeom1, spgeom2, byid, func) :
TopologyException: side location conflict at -78.7709 -8.18245
I loaded the original ecoregions shapefile into arcMap 10 and ran the "check geometry" tool but it found no problems.
The original sources of the data are:
species ranges:
http://www.natureserve.org/getData/birdMaps.jsp
ecoregions:
http://www.worldwildlife.org/science/data/item1875.html
I have temporarily posted here a zip file containing 2 Rdata files and an R script to allow you to reproduce the error (file size is 33mb).
Does anyone have any idea as to how I can fix or get around this problem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Uploading files recursively with WebClient I am writing a .NET application in C# that needs to upload some files onto a server using FTP. I am looking at the UploadFileAsync method provided by he WebClient class:
http://msdn.microsoft.com/en-us/library/ms144232(v=vs.80).aspx
What I am curious about is what happens if I tell it to upload a directory?
In my dreams it would recursively upload the directory and all of its contents.... Does anybody have any experience with this, or know any way I could get all the files up there without having to go through and manually create the sub directories and upload the files one by one?
A: It will not work like that. If you pass a directory, you'll get an error. There's no shortcut of the kind you seek, unfortunately.
A: Yuo can get all the files of any level of a folder easily by Directory.GetFiles(), then loop through the files one by one and upload it.
A: Under UltraVNC, when I upload a directory, it creates a zip of the directory, uploads it as a file, and unzips it there. You might want to call a script that unzips the file.
I just searched on stackoverflow, and I think there are better solutions.
https://stackoverflow.com/questions/2252000/upload-a-folder-by-ftp
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Diff of two directory trees to create file/folder level patch (incl. binary files) There's lots of solutions for creating a file level patch for text files and the like. What I'm looking for is an easy script/shell command that will compare oldversion/ newversion/ and give me a tree of files that I need to copy over oldversion to make it be equal to newversion (assuming files are not removed in the updated version). Note that the two folders contain both binary and text files.
Previously, we were using the hack:
fdupes -qrf newversion/ oldversion/ | grep "newversion" | xargs rm;
Leaving us with the folder "newversion" that could be packaged as a patch.
Unfortunately, this turned out to be disastrous because fdupes does not consider filenames.
What'd be great is something like fdupes that actually did include the filename in the comparison.
A: The diff command can be asked to output filenames which differ.
diff --quiet --recurse --unidirectional-new-file OLDDIR NEWDIR
Files old/main and new/main differ
Files old/main.cpp and new/main.cpp differ
Files old/Makefile and new/Makefile differ
Files old/sounds/popalien.wav and new/sounds/popalien.wav differ
Files old/sounds/saucer.wav and new/sounds/saucer.wav differ
Of course, it's not a nice output, but since you're only looking for NEW files to package as a patch, a quick sed pipe works wonders:
diff --quiet --recurse -unidirectional-new-file OLDDIR NEWDIR | \
sed "s/^.* and \(.*\) differ/\1/"
(broken for readability)
new/main
new/main.cpp
new/Makefile
new/sounds/popalien.wav
new/sounds/saucer.wav
Spaces around 'and' and preceeding 'differ'
The ORDER of the operands to diff makes a difference, first argument is left of ' and ', second is after. Watch out for that.
Also, if you delete a file from NEWDIR, this will not find it as given, only added or changed files. To also output filenames for files not found in either subdir, replace the --unidirection-new-file with --new-file. (short options exist for all except --unidirectional..)
A: diff -ruN oldversion newversion
A: I know it has been long time. I needed same solution. I found this post but it was not sufficient. Then I found rsync can do the job IFF you ``patch`` identical copies, and don't need merging with other changes. I intend on using this with updating yum mirrors on disconnected machines. My full solution is a little more involved, and I am writing commands from memory so some fine details could be wrong, but at the core:
# create identical copy "copy.0"
rsync -a master/ copy.0/
# Presumably transfer copy.0/ to another machine for offline use
# but copy.0 must not mutate outside of this process or sync probably
# will not work.
# some time later update master, e.g. rsync master from upstream mirror
# mutates master in some way, changes/adds/removes remove files including
# binaries
echo -n $'\001\002' > master/new.bin
rm master/gone.bin
# generate rsync batch that can be used to ``patch`` copy.0
# to become identical to master
rsync -a --delete --itemize-changes --only-write-batch=copy.0.batch \
master/ copy.0/
# now the file copy.0.batch contains only the deltas to be applied
# transfer the batch file to where it needs to be applied
# apply the batch to copy.0
rsync -a --delete --itemize-changes --read-batch=copy.0.batch copy.0/
This takes care of deletions and many other things, probably permissions, timestamps etc, but I think it might not handle hard links as hard link and will probably create them as separate unlinked files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: ASP.NET MVC: Accessing ViewModel Attributes on the view Is there any way to access any attributes (be it data annotation attributes, validation attributes or custom attributes) on ViewModel properties from the view? One of the things I would like to add a little required indicator next to fields whose property has a [Required] attribute.
For example if my ViewModel looked like this:
public class MyViewModel
{
[Required]
public int MyRequiredField { get; set; }
}
I would want to do something in the EditorFor template like so:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<int?>" %>
<div class="label-container">
<%: Html.Label("") %>
<% if (PROPERTY_HAS_REQUIRED_ATTRIBUTE) { %>
<span class="required">*</span>
<% } %>
</div>
<div class="field-container">
<%: Html.TextBox("") %>
<%: Html.ValidationMessage("") %>
</div>
A: The information you're looking for is in ViewData.ModelMetadata. Brad Wilson's blog post series on Templates should explain it all, especially the post on ModelMetadata.
As far as the other ValidationAttributes go, you can access them via the ModelMetadata.GetValidators() method.
ModelMetadata.IsRequired will tell you if a complex type (or value type wrapped in Nullable<T>) is required by a RequiredAttribute, but it will give you false positives for value types that are not nullable (because they are implicitly required). You can work around this with the following:
bool isReallyRequired = metadata.IsRequired
&& (!metadata.ModelType.IsValueType || metadata.IsNullableValueType);
Note: You need to use !metadata.ModelType.IsValueType instead of model.IsComplexType, because ModelMetadata.IsComplexType returns false for MVC does not consider to be a complex type, which includes strings.
A: I would suggest not doing that way because you're adding logic in the view which is a bad practice.
Why don't you create a HtmlHelper or LabelExtension, you can call ModelMetaProvider inside the method and find out whether the property has Required attribute decorated?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Advice for website authentication system that queries facebook API I've built a website that authenticates users via facebook.
The way I've set it up is like this: The website uses the facebook JS SDK on the front end, and when the user authenticates with facebook their access_token is sent to my server via an ajax call (using HTTPS for security) - where the graph api is queried and their session is initiated server-side (Using a database for secure session storage of user data).
Can anyone think of any potential problems this approach might lead to? Thanks!
A: This is a very common scenario. The only issue is that unless you request offline_access that token you get is only valid for an hour.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: JPA/Hibernate selective flush I guess I'll start with
The Question
Is there a way to ensure that only entities that have been explicitly 'marked' in some way are flushed to the database?
The Environment
We are using Java EE 5, Seam 2, JBoss AS 6 and Hibernate (although we try to keep direct Hibernate dependencies minimal).
The Goal
Currently we have entities that are mapped to transient DTO objects which are then used in the business layer and bound to facelets for presentation. When we need to save data we map the DTOs back to entities and persist them. I'd like to replace the DTO with a wrapper business object that wraps an entity so that:
*
*No mapping is required as the business object will call getters and setters on the wrapped entity instead of storing it's own copy of the data.
*Upon creation of the business object hints can be specified but if something is not fetched then it can be automatically fetched later on lazily as per JPA. This is my pet peeve. I hate having to manually fetch something extra every time I need it. It often results in over-complicated 'business' code, especially when there is lots of data and it is too slow to fetch it all up-front. When I call getRelatedStuff() it should just be there.
*Saving is as simple as 'marking' the relevant business object(s) and calling flush (I was thinking of using Seam conversation scoped transactions with manual flushing).
The Problem
The problem with this pattern is that JPA is willing and eager to flush everything to the database during a flush. I would rather tell JPA explicitly which entities I want flushed. Any I didn't specify should not be flushed.
As a secondary question, is this pattern even a good idea?
A: Not a good idea. In an ORM, the way to not flush changes to the database is to not make the changes to the objects. If you need such fine-grained control of the framework as you're trying to get, then you're using it wrong. With Hibernate, your business logic should be all but oblivious of there being a database back there somewhere. You're thinking of Hibernate as a layer over an RDBMS. Instead, think of it more like a Map with near-unlimited capacity, where you can store and get objects by id. As with a Map, when you get an object out of it and make changes to the object, those changes are also reflected in the Map, and other gets on the Map will see the updated object state. Of course with Hibernate, changes have to occur in a transaction, but consider that to be a memory transaction, required because the Map is accessed concurrently by multiple threads.
A: Sure you can.
Just call
em.clear();
before
em.merge();
This will cause any object to be detached.
Then you simply pass every object you want to merge/persist as parameters of your method. This will flush to the database only the object you want.
Be careful that, after having called em.clear(), the only persisted object will be the one merged/persisted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android Fragment no view found for ID? I have a fragment I am trying to add into a view.
FragmentManager fragMgr=getSupportFragmentManager();
feed_parser_activity content = (feed_parser_activity)fragMgr
.findFragmentById(R.id.feedContentContainer);
FragmentTransaction xaction=fragMgr.beginTransaction();
if (content == null || content.isRemoving()) {
content=new feed_parser_activity(item.getLink().toString());
xaction
.add(R.id.feedContentContainer, content)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit();
Log.e("Abstract", "DONE");
}
When this code is executed I get the following error in debug..
java.lang.IllegalArgumentException: No view found for id 0x7f080011
for fragment feed_parser_activity{41882f50 #2 id=0x7f080011}
feed_parser_activity is a Fragment that is set to Fragment layout in xml.
I am using a FragmentActivity to host the Fragment Layout holding the feed_parser_layout.
Am I coding this correctly above?
A: I know this has already been answered for one scenario, but my problem was slightly different and I thought I'd share in case anybody else is in my shoes.
I was making a transaction within onCreate(), but at this point the view tree has not been inflated so you get this same error. Putting the transaction code in onResume() made everything run fine.
So just make sure your transaction code runs after the view tree has been inflated!
A: The solution was to use getChildFragmentManager()
instead of getFragmentManager()
when calling from a fragment. If you are calling the method from an activity, then use getFragmentManager().
That will solve the problem.
A: I was facing a Nasty error when using Viewpager within Recycler View.
Below error I faced in a special situation.
I started a fragment which had a RecyclerView with Viewpager (using FragmentStatePagerAdapter). It worked well until I switched to different fragment on click of a Cell in RecyclerView, and then navigated back using Phone's hardware Back button and App crashed.
And what's funny about this was that I had two Viewpagers in same RecyclerView and both were about 5 cells away(other wasn't visible on screen, it was down). So initially I just applied the Solution to the first Viewpager and left other one as it is (Viewpager using Fragments).
Navigating back worked fine, when first view pager was viewable . Now when i scrolled down to the second one and then changed fragment and came back , it crashed (Same thing happened with the first one). So I had to change both the Viewpagers.
Anyway, read below to find working solution.
Crash Error below:
java.lang.IllegalArgumentException: No view found for id 0x7f0c0098 (com.kk:id/pagerDetailAndTips) for fragment ProductDetailsAndTipsFragment{189bcbce #0 id=0x7f0c0098}
Spent hours debugging it. Read this complete Thread post till the bottom applying all the solutions including making sure that I am passing childFragmentManager.
Nothing worked.
Finally instead of using FragmentStatePagerAdapter , I extended PagerAdapter and used it in Viewpager without Using fragments. I believe some where there is a BUG with nested fragments. Anyway, we have options. Read ...
Below link was very helpful :
Viewpager Without Fragments
Link may die so I am posting my implemented Solution here below:
public class ScreenSlidePagerAdapter extends PagerAdapter {
private static final String TAG = "ScreenSlidePager";
ProductDetails productDetails;
ImageView imgProductImage;
ArrayList<Imagelist> imagelists;
Context mContext;
// Constructor
public ScreenSlidePagerAdapter(Context mContext,ProductDetails productDetails) {
//super(fm);
this.mContext = mContext;
this.productDetails = productDetails;
}
// Here is where you inflate your View and instantiate each View and set their values
@Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.product_image_slide_cell,container,false);
imgProductImage = (ImageView) layout.findViewById(R.id.imgSlidingProductImage);
String url = null;
if (imagelists != null) {
url = imagelists.get(position).getImage();
}
// This is UniversalImageLoader Image downloader method to download and set Image onto Imageview
ImageLoader.getInstance().displayImage(url, imgProductImage, Kk.options);
// Finally add view to Viewgroup. Same as where we return our fragment in FragmentStatePagerAdapter
container.addView(layout);
return layout;
}
// Write as it is. I don't know much about it
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
/*super.destroyItem(container, position, object);*/
}
// Get the count
@Override
public int getCount() {
int size = 0;
if (productDetails != null) {
imagelists = productDetails.getImagelist();
if (imagelists != null) {
size = imagelists.size();
}
}
Log.d(TAG,"Adapter Size = "+size);
return size;
}
// Write as it is. I don't know much about it
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
Hope this was helpful !!
A: Just in case someone's made the same stupid mistake I did; check that you're not overwriting the activity content somewhere (i.e. look for additional calls to setContentView)
In my case, due to careless copy and pasting, I used DataBindingUtil.setContentView in my fragment, instead of DataBindingUtil.inflate, which messed up the state of the activity.
A: I had the same issue but my issue was happenning on orientation change. None of the other solutions worked. So it turns out that I forgot to remove setRetainInstance(true); from my fragments, when doing a two or one pane layout based on screen size.
A: My mistake was on the FragamentTransaction.
I was doing this t.replace(R.layout.mylayout); instead of t.replace(R.id.mylayout);
The difference is that one is the layout and the other is a reference to the layout(id)
A: I was having this problem too, until I realized that I had specified the wrong layout in setContentView() of the onCreate() method of the FragmentActivity.
The id passed into FragmentTransaction.add(), in your case R.id.feedContentContainer, must be a child of the layout specified in setContentView().
You didn't show us your onCreate() method, so perhaps this is the same problem.
A: This happens when you are calling from a fragment inside another one.
use :
getActivity().getSupportFragmentManager().beginTransaction();
A: Another scenario I have met.
If you use nested fragments, say a ViewPager in a Fragment with it's pages also Fragments.
When you do Fragment transaction in the inner fragment(page of ViewPager), you will need
FragmentManager fragmentManager = getActivity().getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
getActivity() is the key here.
...
A: This error also occurs when having nested Fragments and adding them with getSupportFragmentManager() instead of getChildFragmentManager().
A: I had this problem (when building my UI in code) and it was caused by my ViewPager (that showed Fragments) not having an ID set, so I simply used pager.setID(id) and then it worked.
This page helped me figure that out.
A: I had this same issue, let me post my code so that you can all see it, and not do the same thing that I did.
@Override
protected void onResume()
{
super.onResume();
fragManager = getSupportFragmentManager();
Fragment answerPad=getDefaultAnswerPad();
setAnswerPad(answerPad);
setContentView(R.layout.abstract_test_view);
}
protected void setAnswerPad(AbstractAnswerFragment pad)
{
fragManager.beginTransaction()
.add(R.id.AnswerArea, pad, "AnswerArea")
.commit();
fragManager.executePendingTransactions();
}
Note that I was setting up fragments before I setContentView. Ooops.
A: This page seems to be a good central location for posting suggestions about the Fragment IllegalArgumentException. Here is one more thing you can try. This is what finally worked for me:
I had forgotten that I had a separate layout file for landscape orientation. After I added my FrameLayout container there, too, the fragment worked.
On a separate note, if you have already tried everything else suggested on this page (and the entire Internet, too) and have been pulling out your hair for hours, consider just dumping these annoying fragments and going back to a good old standard layout. (That's actually what I was in the process of doing when I finally discovered my problem.) You can still use the container concept. However, instead of filling it with a fragment, you can use the xml include tag to fill it with the same layout that you would have used in your fragment. You could do something like this in your main layout:
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="@layout/former_fragment_layout" />
</FrameLayout>
where former_fragment_layout is the name of the xml layout file that you were trying to use in your fragment. See Re-using Layouts with include for more info.
A: I fixed this bug, I use the commitNow() replace commit().
mFragment.getChildFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment_container,fragment)
.commitNowAllowingStateLoss();
The commitNow is a sync method, the commit() method is an async method.
A: I use View Binding in my project and was inattentive to add setContentView() after inflating ActivityHelloWorldBinding class:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHelloWorldBinding.inflate(layoutInflater)
// Add this line.
setContentView(binding.root)
}
A: In my case I was trying to show a DialogFragment containing a pager and this exception was thrown when the FragmentPagerAdapter attempted to add the Fragments to the pager. Based on howettl answer I guess that it was due to the Pager parent was not the view set in setContentView() in my FragmentActivity.
The only change I did to solve the problem was to create the FragmentPagerAdapter passing in a FragmentMager obtained by calling getChildFragmentManager(), not the one obtained by calling getFragmentManager() as I normally do.
public class PagerDialog extends DialogFragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.pager_dialog, container, false);
MyPagerAdapter pagerAdapter = new MyPagerAdapter(getChildFragmentManager());
ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(pagerAdapter);
return rootView;
}
}
A: In my case I had a SupportMapFragment in a recycler view item (I was using the lower overhead "liteMode" which makes the map appear as non-interactive, almost like a static image). I was using the correct FragmentManager, and everything appeared to work fine... with a small list. Once the list of items exceeded the screen height by a bit then I started getting this issue when scrolling.
Turned out, it was because I was injecting a dynamic SupportMapFragment inside a view, which was inside another fragment, to get around some issues I was having when trying to declare it statically in my XML. Because of this, the fragment placeholder layout could only be replaced with the actual fragment once the view was attached to the window, i.e. visible on screen. So I had put my code for initialising the SupportMapFragment, doing the Fragment replace, and calling getMapAsync() in the onAttachedToWindow event.
What I forgot to do was ensure that my code didn't run twice. I.e. in onAttachedToWindow event, check if my dynamic SupportMapFragment was still null before trying to create a new instance of it and do a Fragment replace. When the item goes off the top of the RecyclerView, it is detached from the window, then reattached when you scroll back to it, so this event is fired multiple times.
Once I added the null check, it happened only once per RecyclerView item and issue went away! TL;DR!
A: This issue also happens when you don't put <include layout="@layout/your_fragment_layout"/> in your app_bar_main.xml
A: use childFragmentManager instead of activity!!.supportFragmentManager
A: This exception can also happen if the layout ID which you are passing to FragmentTransaction.replace(int ID, fragment) exists in other layouts that are being inflated. Make sure the layout ID is unique and it should work.
A: With Nested fragments
For me by using getChildFragmentManager() instead of getActivity().getSupportFragmentManager() resolved crash
java.lang.IllegalArgumentException: No view found for id
A: An answer I read on another thread similar to this one that worked for me when I had this problem involved the layout xml.
Your logcat says "No view found for id 0x7f080011".
Open up the gen->package->R.java->id and then look for id 0x7f080011.
When I had this problem, this id belonged to a FrameLayout in my activity_main.xml file.
The FrameLayout did not have an ID (there was no statement android:id = "blablabla").
Make sure that all of your components in all of your layouts have IDs, particularly the component cited in the logcat.
A: I got this error when I upgraded from com.android.support:support-v4:21.0.0 to com.android.support:support-v4:22.1.1.
I had to change my layout from this:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container_frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
To this:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/container_frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
</FrameLayout>
So the layout MUST have a child view. I'm assuming they enforced this in the new library.
A: I encountered this problem when I tried to replace view with my fragment in onCreateView(). Like this:
public class MyProjectListFrag extends Fragment {
private MyProjectListFragment myProjectListFragment;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FragmentManager mFragmentManager = getFragmentManager();
myProjectListFragment = new MyProjectListFragment();
mFragmentManager
.beginTransaction()
.replace(R.id.container_for_my_pro_list,
myProjectListFragment, "myProjectListFragment")
.commit();
}
It told me
11-25 14:06:04.848: E/AndroidRuntime(26040): java.lang.IllegalArgumentException: No view found for id 0x7f05003f (com.example.myays:id/container_for_my_pro_list) for fragment MyProjectListFragment{41692f40 #2 id=0x7f05003f myProjectListFragment}
Then I fixed this issue with putting replace into onActivityCreated(). Like this:
public class MyProjectListFrag extends Fragment {
private final static String TAG = "lch";
private MyProjectListFragment myProjectListFragment;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater
.inflate(R.layout.frag_my_project_list, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
FragmentManager mFragmentManager = getFragmentManager();
myProjectListFragment = new MyProjectListFragment();
mFragmentManager
.beginTransaction()
.replace(R.id.container_for_my_pro_list,
myProjectListFragment, "myProjectListFragment")
.commit();
}
*
*You have to return a view in onCreateView() so that you can replace it later
*You can put any operation towards this view in the following function in fragment liftcycle, like onActivityCreated()
Hope this helps!
A: In my case this exception was thrown when I used different ids for the same layout element (fragment placeholder) while having several of them for different Build Variants. For some reason it works perfectly well when you are replacing fragment for the first time, but if you try to do it again you get this exception.
So be sure you are using the same id if you have multiple layouts for different Build Variants.
A: I was having this problem. In my case I have forgotten to add FrameLayout in my Xml File, after adding frame layout, my problem has been solved.
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/wraper"
android:layout_above="@id/wraper"/>
A: If you are trying to replace a fragment within a fragment with the fragmentManager but you are not inflating the parent fragment that can cause an issue.
In BaseFragment.java OnCreateView:
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.replace(R.id.container, new DifferentFragment())
.commit();
}
return super.onCreateView(inflater, container, savedInstanceState);
Replace super.onCreateView(inflater, container, savedInstanceState);
with inflating the correct layout for the fragment:
return inflater.inflate(R.layout.base_fragment, container, false);
A: I've had the same problem when was doing fragment transaction while activity creation.
The core problem is what Nick has already pointed out - view tree has not been inflated yet. But his solution didn't work - the same exception in onResume, onPostCreate etc.
The solution is to add callback to container fragment to signal when it's ready:
public class MyContainerFragment extends Fragment {
public static interface Callbacks {
void onMyContainerAttached();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.d(TAG, "--- onAttach");
((Callbacks) activity).onMyContainerAttached();
}
//... rest of code
}
And then in activity:
public class MainActivity extends Activity
implements MyContainerFragment.Callbacks
{
@Override
public void onMyContainerAttached() {
getFragmentManager()
.beginTransaction()
.replace(R.id.containerFrame, new MyFragment())
.commit();
}
//...
}
A: In my case, i was using a fragment class file to declare a listview adapter class.
I just used a different file for the public adapter class and the error was gone.
A: It happens also when you have two views in two fragments with the same ids
A: I had the same problem it was caused because I tried to add fragments before adding the container layout to the activity.
A: Sometimes it is because you are using a BottomNavigationView. If you open an Intent from the navigation and in that activity you open a fragment lets say
transaction.replace(R.id.container,new YourFragment());
then the Activity won't be able to find the navigation method you are using.
SOLUTION: Change the activity to fragment and handle navigation with addOnBackStack in your app. If you've implemented the Jetpack Navigation just use fragments in your project.
A: In my case. I have an Activity with serveral Fragments
some time I need to recreate Fragments when
*language is change
*fragment layout some need some not need or content change need to recreate
*other changes
I clear all Fragments and set all to null in activity
but Fragment already create itself, while it host activty
is bean set null, so before call Fragment view
check it null
for example
Activity{
fragment
recreate{
fragment = null then new instance
}
}
Fragment{
if((activity).fragment != null) {
findViewById()
}
}
A: With navigation library the issue can appear when NavHostFragment haven't an id.
Wrong declaration:
<fragment
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:navGraph="@navigation/myGraph"/>
Right declaration:
<fragment
android:id="@+id/myId"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:navGraph="@navigation/myGraph"/>
A: In our case we have purged/corrupted class.dex file along with gradle compiled outputs. Due to cache recompile weren't tried hence no error, but apk was not having the required file causing this confusing error. A gradle resync and fresh build cleared us from all errors.
// Happy coding
A: A bit late, but might help someone:
I was overriding
onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?)
(autocomplete suggested this one first and I added setContentView() here)
Please make sure to override the correct one instead:
onCreate(savedInstanceState: Bundle?)
A: In my case i was using a generic fragment holder using in my activity class and i was replacing this generic fragment with proper fragments at runtime.
Problem was i was giving id's to both include and generic_fragment_layout , removing id from include solved it.
A: As said by https://stackoverflow.com/users/2075875/malachiasz
This solution actually works
getChildFragmentManager().beginTransaction().replace(R.id.cpu_bottomNav_frame,new fragment()).commit();
A: just add viewPager.setOffscreenPageLimit( number of pages );
A: I was also getting the same error then, i realised that the issue was with the .add(R.id.CONTAINERNAME) So basically i had giving the id = CONTAINERNAME in wrong xml ..
So the solution is to first check that you have given the id = CONTAINERNAME in the xml where you want the fragment to be displayed ..
Also note that I was trying to call the fragment form an activity..
I hope so thing small mistake will solve the issue
REFER ON BASIS OF LATEST VERSION OF ANDROID IN YEAR - 2020
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "345"
} |
Q: Open Source .NET Application Projects (not framework or tool projects) with lots of NUnit Tests I would like to get a list some reference or sample application projects in .NET/C#- with good test coverage.
The thing is, I want to see this in action for a true application project with any business logic in it. Instead of frameworks with tests in them... like ASP.NET MVC ,Automapper etc. which are no doubt useful.
A: http://www.ohloh.net/p/nunit/stacks — check for users who contributes to some project. Some examples:
CruiseControl.net
Witty twitter client
octalforty-wizardby
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: bt assembly instruction I have quesetion about bt assembly instruction. I have excerpted part of book to provide context. Please see last example, bt Testme, bx. Why does that copy TestMe+8? Shouldn't it copy TestMe+65?
Very much thank you for help!
6.6.4.2 The Bit Test Instructions: BT, BTS, BTR, and BTC
On an 80386 or later processor, you can use the bt instruction (bit
test) to test a single bit. Its second operand specifies the bit index
into the first operand. Bt copies the addressed bit into the carry
flag. For example, the instruction
bt ax, 12
copies bit twelve of ax into the carry flag.
The bt/bts/btr/btc instructions only deal with 16 or 32 bit operands.
This is not a limitation of the instruction. After all, if you want to
test bit three of the al register, you can just as easily test bit
three of the ax register. On the other hand, if the index is larger
than the size of a register operand, the result is undefined.
If the first operand is a memory location, the bt instruction tests
the bit at the given offset in memory, regardless the value of the
index. For example, if bx contains 65 then
bt TestMe, bx
will copy bit one of location TestMe+8 into the carry
flag. Once again, the size of the operand does not matter. For all
intents and purposes, the memory operand is a byte and you can test
any bit after that byte with an appropriate index. The actual bit bt
tests is at bit position index mod 8 and at memory offset effective
address + index/8.
A: bt TestMe, bx where bx contains 65 is an access 8 bytes (64 bits plus 1) beyond the address of TestMe. It doesn't copy the byte there, only the second bit in that byte (to the carry flag, CF).
A: When the book says "bit one of location TestMe+8", the "8" refers to an address offset, which is measured in bytes. There are 64 bits in 8 bytes, so the 65th bit is bit one of 8 bytes past TestMe.
*
*The byte at TestMe has bits 7..0
*The byte at TestMe+1 has bits 15..8
*The byte at TestMe+2 has bits 23..16
*...
*The byte at TestMe+8 has bits 71..64
So "65" refers to "bit 1" (the second counting from the right) of the byte at address TestMe+8.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How can I get an integer index for a key in hadoop? Intuitively, hadoop is doing something like this to distribute keys to mappers, using python-esque pseudocode.
# data is a dict with many key-value pairs
keys = data.keys()
key_set_size = len(keys) / num_mappers
index = 0
mapper_keys = []
for i in range(num_mappers):
end_index = index + key_set_size
send_to_mapper(keys[int(index):int(end_index)], i)
index = end_index
# And something vaguely similar for the reducer (but not exactly).
It seems like somewhere hadoop knows the index of each key it is passing around, since it distributes them evenly among the mappers (or reducers). My question is: how can I access this index? I'm looking for a range of integers [0, n) mapping to all my n keys; this is what I mean by an "index".
I'm interested in the ability to get the index from within either the mapper or reducer.
A: After doing more research on this question, I don't believe it is possible to do exactly what I want. Hadoop does not seem to have such an index that is user-visible after all, although it does try to distribute work evenly among the mappers (so such an index is theoretically possible).
A: Actually, your reducer (each individual one) gets an array of items back that correspond to the reduce key. So do you want the offset of items within the reduce key in your reducer, or do you want the overall offset of the particular item in the global array of all lines being processed? To get an indeex in your mapper, you can simply prepend a line number to each line of the file before the file gets to the mapper. This will tell you the "global index". However keep in mind that with 1 000 000 items, item 662 345 could be processed before item 10 000.
A: If you are using the new MR API then the org.apache.hadoop.mapreduce.lib.partition.HashPartitioner is the default partitioner or else org.apache.hadoop.mapred.lib.HashPartitioner is the default partitioner. You can call the getPartition() on either of the HashPartitioner to get the partition number for the key (which you mentioned as index).
Note that the HashPartitioner class is only used to distribute the keys to the Reducer. When it comes to a mapper, each input split is processed by a map task and the keys are not distributed.
Here is the code from HashPartitioner for the getPartition(). You can write a simple Java program for the same.
public int getPartition(K key, V value, int numReduceTasks) {
return (key.hashCode() & Integer.MAX_VALUE) % numReduceTasks;
}
Edit: Including another way to get the index.
The following code from should also work. To be included in the map or the reduce function.
public void configure(JobConf job) {
partition = job.getInt( "mapred.task.partition", 0);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Databind repeater using Linq with group by I need to bind a repeater with hierarchical data as follows:
Category1
- Item1
- Item2
Category2
- Item3
- Item4
I currently have a single dataset with the items as well as the category that each item belongs to.
I'm trying to learn Linq and was wondering if there was a way I can do the same using Linq?
Below is what I tried:
var groupbyfilter = from dr in dtListing.AsEnumerable()
group dr by dr["Category"];
DataTable dtFinal = dtListing.Clone();
foreach (var x in groupbyfilter)
x.CopyToDataTable(dtFinal, LoadOption.OverwriteChanges);
rptList.DataSource = dtFinal;
rptList.DataBind();
But trouble with it is it repeats category for each item.
A: You'll need a repeater nested inside another.
Do a distinct on the dtlisting selecting only the category field. Bind this to the outer repeater.
In the 2nd repeater, select data whose where condition has category field which equals to the value that is being databound to the repeater item. You'd have to handle this in the repeater's onitem_databound event.
Here is an example.
<%@ Import Namespace="System.Data" %>
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<div>
Category: <b><%# Container.DataItem%></b>
<asp:Repeater ID="Repeater2" runat="server">
<FooterTemplate>
<%="</ul>" %>
</FooterTemplate>
<HeaderTemplate>
<%= "<ul>"%>
</HeaderTemplate>
<ItemTemplate>
<li>
<%# ((Data.DataRow)Container.DataItem)[1] %>, <%# ((Data.DataRow)Container.DataItem)[0] %>
</li>
</ItemTemplate>
</asp:Repeater>
</div>
</ItemTemplate>
</asp:Repeater>
For this sample I used a csv as my datasource, and created a datatable using it. So my codebehind looks like:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public class _Default : System.Web.UI.Page
{
DataTable csvData;
protected void Page_Load(object sender, System.EventArgs e)
{
csvData = Utils.csvToDataTable("data.csv", true);
GridView1.DataSource = csvData;
GridView1.DataBind();
Repeater1.DataSource =
(from x in csvData.AsEnumerable() select x["category"]).Distinct();
Repeater1.DataBind();
}
protected void Repeater1_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item |
e.Item.ItemType == ListItemType.AlternatingItem) {
Repeater rptr = (Repeater)e.Item.FindControl("Repeater2");
rptr.DataSource =
csvData.AsEnumerable().Where(x => x["category"].Equals(e.Item.DataItem));
rptr.DataBind();
}
}
}
A: You can either use nested repeaters like deostroll says, or specify a grouping field and have a group header in your ItemTemplate that's dynamically hidden (or rendered) every time your grouping field changes.
More detail in fernan's answer at http://forums.asp.net/t/1252235.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can I create a trigger that involves a cursor on a table that the trigger is not made for? For example if I have a trigger for table employee. I want to create a cursor loop from the table department. Then I want to take the attribute and insert it into the table company. I'm guessing the answer is no, because I get a runtime error that says table department cannot be found, but is there any way around this that gets the same effect?
CREATE TRIGGER myTrigger AFTER INSERT
ORDER 1 ON dba.employee
REFERENCING NEW AS newRow
FOR EACH ROW
BEGIN
FOR myloop AS getIDCursor INSENSITIVE CURSOR FOR SELECT department_id FROM department
DO
INSERT INTO company (...) VALUES (...);
END FOR
END
A: Why are you using SQL like a procedural language? Just do:
INSERT INTO company SELECT department_id FROM department
No need for loops.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I avoid overloading the JavaScript CallStack? The javascript below accomplishes the following (this is for a node.js COMET application):
*
*Request is made to the server and held until the server has something to
return.
*Once the request returns the data is processed and another
request is immediately made within the callback function of the
success event.
*If a timeout occurs (the server had nothing to return within the time frame)
another request is made within the callback function of the error event.
My concern (which I believe is valid) is that the requests are continually added to the callstack, much like a recursive function that never ends. After a while, it results in the browser eventually crashing and becoming unresponsive (at least I think this is the cause).
How can I accomplish the same thing and avoid this problem?
function GetData(){
$.ajax({
url: "admin.html",
type: "POST",
dataType: "json",
contentType: 'text/json',
data: JSON.stringify({
cmd: "getData"
}),
timeout: (60 * 1000),
success: function(data, textStatus, jqXHR){
UpdateScreen(data);
GetData();
},
error: function(jqXHR, textStatus, errorThrown){
if(textStatus == "timeout"){
GetData();
}
}
});
}
A: No, I'm pretty sure you are OK. The ajax event is asynchronous, so the GetData function will finish and the browser will wait for events, before it calls GetData again from the success handler.
Think of it as the GetData function just defining what to do, not actually doing it. Then it finishes executing (and clears the stack) and browser does those actions.
A: function GetData(limit){
limit = limit || 0;
$.ajax({
url: "admin.html",
type: "POST",
dataType: "json",
contentType: 'text/json',
data: JSON.stringify({
cmd: "getData"
}),
timeout: (60 * 1000),
success: function(data, textStatus, jqXHR){
UpdateScreen(data);
GetData();
},
error: function(jqXHR, textStatus, errorThrown){
if(textStatus === "timeout" && limit < 20){
GetData(++limit);
} else {
//throw "epic fail"
setTimeout(GetData, 0);
}
}
});
}
Just add a little timeout limit counter. if it gets too big either give up and throw an error or break the call stack by calling setTimeout which is asynchronous.
A: I'm wondering if your UpdateScreen(data) method is the problem. Is that a recursive function as well? People suggesting that you simply timeout the method doesn't actually fix the problem, it simply aborts the process. I would try logging something like console.log("get data success") and console.log("get data error") in your success and error callbacks respectively. If your log page is full of one message, you know where the GetData() method is continually called. It could be always timing out.
On a side note, you should change your if statement for an error to something like
if(jqxhr.responseText == "timeout"){
getData();
}
see here for explanation why: jQuery Ajax error handling, show custom exception messages
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creating an xls or csv file from a Javascript variable I have an app that uses Javascript to perform some calculations and then plot the data, but I'd like to add the option for the user to be able to actually download the data into a csv or xls file.
Is there a way in Javascript (or some other method) to have the user press a button, then it will prompt them for the name of the file to save it as, and it will then create a comma-delimited or excel spreadsheet?
Thanks!
EDIT:
Thanks for all the suggestions everyone. Wish I could mark you all as answers, but upboats will have to do for now
A: It's not hard to open a window and write the csv into it. But I don't know of any way for javascript to change the Content-Type: header. And without that it won't prompt to save or open.
You'll need assistance from the server to do this. You can send the data to the server in a form variable and have the server send it right back with the correct header Content-type: text/csv you may also want the Content-Disposition: header to give your file a name.
A: Yes, but you'll need to use server-side code as well. Use JavaScript to construct a link to a page that streams the csv data back as an attachment. The server output should contain a content-disposition header of attachment; filename="fileName.csv".
A: No, you can't create and/or save a file directly from JavaScript. On some browsers/platforms (IE/Windows), you could create and write to a file via ActiveX object:
function WriteToFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\temp\\Test.txt", true);
s.WriteLine('Hello');
s.Close();
}
Another solution is to use client-side JavaScript (inside a browser) to output CSV data into a separate window (or pop-up) and have a user to copy/paste it into Excel.
A: If you want to do it in a browser website style it might be hard. But Javascript is a good language to do this, but you will need to use .hta instead of a normal .html. Creating an .hta creates a stand alone application just like a normal .exe.
Here is what you want to look for ActiveXObject("Excel.Application")
In order to transform a html into an hta, here is the tag
<HTA:APPLICATION
id="SomeId"
border="thin"
borderStyle="normal"
caption="yes"
maximizeButton="yes"
minimizeButton="yes"
showInTaskbar="yes"
windowState="yes"
innerBorder="yes"
navigable="yes"
scroll="auto"
scrollFlat="yes"
singleinstance="yes"
/>
For futher reading on hta and the excel active X
A: You could certainly write a browser plugin (ActiveX control on IE, NPAPI on others) with FireBreath that would do this; you'd have to write it in C++. Honestly, I agree with others in suggesting that you do this server-side instead, but you can do it with a plugin and it wouldn't be too difficult.
A: I think that it would be possible to do this (up to a certain size limit) with data URIs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Excel multiple grouping on table for different pivot tables? I am using Excel 2007 and using several pivot charts which reference the same table of data. I change the data daily, copy and pasting the data from another source. Is it possible to change the grouping on the table so that I can view the data differently in different pivot tables? For example, one graph views the data by hour and another by month and another by day. It seems that when I change the grouping for one graph, it changes it on every one. My solution has been to copy and paste in the data into three separate tables for data with each one having different groupings.
A: The most flexible solution is to split dates in different columns and calculate all the aggregation levels needed using
- =YEAR([date]), =MONTH([date]), =DAY([date]), =HOUR([date]), =MINUTE([date])
- =CEILING(MONTH([date])/3;1) for quarter
and pull these fields in & out of your Pivot tables / charts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Changing Iframe Width/Height in Javascript Based on Anchor Point Ok, I deal with this all the time in flash but I'm kind of lost in how to accomplish this in Javascript and CSS. I have an iframe (which by definition doesn't have an overflow property) whose width/height i'm trying to modify. Is there an easy way to change this value relative to a certain anchor point? Basically I have an ad that has a contracted and expanded state. If the expanded state expands leftward or upward, how can i modify the width/height in such a way to display the entire contents of the ad?
A: You can absolutely position your ad and anchor it with bottom and right:
.ad {
position: absolute;
bottom: 0;
right: 0;
}
Then when you increase the height and width, it will expand upwards and leftwards.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Facebook API simple authorization failing javascript I have the following in my source code. I get the alert "No Response" and then the facebook page says
"An error occurred with MYAPP. Please try again later"
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js" charset="utf-8"></script>
<script>
FB.init({appId: 'MYAPPID',status: true, cookie:true, xfbml: true});
</script>
<script>
FB.getLoginStatus(function(response){
if(!response.session){
alert("NO RESPONSE");
top.location.href="http://www.facebook.com/dialog/oauth?client_id=MYAPPID&redirect_uri=http://MYWEBSITE";
}
});
Can't see where/if I have gone wrong here.
Thanks
I am getting now the following error:
API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: Invalid redirect_uri: Given URL is not allowed by the Application configuration.
A: You are using older login code. For FB.init, you should be setting oauth: true and you will want to check response.authResponse instead of response.session.
<!DOCTYPE html>
<html>
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({ appId: 'MYAPPID', status: true, cookie: true, xfbml: true, oauth: true });
FB.getLoginStatus(function(response){
if(!response.authResponse){
alert("NO RESPONSE");
top.location.href="http://www.facebook.com/dialog/oauth?client_id=MYAPPID&redirect_uri=http://MYWEBSITE";
}
});
</script>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android Honeycomb: How to style right corner arrow in spinner on an ActionBar This is a pretty specific question. I have a spinner on an ActionBar that is added in the onCreate() method. I have been able to style the text white, but I can't get the underline and the triangle/arrow at the bottom right to appear as white. Here is my styling:
<item name="android:actionDropDownStyle">@style/customActionBarDropDownStyle</item>
<style name="customActionBarDropDownStyle" parent="android:style/Widget.Holo.Light.Spinner">
<item name="android:textColor">#FFFFFF</item>
</style>
I can't find a style item/property that makes the underline and triangle white. Does one exists?
Here's an example. I have highlighted in red the triangle and underline that I want to make white.
A: A bit late answer, but better than never :)
You should create a new 9 patch drawable and set it as a background to android:actionDropDownStyle.
here is an example:
<item name="android:actionDropDownStyle">@style/customActionBarDropDownStyle</item>
<style name="customActionBarDropDownStyle"parent="android:style/Widget.Holo.Light.Spinner">
<item name="android:background">@drawable/custom_spinner_dropdown</item>
</style>
You can't set a color to almost every native component, as their backgrounds are (in most cases) 9-patch pngs.
A: The actionDropDownStyle can not used to change the style of spinner you added on actionbar; its for one of the actionbar mode ActionBar.NAVIGATION_MODE_LIST;
As for your problem, you can define a selector for your spinner in the layout file,just like this:
enter code here
<Spinner
android:dropDownWidth="200dp"
android:background="@drawable/actionbar_spinner"
android:id="@+id/action_spinner"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginRight="10dp" />
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false"
android:drawable="@drawable/spinner_ab_disabled" />
<item android:state_pressed="true"
android:drawable="@drawable/spinner_ab_pressed" />
<item android:state_pressed="false" android:state_focused="true"
android:drawable="@drawable/spinner_ab_focused" />
<item android:drawable="@drawable/spinner_ab_default" />
</selector>
A: Try this : android:background="@null"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How did my SQL Server 2008 trigger get deleted? This is a very strange problem. I've asked about it before here:
How did my trigger get deleted?
I renamed my trigger and I thought it had stopped happening but the problem seems to have come back again.
I've added a trigger to a table in our database. The server is SQL 2008. The trigger doesn't do anything particularly tricky. Just changes a LastUpdated field in the table when certain fields are changed. It's a "After Update" trigger.
There is a large C++ legacy app that runs all kind of huge queries against this database. Somehow (I've got absolutely no idea how) it is deleting this trigger. It doesn't delete any other triggers and I'm certain that it's not explicitly dropping the trigger or table. The developers of this app don't even know anything about my triggers.
How is this possible?
I've tried running a trace using SQL Server Profiler and I've gone through each command that it's sending and run them using SQL Management Studio but my trigger is not affected. It only seems to happen when I run the app.
The other devs reckon that they are not deleting it explicitly. It doesn't exist in sys.objects or sys.triggers so it's not a glitch with SSMS. Guess I'll just rename it and hope for the best? I can't think of anything else to try. A few comments below have asked if the trigger is being deleted or just disabled or not working. As I stated, it's being deleted completely. Also, the problem is not related to the actual contents of the trigger. As I stated, it I remove the contents and replace with some extremely simple code that doesn't do anything then it is still deleted.
A: Look for table drops -- you might be surprised at what actually causes your table to be dropped. (Different things you do through the SSMS UI, as opposed to using tsql directly.)
You can prevent this kind of inadvertant table dropping like this:
Tools -> Options -> Designers-> Uncheck "Prevent saving changes that require table re-creation"
A: Perhaps you could create a DDL trigger on the database and log all the object deletion statements. In particular, you could write the drop events to a table to log to trace it or just flat out block it.
A: Is other application code dropping and re-creating the entire table ? If so, perhaps it is not aware of the trigger.
A: Thanks for the suggestions everyone. In particular Billinkc's suggestion of creating a DDL trigger was cool. I didn't know that such a thing exists.
Anyway after three months of wondering what was going on here I finally got to the bottom of it.
I have a bunch of scripts to create various triggers. They have the typical format of "if trigger exists then delete", "go", followed by "create trigger" and another "go". I use a script to add all these individual triggers to the database in one go. I missed one of the "go" commands at the bottom of a create command (in all these hundreds of lines). This means that trigger A got added to the database with "if trigger B exists then delete" at the bottom of it. That was so confusing...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: put jquery template in external file I use jQuery template on my site, I would like to put them all on a separate file. How do it do it?
Here is one example
<script type="text/template" id="request-template">......</script>
A: if you have a big application, i suggest you look into require.js
in combination with the text plugin
require.js allows you to dynamically load your scripts when they are needed,
the text plugin is ideal for loading text content files the same way you would use it on javascript modules. so you could put your templates in separate files, and list them as dependencies for your javascript, then they get loaded when the javascript needs them.
edit
simple solution: put your script blocks in a separate html file, use jquery to load them in.
separatefile.html
<script type="text/template" id="user-template">user content here...</script>
<script type="text/template" id="form-template">form content here...</script>
<script type="text/template" id="mail-template">mail content here...</script>
your script:
$(function(){
$('#templates').load("/separatefile.html", function(){
// handle everything after you have your templates loaded...
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble with matchmaking in iOS with gamekit and game centre At the moment I'm trying to add online multiplayer to my iOS game (that uses UIKit) using gameKit/GameCenter for matchmaking. I'm trying to present game center's matchmaker interface but with varied success. I have two view controllers (with respective .xib files), mainMenuViewController and onlineViewController, along with a file called GCHelper.h.
In CGHelper I have this:
- (void)findMatchWithMinPlayers:(int)minPlayers
maxPlayers:(int)maxPlayers
viewController:(UIViewController *)viewController
delegate:(id<GCHelperDelegate>)theDelegate
{
if (!gameCenterAvailable) return;
self.presentingViewController = viewController;
delegate = theDelegate;
[presentingViewController dismissModalViewControllerAnimated:NO];
GKMatchRequest *request = [[GKMatchRequest alloc] init];
request.minPlayers = minPlayers;
request.maxPlayers = maxPlayers;
GKMatchmakerViewController *mmvc = [[GKMatchmakerViewController alloc] initWithMatchRequest:request];
mmvc.matchmakerDelegate = self;
[presentingViewController presentModalViewController:mmvc animated:YES];
}
I use this function in my views to show the matchmaking interface. At first I tried it in mainMenuViewController, which is my first view controller using this:
[[GCHelper sharedInstance] findMatchWithMinPlayers:2 maxPlayers:2 viewController:self delegate:self];
And that worked fine but that's not where I wanted to do it, so I tried the exact same thing from onlineViewController and nothing happens, no error, just the blank view of onlineViewController.view stares back at me. I'm fairly new at this so I'm wondering if it's down to how I'm dealing with the views, here's the code I use to switch from the mainMenu to the other view:
-(IBAction)showOnlineView
{
OnlineViewController *onlineViewController = [[OnlineViewController alloc] initWithNibName:@"OnlineViewController" bundle:nil];
UIView *currentView = self.view;
UIView *theWindow = [currentView superview];
[currentView removeFromSuperview];
[theWindow addSubview:onlineViewController.view];
}
Any help would be greatly appreciated. Also, I'm not sure how I should deal with going back to the main menu if the user presses cancel (although that may become self evident once I've got this working, I just thought I'd mention it in case this lack of knowledge on my part makes it obvious I'm going about the whole thing incorrectly).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Dealing with a multiple user environment This is my first time developing an application that will be used by 10-15 people concurentlyso I'm not exactly sure of a good way to minimize update collisions.
Essentially, my application works as follows. New items get inserted into the database via an external service as they get received. Business rules indicate that each item is to be reviewed by two independant employees. Needless to say, there is a one-to-many relationship between the item and reviews. What is the most important aspect of the application is that no item can exceed two reviews and the system must keep track of who were the two reviewers. Also, who acted as the first reviewer and second.
Now, I have everything working. The issue I'm dealing with is this (one of many simmilar scenarios). What happens if all users refreshed their item listing within the same 5 minutes of eachother. User 1 submits a review for item id 1. A second person submits a review on the same item. Now a third person submits a review on item id 1 but there are already 2 reviews so the item has been marked as complete.
What are possible ways to deal with a multi-user environment where there is a great possibility of several users updating the same record?
A: I don't know the details of your app but it seems like the process of doing a review widens the window where multiple folks can start a review and then when they commit it ends up being more than two,
One option is to introduce the concept of starting a review. When someone initiates the action of doing a review, they "start" the review. That marks the review as started. The system shouldn't let more than two starting.
You could also make it more advanced by timing out reviews that we're never "submitted" or having the ability to delete a pending review that was started.
A: Nhibernate has various concurreny models which you implement in your project based upon your needs.
Have a look at NHibernate-Concurrency
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Codeigniter CSRF question I'm just wondering of there is any option where i can turn off CSRF in a specific controller/method. I've got another site that pings my site, but getting blocked because of the CSRF.
Is there any way i can get around this?
A: Create a pre_system hook then put the following code inside your hook controller:
if(stripos($_SERVER["REQUEST_URI"],'/controller/function') !== FALSE)
{
$CFG =& load_class('Config', 'core');
$CFG->set_item('csrf_protection', FALSE);
}
Reference: http://codeigniter.com/forums/viewreply/869900/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: -webkit-tap-highlight-color in Windows Phone? Is there an equivalent to -webkit-tap-highlight-color for Windows Phone 7 (Mango)? I'm writing a mobile site, and I'd like it to display the same way across all browsers, if possible.
I've tried tap-highlight-color and -ms-tap-highlight-color, neither worked.
A: Unfortunately, there is no such equivalent Microsoft propritary extension at this time for WP7. If you take a look at the Microsoft list of attributes, you will see an absence of anything even touch related.
On the JavaScript side, the IE blog just about that IE 10 will specify the pressure of a touch. This might be the closest that we can get for the time being. For now, if you really wanted to do it with JavaScript you would have to keep track of the time that the mouse was down (what a pain). The events you will need are MouseDown, MouseMove, and MouseUp.
Recommendation: If I were you I would go with progressive enhancement and not support it for WP7 at this time. If it's a critical part of your app though, you may have to play around a bit with JavaScript to see if you can get something workable.
A: You can disable tap highlight in IE 10 on specific element with CSS
-ms-touch-action: none;
A: I know this is late to answer, but I have an update.
The answer is still no, unfortunately.
However, IE10 on WP8 allows:
<meta name="msapplication-tap-highlight" content="no"/>
You can only disable the tap color, and it seems that you cannot customize the color.
A: In windows phone 8.1 the meta tag did not worked (PhoneGap App).
<meta name="msapplication-tap-highlight" content="no"/>
But this in the CSS file worked for me
body{
-ms-user-select: none
}
A: The (-webkit-)tap-highlight property is only supported in Safari on iOS (iPhone/iPad) and other browsers that use webkit.
If you're really desperate to display the tap highlight color you could use CSS' :focus selector which is the closest solution to your problem or try to achieve the same behavior with javascript (jQuery).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Change style of all elements with particular class apart from the first one? Let's say I have the HTML
<div class="ms-rtelong"></div>
<input type="text" name="fname"></input>
<input type="text" name="lname"></input>
<div class="ms-rtelong"></div>
<div class="ms-rtelong"></div>
<div class="ms-rtelong"></div>
With
$('.ms-rtelong').css({'width':'650px', 'height':'300px'});
If I want to change the size of all div's but want to leave the first one as it is, how can I do this?
Thanks in advance.
A: The :gt() selector should do it:
$('.ms-rtelong:gt(0)').css({'width':'650px', 'height':'300px'});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery ui tabs+dialog+form tab order I have a jquery dialog that pops up with a form. The form is split across multiple tabs within the dialog. I'm working on keyboard ease and would like for pushing the tab key on the last element of one tab to take me to the first element of the next tab. Right now the tab order is to go through the dialog tabs, then through the first tab of inputs, then to the OK button. Instead of Weight->OK I want it to go Weight->Price. Is there an easy way to do this?
The HTML:
<div id='add_dialog' title='Add'>
<form id="add_form" method="POST">
<input type="hidden" name="action" value="add">
<input type="hidden" name="ProductId" value="2">
<div id="jquery-ui-tabs">
<ul>
<li><a href="#add_details">Details</a></li>
<li><a href="#add_financial">Financial & Comments</a></li>
</ul>
<div id="add_details">
Quantity: <input type="text" name="Quantity" value="1"><br />
QuantityPerPack: <input type="text" name="QuantityPerPack" value="0"><br />
Pc Weight: <input type="text" name="PieceWeight" value=" "><br />
</div>
<div id="add_financial">
Price: <input type="text" name="PriceHigh" value="0.00"><br />
Comment: <textarea name="StockComment"></textarea><br />
</div>
</div>
</form>
</div>
And the initializing javascript:
$('#add_dialog').dialog(
{
autoOpen: false,
maxHeight: 500,
width: 600,
minWidth: 600,
zIndex: 99999,
position: ['center', 50],
buttons:[{
text: "Ok",
class: "dialog_ok",
click: function() {
$(this).dialog("close");
$("#add_form").submit();
}
},
{
text: "Cancel",
class: "dialog_cancel",
click: function() {
$(this).dialog("close");
}
}]
});
A: It wasn't so bad. For posterity, here is the code I eventually used. I added IDs to the two inputs, then I attached a keydown event and if it's a tab I move to the next tab and then focus on the first element.
$('#add_form_pieceweight').keydown(function(e) {
var code = e.keyCode || e.which;
if (code == '9') {
$('#jquery-ui-tabs').tabs('select',1);
$('#add_form_price').focus();
return false;
}
});
A: This is happening because the other form inputs are hidden in a hidden tab div, and thus skipped over for tabbing through. So you have to manually listen for someone pressing tab and then show the other tab.
On "weight" input, bind to keydown. Look at the key they pressed in the event that your lister gets. If someone pressed "tab", select the add_financial href and send it a "click" event to get it to change to the next tab, then select the "price" input and focus() on it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Binding SQLite Parameters directly by Name I recently - very recently - started learning how to program for iOS, and have been stumped by what appears (to me) to be a blatant oversight in SQLite3. Let me qualify that by saying that prior to last week I had zero (practical) experience with Macs, Objective C, Xcode, iOS or SQLite, so I have no delusions about waltzing into field of tried-and-true tools and finding obvious errors on my first try. I assume there's a good explanation.
However, after spending the last few months using SQL Server, MySQL, and PostgreSQL, I was amazed to discover that SQLite doesn't have better functionality for adding parameters by name. Everything I could find online (documentation, forums [including SO]) says to assign parameters using their integer index, which seems like it would be a pain to maintain if you ever modify your queries. Even though you can name the parameters in your statements and do something like
sqlite3_bind_int(stmt, sqlite3_bind_parameter_index(stmt, "@my_param"), myInt);
no one seems to do that either. In fact, no one seems to try to automate this at all; the only alternate approach I could find used a parameter array and a loop counter, and inspected each parameter to determine which object type to insert. I originally considered a similar approach, but a) my boss's stance is that database parameters should always be type checked (and I agree, although I realize that SQLite fields aren't strongly typed and I technically could do it anyways), b) it felt like an inelegant hack, and c) I assumed there was a reason this approach wasn't widely used. So:
1) Why aren't there binding methods in SQLite that accept a parameter name (as, say, a 'const char')? Or are there and I'm missing something?
2) Why doesn't anyone seem to use an approach like the example above?
I dug in the source code a little and think I could easily modify the library or just write my own (typed) class methods that would do the above for me, but I'm assuming there's a reason no one has built this into SQLite yet. My only guess is that the additional memory and cycles needed to find the parameter index are too precious on an [insert iDevice here], and aren't worth the convenience of being able to use parameter names . . . ?
Any insight would be appreciated.
A: *
*There are; it's the sqlite3_bind_parameter_index() function you mentioned that you use to turn a parameter name into an index, which you can then use with the sqlite3_bind_*() functions. However, there's no sqlite3_bind_*_by_name() function or anything like that. This is to help prevent API bloat. The popular Flying Meat Database sqlite wrapper has support for named parameters in one of its branches, if you're interested in seeing how it's used.
If you think about what it would take to implement full named parameter binding methods, consider the current list of bind functions:
int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
int sqlite3_bind_double(sqlite3_stmt*, int, double);
int sqlite3_bind_int(sqlite3_stmt*, int, int);
int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
int sqlite3_bind_null(sqlite3_stmt*, int);
int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
If we wanted to add explicit support for named parameters, that list would double in length to include:
int sqlite3_bind_name_blob(sqlite3_stmt*, const char*, const void*, int n, void(*)(void*));
int sqlite3_bind_name_double(sqlite3_stmt*, const char*, double);
int sqlite3_bind_name_int(sqlite3_stmt*, const char*, int);
int sqlite3_bind_name_int64(sqlite3_stmt*, const char*, sqlite3_int64);
int sqlite3_bind_name_null(sqlite3_stmt*, const char*);
int sqlite3_bind_name_text(sqlite3_stmt*, const char*, const char*, int n, void(*)(void*));
int sqlite3_bind_name_text16(sqlite3_stmt*, const char*, const void*, int, void(*)(void*));
int sqlite3_bind_name_value(sqlite3_stmt*, const char*, const sqlite3_value*);
int sqlite3_bind_name_zeroblob(sqlite3_stmt*, const char*, int n);
Twice as many functions means a lot more time spent maintaining API, ensuring backwards-compatibility, etc etc. However, by simply introducing the sqlite3_bind_parameter_index(), they were able to add complete support for named parameters with only a single function. This means that if they ever decide to support new bind types (maybe sqlite3_bind_int128?), they only have to add a single function, and not two.
*As for why no one seems to use it... I can't give any sort of definitive answer with conducting a survey. My guess would be that it's a bit more natural to refer to parameters sequentially, in which case named parameters aren't that useful. Named parameters only seem to be useful if you need to refer to parameters out of order.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Use jQuery.validate to check that 3 dropdowns all have non-default options selected I want to use the jQuery.validate() plugin to check that the user has chosen an option from 3 dropdown lists - day, month and year for their DOB. I don't need to validate the actual date, just as long as they choose something. I just want the one validation error message to be displayed to read "Please provide your date of birth".
You can imagine what the markup looks like, but here it is anyway:
<div class="dropdown">
<select id="day" class="styled" name="day">
<option value="">--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
[ etc... ]
</select>
</div>
<div class="dropdown">
<select id="month" class="styled" name="month">
<option value="">--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
[ etc... ]
</select>
</div>
<div class="dropdown">
<select id="year" class="styled" name="year">
<option value="">--</option>
<option value="1993">1993</option>
<option value="1992">1992</option>
<option value="1991">1991</option>
<option value="1990">1990</option>
[ etc... ]
</select>
</div>
A: I created three dropdowns for Date of Birth selection and number of days changes dynamically based on the year and month selection. http://jsfiddle.net/ravitejagunda/FH4VB/10/. Fiddle has the complete code for the dropdowns
daysInMonth = new Date(year,month,1,-1).getDate();
A: Add a "required" class in the selects. Check out this fiddle
<select id="day" class="styled required" name="day">
<option value="">--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
This is your js
$('button').click(function() {
$('#myform').valid()
return false;
});
A: Not strictly JQuery, but i did a function in JavaScript, which configures the form drop downs to suit the number of days for a given month/year combination, it expects the drop downs to have the first entry as a description
<select name="reg_day" id="reg_day">
<option>Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select name="reg_month" id="reg_month">
<option>Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
</select>
<select name="reg_year" id="reg_year">
<option>Year</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
<option value="2010">2010</option>
<option value="2009">2009</option>
</select>
The Function
function calculateDays(){
//get the day, month, year drop downs
var dayBox = document.getElementById('reg_day');
var monthBox = document.getElementById('reg_month');
var yearBox = document.getElementById('reg_year');
if(monthBox.value>0){
if(yearBox.value<1800){
var year = new Date().getFullYear();
} else {
var year = yearBox.value;
}
var daysThisMonth = 32 - new Date(year, (monthBox.value-1), 32).getDate();
} else {
var daysThisMonth = 31;
}
//save the first one, and the selected index
var dayBoxText = dayBox.options[0].text;
var dayBoxSelected = dayBox.selectedIndex;
//clear the drop down (days)
for(var count = dayBox.options.length - 1; count >= 0; count--){
dayBox.options[count] = null;
}
//create the first option (ie the bit that says Day, Month, Year)
var theOption = new Option;
theOption.text = dayBoxText;
dayBox.options[dayBox.options.length] = theOption;
//populate the days drop down with the new lists
for(var i = 1; i <= daysThisMonth; i++) {
var theOption = new Option;
theOption.text = i;
theOption.value = i;
dayBox.options[dayBox.options.length] = theOption;
}
//if the day selected is less than days use choose the last, if not choose the selected index
if(dayBoxSelected<daysThisMonth){
dayBox.selectedIndex = dayBoxSelected;
} else {
dayBox.selectedIndex = dayBox.options.length-1;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Could not call install_name_tool Trying to use virutalenv version 1.6.4 (the latest at writing this post) on 10.7, Lion with yes Xcode 4 installed from mac app store, yet i'm getting the below error message:
New python executable in SUPENV/bin/python
Error [Errno 2] No such file or directory while executing command install_name_tool -change /System/Library/Fram.../Versions/2.7/Python @executable_path/../.Python SUPENV/bin/python
Could not call install_name_tool -- you must have Apple's development tools installed
Traceback (most recent call last):
File "/usr/local/bin/virtualenv", line 8, in <module>
load_entry_point('virtualenv==1.6.4', 'console_scripts', 'virtualenv')()
File "/Library/Python/2.7/site-packages/virtualenv-1.6.4-py2.7.egg/virtualenv.py", line 810, in main
never_download=options.never_download)
File "/Library/Python/2.7/site-packages/virtualenv-1.6.4-py2.7.egg/virtualenv.py", line 901, in create_environment
site_packages=site_packages, clear=clear))
File "/Library/Python/2.7/site-packages/virtualenv-1.6.4-py2.7.egg/virtualenv.py", line 1166, in install_python
py_executable])
File "/Library/Python/2.7/site-packages/virtualenv-1.6.4-py2.7.egg/virtualenv.py", line 843, in call_subprocess
cwd=cwd, env=env)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 672, in __init__
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1202, in _execute_child
OSError: [Errno 2] No such file or directory
Any hints on how to solve this problem... I guess the first would be to check if install_name_tool is present on my system, and then force virtualenv to use it...
thanks in advance!
A: Did you actually install Xcode 4? Downloading it from the App Store only downloads the installer for it. Then you need to run the installer; you should find the installer downloaded to /Applications. After you run it, you should find install_name_tool here:
$ which install_name_tool
/usr/bin/install_name_tool
A: You need to both install XCode, run it, and select the optional "command line tools" package and then install those. In more detail:
*
*Download XCode from the App Store
*Run the downloaded XCode binary from Applications or Launchpad
*Select XCode->Preferences, then choose the "Downloads" tab
*Click on the "Command Line Tools" selection and install those
A: With newer versions of virtualenv (at least from 1.8.4 on) it is no longer necessary to install the "Command Line Tools" package from Xcode.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Appending node[index] in XML with jQuery How I got here:
I let my last question on pretty much this same subject gather dust. So, I thought I'd take what I learned and ask a more precise question.
I've got some information in an XML file that I would like to write to various DIVs on my web page, and something isn't going right.
And the last answer I received definitely behaves in jsfiddle:
http://jsfiddle.net/CK6rD/
But implementing the same code completely fails on my server. I'm not sure if it's the AJAX call, or the XML file, or something with permissions, or browser dependent flaws with Chromium. I'm completely stumped.
What I'm working with:
$(document).ready(function(){
$('#header').click(function(){
$('p#test').html('At least <em>this</em> works');
$.ajax({
type: "GET",
url: "archives.xml",
datatype: "xml",
success: function(xml){
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find( "title" );
$("div#viewer").append( $title.eq(0).text() );
}
});
});
});
What I'm asking:
Where should I be looking for my problem if the script doesn't throw an error with Try/Catch and the dev tools in Chromium say everything looks okay too?
As far as I can tell, I have no output from the success function, but how can I test that to be sure?
A: For posterity, the problem was in the AJAX options. The URL must go before the type. At least, that's how my AJAX calls are successfully formed in jQuery these days:
$.ajax({
url: "archives.xml",
type: "GET",
datatype: "xml",
success: function(xml){}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XHTML validation Error
A: You are trying to validate <script type=\"text/javascript\">, which is invalid... the validation service highlights the slash character for you at column 14. You cannot have a slash character before the open quote starts in type=.
Update
Check the HTML source of your page which is what the validator is actually checking... line 21 Column 14 is where your Google Analytics code starts, not the jQuery code.
Line 20: <!-- Google Analytics -->
Line 21: <script type=\"text/javascript\">
You need to remove the slashes here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Valid Characters Between HTML Attributes This might be a silly thing to do; but I'm trying to allow 'some' HTML on a website (okay, it's probably a bad idea). But, for the sake of argument...
Is there ANY non-white space character you can place between an attribute and the '='s sign and still have a modern browser be able to interpret the attribute.
In other words; if the user enters:
<img src="pic1.jpg" width=50 height=50 onClick='alert("Hi");'>
Is there any character(s) that can appear after 'onClick' but before the '=' sign and still have it execute the javascript alert message in any of the big name browsers, besides spaces and enters?
As an example - I tried inserting ' ' (and it fails)...
But is there another clever way of interjecting something I might miss.
A: After a lot of looking; I've been unable to find anything that can appear between the 'attribute = value' that isn't white space.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing Optional Arguments in Classic ASP for Stored Procedure I'm trying to run some stored queries in an Access database from an ASP page. I'd like to use an ADO Command object to run the procedure instead of simply sending a string to the database to execute. My trouble is occurring when I try to create the parameters to send to the stored procedure. I'm using the 'CreateParameter' method of the Command object. It takes 5 optional arguments, of which I only want to use two; name and value (arguments 1 and 5 respectively).
I've tried the following approaches to set up the parameters:
1) Using named arguments
command.Parameters.Append command.CreateParameter name:="name", value:="value"
2) Using named arguments inside brackets
command.Parameters.Append command.CreateParameter(name:="name", value:="value")
3) Leaving out optional parameters I don't need
command.Parameters.Append command.CreateParameter("name", , , , "value")
What is a simple way to achieve what I'm trying to do, and why does my syntax fail in these cases? I'm clearly missing something here!
A:
VBScript doesn't support named arguments with or without brackets. All parameters required to pass (specific or blank) for CreateParameter method of the Command object.
For the section 3 in the question, have a look:
CreateParameter(
name`[optional], <- fits ("name")
type [optional, default = adEmpty], <- NOT fits (type is not empty)
direction[Optional default = adParamInput], <- fits (blank)
size [optional default = 0], <- NOT fits (at least 5 for "value")
value[optional] <- fits ("value")
)
So, you should specify at least type and size for a text valued parameter. Direction is adParamInput already.
Const adVarChar = 200 ' From adovbs.inc or Ado TypeLib
command.Parameters.Append command.CreateParameter("name", adVarChar, , 5, "value")
A: here is an example that can be followed.
http://www.webconcerns.co.uk/asp/accessqueries/accessqueries.asp
see also
http://bytes.com/topic/asp-classic/answers/628368-running-access-stored-queries-parameters
Remember access uses stored queries not stored procedures so some differences apply. For additional information search for
ASP with Access stored queries using parameters - .net
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Metro web service with SSL - Is this a secure conversation I have the following conversation log (from WCF Trace file). It shows a WCF client calling an SSL protected Metro web service. Does the conversation have applied security? How do I know this from the logs?
Message Source: ServiceLevelSendRequest
Message Type: System.ServiceModel.Dispatcher.OperationFormatter+OperationFormatterMessage
<MessageLogTraceRecord Time="2011-09-22T01:33:06.4045159+02:00" Source="ServiceLevelSendRequest" Type="System.ServiceModel.Dispatcher.OperationFormatter+OperationFormatterMessage" xmlns="http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace">
<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<a:Action s:mustUnderstand="1">http://webService/hello/helloRequest</a:Action>
<a:MessageID>urn:uuid:cd9642a0-ac70-4208-84e3-8a901cf5713a</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink"></VsDebuggerCausalityData>
</s:Header>
<s:Body>
<hello xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://webService/">
<name xmlns="">Dani</name>
</hello>
</s:Body>
</s:Envelope>
</MessageLogTraceRecord>
Message Source: TransportSend
Message Type: System.ServiceModel.Security.SecurityAppliedMessage
<MessageLogTraceRecord Time="2011-09-22T01:33:06.4105163+02:00" Source="TransportSend" Type="System.ServiceModel.Security.SecurityAppliedMessage" xmlns="http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace">
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<s:Header>
<a:Action s:mustUnderstand="1">http://webService/hello/helloRequest</a:Action>
<a:MessageID>urn:uuid:cd9642a0-ac70-4208-84e3-8a901cf5713a</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPo/CE9TN8gjlFg7wGpuXg+HYAAAAAjfdEWwkubUe9Mb/DW0Kwl7kxQkfs6KtNkycVwDcjc44ACQAA</VsDebuggerCausalityData>
<a:To s:mustUnderstand="1">https://localhost:8181/megegytest/hello</a:To>
<o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<u:Timestamp u:Id="_0">
<u:Created>2011-09-21T23:33:06.409Z</u:Created>
<u:Expires>2011-09-21T23:38:06.409Z</u:Expires>
</u:Timestamp>
</o:Security>
</s:Header>
<s:Body>
<hello xmlns="http://webService/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<name xmlns="">Dani</name>
</hello>
</s:Body>
</s:Envelope>
</MessageLogTraceRecord>
Message Source: TransportReceive
Message Type: System.ServiceModel.Channels.BufferedMessage
<MessageLogTraceRecord Time="2011-09-22T01:33:06.4165166+02:00" Source="TransportReceive" Type="System.ServiceModel.Channels.BufferedMessage" xmlns="http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace">
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<S:Header>
<To xmlns="http://www.w3.org/2005/08/addressing">http://www.w3.org/2005/08/addressing/anonymous</To>
<Action xmlns="http://www.w3.org/2005/08/addressing" xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" S:mustUnderstand="1">http://webService/hello/helloResponse</Action>
<MessageID xmlns="http://www.w3.org/2005/08/addressing">uuid:0303f4ea-1171-4ad6-b220-4b341d78b299</MessageID>
<RelatesTo xmlns="http://www.w3.org/2005/08/addressing">urn:uuid:cd9642a0-ac70-4208-84e3-8a901cf5713a</RelatesTo>
<wsse:Security S:mustUnderstand="1">
<wsu:Timestamp xmlns:ns14="http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512" xmlns:ns13="http://www.w3.org/2003/05/soap-envelope" wsu:Id="_1">
<wsu:Created>2011-09-21T23:33:06Z</wsu:Created>
<wsu:Expires>2011-09-21T23:38:06Z</wsu:Expires>
</wsu:Timestamp>
</wsse:Security>
</S:Header>
<S:Body>
<ns2:helloResponse xmlns:ns2="http://webService/">
<return xmlns="">Hello Dani !</return>
</ns2:helloResponse>
</S:Body>
</S:Envelope>
</MessageLogTraceRecord>
Message Source: ServiceLevelReceiveReply
Message Type: System.ServiceModel.Security.SecurityVerifiedMessage
<MessageLogTraceRecord Time="2011-09-22T01:33:06.4245171+02:00" Source="ServiceLevelReceiveReply" Type="System.ServiceModel.Security.SecurityVerifiedMessage" xmlns="http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace">
<HttpResponse>
<StatusCode>OK</StatusCode>
<StatusDescription>OK</StatusDescription>
<WebHeaders>
<Transfer-Encoding>chunked</Transfer-Encoding>
<Content-Type>text/xml;charset=utf-8</Content-Type>
<Date>Wed, 21 Sep 2011 23:33:06 GMT</Date>
<Server>GlassFish Server Open Source Edition 3.1.1</Server>
<X-Powered-By>Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.1 Java/Oracle Corporation/1.7)</X-Powered-By>
</WebHeaders>
</HttpResponse>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<S:Header>
<To xmlns="http://www.w3.org/2005/08/addressing">http://www.w3.org/2005/08/addressing/anonymous</To>
<Action xmlns="http://www.w3.org/2005/08/addressing" xmlns:S="http://schemas.xmlsoap.org/soap/envelope/" S:mustUnderstand="1">http://webService/hello/helloResponse</Action>
<MessageID xmlns="http://www.w3.org/2005/08/addressing">uuid:0303f4ea-1171-4ad6-b220-4b341d78b299</MessageID>
<RelatesTo xmlns="http://www.w3.org/2005/08/addressing">urn:uuid:cd9642a0-ac70-4208-84e3-8a901cf5713a</RelatesTo>
<wsse:Security S:mustUnderstand="1">
<wsu:Timestamp xmlns:ns14="http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512" xmlns:ns13="http://www.w3.org/2003/05/soap-envelope" wsu:Id="_1">
<wsu:Created>2011-09-21T23:33:06Z</wsu:Created>
<wsu:Expires>2011-09-21T23:38:06Z</wsu:Expires>
</wsu:Timestamp>
</wsse:Security>
</S:Header>
<S:Body>
<ns2:helloResponse xmlns:ns2="http://webService/">
<return xmlns="">Hello Dani !</return>
</ns2:helloResponse>
</S:Body>
</S:Envelope>
</MessageLogTraceRecord>
WSDL:
<definitions targetNamespace="http://webService/" name="hello">
<wsp:Policy wsu:Id="helloPortBindingPolicy">
<sp:TransportBinding>
<wsp:Policy>
<sp:AlgorithmSuite>
<wsp:Policy>
<sp:Basic128/>
</wsp:Policy>
</sp:AlgorithmSuite>
<sp:IncludeTimestamp/>
<sp:Layout>
<wsp:Policy>
<sp:Lax/>
</wsp:Policy>
</sp:Layout>
<sp:TransportToken>
<wsp:Policy>
<sp:HttpsToken RequireClientCertificate="false"/>
</wsp:Policy>
</sp:TransportToken>
</wsp:Policy>
</sp:TransportBinding>
<sp:Wss10/>
<wsam:Addressing/>
</wsp:Policy>
<types>
<xsd:schema>
<xsd:import namespace="http://webService/" schemaLocation="https://localhost:8181/megegytest/hello?xsd=1"/>
</xsd:schema>
</types>
<message name="hello">
<part name="parameters" element="tns:hello"/>
</message>
<message name="helloResponse">
<part name="parameters" element="tns:helloResponse"/>
</message>
<portType name="hello">
<operation name="hello">
<input wsam:Action="http://webService/hello/helloRequest" message="tns:hello"/>
<output wsam:Action="http://webService/hello/helloResponse" message="tns:helloResponse"/>
</operation>
</portType>
<binding name="helloPortBinding" type="tns:hello">
<wsp:PolicyReference URI="#helloPortBindingPolicy"/>
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
<operation name="hello">
<soap:operation soapAction=""/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>
<service name="hello">
<port name="helloPort" binding="tns:helloPortBinding">
<soap:address location="https://localhost:8181/megegytest/hello"/>
</port>
</service>
</definitions>
A: It uses HTTPS so it is secured. WSDL also demands secure transport through security policy declaring TransportBinding element and HttpsToken. Log will not show any encryption because encryption is done on transport level outside of WCF scope. If you want to see that messages are encrypted you must sniff traffic on network level for example with WireShark. You can also use Fiddler as HTTPS proxy to see that client is doing HTTP CONNECT to tunnel SSL through proxy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Linking dependencies of a shared library I was working with SFML, I compiled a little test program and added the linkage option -lsfml-audio. Then, I used ldd ./program to see the dynamic libraries it was linking to. Surprisingly, there were a lot, none of them had I manually selected in my makefile, nor using pkg-config --libs.
I started reading about shared libraries, and made a little example to solve my doubts. However, I have this question:
why some libraries need you to add the dependencies in your makefile
(either manually or using a script like pkg-config) and other
libraries automatically link their dependencies?
When you're creating your dynamic library, is just as easy as adding the proper -ldependency options in the g++ -shared ... command to avoid the user the hassle of manually adding the dependencies later on. Why many of the available libraries don't do that?
I guess it must be related to the ability of fine tuning which libraries get linked and such.
A: Shared libraries will generally link in their dependencies. However, static libraries are not capable of doing so. pkg-config --libs often includes all dependencies (direct and indirect) so that you can switch to static compilation by simply adding -static without having to add additional library dependencies as well.
Note that these excess direct dependencies are considered unwanted in some cases (eg, debian tries to avoid them in packaged binaries, as they make library soname transitions more traumatic than necessary). You can instruct the linker to strip direct dependencies from the final executable that aren't needed with the -Wl,--as-needed flag.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: invoke command on remote machine is not working using powershell I ran the below commands on my machine to download data from one server to another server using the invoke command
Enable-PSRemoting -force
Enter-PSSession Server1
invoke-command -computername Server1 -credential:'dom\jack' {c:\temp.ps1 -server serverX -id 4231e429-d238-4e32-a1bb-0ee812cd3124 -download $true}
ERROR is: Failed: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
but when i run the above command on my machine as
c:\temp.ps1 -server serverX -id 4231e429-d238-4e32-a1bb-0ee812cd3124 -download $true
it works as expected.
Is there something i am missing when i execute it remotely....please help me.
thanks
A: Try this good References:
http://www.ravichaganti.com/blog/?p=1108
http://technet.microsoft.com/en-us/magazine/ff700227.aspx
It might be something to do with the TrustedHosts or Authentication
setting of a client. You can set it like this:WinRM set
winrm/config/client @{TrustedHosts="*"}
Read more about this here:
http://blogs.dirteam.com/blogs/sanderberkouwer/archive/2008/02/23/remotely-managing-your-server-core-using-winrm-and-winrs.aspx
I use
powershell.exe -ExecutionPolicy Unrestricted -WindowStyle Hidden -NoLogo
I use this code:
try
{
Invoke-Command -credential $testCred -computer $ServerName -scriptblock {
param([String]$scriptDeploy, [String]$destino) &"$scriptDeploy" 'parametro1' $destino
$ScriptBlockOutput = $Error
} -ArgumentList $RutaRemotaParaScriptDeInstalacion, "$dirRemotoDestino"
"`r`n`r`nOK para script de despliegue"
exit 0;
}
catch
{
"`r`n`r`nError en script de despliegue"
"`r`nError in " + $_.InvocationInfo.ScriptName + " at line: " + $_.InvocationInfo.ScriptLineNumber + ", offset: " + $_.InvocationInfo.OffsetInLine + ".";
exit -1
}
A: You need to enable remoting on the remote machine. You also need to make sure the firewall/anti virus does not block the remoting ports. These are port 5985 for http, or port 5986 for https.
If both machines on the same domain it's fairly easy to get working. If the machines are on different domains however then it's more complex. There's a registry setting that needs to be changed on the remote server, and you need to pass credentials. Have a read here for more info. There is of course ssl which can also be enabled, but that's another story.
A: There is a bug in your script.
You should not be executing Enter-PSSession before the Invoke-Command, because the Invoke-Command itself sets up the PSSession.
Use only this:
Invoke-command -computername Server1 -credential:'dom\jack' {c:\temp.ps1 -server serverX -id 4231e429-d238-4e32-a1bb-0ee812cd3124 -download $true}
... Without the Enter-PSSession
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Problem with a Linq to Entity query that contains a passed list of entities I have two entities
User { UserID, Name, UserTypeID }
StudentParent { StudentParentID, StudentID, ParentID }
// where
UserTypeID { 1=student, 2=parent }
Both StudentParent.StudentID and StudentParent.ParentID are foreign keys pointing to User.UserID
I have a list of Students (IEnumerable<User>) that I need to get the list of parents for. I need help figuring out the proper expression to get the list of parents.
Should I be using a contains or any statement to match against the list of Student Users?
A: You should be able to Select the Parent entites from your IEnumerable of students.
students.SelectMany(s => s.StudentParents.Select(sp => sp.ntParent_Parent));
This performs a projection from your collection of students, not all Students.
Logically it is something like
*
*here's a set of students
*for each of those students, get the student parent entities
*for each of those studentparent entities, get the parent
It also may be more useful to select into an anonymous type so you can see which parents belong to which students.
students.Select(s => new {
Student = s,
Parents = s.StudentParents.Select(sp => sp.ntParent_Parent))});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does the hover pseudo-class override the active pseudo-class The title basically says it all.
Suppose I have an element which I want to change color on :hover, but while clicked, I want it to switch back to its original color. So, I've tried this:
a:link, a:visited, a:active {
background: red;
}
a:hover {
background: green;
}
As it turns out, this doesn't work. After a lot of head-scratching, I realized that the :hover state was overriding the :active state. This was easily solved by this:
a:link, a:visited {
background: green;
}
a:hover {
background: red;
}
a:active {
background: green;
}
(I could combine the 1st rule with the 3rd one).
Here's the fiddle: http://jsfiddle.net/V5FUy/
My question: is this the expected behavior? As far as I understand this, the :active state should always override the :hover state, since the :active state will almost always be accompanied with the :hover state.
A: The active state must be declared after the hover state, in your CSS you're clumping together the active state before the active state so it's not being triggered.
If you state the proper order of operation it works, like below, it works fine.
a.noworks:link, a.noworks:visited {
background: red;
}
a.noworks:hover {
background: green;
}
a.noworks:active {
background: red;
}
So, to answer your question, yes this is the expected behavior.
Here is the order of operation:
a:link
a:visited
a:hover
a:active
A: Because in the first code you defined :hover after you defined :active, so :hover "overwrote" :active. In the second, it's the other way around, :active overwrites :hover.
A: yes this is expected behavior,
lets take a look at another example. just adding two classes,
<ul>
<li class="item first">item</li>
<li class="item">item</li>
<li class="item">item</li>
<li class="item">item</li>
<li class="item last">item</li>
</ul>
here the class first also comes together with the class item.
but if we declare our css in the wrong order that would not give the wanted behavior
.first { background: blue; }
.item { background: red; }
as you can see, the last matching selector will be used.
it is the same as your example, no mather what is more logic,
the 2 pseudo-classes are concidered equal, thus the same rules apply
the last matching defenition wins.
edit
pseudoclasses are equals, it is the one defined last that wins! here is a jsFiddle that proves my point :link defined after :hover, :link wins (test) so, your statement of :hover overriding :link is wrong, its just the same like with :active, its all about the order.
A: EDIT:
Sorry, I misunderstand the question.
Basically when you are in active state (with a mouse pointer) you are actually in hover state too. So based on CSS rules it would read the last one in stylesheet.
When you hover over a link and hold down the mouse key It's like this if we take pseud classes as normal classes :
<a class="active hover"></a>
So if your css was
.active{color:green}
.hover{color:red}
it would apply red
but if your css was
.hover{color:red}
.active{color:green}
It would apply green
From W3C
a:link { color: red } /* unvisited links */
a:visited { color: blue } /* visited links */
a:hover { color: yellow } /* user hovers */
a:active { color: lime } /* active links */
Note that the A:hover must be placed after the A:link and A:visited
rules, since otherwise the cascading rules will hide the 'color'
property of the A:hover rule. Similarly, because A:active is placed
after A:hover, the active color (lime) will apply when the user both
activates and hovers over the A element.
A: This is how it works, and I'll try to explain why. As we know CSS will continue searching the document when applying styles and apply the style that is most specific to the element.
Example:
li.betterList { better list styling here }
Is more specific and will overwrite
li { list styling here }
And these Puesdo selectors are all considered the same specificity and thus the last line will overwrite the previous one. This is confirmed by the note on W3Schools
Note: :active MUST come after :hover (if present) in the CSS definition in order to be effective!
you can also throw this CSS on your jsfidle and watch it overwrite since they are the same specificity
.works {background: red}
.works {background: green}
A: This is the expected behavior in so far as most people always place the :hover pseudo-class at the end of the group of rules.
Order of declaration matters with pseudo-classes (see more here: http://reference.sitepoint.com/css/pseudoclasses), so the final rules get precedence, as with other rules in CSS.
For most people, I think the desired behavior:
a:link {
⋮ declarations
}
a:visited {
⋮ declarations
}
a:hover {
⋮ declarations
}
Since the :active is not so useful it is left out... or combined with a:link and a:visited... and then it is overridden by a:hover
W3C spells it out here:
Note that the A:hover must be placed after the A:link and A:visited
rules, since otherwise the cascading rules will hide the 'color'
property of the A:hover rule. Similarly, because A:active is placed
after A:hover, the active color (lime) will apply when the user both
activates and hovers over the A element.
http://www.w3.org/TR/CSS2/selector.html#dynamic-pseudo-classes
Even W3schools gets this one right:
Note: a:hover MUST come after a:link and a:visited in the CSS
definition in order to be effective!!
Note: a:active MUST come after a:hover in the CSS definition in order
to be effective!!
http://www.w3schools.com/css/css_pseudo_classes.asp
A: I think you should at least consider the flow of User Interaction on links (or buttons).
Usually,
*
*:link has always been the default (untouched),
*Then when a User points to the button, then that is where :hover comes into play.
*Once a User points to the link or button, then he/she will click, that is where :active comes in.
That is the standard sequence of how we interact with links (or buttons). With the exception of :visited, where the result is only obvious when the User has previously pressed the link.
It would be really helpful if you keep in mind the mnemonic: ' L o V e H A t e ' when dealing on links (except for :visited, which doesn't work for buttons).
However, if you really want to do an override, say, you want to change the color of a link that was already visited on active state, you can do something like:
a:visited:active {
color: red;
}
But the bottom line is, avoid changing the standard sequence if it's not necessary.
A: You can have the :active pseudo-class override the :hover pseudo-class regardless of the order of declaration by using the :not() selector.
a:link, a:visited, a:active {
background: red;
}
a:hover:not(:active) {
background: green;
}
This way, the :hover selector is triggered only when the :active selector is not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Random Code Overkill? I have some code I am using
function genCode ($entropy=1) {
$truCde = "";
$indx = 0;
$leng = 30*$entropy;
while ($indx < $leng) {
$code = "";
$length = 100*$entropy;
$index = 0;
while ($index < $length) {
$code .= rand();
$index++;
}
$index = 0;
while ($index < $length) {
$code = sha1($code);
$index++;
}
$truCde .= $code;
$indx++;
}
$finalCode = sha1(rand()) . hash("sha256",$truCde . md5($entropy*rand()));
$finalCode .= sha1(md5(strlen($finalCode)*$entropy));
return hash (
"sha256",
sha1($finalCode) . sha1(md5($finalCode)) . sha1(sha1($finalCode))
);
}
to generate a random code for e-mail verification. Is there code that takes less time to generate random codes. It takes about 1-2 seconds to run this code, but I am looking to shave .7 seconds off this because the rest of the script will take longer.
A: That's massive overkill. Calling rand() repeatedly isn't going to make the code "more random", nor will using random combinations of SHA and MD5 hashes. None of that complexity improves the verification codes.
An improvement that would make a difference would be to use mt_rand() in preference to rand(). The Mersenne Twister pseudo RNG is much stronger than most default rand() implementations. The PHP documentation hints that rand() may max out at 215 meaning you can only generate 32,768 unique verification codes.
Other than that, a single hash call will do.
sha1(mt_rand())
(You don't even really need to call a hash function as the unpredictability of your codes will come from the random number generator, not the hash function. But hash functions have the nice side effect of creating long hex strings which "look" better.)
A: If you just want to generate random strings to test that someone has access to an email address, or something like that, I would throw out that code and use something a lot more straightforward. Something like the following would likely do.
function genCode () {
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
$returnValue = '';
for ($i = 0; $i < 20; $i++) {
$returnValue .= $chars[mt_rand(0, 35)];
}
return $returnValue;
}
You can hash the return value if you want, but I don't know what the point would be other than to obfuscate the scheme used to come up with the random strings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Difference between XX:MaxDirectMemorySize, Xmx,XX:JavaMemMax The subject line pretty much sums up my question.
A: *
*XX:MaxDirectMemorySize:
This option specifies the maximum total size of java.nio (New I/O package) direct buffer allocations.
*Xmx:
The -Xmx option sets the maximum Java heap size.
*XX:JavaMemMax - Is this a thing?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Rails 3.1: how to run an initializer only for the web app (rails server/unicorn/etc) My webapp needs to encrypt its session data. What I setup is:
config/initializers/encryptor.rb:
require 'openssl'
require 'myapp/encryptor'
MyApp::Encryptor.config[ :random_key ] = OpenSSL::Random.random_bytes( 128 )
Session.delete_all
app/models/session.rb:
require 'attr_encrypted'
class Session < ActiveRecord::Base
attr_accessible :session_id, :data
attr_encryptor :data, :key => proc { MyApp::Encryptor.config[ :random_key ] }, :marshal => true
# Rest of model stuff
end
That all works great, and keeps the session data secured. Here's the problem: when I run my custom rake tasks it loads the initializer and clears all the sessions. Not good!
What can I put in my initializer to make sure it ONLY runs for the webapp initialization? Or, what can I put in my initializer to make it NOT run for rake tasks?
Update: OK, what I've done for the moment is add MYAPP_IN_RAKE = true unless defined? MYAPP_IN_RAKE to my .rake file. And then in my initializer I do:
unless defined?( MYAPP_IN_RAKE ) && MYAPP_IN_RAKE
# Web only initialization
end
Seems to work. But I'm open to other suggestions.
A: You might make a modification to your application in `config/application.rb' like this:
module MyApp
def self.rake?
!!@rake
end
def self.rake=(value)
@rake = !!value
end
Then in your Rakefile you'd add this:
MyApp.rake = true
It's nice to use methods rather than constants since sometimes you'd prefer to change or redefine them later. Plus, they don't pollute the root namespace.
Here's a sample config/initializers/rake_environment_test.rb script:
if (MyApp.rake?)
puts "In rake"
else
puts "Not in rake"
end
The programmable nature of the Rakefile affords you significant flexibility.
A: There is another work around:
unless ENV["RAILS_ENV"].nil? || ENV["RAILS_ENV"] == 'test'
When you launch with rake your ENV["RAILS_ENV"] will be nil. The test for 'test' is to avoid to run when using rspec.
I know that is reckon to use Rails.env but it return "development" when it is not initialised.
http://apidock.com/rails/Rails/env/class
# File railties/lib/rails.rb, line 55
def env
@_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"]
|| ENV["RACK_ENV"] || "development")
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Error : String or Binary data would be truncated i have written a query as below. lets say i have data in @Test table as "New York and Texas have CCRxSM federraly approved". Word CCRxSM is a superscript word but it didnt loaded as superscript. SM should be on top like CCRx℠.
Declare @Test Table (Foo1 varchar(1023))
Insert @Test(Foo1) Values ('New York and Texas have CCRxSM federraly approved');
Select Foo1,
Case When Right(Foo1, 21) = 'SM'
Then Left(Foo1, Len(Foo1) - 2) + NChar(8480)
Else Foo1 End
From @Test
when i run my query i get error String or Binary data would be truncated.
I am using SQL SERVER 2005.
JUST WANTED TO ADD, IF I JUST USE WORD CCRxSM THEN IT WORKS. so dont know why it doesnt work for complete record.
Thanks
A: You defined your column Foo1 to have a max length of 10, then you tried inserting 51 characters in it. So obviously it would truncate.
And CCRxSM doesn't look superscript to me. It's just letters. Superscript and things like that are formatting.
A: The Foo1 column in the @Test table can only be 10 characters long, so when you run your insert statement, it would only insert 'New York a'. The rest will be truncated.
You can change it to
DECLARE @Test TABLE (Foo1 varchar(100))...
A: Try this:
Declare @Test Table (Foo1 nvarchar(1023))
Insert @Test(Foo1) Values ('New York and Texas have CCRxSM federraly approved');
Select Foo1, REPLACE(foo1,'xSM','x'+nchar(8480)) as updatedFoo1
From @Test
Your query
Declare @Test Table (Foo1 varchar(1023))
Insert @Test(Foo1) Values ('New York and Texas have CCRxSM federraly approved');
Select Foo1,
Case When Right(Foo1, 21) = 'SM'
Then Left(Foo1, Len(Foo1) - 2) + NChar(8480)
Else Foo1 End
From @Test
Based on the code, the right(foo1,21) is SM federraly approved not just SM Also, keep in mind if you run this in query analyzer, be sure the query results are in a Unicode font so you can see the SM superscript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why isn't Android's onProviderEnabled() method being called? My Android app has two location listeners, one for fine and one for coarse listening. I want to be able to detect when the user turns their location services off and on.
Whenever I turn my phones GPS or network location services OFF the onProviderDisabled method is called as expected. When I turn GPS or network services ON the onProviderEnabled is never called!
I have put the code for one of the listeners below....
Update...
I have discovered that the problem is related to unregistering the listeners in onPause. When I remove the code "locationManager.removeUpdates(myFineLocationListener);" the onProviderEnabled() method IS called.
Perhaps the act of disabling the (say) GPS automatically unregisters the listener? Perhaps I should unregister thje listener in onDestroy rather than onPause() ???
PS. Maybe it is relevant that I mention that my activity has a button that goes directly to the devices location settings page. It acts as a shortcut. I use this shortcut to disable/enable location services then use the Back button to return to my app. I will put the code for this button at the very end of this post.
Code:
(The createLocListeners() method is called from onCreate();)
void createLocListeners() {
//if null, create a new listener
//myFineLocationListener is a class variable
if (myFineLocationListener == null) {
//Listen for FINE location updates
myFineLocationListener = new LocationListener(){
@Override
public void onLocationChanged(Location location) {
//Do something
}
@Override
public void onProviderDisabled(String provider) {
//This gets called when I change location settings (eg GPS on or off) on the phone }
@Override
public void onProviderEnabled(String provider) {
//This DOES NOT get called when I change location settings (eg GPS on or off) on the phone
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}; //end on location listener
} //end if fine listener is null
} //end createLocListener() function
@Override
protected void onResume() {
super.onResume();
//REGISTER LOCATION LISTENERS
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LISTENING_INTERVAL, LISTENING_DISTANCE, myFineLocationListener);
}
catch (IllegalArgumentException e){
//Tried catching exceptions but there weren't any
}
catch (RuntimeException e) {
}
}// end onResume()
@Override
protected void onPause() {
super.onPause();
//UNREGISTER LOCATION LISTENERS
locationManager.removeUpdates(myFineLocationListener);
} //end onPause
Similar problem: Location service onProviderEnabled never called
Code for button that opens the location Settings page...
//JUMP TO LOCATION SERVICES SETTINGS
ibLoc.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}); //end jump to location services button listener
A: IMO, when you go to settings the onPause() is called and listeners are unregistered. Then you enable the GPS and return to your activity. So when you register the listeners the GPS is already enabled, so listener onProviderEnabled() is never called, since it is only called when GPS status is changed to enabled.
A: I had mLocationManager.removeUpdates(this) in onStop() which was getting called when I pulled down the Notification Tray to turn on the locations services. So though I turn on the locations, my onProviderEnabled() was not getting called. Thanks for the hint @Peter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: AppWidget alarmmanager not updating So, I've got a widget, I want it to update every 60 seconds. When the widget is first added to the homescreen, it runs its update function just fine. Beyond that it's supposed to start an AlarmManager, which will rerun the update method every 60 seconds. That's the part that it doesn't seem to be actually doing. Here's my code:
public class ClockWidget extends AppWidgetProvider {
public static String CLOCK_WIDGET_UPDATE = "com.nickavv.cleanwidget.CLEANCLOCK_UPDATE";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int appWidgetIds[]) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.clocklayout);
appWidgetManager.updateAppWidget(appWidgetId, views);
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
Log.d("log","Entered update cycle");
//Unimportant for these purposes
appWidgetManager.updateAppWidget(appWidgetId, views);
}
private PendingIntent createClockTickIntent(Context context) {
Intent intent = new Intent(CLOCK_WIDGET_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
Log.d("onEnabled","Widget Provider enabled. Starting timer to update widget every minute");
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 60000, createClockTickIntent(context));
}
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
Log.d("onDisabled", "Widget Provider disabled. Turning off timer");
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(createClockTickIntent(context));
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.d("onReceive", "Received intent " + intent);
if (CLOCK_WIDGET_UPDATE.equals(intent.getAction())) {
Log.d("onReceive", "Clock update");
// Get the widget manager and ids for this widget provider, then
// call the shared
// clock update method.
ComponentName thisAppWidget = new ComponentName(context.getPackageName(), getClass().getName());
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int ids[] = appWidgetManager.getAppWidgetIds(thisAppWidget);
for (int appWidgetID: ids) {
updateAppWidget(context, appWidgetManager, appWidgetID);
}
}
}
}
It's the product of a few tutorials I've found on the matter, and my own knowledge of Android. According to my logcats, it never gets to the Log.d("onReceive", "Clock update"); line. And yes, my Manifest is set up with the clock update intent. Thanks!
EDIT: Additional info. I put a log line in the createClockTickIntent method, and it fires off. So I guess this means that my application is running the alarmManager.setRepeating line, no idea why is isn't actually repeating.
A: Arggghhh, it was a simple typo. The intent filter was "com.nickavv.cleanwidgets.CLEANCLOCK_UPDATE", and I had written "com.nickavv.cleanwidget.CLEANCLOCK_UPDATE"
What a pain, but hey, now I know.
So, moral of the story for anybody with a similar problem to me: Check your spelling! Check it twice, or ten times. On everything!
A: You have to make an appwidget-provider and set updatePeriodMillis on 0.6 second , then it will be update per 60 seconds.
<?xml version="1.0" encoding="utf-8" ?>
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="146dp"
android:initialLayout="@layout/YourLayout"
android:updatePeriodMillis="0.6"
android:minHeight="144dp"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Problem inflating custom view for AlertDialog in DialogFragment I'm trying to create a DialogFragment using a custom view in an AlertDialog. This view must be inflated from xml. In my DialogFragment class I have:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("Title")
.setView(getActivity().getLayoutInflater().inflate(R.layout.dialog, null))
.setPositiveButton(android.R.string.ok, this)
.setNegativeButton(android.R.string.cancel, null)
.create();
}
I have tried other inflation methods for .setView() such as:
.setView(getActivity().getLayoutInflater().inflate(R.layout.dialog, (ViewGroup) getView(), false))
and
.setView(getActivity().getLayoutInflater().inflate(R.layout.dialog, (ViewGroup) getTargetFragment().getView(), false))
After setting the target fragment in the fragment that is showing this dialog.
All of these attempts to inflate my custom view result in the following exception:
E/AndroidRuntime(32352): android.util.AndroidRuntimeException: requestFeature() must be called before adding content
E/AndroidRuntime(32352): at com.android.internal.policy.impl.PhoneWindow.requestFeature(PhoneWindow.java:214)
E/AndroidRuntime(32352): at com.android.internal.app.AlertController.installContent(AlertController.java:248)
E/AndroidRuntime(32352): at android.app.AlertDialog.onCreate(AlertDialog.java:314)
E/AndroidRuntime(32352): at android.app.Dialog.dispatchOnCreate(Dialog.java:335)
E/AndroidRuntime(32352): at android.app.Dialog.show(Dialog.java:248)
E/AndroidRuntime(32352): at android.support.v4.app.DialogFragment.onStart(DialogFragment.java:339)
E/AndroidRuntime(32352): at android.support.v4.app.Fragment.performStart(Fragment.java:1288)
E/AndroidRuntime(32352): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:873)
E/AndroidRuntime(32352): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1041)
E/AndroidRuntime(32352): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:625)
E/AndroidRuntime(32352): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1360)
E/AndroidRuntime(32352): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:411)
E/AndroidRuntime(32352): at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime(32352): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(32352): at android.os.Looper.loop(Looper.java:132)
E/AndroidRuntime(32352): at android.app.ActivityThread.main(ActivityThread.java:4028)
E/AndroidRuntime(32352): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(32352): at java.lang.reflect.Method.invoke(Method.java:491)
E/AndroidRuntime(32352): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
E/AndroidRuntime(32352): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
E/AndroidRuntime(32352): at dalvik.system.NativeStart.main(Native Method)
While if I try to use the DialogFragment's getLayoutInflator(Bundle) like this:
.setView(getLayoutInflater(savedInstanceState).inflate(R.layout.dialog, null))
I get a StackOverflowError.
Does anyone know how to inflate a custom view for an AlertDialog in a DialogFragment?
A: The first error line gives me the hint that this is related to how you are creating your dialog - not the dialog itself.
Are you creating the dialog automatically (which could mean this gets called before the views are all set up) or in response to a button click? I initially had problems with fragments due to instantiation order.
I used the same code to set the view as you have, and my result works. I cut out the other setup to make this look cleaner, but it works with or without it.
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_layout, null);
builder.setView(view);
return builder.create();
}
A: I'm surprised by these answers as none of them solve the problem.
A DialogFragment allows you to reuse the same UI for both a dialog and integrated in your app elsewhere as a fragment. Quite a useful feature. As per google's documentation, you can achieve this by overriding onCreateDialog and onCreateView.
http://developer.android.com/reference/android/app/DialogFragment.html
There are three scenarios here:
*
*Override onCreateDialog only - Works as a dialog but cannot be
integrated elsewhere.
*Override onCreateView only - Does not work as a dialog but can be
integrated elsewhere.
*Override both - Works as a dialog and can be integrated
elsewhere.
Solution:
The AlertDialog class is calling another class which calls requestFeature. To fix this.. Don't use the AlertDialog, instead use a plain Dialog or whatever super.onCreateDialog returns. This the solution that I have found works best.
Caveat:
Other dialogs such as DatePickerDialog, ProgressDialog, TimePickerDialog all inherit from AlertDialog and will likely cause the same error.
Bottom Line:
DialogFragment is good if you need to create very customized interface that needs to be used in several places. It doesn't appear to work to reuse existing android dialogs.
A: I had the same problem. In my case it was becasue Android Studio created a template onCreateView that re-inflated a new view instead of returning the view created in onCreateDialog. onCreateView is called after onCreateDialog, so the solution was to simply reurnt the fragments view.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return this.getView();
}
A: Avoid request feature crash and use same layout:
public class MyCombinedFragment extends DialogFragment
{
private boolean isModal = false;
public static MyCombinedFragment newInstance()
{
MyCombinedFragment frag = new MyCombinedFragment();
frag.isModal = true; // WHEN FRAGMENT IS CALLED AS A DIALOG SET FLAG
return frag;
}
public MyCombinedFragment()
{
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if(isModal) // AVOID REQUEST FEATURE CRASH
{
return super.onCreateView(inflater, container, savedInstanceState);
}
else
{
View view = inflater.inflate(R.layout.fragment_layout, container, false);
setupUI(view);
return view;
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder alertDialogBuilder = null;
alertDialogBuilder = new AlertDialog.Builder(getActivity());
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_layout, null);
alertDialogBuilder.setView(view);
alertDialogBuilder.setTitle(“Modal Dialog“);
alertDialogBuilder.setPositiveButton("Cancel", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
setupUI(view);
return alertDialogBuilder.create();
}
}
A: Faced the same issue, and it took lot of time to get rid of the error. Finally passing resource ID to setView() method solved the problem. Add set view as below:
.setView(R.layout.dialog)
A: In your code where you call
create().
Replace with
show().
A: I haven't inflated from XML but I have done dynamic view generation in a DialogFragment successfully:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
m_editText = new EditText(getActivity());
return new AlertDialog.Builder(getActivity())
.setView(m_editText)
.setPositiveButton(android.R.string.ok,null)
.setNegativeButton(android.R.string.cancel, null);
.create();
}
A: What you want to do instead is create your custom view in the onCreateView method like you normally would. If you want to do something like change the title of the dialog, you do that in onCreateView.
Here's an example to illustrate what I mean:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getDialog().setTitle("hai");
View v = inflater.inflate(R.layout.fragment_dialog, container, false);
return v;
}
Then you just call:
DialogFragment df = new MyDialogFragment();
df.show(..);
And voila, a dialog with your own custom view.
A: As i needed long time for solving the same problem (Pop up a simple Text Dialog) i decided to share my solution:
The layoutfile connectivity_dialog.xml contains a simple TextView with the message text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:text="Connectivity was lost"
android:textSize="34sp"
android:gravity="center"
/>
</RelativeLayout>
The Activity showing the "dialog" implements a inner class (as DialogFragment is a Fragment and not a Dialog; further info see https://stackoverflow.com/a/5607560/6355541). The Activity can activate and deactivate the DialogFragment via two functions. If you're using android.support.v4, you may want to change to getSupportFragmentManager():
public static class ConnDialogFragment extends DialogFragment {
public static ConnDialogFragment newInstance() {
ConnDialogFragment cdf = new ConnDialogFragment();
cdf.setRetainInstance(true);
cdf.setCancelable(false);
return cdf;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.connectivity, container, false);
}
}
private void dismissConn() {
DialogFragment df = (DialogFragment) getFragmentManager().findFragmentByTag("conn");
if (df != null) df.dismiss();
}
private void showConn() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("conn");
if (prev != null) ft.remove(prev);
ft.addToBackStack(null);
ConnDialogFragment cdf = ConnDialogFragment.newInstance();
cdf.show(ft, "conn");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "50"
} |
Q: How to send checked radios values? I have a list of items with checkboxes. I need to send that list (just as I would with a form), to a specific PHP file that erased those checked items, and returns the new list.
<table style="float:left;width:100%">
<tbody>
<?php foreach ($items as $item): ?>
<tr>
<div>
<td ?>;
<input type="checkbox" name="item_<?php echo $item['NAME'];?>" value="<?php echo $item['ID'];?>" />
</td>
</div>
</tr>
<?php endforeach; ?>
</tbody>
on the other hand I need to have a javascript function ti serialize all these values like a $_POST.
That's:
$.get("deleteItems.php", theNeededArray, function(data){....});
so I need to get that array.
I know this: var checkedItems = $("input:checked");
contains what I need but I need to extract those values into an array that looks like this:
{ item_one: "cardboard" , item_two: "rabbit" , ...}
I'd love it if someone could also shed some light on the returned value of jQuery. it seems like bigger object than I thought.
A: you could do following
$("input:checked").map(function() { return $(this).val() });
after this you get something like this:
var result = ["myid1", "myid2"]
this is all extensable, try your self to extend to your needs
A: You can simply serialize the form:
$.get("deleteItems.php", $('form').serialize(), function(data){....});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I use a cell containing a date to reference for multiple Pivot Tables in Excel? I am using Excel 2007 & about 20 pivot charts/graphs which reference the same table of data in Excel. I change the data daily, copy and pasting the data from another source. Can I somehow create a reference cell that contains a date for the pivot tables so that I don’t have to change the dates on every graph drop down every day? Another solution would be to have all the graphs reference the same data section on the pivot table, is that possible?
A: as far as the data range of a pivot table is concerned, you can base multiple Pivots on the same data range.
*
*define the 1st Pivot Table by selecting the data range
*for Pivot Tables 2..n select the 1st table as the data source
for Pivot charts - if you just want to display the actual date in a title
*
*create the Pivot Chart
*click the title and enter a formula making use of your "dynamic title cell" in same way as in sheets (e.g. =Sheet1!$A$1)
*at least in Excel 2003 it's not possible to do this in a Pivot Chart Title: ="Stat for " & Sheet1!$A$1; so as a workaround you do this in cell A1 of Sheet1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Need to find a way to extract coordinates of shaded region from an image file I have an image file that has pizza shaped shaded regions in it:
I need a way to extract the coordinates of the shaded region so i can use them in html code to make the area clickable. This needs to be done dynamically as i have thousands of images. I am currently developing the site in PHP so anything in php or javascript would be helpful. If anyone has any idea how to do this please let me know.
A: I can think of a number of steps you will need to take, but since you have no starting point I will describe what would be my approach on a high level.
*
*Find the center point, call it c. Not too hard width/2 height/2. It
looks like these images were generated by a computer so I would
presume they are all standard their dimensions and position of the
circle.
*You will now need to find all the points on the circle with radius r
(the distance from the center to the easily identifiable orange
area that only exists in the shaded region) and center c.
*Test all those points on your image using PHPs imagick library and
getImagePixelColor to test if the result is close to the easily
identifiable orange. If it is, you have a match.
*For every match, the vector from the center of the circle to the
match is part of a shaded area. Find only the outermost matches of a
region and you have your coordiantes.
I'm sure this is only one approach and there are many ways to do it, but I would suggest you start implementing on you think will work then ask a more specific question when you get stuck.
A: I would use ImageMagick to convert the disc from polar to cartesian coordinates and then, when you clarify which shaded regions you actually mean, I suspect the rest will be easy:
convert disc.png -distort DePolar 0 cartesian.jpg
As I have no feedback from you, I am kind of thinking on my feet. So, you could also convert everything that isn't shaded grey to white and everything that is grey to black, like this:
convert disc.png -fuzz 5% -fill black -opaque rgb\(211,211,211\) -fill white +opaque black out.png
And, you could do both in one go:
convert disc.png -distort depolar 0 -fuzz 5% -fill black -opaque rgb\(211,211,211\) -fill white +opaque black out.png
Then you can squidge the image down to a single row, like this:
convert disc.png -distort depolar 0 -fuzz 5% -fill black -opaque rgb\(211,211,211\) -fill white +opaque black -resize x1\! out.png
(I'll show that as 10 pixels high so you can see it)
Now, your coordinates are where the row changes from black to white and white to black. You can extract these into text and parse them out. Either like this:
convert disc.png -distort depolar 0 -fuzz 5% -fill black -opaque rgb\(211,211,211\) -fill white +opaque black -resize x1\! -colorspace gray -threshold 50% txt: | more
# ImageMagick pixel enumeration: 1000,1,255,srgba
0,0: (255,255,255,1) #FFFFFF white
1,0: (255,255,255,1) #FFFFFF white
2,0: (255,255,255,1) #FFFFFF white
3,0: (255,255,255,1) #FFFFFF white
4,0: (255,255,255,1) #FFFFFF white
5,0: (255,255,255,1) #FFFFFF white
6,0: (255,255,255,1) #FFFFFF white
7,0: (255,255,255,1) #FFFFFF white
Or like this:
convert disc.png -distort depolar 0 -fuzz 5% -fill black -opaque rgb\(211,211,211\) -fill white +opaque black -resize x1\! -colorspace gray -threshold 50% -compress none pbm: | more
P1
1000 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Facebook TestConsole Can anybody tell me how I can put an Array into the testconsole for example here?
http://developers.facebook.com/docs/reference/rest/dashboard.multiAddNews/
the "uids" and "news" requests an array parameter. It´s really funny right now for me, because i tried many methods and i was searching around. i didnt find one example of what i can put in there...
I was trying some of these
{"message":"test"}
"message":"test"
[{"message":"test"}]
[{\"message\":\"test\"]
message=test;
A: Please note:
1) the above method is deprecated
2) it won't work in any case in the test console since it should be called with app access token and the test console is working with user token.
To your question: uids should look like ["12345","56789"], while news is array of jsons
hope this helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Drag and Drop files from Applet to Desktop I was wondering how to drag and drop files from a java applet to the desktop. So far i've been able to display all the files with the right icon and name, but I have no clue on how to implement dragging and dropping. BTW I am a noob so it would be great if you could explain things in detail.
A: I suggest looking at the Java site tutorials:
http://download.oracle.com/javase/tutorial/uiswing/dnd/intro.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iOS Interface Builder Custom Styles? Simple question. Does anyone know why Interface Builder doesn't allow for applying custom styles on UI elements? Why is it only possible to do this programmatically?
I can see how this might be difficult for custom UIView subclasses but the default controls definitely only have a tiny subset of the style options available through IB, such as background color or changing font colors. Why is this the case? Is there any way to approach a concept like application themes through IB?
A: My personal feeling is that Apple does this right. They provide the elements and styles that fit the HIG. If they start adding other elements/styles then where do the start, and where do they draw the line?
Also, it isn't like Apple actively prevents using custom elements/styles, they just don't include it in the tool set.
The last thing we need is a tool set full of bloat.
A: You'd really have to ask Apple as to the why. I'd guess that it's some combination of promoting consistent use of standard interface elements and limited development resources.
You can, of course, build interfaces using your own custom subclasses of the standard interface elements in IB. It's a little more work, since you have to change the type of each object you add from UIButton to MyGreenButton or whatever, but it's not difficult.
It's also not hard to imagine coming up with a controller-type class that could connect to all your controls and whatnot to customize their appearance in some consistent, theme-like manner. Add an instance of that to each nib, connect all the controls, and let it do it's thing. You wouldn't see the effect until you actually run the app, of course, but it sounds like you're talking about customizing colors and fonts rather than size.
A: Unfortunately you are at the mercy of the Almighty Apple Deity..... Bow at their feet and give thanks that you have what they give you..... lol...
Seriously tho. Apple puts in what apple wants and you can request additions, but the IB is fairly minimal in the way of features.
I think this may be by design. Somehow an Elegant Simplicity ?
The ability to customize the controls is given to the programmer however I think they want the controls standardized. I just dont know why they didnt give a little more variety in the controls that are available. Like a few more button styles for the ios devices...
If you find out otherwise I would definitely be all ears.
A: I think that apple should let you to customize more the controls, for games it takes too much time to make the custom control ( you can make it faster in android as you can configure it in xml)
Btw PaintCode is another option to make your own style for components, it will generate the code but its more like interface builder
http://www.paintcodeapp.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Collection of Lines I have to draw a collection of lines in WPF with different colors. Each color part is a line.
For Example we have a line starting from (0,0) to (10,0) on xaxis.
I want red color from (0,0) to (3,0) and green from (3,0) to (7,0) and yellow from (7,0) to (10,0).
I want to treat this whole thing as a single line . I have one way that is drawing different lines from those points and giving different strokes for each line. Is there something in WPF for collection of lines with different colors.
A: What classes do you use? If you can apply a brush to the line you can create a LinearGradientBrush which looks like that. You will need stops on the same offset with different colours to get a hard change.
e.g.
<Line X1="0" Y1="0" X2="100" Y2="0" StrokeThickness="5">
<Line.Stroke>
<LinearGradientBrush>
<GradientStop Offset="0.3" Color="Red"/>
<GradientStop Offset="0.3" Color="Yellow"/>
<GradientStop Offset="0.7" Color="Yellow"/>
<GradientStop Offset="0.7" Color="Green"/>
</LinearGradientBrush>
</Line.Stroke>
</Line>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error after installing NPM for node.js After installing npm I get the following error report
info it worked if it ends with ok
verbose cli [ 'node', '/home/ash/local/bin/npm' ]
info using npm@1.0.30
info using node@v0.4.12
verbose config file /home/ash/.npmrc
verbose config file /home/ash/local/etc/npmrc
ERR! Error: ENOENT, No such file or directory
ERR! Report this *entire* log at:
ERR! <http://github.com/isaacs/npm/issues>
ERR! or email it to:
ERR! <npm-@googlegroups.com>
ERR!
ERR! System Linux 2.6.38-11-generic
ERR! command "node" "/home/ash/local/bin/npm"
ERR! cwd /home/ash
ERR! node -v v0.4.12
ERR! npm -v 1.0.30
verbose exit [ 1, true ]
I have installed node and npm using the method outlined in this gist using the "git all the way method". However I changed the directory locations for the npm and node repos.
It is set up like so
~/
Apps/
Dev/
node/ << node repo
npm/ << npm repo
local/ << default setup location as outlined in the gist
Does anyone know what's going wrong here.
EDIT
Bash history
$ mkdir ~/local
$ echo 'export PATH=$HOME/local/bin:$PATH' >> ~/.bashrc
$ . ~/.bashrc
$ cd Apps/Dev/node
$ ./configure --prefix=~/local
$ make install
$ cd ../npm
$ sudo PATH=~/local/bin:$PATH make install
$ export PATH=~/local/bin:$PATH >> ~/.bashrc
A: Here is a similar problem:
https://github.com/isaacs/npm/issues/1004
As it turns out it's not a very good idea to have "bin" listed in the
~/.gitignore file (it will exclude the npm/bin from the install
package)
I hadn't touched my ~/.gitignore in the last 2 years maybe - turns out
it was full of rather dumb stuffs. Spring cleaning ~/.gitignore took
care of the problem. Mission accomplished, npm v1.0.9-1 is now
successfully installed (phew)
ALSO: Do you have a directory "/home/ash/local/etc/npmrc"?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use a url as the InputSource for StringReader I apologize for the stupid question, but I am trying to use a xml file that is online in the following code.
String uri =
"http://www.myserver.com/xml?month=Jan";
URL url = new URL(uri);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
InputStream xml1 = connection.getInputStream();
InputSource xml = new InputSource(new StringReader(xml1));
I have tried researching the answer before having to ask, but however I try to get this to work I get the error that "The constructor StringReader(InputStream) is undefined"
Thank you for any help you may provide.
A: Try
InputSource xml = new InputSource(xml1);
As the error message says, there is no constructor for StringReader that takes an instance of InputStream.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to access 2d array values? do you have any idea why the "echo" in the following loop doesn't work?
while( $nl = mysql_fetch_array($Lresult) )
{
$clkword[$i] = $nl['Word'];
$relatedlinks[$i] = array(
$i => array(
"CWord" => $nl['Word'],
"RLinks" => $nl['Link_Add']
)
);
echo $relatedlinks[$i]['CWord'];
$i++;
}
A: Because the way you've set it up, $relatedlinks[$i] is an array containing (at the key $i) an array containing keys "CWord" and "RLinks". In other words, you have an array inside an array inside an array, whereas what you wanted was an array inside an array. Change the line
$relatedlinks[$i]=array($i => array("CWord" => $nl['Word'],
"RLinks" => $nl['Link_Add']));
to read
$relatedlinks[$i] = array( "CWord" => $nl['Word'],
"RLinks" => $nl['Link_Add']
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Telerik Reporting | Set Report Parameter Via Query String Problem:
I am trying to pass a Report Parameter value from the query string on the page to my report that already has the parameter defined. I just can't seem to get the value passed all the way to the report.
Telerik.Reporting.Report report = new MyCustomReportLibrary.TelerikReport();
report.ReportParameters["parameterName"].Value = Request.QueryString["Id"];
ReportViewer.Report = report;
This syntax above is fine but when the variable "report" is created by the TelerikReport() constructor it doesn't have a value for the parameter yet and when I set it after the fact it doesn't seem to matter. Even if I try to call a ReportViewer.RefreshReport().
Places I have looked:
*
*Telerik Documentation on using Telerik Reporting in Web Apps
*Telerik Community Support
*I also submitted a telerik support ticket but tomorrow is Bulgarian Independence day.
Thanks for the help,
Chris
A: I was able to get it to work by altering the Contructor for MyCustomReportLibrary.TelerikReport. Hope this helps anyone looking for the answer.
Much like this example
Telerik Forums | Pass Report parameters from Rad window to a telerik report
Telerik Report Code (TelerikReport.cs)
public TelerikReport(int Id)
{
//
// Required for telerik Reporting designer support
//
InitializeComponent();
this.ReportParameters["parameterName"].Value = Id;
}
ASP.Net Page Code (ReportViewerPage.cs)
protected void Page_Load(object sender, EventArgs e)
{
Report raReport = new TelerikReport(Request.QueryString["Id"] as int);
ReportViewer1.Report = raReport;
}
A: I will offer another answer that is simple and works for MVC (Q3 2015).
MVC
@(Html
.TelerikReporting()
.ReportViewer()
.Id("reportViewer1")
.ServiceUrl(Url.Content("/Controllers/Reports/"))
//Setting the ReportSource Parameters overrides the default specified in the report.
.ReportSource(new TypeReportSource() { TypeName = @ViewBag.TypeName, Parameters = { new Parameter("startDate", Request.QueryString["startDate"]) } })
//To make the query string parameter optional, try:
//.ReportSource(new TypeReportSource() { TypeName = @ViewBag.TypeName, Parameters = { Request.QueryString["startDate"] != null ? new Parameter("startDate", Request.QueryString["startDate"]) : new Parameter() } })
.ViewMode(ViewMode.Interactive)
.ScaleMode(ScaleMode.Specific)
.Scale(1.0)
.PersistSession(false)
.PrintMode(PrintMode.AutoSelect)
)
The Report is nothing special.
public TelerikApplicationReport()
{
InitializeComponent();
}
A: This is another example. Pass parameters directly to the report.
In Asp.net page
protected void Button1_Click(object sender, EventArgs e)
{
var instanceReportSource = new Telerik.Reporting.InstanceReportSource();
instanceReportSource.ReportDocument = new SampleReport(TextBox1.Text);
this.ReportViewer1.ReportSource = instanceReportSource;
}
In report
public partial class SampleReport : Telerik.Reporting.Report
{
public SampleReport(string invoiceNumber)
{
InitializeComponent();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Django model.save() not working with loaddata I have a model which is overriding save() to slugify a field:
class MyModel(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(max_length=200)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(MyModel, self).save(*args, **kwargs)
When I run load data to load a fixture, this save() does not appear to be called because the slug field is empty in the database. Am I missing something?
I can get it to work by a pre_save hook signal, but this is a bit of a hack and it would be nice to get save() working.
def mymodel_pre_save(sender, **kwargs):
instance = kwargs['instance']
instance.slug = slugify(instance.name)
pre_save.connect(mymodel_pre_save, sender=MyModel)
Thanks in advance.
A: No you're not. save() is NOT called by loaddata, by design (its way more resource intensive, I suppose). Sorry.
EDIT: According to the docs, pre-save is not called either (even though apparently it is?).
Data is saved to the database as-is, according to https://docs.djangoproject.com/en/dev/ref/django-admin/#what-s-a-fixture
A: I'm doing something similar now - I need a second model to have a parallel entry for each of the first model in the fixture. The second model can be enabled/disabled, and has to retain that value across loaddata calls. Unfortunately, having a field with a default value (and leaving that field out of the fixture) doesn't seem to work - it gets reset to the default value when the fixture is loaded (The two models could have been combined otherwise).
So I'm on Django 1.4, and this is what I've found so far:
*
*You're correct that save() is not called. There's a special DeserializedObject that does the insertion, by calling save_base() on the Model class - overriding save_base() on your model won't do anything since it's bypassed anyway.
*@Dave is also correct: the current docs still say the pre-save signal is not called, but it is. It's behind a condition: if origin and not meta.auto_created
*
*origin is the class for the model being saved, so I don't see why it would ever be falsy.
*meta.auto_created has been False so far with everything I've tried, so I'm not yet sure what it's for. Looking at the Options object, it seems to have something to do with abstract models.
*So yes, the pre_save signal is indeed being sent.
*Further down, there's a post_save signal behind the same condition that is also being sent.
Using the post_save signal works. My models are more complex, including a ManyToMany on the "Enabled" model, but basically I'm using it like this:
from django.db.models.signals import post_save
class Info(models.Model):
name = models.TextField()
class Enabled(models.Model):
info = models.ForeignKey(Info)
def create_enabled(sender, instance, *args, **kwards):
if Info == sender:
Enabled.objects.get_or_create(id=instance.id, info=instance)
post_save.connect(create_enabled)
And of course, initial_data.json only defines instances of Info.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How to wrap Class into an object? I need to store a Class in NSDictionary. Is there any other way than doing it with NSStringFromClass?
A: Use setObject: forKey:
A class is a valid item that can be passed to setObject which takes in id for argument.
A: @class MyClass;
MyClass* myObject;
[myDictionary setValue:myObject forKey:@"key"];
and Bob's your uncle. You don't need to convert a class into anything to put it into a dictionary.
If you want to store the dictionary in NSUserDefaults, into NSData, or somesuch, take a look at answers specifically for that. For example, search here at StackOverflow for [ios] custom class NSUserDefaults, or look into conforming to NSCoding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create a column with a quartile rank? I have a table called tableOne in R like this:
idNum binaryVariable salePrice
2 1 55.56
4 0 88.33
15 0 4.45
87 1 35.77
... ... ...
I'd like to take the values produced from: summary(tableOne$salePrice) to create four quartiles by salePrice. I'd then like to create a column tableOne$quartile with which quartile each rows salePrice is in. It would look like:
idNum binaryVariable salePrice quartile
2 1 55.56 3
4 0 88.33 4
15 0 4.45 1
87 1 35.77 2
... ... ... ...
Any suggestions?
A: A data.table approach
library(data.table)
tableOne <- setDT(tableOne)[, quartile := cut(salesPrice, quantile(salesPrice, probs=0:4/4), include.lowest=TRUE, labels=FALSE)]
A: With dplyr you could use the ntile function:
ntile(x, n)
tableOne$quartile <- ntile(tableOne$salesPrice, 4)
This will add a column to the table assigning a quantile based on n to each row with the price quantile it is in.
Note: This method starts with the lower values at 1 and works upwards from there.
A: Setting the parameter labels=FALSE in cut() returns category names as integers. See ?cut
tableOne <- within(tableOne, quartile <- cut(salesPrice, quantile(salesPrice, probs=0:4/4), include.lowest=TRUE, labels=FALSE))
A: This should do it:
tableOne <- within(tableOne, quartile <- as.integer(cut(salesPrice, quantile(salesPrice, probs=0:4/4), include.lowest=TRUE)))
...Some details:
The within function is great for calculating new columns. You don't have to refer to columns as
tableOne$salesPrice etc.
tableOne <- within(tableOne, quartile <- <<<some expression>>>)
The quantile function calculates the quantiles (or in your case, quartiles). 0:4/4 evaluates to c(0, 0.25, 0.50, 0.75, 1).
Finally the cut function splits your data into those quartiles. But you get a factor with weird names, so as.integer turns it into groups 1,2,3,4.
Try ?within etc to learn more about the functions mentioned here...
A: You can use the following script
tableOne$Quartile<-ifelse(tableOne$salesPrice<=quantile(tableOne$salesPrice,c(0.25)),1,
ifelse(tableOne$salesPrice<=quantile(tableOne$salesPrice,c(0.5)),2,
ifelse(tableOne$salesPrice<=quantile(tableOne$salesPrice,c(0.75)),3,
ifelse(tableOne$salesPrice<=quantile(tableOne$salesPrice,c(1)),4,NA))))
A: using package cutr we can do :
# devtools::install_github("moodymudskipper/cutr")
library(cutr)
df$quartile <- smart_cut(df$salePrice, 4, "g", output = "numeric")
# idNum binaryVariable salePrice quartile
# 1 2 1 55.56 3
# 2 4 0 88.33 4
# 3 15 0 4.45 1
# 4 87 1 35.77 2
A: The following code creates an ntile group vector:
qgroup = function(numvec, n = 4){
qtile = quantile(numvec, probs = seq(0, 1, 1/n))
out = sapply(numvec, function(x) sum(x >= qtile[-(n+1)]))
return(out)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: Posting same form to different actions depending on button clicked I have a similar post on this on StackOverflow but perhaps my misunderstanding is more substantial.
I have an action Index() and an Index view its rendering.
From Index() view depending on the button clicked [HttpPost]Index() or [HttpPost]Search() must be called cause I'm posting some data. Is the only way to post to different actions is by using jQuery ? If jQuery is the only way, if my actions return views(complete Html pages), to I have to clean the whole document element from the $.post and fill it up with my views html ? I'm pretty new to all this, thanks a ton!
@using (Html.BeginForm())
{
<input name="startDate" type="text" size="20" class="inputfield" id="datepicker" />
<a href="#" id="apply_button">...</a>
<a href="#" id="go_button">...</a>
}
public ActionResult Index(string lang)
{
return View();
}
//Perhaps this action is needed
[HttpPost]
public ActionResult Index(string lang, string startDate)
{
return View();
}
[HttpPost]
public ActionResult Search(string lang, string startDate)
{
return View();
]
A: You can change the form's action attribute depending on which button was clicked.
e.g. To post to the 'search' action when the 'go' button is clicked:
$('#go_button').click(function() {
$('form').attr("action", "Search"); //change the form action
$('form').submit(); // submit the form
});
A: Additional to accepted answer when you are in need to change action as well as Controller too:
$('#go_button').click(function() {
$('form').attr("action", "@("Search","OtherControllerName")"); //change the form action
$('form').submit(); // submit the form
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Android save certain values on rotation I have an activity that runs asynctasks among other things, I don't want everything to be reset when the layout changes.
I put this in the activity's manifest element android:configChanges="orientation" but unfortunately the activity doesn't even switch from the landscape to portrait layout anymore when that is there!
I only halfway understand saveInstanceStates and passing Bundles around, and I'm definitely not sure how to use that with complex data objects, insight appreciated there
What I would like to do is make sure that the asynctasks don't run again, (I could save variables to disk, and do a conditional check for them before running the asynctask) if there is some android way to really watch out for this that would be great!
thanks
A: I believe this library will definitely serve your purpose
http://brainflush.wordpress.com/2009/11/16/introducing-droid-fu-for-android-betteractivity-betterservice-and-betterasynctask/
A: When you put android:configChanges="orientation" in the manifest, you are declaring that android won't need to handle orientation change. Thus, the orientation never happens.
You can check out how to save value to bundle onConfigurationChange(in your case, orientation) in this thread.How do I save an Android application's state?
In brief, you save some value to bundle by overriding onSaveInstanceState(Bundle savedInstanceState). Retrieve the value you saved to bundle by either overriding onRestoreInstanceState(Bundle savedInstanceState) or checking bundle parameter at onCreate.
A: I decided to post what is working for me, is this what yours looks like? This is from my manifest:
<activity android:name=".MediaSelectActivity"
android:configChanges="orientation|keyboardHidden"
android:label="Select Media Item for Vision"
></activity>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Find distance between 2 points in fastest way This code calculates the distance between 2 points by using distance formula, Math.sqrt ( (x1 – x2)^2 + (y1 – y2) ^2). My first point has mmx and mmy coordination and second one has ox and oy coordination. My question is simple, is there any FASTER way for calculate this?
private function dist(mmx:int, mmy:int, ox:int, oy:int):Number{
return Math.sqrt((mmx-ox)*(mmx-ox)+(mmy-oy)*(mmy-oy));
}
This is my code, Thanks for help.
public function moveIT(Xmouse, Ymouse):void{
f = Point.distance( new Point( Xmouse, Ymouse ), new Point( mainSP.x, mainSP.y ) );// distance between mouse and instance
distancePro = Point.distance( pointO, new Point( mainSP.x, mainSP.y ) );// distance from start point
if ( f < strtSen ){ // move forward
tt.stop(); tt.reset(); // delay timer on destination
mF = true; mB = false;
ag = Math.atan2((Ymouse - mainSP.y),(Xmouse - mainSP.x)); // move-forward angle, between mouse and instance
}
if (mF){ /// shoot loop
if (f > 5){// 5 pixel
mainSP.x -= Math.round( (400 /f) + .5 ) * Math.cos(ag);
mainSP.y -= Math.round( (400 /f) + .5 ) * Math.sin(ag);
}
if ( distancePro > backSen ){// (backSen = max distance)
mF = false;
tt.start();// delay timer on destination
}
}
if (mB){ /// return loop
if ( distancePro < 24 ){// back angle re-calculation
agBACK = Math.atan2((y1 - mainSP.y),(x1 - mainSP.x));
}
mainSP.x += (Math.cos(agBACK) * rturnSpeed);
mainSP.y += (Math.sin(agBACK) * rturnSpeed);
if ( distancePro < 4 ){ // fix position to start point (x1,y1)
mB = false;
mainSP.x = x1; mainSP.y = y1;
}
}
}
private function scTimer(evt:TimerEvent):void {// timer
tt.stop();
agBACK = Math.atan2((y1 - mainSP.y),(x1 - mainSP.x));// move-back angle between start point and instance
mB = true;
}
Also: pointO = new Point(x1,y1); set start point. I can not use mouseX and mouseY because of the way that the application is called by parent class, so I can just pass x and y to my loop.
A: I think that if you in-line your function instead of making an actual function call, it is the fastest way possible.
f = Math.sqrt((Xmouse-mainSP.x)*(Xmouse-mainSP.x)+(Ymouse-mainSP.y)*(Ymouse-mainSP.y));
distancePro = Math.sqrt((x1-mainSP.x)*(x1-mainSP.x)+(y1-mainSP.y)*(y1-mainSP.y));
Using Point.distance is WAY more readable, but it is several times slower. If you want speed, you want to inline your math directly.
A: Use Point.distance
d = Point.distance( new Point( x1, y1 ), new Point( x2, y2 ) );
It'll be executed in native code which is typically faster than interpreted code.
If you're in 3D space, use Vector3D.distance
If you're doing collision detection, comparing the lengths of vectors (2D or 3D) is quite common and can be resource intensive due to the use of the sqrt function. If you compare the lengthSquared instead, it will be much more performant.
A: Calling a static function is a bit expensive. You can save that overhead by doing this:
private var sqrtFunc = Math.sqrt;
private function dist(mmx:int, mmy:int, ox:int, oy:int):Number{
return sqrtFunc((mmx-ox)*(mmx-ox)+(mmy-oy)*(mmy-oy));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: EF code-first: How to load related data (parent-child-grandchild)? I have this entity:
public class DynamicPage {
public int PageId { get; set; }
public int Order { get; set; }
public string MenuText { get; set; }
public string MenuHover { get; set; }
public int? ParentId { get; set; }
public virtual DynamicPage Parent { get; set; }
public virtual ICollection<DynamicPage> Children { get; set; }
}
This entity may have 3 level: Parent -> Child -> Grandchild. How can I load the Parent (level 1) whit all associated children (level 2) and for each child, associated grandchild (level 3) if any? Thanks to help.
A: EF 4.1 feature and syntax:
var entity = context.Parents
.Include(p => p.Children.Select(c => c.GrandChildren))
.FirstOrDefault(p => p.Id == 1); // or whatever condition
A: If you want to make life easy on yourself, follow the EF Code First conventions of naming your table IDs simply Id (or, alternatively, name of table + Id, e.g., DyanmicPageId).
This should leave you with something like this:
public class DynamicPage
{
public int Id { get; set; }
public int Order { get; set; }
public string MenuText { get; set; }
public string MenuHover { get; set; }
public int? ParentId { get; set; }
public virtual DynamicPage Parent { get; set; }
public virtual ICollection<DynamicPage> Children { get; set; }
}
Then you need to set up the relationship between parents and children explicitly in an OnModelCreating method in your DbContext class.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<DynamicPage>()
.HasMany(page => page.Children)
.WithRequired(child => child.Parent)
.HasForeignKey(child => child.ParentId);
}
You can then select children or grandchildren as needed:
var parent = dbContext.DynamicPages.Where(page => page.ParentId == null);
var children = parent.Children;
var grandchildren = parent.SelectMany(page => page.Children);
var allRelatedPages = parent.Union(children).Union(grandchildren);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: ItemCommand in Listview not firing in the usercontrol I have user control which has the linkbutton in the Item Template, I am trying to capture the Itemcommand event in the code behind, but the event is not getting fired.
I have gone through the other similar questions, but it didnot help me. Below is my code snippet, could anyone help me on this?
Listview-
<asp:ListView runat="server" ID="lvTherapeuticAlternatives" OnItemCommand="TherapeuticAlternatives_OnItemCommand">
ItemTemplate-
<ItemTemplate>
<tr class='data'>
<td style="width:210px;">
<asp:LinkButton ID="lnkMedSelection" runat="server" CommandName="SelectedMed" CommandArgument='<%#Eval("NDC") & ", " & Eval("DrugGenericProductID") %>' >
<asp:Label ID="lblDrugName" runat="server" Text='<%# Eval("DrugDescription") %>' />
</asp:LinkButton >
</td>
<td style="width:70px;" align="center">
<asp:Label ID="lblBrandGeneric" runat="server" Text='<%# Eval("descBrandGeneric") %>' />
</td>
<td style="width:110px;" align="center">
<asp:Label ID="lblStatus" runat="server" Text='<%# Eval("FormularyStatusDescription") %>' />
</td>
<td style="width:210px;" align="left">
<asp:Label ID="lblFlat" runat="server" Text='<%# Eval("CopayInfo") %>' />
</td>
</tr>
</ItemTemplate>
Codebehind-
Protected Sub TherapeuticAlternatives_OnItemCommand(ByVal sender As Object, ByVal e As ListViewCommandEventArgs) Handles lvTherapeuticAlternatives.ItemCommand
End Sub
A: The Item command was not firing, it is because I had a ISPostback check in Page load event so it was resisting the event handler to call the method registered for ItemCommand event.
When I remove the IsPostback check in the webcontrol, the event is getting fired.
A: From MSDN:
The ItemCommand event is raised when a button in the ListView control is clicked. This enables you to perform a custom routine whenever this event occurs.
And you don't have any button or any other type of control on your ListView that may raise a PostBack; therefore, your ItemCommand handler is never raised.
Update
If you declare your LinkButton like this (pay attention only to the OnClick event):
<asp:LinkButton ID="lnkMedSelection" OnClick="lnkMedSelection_Click" runat="server" CommandName="SelectedMed" CommandArgument='<%#Eval("NDC") & ", " & Eval("DrugGenericProductID") %>' >
And you add in your code behind this:
Protected Sub lnkMedSelection_Click(sender As Object, e As EventArgs)
' Do something here for example:
Label2.Text = "Linked button clicked"
End Sub
Protected Sub TherapeuticAlternatives_OnItemCommand(ByVal sender As Object, ByVal e As ListViewCommandEventArgs) Handles lvTherapeuticAlternatives.ItemCommand
'Notice how this event is also raised.
' You can put a break point or simply test with a label as so:
Label1.Text = "ItemCommand Fired"
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I run a process without blocking user interface in my iphone app I am accessing the photo library on the iphone and it takes a long time to import the pictures i select in my application, how do i run the process on a secondary thread , or what solution do i use to not block the user interface?
A: I did a full explanation with sample code using performSelectOnBackground or GCD here:
GCD, Threads, Program Flow and UI Updating
Here's the sample code portion of that post (minus his specific problems:
performSelectorInBackground Sample:
In this snippet, I have a button which invokes the long running work, a status label, and I added a slider to show I can move the slider while the bg work is done.
// on click of button
- (IBAction)doWork:(id)sender
{
[[self feedbackLabel] setText:@"Working ..."];
[[self doWorkButton] setEnabled:NO];
[self performSelectorInBackground:@selector(performLongRunningWork:) withObject:nil];
}
- (void)performLongRunningWork:(id)obj
{
// simulate 5 seconds of work
// I added a slider to the form - I can slide it back and forth during the 5 sec.
sleep(5);
[self performSelectorOnMainThread:@selector(workDone:) withObject:nil waitUntilDone:YES];
}
- (void)workDone:(id)obj
{
[[self feedbackLabel] setText:@"Done ..."];
[[self doWorkButton] setEnabled:YES];
}
GCD Sample:
// on click of button
- (IBAction)doWork:(id)sender
{
[[self feedbackLabel] setText:@"Working ..."];
[[self doWorkButton] setEnabled:NO];
// async queue for bg work
// main queue for updating ui on main thread
dispatch_queue_t queue = dispatch_queue_create("com.sample", 0);
dispatch_queue_t main = dispatch_get_main_queue();
// do the long running work in bg async queue
// within that, call to update UI on main thread.
dispatch_async(queue,
^{
[self performLongRunningWork];
dispatch_async(main, ^{ [self workDone]; });
});
}
- (void)performLongRunningWork
{
// simulate 5 seconds of work
// I added a slider to the form - I can slide it back and forth during the 5 sec.
sleep(5);
}
- (void)workDone
{
[[self feedbackLabel] setText:@"Done ..."];
[[self doWorkButton] setEnabled:YES];
}
A: Use an asynchronous connection. It won't block the UI while it does the fetching behind.
THIS helped me a lot when I had to do download images, lot of them.
A: One option is use performSelectorInBackground:withObject:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Using Key Bindings with Arrow Keys I'm creating a game that uses the arrow keys to move a sprite. I've added key bindings for the arrow keys and the letter n, but arrow keys aren't working. Here's my code:
public class MyPanel extends JPanel {
Sprite sprite = new Sprite();
Timer gameClock = new Timer(DELAY, new ActionListener(){
public void actionPerformed(ActionEvent e){
sprite.move();
// omit other methods
}
});
// omit other member variables
public MyPanel(){
Abstract Action newGameAction = new AbstractAction("new game") {
public void actionPerformed(ActionEvent e){
doNewGame();
}
}
setFocusable(true);
addKeyBinding(new Pair<String, Action>("N", newGameAction));
ArrayList<Pair<String, Action>> pairs = sprite.findKeyBindingPairs();
for (Pair<String, Action> p : pairs)
addKeyBindings(p);
gameClock.start();
// omit other panel init
}
private void addKeyBindings(Pair<String, Action> pair) {
String key = pair.getFirstElement();
Action action = pair.getSecondElement();
String desc = action.getValue(AbstractAction.NAME).toString();
getInputMap().put(KeyStroke.getKeyStroke(key), desc);
getActionMap().put(desc, action);
}
// omit other methods
}
public class Sprite {
private class ChangeDirAction extends AbstractAction {
int dx, dy;
ChangeDirAction(String name, int dx, int dy){
super(name);
this.dx = dx;
this.dy = dy;
}
public void actionPerformed(ActionEvent e){
setVelocity(dx, dy);
}
}
private int dx_, dy_;
Point pos;
// omit other instance variables
public void move(){
// With printlns dx_ and dy_ are both 0 here. Why?
Point newPos = new Point(pos);
newPos.translate(dx_, dy_);
// omit code to test whether newPos is valid
if (isWall(newPos) || isOutsidePanel(newPos))
setVelocity(0, 0);
else
pos = newPos;
}
private void setVelocity(int dx, int dy){
dx_ = dx;
dy_ = dy;
// With printlns dx_ and dy_ change when arrow keys are pressed
}
public ArrayList<Pair<String, Action>> findKeyBindingPairs(){
Pair<String, Action> leftPair = new Pair<String, Action>("LEFT", new ChangeDirAction("left", -1, 0));
Pair<String, Action> rightPair = new Pair<String, Action>("RIGHT", new ChangeDirAction("right", 1, 0));
Pair<String, Action> upPair = new Pair<String, Action>("UP", new ChangeDirAction("up", 0, -1));
Pair<String, Action> downPair = new Pair<String, Action>("DOWN", new ChangeDirAction("down", 0, 1));
ArrayList<Pair<String, Action>> result = new ArrayList<Pair<String, Action>>();
result.add(leftPair);
result.add(rightPair);
result.add(upPair);
result.add(downPair);
return result;
}
// omit other methods
}
A: I figured it out while trying to do an SSCCE. When I start a new game, I create a new Sprite object without the key bindings of the old one, so my key binding data is lost. I moved my code to add key bindings to the doNewGame() method and it works now.
A: Don't call your custom class "Panel". There is an AWT class called "Panel" so your code is confusing. Use a more descriptive name.
The default InputMap is used to handle Key Bindings when the component has focus. I would guess you need to add:
setFocusable( true );
in the constructor of your class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: color State list + shape on button? I have a state list like this:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="@color/dark_green" />
<item android:drawable="@color/bright_green" />
</selector>
And a shape like this (for rounding my button):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:bottomRightRadius="7dp" android:bottomLeftRadius="7dp" android:topLeftRadius="7dp" android:topRightRadius="7dp"/>
</shape>
My question is how do I apply both of them? If i set the backgroundResource to the color list, then I get the color, but then I cant use it for the shape. I tried using backgroundResource for the shape and backgroundColor for the color, but that didn't work.
A: <selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="@color/dark_green" >
<shape android:shape="rectangle">
<corners android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
<item/>
<item android:drawable="@color/bright_green" />
</selector>
I have done same of things like your.but,it doesn't work,when you use your dradwalbe. If you use like this(use solid to filing button not use drawable,can drow Rounded Button), it can be work.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FFEC7600" />
<corners
android:topLeftRadius="5dip"
android:topRightRadius="5dip"
android:bottomLeftRadius="5dip"
android:bottomRightRadius="5dip" />
</shape>
</item>
A: Have you tried to bundle them in an LayerDrawable XML definition?
Something like that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Handling PHP ^C CLI Script I have a php script that runs in the background 24/7. I have to occasionally terminate it, and the point of the script is to cache transaction data to memcahced from bitcoin RPC (if you don't know what that is, it is irrelevant). I want the script to execute a function when the program receives the signal sent on ^C (control C).
A: You probably want pcntl_signal. The signal you need to catch is SIGINT.
A: In case anybody else is looking, I've found an answer that doesn't require pcntl_signal.
You can use system("stty intr ^-"); to stop ^C from exiting the script automatically. You can then capture it as ord(fread(STDIN, 1)) == 3 within PHP, and handle exiting manually.
I'm working on a library that does this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: rake_test_loader.rb - stack level too deep `--> rake test
Coverage report generated for Unit Tests to /home/chris-kun/code/thirsty/coverage. 0 / 0 LOC (0.0%) covered.
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/rake_test_loader.rb:9: stack level too deep (SystemStackError)
rake aborted!
Command failed with status (1): [/usr/bin/ruby -I"lib:test" -I"/usr/lib/rub...]
Tasks: TOP => test
(See full trace by running task with --trace)
I'm just not sure what to do with the above. Where are the places I should start looking for issues?
UPDATE:
so the error seems to be triggering when I try and load the environment from inside a helper file for my unit tests. (see https://github.com/thumblemonks/riot/issues/45)
UPDATE:
stack trace:
`--> bundle exec rake test --trace
** Invoke test (first_time)
** Execute test
** Invoke test:units (first_time)
** Invoke test:prepare (first_time)
** Execute test:prepare
** Execute test:units
** Invoke test:functionals (first_time)
** Invoke test:prepare
** Execute test:functionals
** Invoke test:integration (first_time)
** Invoke test:prepare
** Execute test:integration
/usr/lib/ruby/gems/1.9.1/gems/rest-open-uri-1.0.0/lib/rest-open-uri.rb:97: warning: already initialized constant Options
/usr/lib/ruby/gems/1.9.1/gems/rest-open-uri-1.0.0/lib/rest-open-uri.rb:339: warning: already initialized constant StringMax
/usr/lib/ruby/gems/1.9.1/gems/rest-open-uri-1.0.0/lib/rest-open-uri.rb:400: warning: already initialized constant RE_LWS
/usr/lib/ruby/gems/1.9.1/gems/rest-open-uri-1.0.0/lib/rest-open-uri.rb:401: warning: already initialized constant RE_TOKEN
/usr/lib/ruby/gems/1.9.1/gems/rest-open-uri-1.0.0/lib/rest-open-uri.rb:402: warning: already initialized constant RE_QUOTED_STRING
/usr/lib/ruby/gems/1.9.1/gems/rest-open-uri-1.0.0/lib/rest-open-uri.rb:403: warning: already initialized constant RE_PARAMETERS
Coverage report generated for Unit Tests to /home/chris-kun/code/thirsty/coverage. 0 / 0 LOC (0.0%) covered.
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/rake_test_loader.rb:9: stack level too deep (SystemStackError)
rake aborted!
Command failed with status (1): [/usr/bin/ruby -I"lib:test" -I"/usr/lib/rub...]
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils.rb:53:in `block in create_shell_runner'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils.rb:45:in `call'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils.rb:45:in `sh'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils_ext.rb:36:in `sh'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils.rb:80:in `ruby'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils_ext.rb:36:in `ruby'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/testtask.rb:99:in `block (2 levels) in define'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/file_utils_ext.rb:57:in `verbose'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/testtask.rb:98:in `block in define'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:205:in `call'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:205:in `block in execute'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:200:in `each'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:200:in `execute'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:158:in `block in invoke_with_call_chain'
/usr/lib/ruby/1.9.1/monitor.rb:201:in `mon_synchronize'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:151:in `invoke_with_call_chain'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/task.rb:144:in `invoke'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:112:in `invoke_task'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:90:in `block (2 levels) in top_level'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:90:in `each'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:90:in `block in top_level'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:84:in `top_level'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:62:in `block in run'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:129:in `standard_exception_handling'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/lib/rake/application.rb:59:in `run'
/usr/lib/ruby/gems/1.9.1/gems/rake-0.9.2/bin/rake:32:in `<top (required)>'
/usr/lib/ruby/gems/1.9.1/bin/rake:19:in `load'
/usr/lib/ruby/gems/1.9.1/bin/rake:19:in `<main>'
Tasks: TOP => test
A: The same thing happened to me. Are you using a code coverage tool? Where are you putting the require? Is it on the very first line of the test file?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: requestmapping with Spring, automatically adding extension I am trying to map a function to two URIs: api/members/editPreferences.xml and api/members/editPreferences.json
when i test it in the browser, api/members/editPreferences.xml works, and api/members/editPreferences works, automatically redirecting to api/members/editPreferences.xml
however, api/members/editPreferences.json does not work, because Spring automatically adds ".xml" to the end of the URI. specifically the error says:
HTTP ERROR 404
Problem accessing /api/members/editPreferences.json.xml. Reason:
NOT_FOUND
how do i get spring to stop adding ".xml" to the end of the URI?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Centering photo gallery on screen How do you center the photo gallery on the screen? I don't want users to have to scroll to find the gallery..
Javascript:
<!-- The JavaScript -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $ps_albums = $('#ps_albums');
var $ps_container = $('#ps_container');
var $ps_overlay = $('#ps_overlay');
var $ps_close = $('#ps_close');
/**
* when we click on an album,
* we load with AJAX the list of pictures for that album.
* we randomly rotate them except the last one, which is
* the one the User sees first. We also resize and center each image.
*/
$ps_albums.children('div').bind('click',function(){
var $elem = $(this);
var album_name = 'album' + parseInt($elem.index() + 1);
var $loading = $('<div />',{className:'loading'});
$elem.append($loading);
$ps_container.find('img').remove();
$.get('photostack.php', {album_name:album_name} , function(data) {
var items_count = data.length;
for(var i = 0; i < items_count; ++i){
var item_source = data[i];
var cnt = 0;
$('<img />').load(function(){
var $image = $(this);
++cnt;
resizeCenterImage($image);
$ps_container.append($image);
var r = Math.floor(Math.random()*41)-20;
if(cnt < items_count){
$image.css({
'-moz-transform' :'rotate('+r+'deg)',
'-webkit-transform' :'rotate('+r+'deg)',
'transform' :'rotate('+r+'deg)'
});
}
if(cnt == items_count){
$loading.remove();
$ps_container.show();
$ps_close.show();
$ps_overlay.show();
}
}).attr('src',item_source);
}
},'json');
});
/**
* when hovering each one of the images,
* we show the button to navigate through them
*/
$ps_container.live('mouseenter',function(){
$('#ps_next_photo').show();
}).live('mouseleave',function(){
$('#ps_next_photo').hide();
});
/**
* navigate through the images:
* the last one (the visible one) becomes the first one.
* we also rotate 0 degrees the new visible picture
*/
$('#ps_next_photo').bind('click',function(){
var $current = $ps_container.find('img:last');
var r = Math.floor(Math.random()*41)-20;
var currentPositions = {
marginLeft : $current.css('margin-left'),
marginTop : $current.css('margin-top')
}
var $new_current = $current.prev();
$current.animate({
'marginLeft':'250px',
'marginTop':'-385px'
},250,function(){
$(this).insertBefore($ps_container.find('img:first'))
.css({
'-moz-transform' :'rotate('+r+'deg)',
'-webkit-transform' :'rotate('+r+'deg)',
'transform' :'rotate('+r+'deg)'
})
.animate({
'marginLeft':currentPositions.marginLeft,
'marginTop' :currentPositions.marginTop
},250,function(){
$new_current.css({
'-moz-transform' :'rotate(0deg)',
'-webkit-transform' :'rotate(0deg)',
'transform' :'rotate(0deg)'
});
});
});
});
/**
* close the images view, and go back to albums
*/
$('#ps_close').bind('click',function(){
$ps_container.hide();
$ps_close.hide();
$ps_overlay.fadeOut(400);
});
/**
* resize and center the images
*/
function resizeCenterImage($image){
var theImage = new Image();
theImage.src = $image.attr("src");
var imgwidth = theImage.width;
var imgheight = theImage.height;
var containerwidth = 460;
var containerheight = 330;
if(imgwidth > containerwidth){
var newwidth = containerwidth;
var ratio = imgwidth / containerwidth;
var newheight = imgheight / ratio;
if(newheight > containerheight){
var newnewheight = containerheight;
var newratio = newheight/containerheight;
var newnewwidth =newwidth/newratio;
theImage.width = newnewwidth;
theImage.height= newnewheight;
}
else{
theImage.width = newwidth;
theImage.height= newheight;
}
}
else if(imgheight > containerheight){
var newheight = containerheight;
var ratio = imgheight / containerheight;
var newwidth = imgwidth / ratio;
if(newwidth > containerwidth){
var newnewwidth = containerwidth;
var newratio = newwidth/containerwidth;
var newnewheight =newheight/newratio;
theImage.height = newnewheight;
theImage.width= newnewwidth;
}
else{
theImage.width = newwidth;
theImage.height= newheight;
}
}
$image.css({
'width' :theImage.width,
'height' :theImage.height,
'margin-top' :-(theImage.height/2)-10+'px',
'margin-left' :-(theImage.width/2)-10+'px'
});
}
});
</script>
A: .ps_container {
width: 480px;
height: 350px;
position: fixed; /* EDIT: changed absolute to fixed*/
top: 50%;
margin-top: -175px;
left: 50%;
margin-left: -240px;
z-index: 100;
}
style.css line:59
Modify the .ps_container rule to the above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it worth using memcached on node.js Is there any particular reason to use memcached for fast access to cached data instead of just creating a global CACHE variable in the node program and using that?
Assume that the application will we running in one instance and not distributed across multiple machines.
The global variable option seems like it would be faster and more efficient but I wasn't sure if there was a good reason to not do this.
A: It depends on the size and number of items. If you're working with a few items of modest size and they don't need to be accessible to other node instances then using an object has a key/value store is fine. The one trick is that when you go to delete/remove items from the cache/object make sure you don't keep any other references to it, otherwise you will have a leak.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get an ascii value of a NSString*, pointing to a character? When presented with an @"a", i'd like to be able to get it's ascii value of 97.
I thought this does it
NSString *c = [[NSString alloc] initWithString:@"a"];
NSLog(@"%d", [c intValue]); // Prints 0, expected 97
But ... you guessed it (or knew it :)) .. it does not.
How can i get an ascii value of a NSString*, pointing to a single character?
A: NSString *str = @"a";
unichar chr = [str characterAtIndex:0];
NSLog(@"ascii value %d", chr);
And why your method does not work is because you are operating on a STRING remember? Not a single character. Its still a NSString.
A: NSLog(@"%d",[c characterAtIndex:0]);
NSString class reference: The integer value of the receiver’s text, assuming a decimal representation and skipping whitespace at the beginning of the string. Returns INT_MAX or INT_MIN on overflow. Returns 0 if the receiver doesn’t begin with a valid decimal text representation of a number.
So it returned 0 because you called intValue on invalid decimal text representation of a number.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Static variables in PHP I have found different information regarding static variables in PHP but nothing that actually explains what it is and how it really works.
I have read that when used within a class that a static property cannot be used by any object instantiated by that class and that a static method can be used by an object instantiated by the class?
However, I have been trying to research what a static variable does within a function that is not in a class. Also, does a static variable within a function work somewhat like closure in javascript or am I totally off in this assumption?
A:
I have read that when used within a class that a static property cannot be used by any object instantiated by that class
It depends on what you mean by that. eg:
class Foo {
static $my_var = 'Foo';
}
$x = new Foo();
echo $x::$my_var; // works fine
echo $x->my_var; // doesn't work - Notice: Undefined property: Foo::$my_var
and that a static method can be used by an object instantiated by the class???
Yes, an instantiated object belonging to the class can access a static method.
The keyword static in the context of classes behave somewhat like static class variables in other languages. A member (method or variable) declared static is associated with the class and rather than an instance of that class. Thus, you can access it without an instance of the class (eg: in the example above, I could use Foo::$my_var)
However, I have been trying to research what a static variable does within a function that is not in a class.
Also, does a static variable within a function work somewhat like closure in javascript or am I totally off in this assumption.
Outside of classes (ie: in functions), a static variable is a variable that doesn't lose its value when the function exits. So in sense, yes, they work like closures in JavaScript.
But unlike JS closures, there's only one value for the variable that's maintained across different invocations of the same function. From the PHP manual's example:
function test()
{
static $a = 0;
echo $a;
$a++;
}
test(); // prints 0
test(); // prints 1
test(); // prints 2
Reference: static keyword (in classes), (in functions)
A: static has two uses in PHP:
First, and most commonly, it can be used to define 'class' variables/functions (as opposed to instance variables/functions), that can be accessed without instantiating a class:
class A {
public static $var = 'val'; // $var is static (in class context)
public $other_var = 'other_val'; // non-static
}
echo A::$var; // val
echo A::$other_var // doesn't work (fatal error, undefined static variable)
$a = new A;
echo $a->var // won't work (strict standards)
echo $a->other_var // other_val
Secondly, it can be used to maintain state between function calls:
function a() {
static $i = 0;
$j = 0;
return array($i++, $j++);
}
print_r(a()); // array(0, 0)
print_r(a()); // array(1, 0)
print_r(a()); // array(2, 0)
//...
Note that declaring a variable static within a function works the same regardless of whether or not the function is defined in a class, all that matters is where the variable is declared (class member or in a function).
A: class Student {
static $total_student = 0;
static function add_student(){
return Student::$total_student++;
}
}
First: for the add_student function, the best practice is to use static not public.
Second: in the add_student function, we are using Student::$total_student,not use $this->total_student. This is big different from normal variable.
Third:static variable are shared throughout the inheritance tree.
take below code to see what is the result:
class One {
static $foo ;
}
class Two extends One{}
class Three extends One{}
One::$foo = 1;
Two::$foo = 2;
Three::$foo = 3;
echo One::$foo;
echo Two::$foo;
echo Three::$foo;`
A: A static variable in a function is initialized only in the first call of that function in its running script.
A: At first i will explain what will happen if static variable is not used
<?php
function somename() {
$var = 1;
echo $var . "<br />";
$var++;
}
somename();
somename();
somename();
?>
If you run the above code the output you gets will be 1 1 1 . Since everytime you called that function variable assigns to 1 and then prints it.
Now lets see what if static variable is used
<?php
function somename() {
static $var = 1;
echo $var . "<br />";
$var++;
}
somename();
somename();
somename();
?>
Now if you run this code snippet the output will be 1 2 3.
Note: Static keeps its value and stick around everytime the function is called. It will not lose its value when the function is called.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "51"
} |
Q: Trouble adding cells to a tableView I have a page with a button on it. When the button is pressed, i want the table view on the next page to add a cell with a label that has the text of 1 and i want there to be a picture also, but i know how to do this. I just want to add a cell to a table view when a button is pressed on the page before the table. How can i do this? Ive tried this code:
FinalCartViewController * viewController = (FinalCartViewController
*)self.parentViewController;
custom.customCellLabel.text = @"1";
[viewController addObject:[NSMutableDictionary dictionaryWithObject:
custom.customCellLabel.text forKey:@"name"]];
custom is an ivar that is created from the FinalCartViewController.
This code was in the method for the button that i want to use to add the cell. And i used [myTalbleView reloadData]; in the tableView's viewDidLoad. But my app crashes when i press the button to add the cell. Could somebody please help me? Thanks.
A: FinalCartViewController * viewController = (FinalCartViewController
*)self.parentViewController;
If the FinalCartViewController (I assume is the Table View) is the NEXT page, how can it be the PARENT view? The Parent view refers to the previous view.
You need to initialise the FinalCartViewController and save reference to it, so you can add objects to it. Although, the better practice would be to have a shared datasource that you add to and then pass to the FinalCartViewController.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can Servlets have multi-step interactions? Is there any way to start executing java Servlet code (specifically, in Websphere Application Server) (one session, one thread on the Servlet) and then pause to get more information from the calling client at various points? I require that the current session, and ongoing Servlet thread, not die until specified, and instead keep waiting (open) for information from the client.
Is this kind of ongoing conversation possible? Or can the Servlet call to "doPost" only be started - and then the Servlet ignores the client until it finishes?
A: As suggested, I would use an object stored in session to maintain the state needed. You can also modify the session on a servlet by servlet basis if you need certain actions to extend the session timeout beyond the webapp defaults using the following method in the HttpSession API:
public void setMaxInactiveInterval(int interval) Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. A negative time indicates the session should never timeout.
You just need to establish your logic for your object setting/retrieval from session. Typically something like this:
HttpSession session = req.getSession();
MyBeanClass bean;
Object temp = null;
temp = session.getAttribute("myBean");
if(temp !=null) {
bean = (MyBeanClass) temp;
} else {
bean = new MyBeanClass();
}
// Logic
session.setAttribute("myBean", bean);
A: I have not done this with directly, but the underlying support is somewhat related to Jetty's continuation model and Servlet 3.0 Suspend/Resume support.
Web frameworks that work like the post description (actually, they are resumed across different connections) are sometimes called Continuation-Based frameworks. I am unsure of any such frameworks in Java (as the Java language is not conducive to such models) but there are two rather well known examples of the general principle:
*
*Seaside (for Smalltalk) and;
*Lift (for Scala).
Hope this was somewhat useful.
A: You can save/update your session state between requests and when the next request comes, you can restore and continue whatever you were doing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Creating a dynamic table for .NET code-behind C# I'm having trouble creating a table and putting data pulled from SQL into it. My solution at the moment is to create a table in Default.aspx, and then create the rows and cells in the C# code.
My aspx code:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Select a topic to view.
</h2>
<asp:Table ID="solutions" runat="server" Width="100%">
</asp:Table>
</asp:Content>
And where all the action should, but doesn't happen:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HtmlAgilityPack;
using System.Data.SqlClient;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection anca = new System.Data.SqlClient.SqlConnection();
anca.ConnectionString = "Data Source=anca;Initial Catalog=servicedesk;
anca.Open();
SqlCommand sub = new SqlCommand("SELECT TITLE FROM dbo.Solution", anca);
SqlDataReader sReader = sub.ExecuteReader();
List<String> subject = new List<string>();
int solCount = 0;
while (sReader.Read())
{
subject.Add(sReader.ToString());
solCount++;
}
sReader.Close();
TableRow newRow = new TableRow();
TableCell newcell = new TableCell();
int adder = 0;
while (adder <= solCount)
{
solutions.Rows.Add(newRow);
for (int i = 0; i <= 6; i++)
{
newRow.Cells.Add(newcell);
newcell.Text = subject[adder].ToString();
}
}
}
}
}
Obviously I'm a bit green with it all. Basically what happens is it pulls all of the solution titles from a database and I want the titles to each be in a cell of their own, where I will go on to link them to the respective pages. Hopefully it all makes sense, if not I am happy to provide more information.
A: First you are adding empty row to table and then filling the row with content. You should add the row after its filled with cell content (i.e. after the loop not before). Also if I am not seeing it wrong, you are not increasing "adder" each loop so it should fall into infinite loop. Also seems like you are pulling only title from DB...so I don't know why you were trying to add 7 columns/cells each row. By the way posting this from office so let me know if I did anything wrong and I will fix it asap :).
while (adder < solCount)
{
var cell = new TableCell();
var row = new TableRow();
cell.Text = subject[adder].ToString();
row.Cells.Add(newcell);
solutions.Rows.Add(newRow);
++adder;
}
I think a more elegant way will be using ListView or Repeater control rather than dynamically generating the table like that.
A: 'MSI' is partly right - (infinite loop..) and use ListView or Repeater or GridView and those controls will take care of the number of rows that your data access code returns. In case, if you want to create on your own for whatever reason, then here is the sample code:
for(int rowCount=0; rowCount<solCount; rowCount++)
{
TableRow row = new TableRow();
solutions.Rows.Add(row);
for(int colCount=0; colCount<6; colCount++)
{
TableCell cell = new TableCell();
row.Cells.Add(cell);
cell.Controls.Add(new LiteralControl(subject[rowCount].ToString());
}
}
Here is an example from MSDN.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: For a WPF AttachedProperty, can you validate the value based on the type you're attaching to? In short, we're creating an attached property that's only to be applied to FrameworkElement or one of its subclasses. What we want is to block the set if it's being applied to anything that's not.
Now we can't use the ValidateValueCallback as that only gets passed the value of the property, not what you're attaching the property to.
Similarly, we can't use the PropertyChangedCallback because the value is already set at that point, and NewValue is read-only, and for some reason, we can't get ClearValue to 'stick' inside.
So... anyway to do what we want?
A: Duh! It wasn't ValidateValueCallback, it was CoerceValueCallback since that gives you the object! Done and done!
UPDATE
Scratch that. That's actually not 100% correct as I forgot about value precedence.
MSDN: Dependency Property Value Precedence
In other words, it's still actually set, but it's just coerced back again to the default value, which means 'not set' in our case. Damn.
I'm starting to think the only real way to do this here is to simply to throw an InvalidOperationExcepton in the PropertyChangedCallback but I'm not sure even that will 100% work as I believe the value has already been set once you're inside it.
I'll get back to you with a definitive. Keep the answers coming!
A: Yes this is possible -- but you do it in your Get and Set methods by controlling the type of the first parameter. If you want only FrameworkElements to be able to get or set the value then you only use framework elements in the get and set methods. This will prevent non-Framework elements from being able to set the value via XAML
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.RegisterAttached(...)
public static bool GetMyProperty(FrameworkElement e)
{
return (bool)e.GetValue(MyPropertyProperty);
}
public static void SetMyProperty(FrameworkElement e, bool value)
{
e.SetValue(MyPropertyProperty, value);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# + MVC3 + Session state + Sql Azure I saw this post in StackOverflow that encouraged me to use Session State in my Azure application.
I followed this post and generated the tables, but my problem is I can't have an additional Database for that, I'd have additional costs too.
My question is: there's a way to make the Session State know that it should run in both tables, even if I don't have a specific connectionString pointing to the database ASPState?
A: If you need session state then I would recommend skipping the SQLAzure provider and using the AppFabricCacheSessionStoreProvider instead. It is now in production, in some of your links above it wasn't yet. I have found it pretty easy to use but there are additional costs. But if you use SQL Azure you could end up with additional costs pretty soon anyway as the database size grows.
Having said that, I am in the process of eliminating session use in my app on Azure. Make it much easier to add more server with no worries, unless your app has sessions deeply ingrained.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7508294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.