text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How can i figure out the type of all the scripts in the directory I want to know How can i figure out the type of all the scripts in the directory "/usr/bin" ?
A: I think what you are looking for is file(1) which identifies file types based on magic numbers. Wrap this in a shell script like the one below to get a listing of the directory.
for a in /usr/bin/*; do
file ${a}
done
IIRC by default the output will include the file name.
A: Use file command:
file /usr/bin/*
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: what i can set create/last modified/last access of a file? in: How to get create/last modified dates of a file in Delphi? i have found as get create/last modified/last access date/time of a un file, but for set this value in a file, what i can to do?
Thanks very much.
A: Try the SysUtils.FileSetDate function from the SysUtils unit, which internally call the SetFileTime WinApi function.
this funcion has two versions
function FileSetDate(const FileName: string; Age: Integer): Integer;
function FileSetDate(Handle: THandle; Age: Integer): Integer;
The Age parameter is the Time to set. You must use the DateTimeToFileDate to convert a TDateTime Value to the Windows OS time stamp.
Like this
FileSetDate(FileName, DateTimeToFileDate(Now));
A: In unit IOUtils.pas you can find the corresponding methods in the records TFile and TDirectory: SetCreationTime, SetLastAccesstime, SetLastWriteTime accompanied by their UTC sibblings.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Two queries faster than than one? I have a table with columns:
CREATE TABLE aggregates (
a VARHCAR,
b VARCHAR,
c VARCHAR,
metric INT
KEY test (a, b, c, metric)
);
If I do a query like:
SELECT b, c, SUM(metric) metric
FROM aggregates
WHERE a IN ('a', 'couple', 'of', 'values')
GROUP BY b, c
ORDER BY b, c
The query takes 10 seconds, explain is:
+----+-------------+------------+-------+---------------+------+---------+------+--------+-----------------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+-------+---------------+------+---------+------+--------+-----------------------------------------------------------+
| 1 | SIMPLE | aggregates | range | test | test | 767 | NULL | 582383 | Using where; Using index; Using temporary; Using filesort |
+----+-------------+------------+-------+---------------+------+---------+------+--------+-----------------------------------------------------------+
If I also group by/order by column a, so it doesn't need temporary/filesort, but then do the same thing in another query myself:
SELECT b, c, SUM(metric) metric
FROM (
SELECT a, b, c, SUM(metric) metric
FROM aggregates
WHERE a IN ('a', 'couple', 'of', 'values')
GROUP BY a, b, c
ORDER BY a, b, c
) t
GROUP BY b, c
ORDER BY b, c
The query takes 1 second and the explain is:
+----+-------------+------------+-------+---------------+------+---------+------+--------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+-------+---------------+------+---------+------+--------+---------------------------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 252 | Using temporary; Using filesort |
| 2 | DERIVED | aggregates | range | test | test | 767 | NULL | 582383 | Using where; Using index |
+----+-------------+------------+-------+---------------+------+---------+------+--------+---------------------------------+
Why is this? Why is it faster if I do the grouping in a separate, outer query, instead of it just doing it all in one?
A: The way SQL works is the less data you have at each step the faster the query will perform.
Because you are doing the grouping in the inner query first you are getting rid of a lot of data that the outside query no longer needs to process.
SQL optimisation should answer some of your questions. But the most important thing to remember is the more things you can eliminate early on in the query, the faster the query will run.
There is also a part of the database that tries different ways to run a query. This part of the server will most of the time choose the fastest path, but being more specific in your queries can really help it along.
More on that on this page: Readings In Database Systems
Looking at your explain it seems the filesort on such a huge number of rows is probably hurting the query a lot. since the rows in the primary query (second query's outer scope) will be working off an in memory table.
A: In the first case the index is used to find matching records, but cannot be used to sort as you do not include the leftmost column in the group/order by clauses. I would be interested to see both queries profiles:
set profiling =1;
run query 1;
run query 2;
show profile for query 1;
show profile for query 2;
A: **** Edited: Not good answer since I didn't see the where part.
I think it's simply that on the second query MySQL is using an index and the first is not.
If you create an index like (b, c, metric) I'm pretty sure the first query is going to be faster than the second.
Edited to be more verbose:
First query:
*
*There is not a good index to perform the query.
*The test index is on (a,b,c,metric) and you need a index on (b,c) ((b,c,metric) would be good also)
*Maybe MySQL is using test index, but is not a good index so is like full scan the table.
Second query:
*
*Is using the index (a,b,c)
*On second instance is performing a non index query but with less data than the first query.
A: Just out of curiousity, can you try this version?:
SELECT b, c, SUM(metric) metric
FROM aggregates
WHERE a = 'some-value'
GROUP BY b, c
and this one:
SELECT b, c, metric
FROM (
SELECT a, b, c, SUM(metric) metric
FROM aggregates
WHERE a = 'some-value'
GROUP BY a, b, c
) t
ORDER BY b, c
and this:
SELECT b, c, SUM(metric) metric
FROM aggregates
WHERE a = 'some-value'
GROUP BY a, b, c
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Ext JS - Problems getting the real char typed ? Here is my problem... Considering this code...
'keydown': function (textThis,e) {
var cc = String.fromCharCode(e.keyCode);
Ext.MessageBox.alert('Caracter',cc);
}
I always get the the char I type but in uppercase... Even if I type it in minus... How can I solve this ?. Thankx in adavnce from Cordoba Argentina
A: The keydown and keyup events fire for every single keystroke (e.g. for the shift key as well). They report the key (the 'key' doesn't have a lower or upper-case). keypress reports a single event for combined strokes (e.g. SHIFT plus A) and the ASCII code (with correct representation of upper/lower case).
The solution is to listen to the keypress event. If you are supporting older browsers you should go with this code (according to this website):
String.fromCharCode(evt.charCode || evt.keyCode);
More details in this stackoverflow question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is there a way to download partial part of a webpage, rather than the whole HTML body, programmatically? We only want a particular element from the HTML document at nytimes.com/technology. This page contains many articles, but we only want the article's title, which is in a . If we use wget, cURL, or any other tools or some package like requests in Python , whole HTML document is returned. Can we limite the returned data to specific element, such as the 's?
A: The HTTP protocol knows nothing about HTML or DOM. Using HTTP you can fetch partial documents from supporting web servers using the Content-Range header, but you'll need to know the byte offsets of the data you want.
The short answer is that the web service itself must support what you're requesting. It is not something that can be provided at the HTTP layer.
A: If you are specifically wanting to process parts of an HTML document located at the ny times url you give, you are probably going about it the wrong way. If you just want a list of the articles, by headline for instance, then what you want is the web feed. In this case, the times publishes an RSS feed from that very category of articles. Note, if you hit this page with a browser, the browser will recognize it as a feed and handle it at higher level, i.e. ask if you want to subscribe to the feed. But, you can hit this with curl and see an unparsed stream of XML. Each item in the feed will represent an article and contain meta data such as a URL to the full article, the title, etc.
Also note that there is probably some web feed specific packages to whatever language platform you are using that will give you high level access to the feed data. This will allow you to write code like:
foreach ( article in feed )
title = article.getTitle();
rather than parsing the xml your self.
A: Yes, cURL does have the ability to only download the HTML file headers and not the rest of the content. Use the -I switch to issue a HEAD http request.
From the Man page:
-I, --head
(HTTP/FTP/FILE) Fetch the HTTP-header only! HTTP-servers feature the command HEAD which this uses to get nothing but the header of a document. When used on a FTP or FILE file, curl displays the file size and last modification time only.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Should a table connecting two tables have its own ID? I have two tables:
First
------
id
name
Second
------
id
name
And another table connecting the first two:
Third
------
first_id
second_id
The third table is there only to resolve the M:N issue. Should it have its own ID?
A: No, you normally don't need an id field on the table connecting the two. You can make the primary key for the connecting table (first_id, second_id).
A: If it's just a simple mapping table, then I would say no. What purpose would that extra ID serve? Just make the primary key a composite: (first_id, second_id).
Having said that, I have seen cases where it's arguable to have a separate ID because it's easier to work with some ORM tools. But generally I would say you should avoid the extra ID column if you can.
A: I started using Composite PKs out of the two columns and it worked for me for a while.
As business grew and business rules changed, some of these table started getting additional attributes or participating in relationships and then I either needed to add a single column PK or just carry a double key down (which grows old real fast).
I decided then to standardize my own design. Now, as a part of my design, I use an additional single column PK for all join tables.
A: If the table only contains the two foreign keys, there is no reason to have an additional key. You won't be using it in any query.
When you join the tables using the connection table, you are making a join against one foreign key at a time, not against both foreign keys at once, so there is no use for another key in the connection table. Example:
select t1.name, t2.name
from First t1
inner join Third t3 on t3.first_id = t1.id -- one foreign key
inner join Second t2 on t2.id = t3.second_id -- the other foreign key
Just make a primary key combining the two foreign keys.
PRIMARY KEY (first_id, second_id)
A: It depends on role of the table "'third" (connection or join table). Lets assume for example, that this table express a relation between two others tables. Since it is all, there is no need for additional Id.
But what if that relation, between table "One" and "Two" became temporary? I mean, that relation is for some period of time. For example ownership, marriage, etc. Then you can't add another record/entity to the connection table ("Third") because such a relation already exist.
So it is safer to establish for each table it's own Id. Exept we are sure, that in the future, temporary (since that multitimes) relation will not happen.
=========================================
sorry for my english
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Migrating MVC 3 site to Azure web role I am trying to migrate an existing MVC 3 web site to an Azure web role. My development environment uses a host header:
lcladmin.mysite.com
The host header is setup in my hosts file to point to 127.0.0.1. If I use the default settings in ServiceConfiguration.csdef the site loads fine as 127.0.0.1, but the features that depend on using host headers don't work. So I tried setting the hostHeader attribute on the Binding in SericeConfiguration.csdef and now I get this error dialog in Visual Studio 2010:
*There was an error attaching the deubgger to the IIS worker process for URL 'http://lcladmin.mysite.com:81/' for role instance 'deployment(17).Azure.Admin_IN_0'. Unable to start debugging on the web server. The debug request could not be processed by the server due to invalid syntax.*
At this point I can browse the site in my web browser and everything seems to be working as it should and any existing breakpoints will get hit in VS. However, VS is unusable because of the modal error dialog with the above message.
Here's the contents of my ServiceConfiguration.csdef:
<ServiceDefinition name="Azure" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"> <WebRole name="Admin" vmsize="Small">
<Sites>
<Site name="Web">
<Bindings>
<Binding name="Endpoint1" endpointName="Admin" hostHeader="lcladmin.mysite.com" />
</Bindings>
</Site>
</Sites>
<Endpoints>
<InputEndpoint name="Admin" protocol="http" port="81" />
</Endpoints>
<Imports>
<Import moduleName="Diagnostics" />
</Imports>
I don't think this is a problem specific to the site I am migrating either. If I add a new Azure project to my solution, and a new MVC 3 web role and the only change I make is to add the hostHeader attribute, it does the same thing.
A: This blog entry by Michael Neel solved the same problem for me: Debugging Azure WebRoles with Multiple Sites
After reading Michael's entry, the key for me was to get the right ip address in the hosts file - like mentioned in one of the comments of his entry - my ip needed to be 127.255.0.0 (which you can look up on your system in IIS after the deploy has happened to the azure emulator, look at the site's bindings)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Database Selection and Datetime Sorting (real-time Python dashboard) I have a dashboard for real-time updates and latest notifications.
Imagine this is a blogging system where you can subscribe to authors posts and comments.
I then want 2 type of notifications to appear in my dashboard, sorted by insertion time:
*
*Last posts
*Last comments
Imagine I only want 10 updates to show up when I load the dashboard (later updtes I'm getting through ajax). How should I query the database and how should I sort the results?
I've thought of querying the 2 tables (posts and comments) for data that I've subscribed, add that data to a list and sort those results for datetime and then return the last 10, but I feel this is not a very good solution since it would take lots of time to sort if those tables (and my subscriptions) begin to grow.
What are your answers/thoughts for this problem?
A: Query the first table ordering by descending insertion time and limiting results to 10. Then query the second table the same way. Then merge results in python and return the first 10 of them.
A django example could look like this:
from operator import attrgetter
recent_posts = Post.objects.order_by('-created')[:10]
recent_comments = Comment.objects.order_by('-created')[:10]
both_combined = list(recent_posts) + list(recent_comments)
both_sorted = sorted(both_combined, key=attrgetter('created'), reverse=True)
most_recent = both_sorted[:10]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: XML parser Jar confusion I need to know which jar contains the following class
com.ibm.xml.jaxp.datatype.XMLGregorianCalendar
kindly help me
A: Use the following code snippet:
System.out.println(com.ibm.xml.jaxp.datatype.XMLGregorianCalendar.class.getProtectionDomain().getCodeSource().getLocation());
A: this jar exists in xml-apis.jar
A: Are you using Maven ?
mvn dependency:tree
Then in the output look for: com.ibm.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Secure hidden variables in rails? When I've worked with drupal, where you might normally pass variables through the client via a hidden field on a form, there was an option to use a 'secure hidden field', which meant that the hidden values you were passing through were done via the authenticity token and maintained server side, thereby preventing the user seeing/modifying them.
Is this something that's possible with rails? If so, how is it done?
A: The Rails session object will accomplish what you're trying to do here. First, you should configure your Rails stack to use the ActiveRecord or Memcache sessions. This will drop a session cookie on your user's web browser, with an ID containing no data. This ID relates to a session object containing information about your user. In code, you can set this like:
session[:myvar] = "data I want to store"
This data will never be sent over the wire, but available on the server side at any time, simply by accessing the session store like:
puts session[:myvar]
This is all done transparently to you by the Rails stack - no need for you to manually set or reference the cookie.
To further secure the session, you can require the session token to be sent over SSL. More information here:
http://guides.rubyonrails.org/security.html#what-are-sessions
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How can I implement incremental search on a listbox? I want to implement incremental search on a list of key-value pairs, bound to a Listbox.
If I had three values (AAB, AAC, AAD), then a user should be able to select an item in the available list box and type AAC and this item should be highlighted and in focus. It should be also in incremental fashion.
What is the best approach to handle this?
A: Add a handler to the KeyChar event (the listbox is named lbxFieldNames in my case):
private void lbxFieldNames_KeyPress(object sender, KeyPressEventArgs e)
{
IncrementalSearch(e.KeyChar);
e.Handled = true;
}
(Important: you need e.Handled = true; because the listbox implements a "go to the first item starting with this char" search by default; it took me a while to figure out why my code was not working.)
The IncrementalSearch method is:
private void IncrementalSearch(char ch)
{
if (DateTime.Now - lastKeyPressTime > new TimeSpan(0, 0, 1))
searchString = ch.ToString();
else
searchString += ch;
lastKeyPressTime = DateTime.Now;
var item = lbxFieldNames
.Items
.Cast<string>()
.Where(it => it.StartsWith(searchString, true, CultureInfo.InvariantCulture))
.FirstOrDefault();
if (item == null)
return;
var index = lbxFieldNames.Items.IndexOf(item);
if (index < 0)
return;
lbxFieldNames.SelectedIndex = index;
}
The timeout I implemented is one second, but you can change it by modifying the TimeSpan in the if statement.
Finally, you will need to declare
private string searchString;
private DateTime lastKeyPressTime;
A: If I'm interpreting your question correctly, it seems like you want users to be able to start typing and have suggestions made.
You could use a ComboBox (instead of a ListBox):
*
*Set the DataSource to your list of KeyValuePairs,
*Set the ValueMember to "Key" and the DisplayMember to "Value",
*Set AutoCompleteMode to SuggestAppend, and
*Set AutoCompleteSource to ListItems
A: You can use the TextChanged event to fire whenever the user enter a char, and you can also use the listbox event DataSourceChanged with it to hover a specific item or whatever you want.
I will give you an example:
private void textBox1_TextChanged(object sender, EventArgs e)
{
listBox1.DataSource = GetProducts(textBox1.Text);
listBox1.ValueMember = "Id";
listBox1.DisplayMember = "Name";
}
List<Product> GetProducts(string keyword)
{
IQueryable q = from p in db.GetTable<Product>()
where p.Name.Contains(keyword)
select p;
List<Product> products = q.ToList<Product>();
return products;
}
So whenever the user start to enter any char the getproducts method executes and fills the list box and by default hover the first item in the list you can handle that also using the listbox event DataSourceChanged to do whatever you want to do.
There is also another interesting way to do that, which is: TextBox.AutoCompleteCustomSource Property:
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
AutoCompleteStringCollection stringCollection =
new AutoCompleteStringCollection();
textBox1.AutoCompleteCustomSource = stringCollection;
This list can take only string[], so you can get them from your data source then
when the text changed of the textbox add the similar words from your data source which had been filled into the textbox autocomplete custom source:
private void textBox1_TextChanged(object sender, EventArgs e)
{
listBox1.Items.Clear();
if (textBox1.Text.Length == 0)
{
listbox1.Visible = false;
return;
}
foreach (String keyword in textBox1.AutoCompleteCustomSource)
{
if (keyword.Contains(textBox1.Text))
{
listBox1.Items.Add(keyword);
listBox1.Visible = true;
}
}
}
Add another event ListBoxSelectedindexchanged to add the selected text to the text box
A: Maybe you could add an event for TextChanged on the control where the user is typing is search (i'm guessing a TextBox). In the event, you could loop through all items to search the one that is the most corresponding to the words typed by the user.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Reorder legend without changing order of points on plot I keep running into this issue in ggplot2, perhaps someone can help me.
I have a plot where the order of the variables in the legend is in reverse order to how they are displayed on the plot.
For example:
df=data.frame(
mean=runif(9,2,3),
Cat1=rep(c("A","B","C"),3),
Cat2=rep(c("X","Y","Z"),each=3))
dodge=position_dodge(width=1)
ggplot(df,aes(x=Cat1,y=mean,color=Cat2))+
geom_point(aes(shape=Cat2),size=4,position=dodge)+
scale_color_manual(values=c("red","blue","black"))+
scale_shape_manual(values=c(16:19))+
coord_flip()
produces:
So the points are displayed on the plot as Cat2=Z,Y, then X (black diamonds, blue triangle, red circle) but in the legend they are displayed as Cat2=X, Y, then Z (red circle, blue triangle, black diamond).
How can I reverse the order of the legend without shifting the points on the plot? Reordering the factor produces the opposite problem (points on the plot are reversed).
Thanks!
A: To flesh out Hadley's comment, we would do something like this:
ggplot(df,aes(x=Cat1,y=mean,color=Cat2))+
geom_point(aes(shape=Cat2),size=4,position=dodge)+
scale_color_manual(values=c("red","blue","black"),breaks = c('Z','Y','X'))+
scale_shape_manual(values=c(16:19),breaks = c('Z','Y','X'))+
coord_flip()
Note that we had to set the breaks in both scales. If we did just one, they wouldn't match, and ggplot would split them into two legends, rather than merging them.
A: As far as i understand what you want to achieve, this simple manipulation does the trick for me:
*
*define a Cat2 as a factor (with the levels in the adequate order) and
*chage the order of colours and shapes to match the levels order (in the scale_manual commands)
Here is the code to do it:
library(ggplot2)
df=data.frame(
mean=runif(9,2,3),
Cat1=rep(c("A","B","C"),3),
Cat2=factor(rep(c("X","Y","Z"),each=3), levels=c('Z', 'Y', 'X')))
dodge=position_dodge(width=1)
ggplot(df,aes(x=Cat1,y=mean,color=Cat2))+
geom_point(aes(shape=Cat2),size=4,position=dodge)+
scale_color_manual(values=c("black","blue","red"))+
scale_shape_manual(values=c(18:16))+
coord_flip()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: int/char conversion in network frames with C++/boost::asio Using g++ and boost::asio, I'm trying to format network message frames containing the size of the data to be transmited:
+----------------+------------------------+
| Length | Message string |
| 4 bytes | n bytes |
+----------------+------------------------+
Using the examples of asio blocking tcp echo client/server under a 32 byte Linux, I'm stucked with transmitting the correct size in the frame. The client is supposed to be a Windows machine.
CLIENT:
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>
#include <stdint.h>
#include <arpa/inet.h>
using boost::asio::ip::tcp;
enum { max_length = 1024 };
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n";
return 1;
}
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), argv[1], argv[2]);
tcp::resolver::iterator iterator = resolver.resolve(query);
tcp::socket s(io_service);
s.connect(*iterator);
std::cout << "sizeof uint32_t=" << sizeof(uint32_t) << std::endl;
uint32_t len = 1234;
std::cout << "len=" << len << std::endl;
// uint => char 4
char char_len[4];
char_len[0] = (len >> 0);
char_len[1] = (len >> 8);
char_len[2] = (len >> 16);
char_len[3] = (len >> 24);
std::cout << "char[4] len=["
<< char_len[0] << ',' << char_len[1] << ','
<< char_len[2] << ',' << char_len[3] << ']'
<< std::endl;
// char 4 => uint
uint32_t uint_len = *(reinterpret_cast<uint32_t *>( char_len ));
std::cout << "uint len=" << uint_len << std::endl;
// network bytes order
uint32_t net_len = htonl( len );
std::cout << "net_len=" << net_len << std::endl;
// uint => char 4
char net_char_len[4];
net_char_len[0] = (net_len >> 0);
net_char_len[1] = (net_len >> 8);
net_char_len[2] = (net_len >> 16);
net_char_len[3] = (net_len >> 24);
std::cout << "net char[4] len=["
<< net_char_len[0] << ',' << net_char_len[1] << ','
<< net_char_len[2] << ',' << net_char_len[3] << ']'
<< std::endl;
boost::asio::write(s, boost::asio::buffer(char_len, 4));
char reply[max_length];
size_t reply_length = boost::asio::read(s,
boost::asio::buffer(reply, 1 ));
std::cout << "Reply is: ";
std::cout.write(reply, reply_length);
std::cout << "\n";
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
SERVER:
#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
using boost::asio::ip::tcp;
const int max_length = 1024;
typedef boost::shared_ptr<tcp::socket> socket_ptr;
void session(socket_ptr sock)
{
try
{
for (;;)
{
char data[max_length];
boost::system::error_code error;
size_t length = sock->read_some(boost::asio::buffer(data), error);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
uint32_t net_len;
size_t len_len = sock->read_some( boost::asio::buffer( reinterpret_cast<char*>(&net_len), 4), error );
std::clog << "net len=" << net_len << std::endl;
uint32_t len = ntohl( net_len );
std::clog << "uint len=" << len << std::endl;
char char_len = (char)len;
std::clog << "char len=" << len << std::endl;
boost::asio::write(*sock, boost::asio::buffer( &char_len, size_t(1)));
}
}
catch (std::exception& e)
{
std::cerr << "Exception in thread: " << e.what() << "\n";
}
}
void server(boost::asio::io_service& io_service, short port)
{
tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
for (;;)
{
socket_ptr sock(new tcp::socket(io_service));
a.accept(*sock);
boost::thread t(boost::bind(session, sock));
}
}
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: blocking_tcp_echo_server <port>\n";
return 1;
}
boost::asio::io_service io_service;
std::cout << "Started" << std::endl;
std::cout << "sizeof uint32_t=" << sizeof(uint32_t) << std::endl;
using namespace std; // For atoi.
server(io_service, atoi(argv[1]));
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
Should compile with a simple script:
g++ -o client -I/usr/include/boost -L/usr/lib -lboost_system -lboost_thread-mt client.cpp
g++ -o server -I/usr/include/boost -L/usr/lib -lboost_system -lboost_thread-mt server.cpp
The client is unable to decode the length and the server does not seems to receive the right irt. What am I missing?
A: One problem seems to be that the client send some data, then want to receive something and send it back to the server, but the server does 2 reads and then it sends something. So, the 2nd read() will probably receive 0 bytes.
Also, the read() function reads as long there is some bytes available. In that case, even if the client do 2 write(), the server can read all the bytes with the first read() and the 2nd read() will still see 0 bytes. You have to handle the data stored in the buffer based on your protocol.
Your conversion from len to char_len will not work as expected. As the char_len array contains chars, the cout try to display the char on the screen, but any value below 32 is not displayable. If you want to display the ASCII value of each char, you have to cast them in int just before giving them to cout.
You should simply send "len" as-is:
boost::asio::write(s, boost::asio::buffer(&len, 4));
But I did not saw any message sent in you sample. I only see some lenght being exchanged between the client and the server.
That's all that I can say based on that code.
Edit: I left the byte-order out the keep the respond short.
A: From what I can see in your code, you're actually not sending network byte order, your send statement is like: boost::asio::write(s, boost::asio::buffer(char_len, 4)); and char_len looks like it's filled in host order...
May be you ought to provide the output from your log statements - it may make things a little clearer...
A: I finally manage to find what went wrong.
There was a residual read at the bottom of the server code, that was preventing the second one to read the correct bytes, as said @PRouleau.
The client was also writing the wrong variable, as @Nim pointed out.
The sevrer's error check was not at the right place.
Finally I get the following outpout:
Client:
sizeof uint32_t=4
len=1234
uint len=1234
net_len=3523477504
net char[4] len=[0,0,4,-46]
Server:
Started
sizeof uint32_t=4
net len=3523477504
uint len=1234
With the following code :
CLIENT:
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <boost/asio.hpp>
#include <stdint.h>
#include <arpa/inet.h>
using boost::asio::ip::tcp;
enum { max_length = 1024 };
int main(int argc, char* argv[])
{
try
{
if (argc != 3)
{
std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n";
return 1;
}
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(tcp::v4(), argv[1], argv[2]);
tcp::resolver::iterator iterator = resolver.resolve(query);
tcp::socket s(io_service);
s.connect(*iterator);
std::cout << "sizeof uint32_t=" << sizeof(uint32_t) << std::endl;
uint32_t len = 1234;
std::cout << "len=" << len << std::endl;
// uint => char 4
char char_len[4];
char_len[0] = (len >> 0);
char_len[1] = (len >> 8);
char_len[2] = (len >> 16);
char_len[3] = (len >> 24);
std::cout << "char[4] len=["
<< char_len[0] << ',' << char_len[1] << ','
<< char_len[2] << ',' << char_len[3] << ']'
<< std::endl;
// char 4 => uint
uint32_t uint_len = *(reinterpret_cast<uint32_t *>( char_len ));
std::cout << "uint len=" << uint_len << std::endl;
// network bytes order
uint32_t net_len = htonl( len );
std::cout << "net_len=" << net_len << std::endl;
// uint => char 4
char net_char_len[4];
net_char_len[0] = (net_len >> 0);
net_char_len[1] = (net_len >> 8);
net_char_len[2] = (net_len >> 16);
net_char_len[3] = (net_len >> 24);
std::cout << "net char[4] len=["
<< net_char_len[0] << ',' << net_char_len[1] << ','
<< net_char_len[2] << ',' << net_char_len[3] << ']'
<< std::endl;
std::cout << "net char[4] len=["
<< (int)net_char_len[0] << ',' << (int)net_char_len[1] << ','
<< (int)net_char_len[2] << ',' << (int)net_char_len[3] << ']'
<< std::endl;
boost::asio::write(s, boost::asio::buffer( net_char_len, 4));
/*
char reply[max_length];
size_t reply_length = boost::asio::read(s, boost::asio::buffer(reply, 1 ));
std::cout << "Reply is: ";
std::cout.write(reply, reply_length);
std::cout << "\n";
*/
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
SERVER:
#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/smart_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
using boost::asio::ip::tcp;
const int max_length = 1024;
typedef boost::shared_ptr<tcp::socket> socket_ptr;
void session(socket_ptr sock)
{
try
{
for (;;)
{
char data[max_length];
boost::system::error_code error;
uint32_t net_len;
size_t len_len = sock->read_some( boost::asio::buffer( reinterpret_cast<char*>(&net_len), 4), error );
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
std::cout << "net len=" << net_len << std::endl;
uint32_t len = ntohl( net_len );
std::cout << "uint len=" << len << std::endl;
//char reply = '1';
//std::cout << "char len=" << char_len << std::endl;
//boost::asio::write(*sock, boost::asio::buffer( &reply, size_t(1)));
}
}
catch (std::exception& e)
{
std::cerr << "Exception in thread: " << e.what() << "\n";
}
}
void server(boost::asio::io_service& io_service, short port)
{
tcp::acceptor a(io_service, tcp::endpoint(tcp::v4(), port));
for (;;)
{
socket_ptr sock(new tcp::socket(io_service));
a.accept(*sock);
boost::thread t(boost::bind(session, sock));
}
}
int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: blocking_tcp_echo_server <port>\n";
return 1;
}
boost::asio::io_service io_service;
std::cout << "Started" << std::endl;
std::cout << "sizeof uint32_t=" << sizeof(uint32_t) << std::endl;
using namespace std; // For atoi.
server(io_service, atoi(argv[1]));
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: setContentView causes Null Pointer Exception I have my main activity trying to call a method from an imported package. I have posted the call and method below. The error message I am getting is that the line
setContentView(twitterSite);
I am getting a null point exception!
TweetToTwitterActivity twitter = new TweetToTwitterActivity();
twitter.loginNewUser(v, context);
Method
public void loginNewUser(View v, Context context) {
mPrefs = context.getSharedPreferences("twitterPrefs", MODE_PRIVATE);
Log.i(TAG, "Got Preferences");
// Load the twitter4j helper
mTwitter = new TwitterFactory().getInstance();
Log.i(TAG, "Got Twitter4j");
// Tell twitter4j that we want to use it with our app
mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
try {
Log.i(TAG, "Request App Authentication");
mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
Log.i(TAG, "Starting Webview to login to twitter");
WebView twitterSite = new WebView(context);
twitterSite.requestFocus(View.FOCUS_DOWN);
twitterSite.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()) {
v.requestFocus();
}
break;
}
return false;
}
});
twitterSite.loadUrl(mReqToken.getAuthenticationURL());
setContentView(twitterSite);
} catch (TwitterException e) {
Log.e("HelloWorld", "Error in activity", e);
Toast.makeText(this, "Twitter Login error, try again later", Toast.LENGTH_SHORT).show();
}
}
Stacktrace
09-26 08:21:12.123: ERROR/AndroidRuntime(171): Uncaught handler: thread main exiting due to uncaught exception
09-26 08:21:12.312: ERROR/AndroidRuntime(171): java.lang.NullPointerException
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.app.Activity.setContentView(Activity.java:1631)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at com.blundell.tut.ttt.TweetToTwitterActivity.loginNewUser(TweetToTwitterActivity.java:184)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at com.reason.max.Reason$3.onClick(Reason.java:239)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.view.View.performClick(View.java:2344)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.view.View.onTouchEvent(View.java:4133)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.widget.TextView.onTouchEvent(TextView.java:6510)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.view.View.dispatchTouchEvent(View.java:3672)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1712)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1202)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.app.Dialog.dispatchTouchEvent(Dialog.java:609)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1696)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.view.ViewRoot.handleMessage(ViewRoot.java:1658)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.os.Handler.dispatchMessage(Handler.java:99)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.os.Looper.loop(Looper.java:123)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at android.app.ActivityThread.main(ActivityThread.java:4203)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at java.lang.reflect.Method.invokeNative(Native Method)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at java.lang.reflect.Method.invoke(Method.java:521)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
09-26 08:21:12.312: ERROR/AndroidRuntime(171): at dalvik.system.NativeStart.main(Native Method)
A: setContentView is a method for Activity class. so if your function is not in activity class you have to mention the activity for which it has to set content.
((Activity) context).setContentView(twitterSite);
That is the reason why you have to typecast context to Activity.
A: ur first line in onCreate() method must be
super.onCreate(savedInstanceState);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: rspec+capybara+selenium+spork not closing browser The same problem with rails tests as here, but on Mac OS X.
And when I start specs next time, they hang on js specs until I close the browser manually. And those tests fail, I need to restart specs again.
What's the solution here?
A: https://github.com/timcharper/spork/issues/144
1) [optional] to close only my processes
cp /Applications/Firefox.app/Contents/MacOS/firefox-bin /Applications/Firefox.app/Contents/MacOS/firefox-bin-selenium
Selenium::WebDriver::Firefox.path = "/Applications/Firefox.app/Contents/MacOS/firefox-bin-selenium"
2)
Spork.each_run do
\`killall firefox-bin-selenium\`
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: my first jquery plugin: need tips for doing it better + timeout problem I'm building my first jquery plugin and would like some tips to do it better. I also have an error in my code which I like to get rid off. I'm trying to refresh the content of my widget via a setTimeout in my ajax success callback. it is working (without argument) but I like to pass an argument like so
setTimeout(refresh(o.refresh), 5000);
I'm not sure it is done like that but I followed my intuition. I have the following error in firebug
useless setTimeout call (missing quotes around argument?)
I don't understand this error because the argument provided to the refresh function is a variable. I need to pass an argument to see if the event is triggered by a user double click (widget toggles open) or by the setTimeout method (widget is open so there is no need to close it). I'm not sure that what I'm trying to do is even possible. I could solve my problem by adding a conditional ajax call for the refresh option but I don't want duplicate code. hope anyone can give me some hints 'n' tips, not only for my error but also in general (plugin development). as a jquery starter I'm not sure my code is conventional.
peace
/**
* @author kasperfish
*/
(function($){
$.fn.extend({
widgetIt: function(options) {
var defaults = {
title: 'Widget Title',
load:'',
top: '50px',
left: '400px',
width: '500px',
afterLoad: function(){},
reload:false,
refresh:true
};
var options = $.extend(defaults, options);
var o=options;
return this.each(function() {
var container=$(this).css({'z-index':3, display:'inline-block',position:'absolute',top:o.top,left:o.left,'max-width':o.width})
.addClass('widget_container');
var header = $('<div></div>')
.addClass('ui-widget-header widgethead')
.css({'min-width':'130px'});
var title =$('<div></div>').addClass("w_tit").html(o.title);
var content =$('<div></div>')
.addClass("w_content")
.hide();
//append
$(title).appendTo(header) ;
$(header).appendTo(container) ;
$(content).appendTo(container) ;
//make draggable
$(container).draggable({
cancel: 'input,option, select,textarea,.w_content',
opacity: 0.45,
cursor: 'move'
});
//binding
var display=$(content).css('display'); //check if widget is open=block or closed=none
var reload=true ; //set initially to true->reload content every time widget opened
var refreshcontent=false;
$(header).dblclick(function refresh(refreshcontent){
if(!refreshcontent)//if it's not a refresh
$(content).fadeToggle();//open or close widget
//[show ajax spinner]
if(display="block" && reload){//only load on widget open event
$.ajax({
url: o.load,
context: content,
success: function(data){
$(content).html(data);
reload=false;
//[hide ajax spinner]
setTimeout(refresh(o.refresh), 5000);//refresh every 5s
o.afterLoad.call();},
error: function(){
// error code here
}
});
}else if(display="none"){reload=o.reload;}//set reload true or false
});
$(header).click(function (){
$(container).topZIndex('.widget_container');
});
//close all open widgets and animate back to original position
$('#deco').click(function (){
$(content).hide();
$(container).animate({ "left": o.left, "top": o.top}, "slow");
});
});
}
});
})(jQuery);
A: You're passing the result of refresh(o.refresh) to setTimeout, which is why it's useless. Instead, you need to pass a function that calls refresh(o.refresh) when the setTimeout fires:
setTimeout(function () { refresh(o.refresh); }, 5000);
As for "tips" to make your code better, I suggest you ask that part of your question on Code Review, which is more suited to that type of question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Attempting to globally cache data in a C# WebService but having issues I am working with an API that runs pretty slowly, and as a result my application is taking a pretty big performance hit. I have managed to optimize some of the code and cut down the loading time considerably, but I would also like to cache some data across all sessions to minimize the amount of server hits I have to make. There is one API call I make now that takes almost 10 seconds to run, and the data returned rarely changes (maybe once every few weeks). What I would like to do is cache that result, as well as the time it was retrieved, and only make the API call if a certain amount of time has passed since the last call, otherwise returning the cached results. Currently I am attempting this:
[WebMethod]
public List<RegionList> getRegionLists() {
if (GlobalAppCache.RegionListsLastUpdate == DateTime.MinValue || GlobalAppCache.RegionListsLastUpdate.AddMinutes(15) > DateTime.Now)
{
List<RegionList> regionLists = new List<RegionList>( );
// Do Some API Calls
GlobalAppCache.RegionListsLastUpdate = DateTime.Now;
GlobalAppCache.CachedRegionLists = regionLists;
return regionLists;
}
return GlobalAppCache.CachedRegionLists;
}
With the GlobalAppCache class being:
public class GlobalAppCache {
public static DateTime RegionListsLastUpdate{get;set;}
public static List<RegionList> CachedRegionLists{get;set;}
}
This method of caching doesn't appear to be working (The API Call is made every time, and the cached results are never returned), and I haven't been able to get anything having to do with the Application[] array to work either. Could anyone point me in the right direction? If I can get this working I may be able to improve performance by caching more items in this GlobalAppCache object. Thanks!
A: Try writing to the HttpApplicationState object Application. When retrieving the Data you should pay attention to the casting to correct datatype:
Application["LastUpdate"] = DateTime.Now;
..
..
..
object o = Application["LastUpdate"];
if (o != null) DateTime dLastUpdate = Convert.ToDateTime(o);
...
...
The Application object dies when the AppPool the webservice runs in gets restarted / recycled
A: Ok, I have found a solution for my issue. Apparently while reading the documentation for the WebMethod flag, I missed the CacheDuration property. Since I was trying to cache the output of my methods, simply changing
[WebMethod]
to
[WebMethod(CacheDuration = (60*60*24*2))]
fixed it!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Keep on running an app after the screen auto-locks - Phonegap (Android/iOS) I am developing an app that tracks the users movement over GPS (bike riding in particular) and I realized that when the screen auto-locks, the app would stop running (if I'm not mistaken, I'm not completely certain on this).
Is there a way to prevent the phone from auto-locking? Or as an alternative, is there a way (by using Phonegap) to keep on tracking the user's movement after the screen auto-locks (as a background process of some sort)?
Thank you.
A: I'm pretty sure you need to use a Service for this. Services can be started by Activities to run in the background - i.e. you could start the Service in the onPause() method of your Activity.
A service is a component that runs in the background to perform
long-running operations or to perform work for remote processes. A
service does not provide a user interface. For example, a service
might play music in the background while the user is in a different
application, or it might fetch data over the network without blocking
user interaction with an activity. Another component, such as an
activity, can start the service and let it run or bind to it in order
to interact with it.
Source: http://developer.android.com/guide/topics/fundamentals.html
Google provides developers with a guide to using Services on the Android developer site. Here's the direct link: http://developer.android.com/guide/topics/fundamentals/services.html
A: You can use service for this.
A: You can add a plugin that start a service. Add callbacks and methods to the plugin to get notifications or to retrieve information. Plugin is basically a communication layer between Cordova/Phonegap and native.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Sending an email from a batch job that is defined in a JSP I have a batch job that runs outside any request, response scope.
I would like to be able to define the email content in JSP since the email content is primarly an HTML document with placeholders for values.
Basically, I would like to be able to run a JSP from a static method.
Is this possible? The solutions online suggests having access to a request and response, implementing httpservlet. Can I not fake these?
I know this is a difficult question, but it would feel good to find a solution for it.
A: JSP as a view technology is inseparably tied to the HTTP request/response cycle. You're better off using some other templating engine such as FreeMarker to generate the e-mail message body.
A: You should be able to fire just a HTTP request on the JSP and get its HTTP response.
InputStream response = new URL("http://localhost/context/page.jsp").openStream();
// ...
But, JSP is definitely the wrong tool for the job. You don't need to send an unnecessary HTTP request. Rather use a template engine or make use of a plan text/html file with MessageFormat API.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does Hashtable not take null key? Why does Hashtable not take a null key?
Also why does HashMap allow null keys?
What is the purpose of making these two classes Key behaviour so different?
A: It is just an implementation detail.
Hashtable is the older class, and its use is generally discouraged. Perhaps they saw the need for a null key, and more importantly - null values, and added it in the HashMap implementation.
A: Hashtable predates the collections framework, and was part of JDK 1.0. At that time null keys were probably considered not useful or not essential, and were thus forbidden. You might see it as a design error, just as the choice of the name Hashtable rather than HashTable.
Then, several years later, came the collections framework, and Hashtable was slightly modified to fit into the framework. But the behavior on null keys was not changed to keep backward compatibility.
Hashtable should be deprecated, IMHO.
A: I will let you know how the hashmap stores the objects internally:
HashMap stores the values through put(key,value) and gets the values thorugh get(key). The process follows the concept of Hashing.
When we say put(key,value) - Internally hashCode() for the key is calculated and being taken as the input for hashfunction() to find the bucket location for storing.
In case of Collision - while calculating the hashcode() there may be a possibility the key is different but the hashcode() is same, at that time after finding out the bucket location the storing is done in the linked list. Please Note - While storing as the Map.Entry both the key-value is stored.
When Retrieve of the value through key is done then if during the collision where the key's hashcode() may be same then the value is retrived though equals() function to find out the desired key's value.
Regards,
Anand
A: From the Hashtable JavaDoc:
To successfully store and retrieve objects from a hashtable, the objects used
as keys must implement the hashCode method and the equals method.
In a nutshell, since null isn't an object, you can't call .equals() or .hashCode() on it, so the Hashtable can't compute a hash to use it as a key.
HashMap is newer, and has more advanced capabilities, which are basically just an improvement on the Hashtable functionality. As such, when HashMap was created, it was specifically designed to handle null values as keys and handles them as a special case.
Specifically, the use of null as a key is handled like this when issuing a .get(key):
(key==null ? k==null : key.equals(k))
A: Apart from all the details given in other answers, this is how hashmap allow NULL Keys. If you look at the method putForNullKey() in Hashmap (JDK 5) , it reserves the index "0" for the null key. All values for the null key are kept inside the "0" index of the array.
There is nothing special about storing NULL value as all the put and lookup operations work based on the Key object.
In hashtable, Java does not have these mechanisms and hence hashtable does not support NULL key or values.
A: They're two separate classes for two different things. Also, HashTable is synchronized. HashTable also came before HashMap, so naturally it would be less advanced. It probably didn't make sense to generate a null hashcode in early Java.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Javascript minification and HTML5 manifest We have created a HTML5 application which also works in offline mode. The HTML element includes the manifest attribute and our manifest includes all necessary files to be able to use the application offline. We are trying to find a way to minify our javascript files in an automated way, but also have a working manifest file (without the need for manually editing the manifest file after minification). Mostly when working with minified javascript files it is best to use something like a version number in the file name or a querystring variable to be sure new versions of the minified javascript files are loaded, but this doesn't work well when combined with a manifest file which doesn't support changing querystring variables or different file names.
We have tried AjaxMin and SquishIt, but weren't able to get this working. Do you guys have any ideas or working solutions for making this combination work?
Our HTML:
<html manifest="app.manifest">
Our manifest:
CACHE MANIFEST
NETWORK:
data
CACHE:
scripts/application/application.js
scripts/application/database.js
scripts/application/knockout.extensions.js
scripts/application/main.js
scripts/application/models.js
scripts/application/prototype.extensions.js
etc...
Thanks!
A: If you want to push an update you only need to change the manifest by one or more bytes. Most people use a comment with a version number.
#version 0.1
When the browser shows the cached the page it download the manifest in the background. If it is changed it will re-download* all files in the manifest. So also your new JS file. So this is all you need to do to trigger downloading the new file.
Once everything is downloaded correctly the new files will be used the next time you load the page.
(*) when re-downloading the browser will sent the Last-Modified and/or E-Tag headers so the server can return a 304 if the file has not modified (to reduce bandwidth use). Also some browser will respect the expires headers, so send expire headers that are not to far into the future, or even better that are in the past, since caching based on the expires header is useless when using appCache.
Also note that firefox will guess a expires value based on the last-modified header if no expires is send. If the file hasn't changed for a while, and you are using appcache, there is no way to force firefox to re-download that file, except changing it's filename (almost lost my sanity trying to figure out why FX didn't update some files).
Not sure what you minification problem is. Does the new JS now work, or where you not able to get the browser to use the new file?
A: You have some build process or release process to minify your JavaScript, right? Now you have to make re-generating a newer version of manifest part of that process. After your build tool (make, rake, ant or whatever) rebuild the new minified JavaScript, it also needs to generate a new manifest file pointing to the new JavaScript files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using OpenGL in Matlab with Java? In Matlab I have
import javax.media.opengl.GL;
How do I now use OpenGL? Can anyone provide a very small sample?
Please note: If this wasnt in Matlab then it would be easy. But the question specifically relates to using this in Matlab.
A: MATLAB comes with the JOGL 1.x libraries available on its static classpath, so it's a matter of compiling your source code (with those JAR files on the classpath), then running the program inside MATLAB.
Below is a "hello world" OpenGL example in Java. I show how to compile and run it directly from inside MATLAB:
HelloWorld.java
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCanvas;
import javax.media.opengl.GLEventListener;
public class HelloWorld implements GLEventListener {
public static void main(String[] args) {
Frame frame = new Frame("JOGL HelloWorld");
GLCanvas canvas = new GLCanvas();
canvas.addGLEventListener(new HelloWorld());
frame.add(canvas);
frame.setSize(300, 300);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void display(GLAutoDrawable drawable) {
GL gl = drawable.getGL();
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
gl.glClear(GL.GL_COLOR_BUFFER_BIT);
gl.glColor3f(1.0f, 1.0f, 1.0f);
gl.glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
gl.glBegin(GL.GL_POLYGON);
gl.glVertex2f(-0.5f, -0.5f);
gl.glVertex2f(-0.5f, 0.5f);
gl.glVertex2f(0.5f, 0.5f);
gl.glVertex2f(0.5f, -0.5f);
gl.glEnd();
gl.glFlush();
}
public void init(GLAutoDrawable drawable) {
}
public void reshape(GLAutoDrawable drawable,
int x, int y, int width, int height) {
}
public void displayChanged(GLAutoDrawable drawable,
boolean modeChanged, boolean deviceChanged) {
}
}
HelloWorld_compile_run.m
%# compile the Java code
jPath = fullfile(matlabroot,'java','jarext',computer('arch'));
cp = [fullfile(jPath,'jogl.jar') pathsep fullfile(jPath,'gluegen-rt.jar')];
cmd = ['javac -cp "' cp '" HelloWorld.java'];
system(cmd,'-echo')
javaaddpath(pwd)
%# run it
javaMethodEDT('main','HelloWorld','')
You could try calling Java commands directly in MATLAB (as @DarkByte has shown), but at some point, you have to handle OpenGL events by implementing GLEventListener interface methods: init, display, reshape, etc.. As you can't define Java classes directly in MATLAB, you might as well write the whole thing in Java as I did.
A: Some info from this link:
*
*In matlab, you do not need to type "new"--objects are created as needed.
*In matlab, you use 'single quotes' where you use "double quotes" in java.
*In java you call a routine with no inputs by putting () after its name. This is unnecessary in matlab.
Little example:
import javax.swing.*
J = JFrame('Hi there')
L = JLabel('A Label');
P = J.getContentPane
P.add(L)
J.setSize(200,200);
J.setVisible(1)
And please check here for the MathWorks documentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Disable the building of one project in an Eclipse workspace I have a workspace with some projects of mine and a really big project, which takes two hours to be built. I would like to disable the automatic building of this wide project while maintaining the build enabled for the other projects. Is that possible? How would I do it? Is there other options to solve my problem.
A: You can "close" the project (right-click "Close Project"); that stops Eclipse from looking at it altogether.
Alternatively, in the project properties, under the "Builders" tab, you could uncheck "Java Builder". I think this would turn off compiling and (most?) error checking.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I change the culture of a WinForms application at runtime I have created Windows Form Program in C#. I have some problems with localization. I have resource files in 2 languages(one is for english and another is for french). I want to click each language button and change language at runtime.
But when i am clicking on button, it doesn't work. i am using this code.
private void btnfrench_Click(object sender, EventArgs e)
{
getlanguage("fr-FR");
}
private void getlanguage(string lan)
{
foreach (Control c in this.Controls)
{
ComponentResourceManager cmp =
new ComponentResourceManager(typeof(BanksForm));
cmp.ApplyResources(c, c.Name, new CultureInfo(lan));
}
}
would any pls help on this......
Many Thanks....
A: You might have to call ApplyResources recursively on the controls:
private void btnfrench_Click(object sender, EventArgs e)
{
ApplyResourceToControl(
this,
new ComponentResourceManager(typeof(BanksForm)),
new CultureInfo("fr-FR"))
}
private void ApplyResourceToControl(
Control control,
ComponentResourceManager cmp,
CultureInfo cultureInfo)
{
cmp.ApplyResources(control, control.Name, cultureInfo);
foreach (Control child in control.Controls)
{
ApplyResourceToControl(child, cmp, cultureInfo);
}
}
A: This worked:
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fr-BE");
ComponentResourceManager resources = new ComponentResourceManager(typeof(Form1));
resources.ApplyResources(this, "$this");
applyResources(resources, this.Controls);
}
private void applyResources(ComponentResourceManager resources, Control.ControlCollection ctls)
{
foreach (Control ctl in ctls)
{
resources.ApplyResources(ctl, ctl.Name);
applyResources(resources, ctl.Controls);
}
}
Be careful to avoid adding whistles like this that nobody will ever use. It at best is a demo feature, in practice users don't change their native language on-the-fly.
A: Updating the CultureInfo at runtime might reset component size. This code preserves the size and position of the controls
(there will still be visible flickering though, which using SuspendLayout() couldn't fix)
private void langItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
//I store the language codes in the Tag field of list items
var itemClicked = e.ClickedItem;
string culture = itemClicked.Tag.ToString().ToLower();
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
ApplyResourceToControl(
this,
new ComponentResourceManager(typeof(GUI)),
new CultureInfo(culture));
}
private void ApplyResourceToControl(
Control control,
ComponentResourceManager cmp,
CultureInfo cultureInfo)
{
foreach (Control child in control.Controls)
{
//Store current position and size of the control
var childSize = child.Size;
var childLoc = child.Location;
//Apply CultureInfo to child control
ApplyResourceToControl(child, cmp, cultureInfo);
//Restore position and size
child.Location = childLoc;
child.Size = childSize;
}
//Do the same with the parent control
var parentSize = control.Size;
var parentLoc = control.Location;
cmp.ApplyResources(control, control.Name, cultureInfo);
control.Location = parentLoc;
control.Size = parentSize;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How to create C# program that sends to local message queue. I have a C# Program that is attempting to send to my own local Windows message queue. I have installed message queue and out of desperation gave all access rights to "Everyone" on both the Message Queue itself and the Public queue that I'm trying to write to. I have a form which has two text boxes and two buttons. One pair for sending and another pair for receiving. I click send and get no errors, it can detect that there is in fact a message queue of that name. But the send method seems to go off without actually getting it into the queue. Thanks for any help! Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Messaging;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public MessageQueue myNewPublicQueue;
private static object lockObject = new object();
/// <summary>
///
/// </summary>
public Form1()
{
InitializeComponent();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttoSend_Click(object sender, EventArgs e)
{
if (MessageQueue.Exists(@".\queuename"))
{
myNewPublicQueue = new System.Messaging.MessageQueue(@".\queuename");
System.Messaging.Message mm = new System.Messaging.Message();
mm.Body = textBoxSend.Text;
mm.Label = "First Test Message";
myNewPublicQueue.Send(mm);
}
}
private void buttonGet_Click(object sender, EventArgs e)
{
myNewPublicQueue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);
// Start listening.
myNewPublicQueue.BeginReceive();
}
private void queue_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e)
{
lock (lockObject)
{
// The message is plain text.
string text = (string)e.Message.Body;
Console.WriteLine("Message received: " + text);
textBoxGet.Text = text;
}
// Listen for the next message.
myNewPublicQueue.BeginReceive();
}
public enum MessageType
{
MESSAGE_TYPE_PLAIN_TEXT = 0,
MESSAGE_TYPE_HELLO_WORLD = 1
};
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
A: When you call the MessageQueue.Send() method, check the Outgoing Queues folder in Message Queueing. You should see a temporary queue has been set up (note, this will only happen if the destination queue is on another machine to the sending machine). Check that queue and you should see your message in it. This means that you have addressed the queue incorrectly in your code.
Try this: create a private queue and address it using the format FORMATNAME:DIRECT=OS:<server name>\PRIVATE$\<queue name>. From your question it sounds like you really do not need to use public queues.
Also, don't bother checking if the queue exists unless you are intending to handle when it doesn't (for example by raising an exception or creating it programatically).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Nivo Slider CSS Positioning Issue hoping someone may be able to help here; i've got what appears to be a css glitch on my nivo slider. Each slide is dropping about 20px below where it should appear. See what i mean here; http://whatscooking.goodstuffdesign.co.uk
Any help, is hugely appreciated.
Matt
A: You have not included the Nivo Slider CSS file on your page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: implement Drag and Drop in UITable view **I need to implement Drag and Drop in my table view.I have a table View in left side of my screen and i have an image View on right side of an screen.
I need to Drag a image from my table view to right side image view.
let me explain ..
I have an class named as "myClass" which contains the properties iD, name and imageURL.
image url holds the photolibrary alasset url.
myClass.h
@interface myClass: NSObject {
NSInteger iD;
NSString *name;
NSString *imageURL;
}
@property (nonatomic, assign) NSInteger iD;
@property (nonatomic, assign) NSString *name;
@property (nonatomic, assign) NSString *imageURL;
myClass.m
@implementation myClass
@synthesize iD;
@synthesize name;
@synthesize imageURL;
@end
So I added 50 image details with iD, name, imageURL as myClass objects in to an NSMutableArray named as *BundleImagesArray *
i displayed it in a table view. my code is:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section {
//getting all image details with iD,name,imageURL as **myClass** objects
BundleImagesArray = [staticDynamicHandler getImageFromBundle];
int count = [BundleImagesArray count];
for (int i = 0; i<count; i++) {
//this array for easy scrolling after first time the table is loaded.
[imageCollectionArrays addObject:[NSNull null]];
}
return count;
}
cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
//removing all the subviews
if ([cell.contentView subviews]) {
for (UIView *subview in [cell.contentView subviews]) {
[subview removeFromSuperview];
}
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
[cell setAccessoryType:UITableViewCellAccessoryNone];
myClass *temp = [BundleImagesArray objectAtIndex:indexPath.row];
//adding image view
UIImageView *importMediaSaveImage=[[[UIImageView alloc] init] autorelease];
importMediaSaveImage.frame=CGRectMake(0, 0, 200,135 );
[cell.contentView addSubview:importMediaSaveImage];
//adding image label
UILabel *sceneLabel=[[[UILabel alloc] initWithFrame:CGRectMake(220,0,200,135)] autorelease];
sceneLabel.font = [UIFont boldSystemFontOfSize:16.0];
sceneLabel.textColor=[UIColor blackColor];
[cell.contentView addSubview:sceneLabel];
sceneLabel.text = temp.name;
if([imageCollectionArrays objectAtIndex:indexPath.row] == [NSNull null]){
//getting photlibrary image thumbnail as NSDAta
NSData *myData = [self photolibImageThumbNailData::temp.imageURL]
importMediaSaveImage.image =[UIImage imageWithData:myData ];
[imageCollectionArrays replaceObjectAtIndex:indexPath.row withObject:importMediaSaveImage.image];
} else {
importMediaSaveImage.image = [imageCollectionArrays objectAtIndex:indexPath.row];
}
temp = nil;
return cell
}
I need to Drag a image from my table view to my right side image view.can any one provide me a good way to do it
A: Drag and drop is not a standard interaction mode on the iPad. Users will not understand what they are supposed to do. You should allow a user to select an item in the left-hand table view using a simple tap instead and then update the image view based on the selection. Take a look at the Human Interface Guidelines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: BASH while line numbers in file is smaller than x i want to make a loop that reads some files
and i want it to stop when wc output is smaller than 5 in this case
the file "file" contains the names of the files that will be worked on
for i in `cat file`
do
echo printing $i ...
a=`wc $i`
while [ $a -gt 5 ]
do
echo 3
sleep 10
done
done
this part is not working
a=`wc $i`
while [ $a -gt 5 ]
A: Your going to want to use wc -l to get the line count of the file. Also you will want to decrement $a so you don't have an infinite loop.
A: a=$(wc -l $i|awk '{print $1}')
try this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: "My Contacts" group google contacts I just wrote a small python script that gets me all the groups on my google contacts list, however for some reason "My Contacts" does not show up in that. I'm using the 3.0 api and was having similar problems with the 2.0 api too. The following is an except taken from the Google 2.0 Contacts documentation.
To determine the My Contacts group's ID, for example, you can retrieve a feed of all the groups for a given user, then find the group entry that has the subelement, and take the value of that group entry's element.
Currently the response that I get does not have a gContact:systemGroup tag anywhere. How should I proceed in order to get the group id of a particular group?
My script is as shown below:-
user="blah@gmail.com"
pas="blah"
data={"Email":user, "Passwd":pas, "service": "cp", "source":"tester"}
import urllib
data = urllib.urlencode(data)
import urllib2
req = urllib2.Request('https://www.google.com/accounts/ClientLogin', data)
resp = urllib2.urlopen(req)
x = resp.read()
auth=a[-1].split('=')[-1]
req = urllib2.Request('https://www.google.com/m8/feeds/groups/blah@gmail.com/full/', headers={'Authorization':'GoogleLogin auth='+auth})
resp = urllib2.urlopen(req)
x = resp.read()
print x
print "My Contacts" in x
print "gContact:systemGroup" in x
Some clues on how I could troubleshoot this would be awesome, thanks.
A: Why not use the Python Client Library directly? It includes a set of methods that do exactly what you want.
import gdata.contacts.client
import gdata.contacts.data # you might also need atom.data, gdata.data
gd_client = gdata.contacts.data.ContactsClient(source='eQuiNoX_Contacts')
gd_client.ClientLogin('equinox@gmail.com', '**password**')
feed = gd_client.GetGroups()
for entry in feed.entry:
print 'Atom Id: %s' % group.id.text
print 'Group Name: %s' % group.title.text
if not entry.system_group:
print 'Edit Link: %s' % entry.GetEditLink().href
print 'ETag: %s' % entry.etag
else:
print 'System Group Id: %s' % entry.system_group.id
Does this solve your problem? It's cleaner, in a way. If you're still having trouble with:
...for some reason "My Contacts" does not show up...
then from the documentation:
Note: The feed may not contain all of the user's contact groups, because there's a default limit on the number of results returned. For more information, see the max-results query parameter in Retrieving contact groups using query parameters.
Note: The newer documentation includes sample Python code side-by-side with the protocol explanation; the Python code helps me wrap my head around the generic protocol.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MapOverlay draw() method optimization Here is my draw method. I have 755 roads and about 10 coordinates on each road. So I need two for loop to draw paths. It is running too slow. Any help on optimizing this code. Maybe I don't have to create some of objects.
Projection projection = mv.getProjection();
roadList = getRoadList();
int length = roadList.length;
for (int i = 0; i < length; i++) {
Coordinate[] coordinateList = roadList[i].getCoordinateList();
int numberOfCoordinates = coordinateList.length;
Path path = new Path();
for (int j = 0; j < numberOfCoordinates - 1; j++) {
Coordinate coordinateFrom = coordinateList[j];
Coordinate coordinateTo = coordinateList[j + 1];
GeoPoint geoPointFrom = coordinateFrom.getGeoPoint();
GeoPoint geoPointTo = coordinateTo.getGeoPoint();
Point pointFrom = new Point();
Point pointTo = new Point();
projection.toPixels(geoPointFrom, pointFrom);
projection.toPixels(geoPointTo, pointTo);
path.moveTo(pointFrom.x, pointFrom.y);
path.lineTo(pointTo.x, pointTo.y);
if (!canvas.quickReject(path, EdgeType.BW)) {
if (j == numberOfCoordinates - 2) {
canvas.drawPath(path, paint);
}
}
}
}
In get methods there is not any calculations. They are just getting some predefined variables.
A: I would suggest creating the Paths outside the onDraw() method rather than each time it's called (which could be hundreds of times). The data doesn't seem to change between calls. Create them as you get the data and keep them in a Collection of some sort. Then draw them in onDraw().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: redirect user depending on location I am getting the user's location from his IP address. What would be the best practice to redirect the user to preferrable language website only once? It has to be possible to pick another language and not be redirected again.
A: I would say store a cookie with location preference.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sorting JTable causes NullPointerException I have a JTable which, when the appropriate button is clicked, begins to fill with the results of a file tree walk that goes on in the background. This works fine.
I then decided I want the table to be sorted. After some reading I created a TableRowSorter and set the table to use it. It appeared to work, but upon closer inspection I noticed several of the file results were absent. I disabled the sorter and ran the program again and all of the files were present, upon re-enabling the sorter again some were missed, but it seemed to be different files each time that were being dropped.
To examine this I created a self-contained block of code as a test (see below), which was to be representative of the JTable code (In fact, large chunks were lifted directly from the existing program code). The file tree walk is represented by a for loop. Again, it worked perfectly without the sorter. When I enabled the sorter, however, (by uncommenting line 29) the entire program frozeand I was told there was a NullPointerException.
I have no Idea what is causing either of these problems, nor if they are, in fact, even related. Any ideas on what is wrong are welcome.
import javax.swing.table.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Sort extends JFrame{
private JTable table;
private DefaultTableModel model;
private TableRowSorter<DefaultTableModel> sorter;
private JButton go;
public Sort(){
super("Sort");
// Create table and model
model = new DefaultTableModel(0, 4);
table = new JTable(model);
// Setup sorting
sorter = new TableRowSorter<DefaultTableModel>(model);
ArrayList<RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>();
sortKeys.add(new RowSorter.SortKey(2, SortOrder.ASCENDING));
sortKeys.add(new RowSorter.SortKey(3, SortOrder.ASCENDING));
sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
sorter.setSortKeys(sortKeys);
//table.setRowSorter(sorter);
// Create Scroll Pane
JScrollPane tableScroller = new JScrollPane(table);
table.setFillsViewportHeight(true);
tableScroller.setPreferredSize(new Dimension(500, 200));
// Setup button
go = new JButton("Go");
go.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>(){
public Void doInBackground(){
for(int i = 0; i < 200; i++){
model.addRow( new Object[] { (new Integer(i)), String.valueOf(i), String.valueOf(i%50), String.valueOf(i%10) } );
}
return null;
}
};
worker.execute();
}
});
// Assemble GUI
JPanel panel = new JPanel(new BorderLayout());
panel.add(tableScroller, BorderLayout.CENTER);
panel.add(go, BorderLayout.SOUTH);
setContentPane(panel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Sort();
}
});
}
}
Stacktrace
This is part of the stack trace, it repeats..
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.DefaultRowSorter.convertRowIndexToModel(DefaultRowSorter.java:518)
at javax.swing.JTable.convertRowIndexToModel(JTable.java:2645)
at javax.swing.JTable.getValueAt(JTable.java:2720)
at javax.swing.JTable.prepareRenderer(JTable.java:5718)
at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2114)
at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:2016)
at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1812)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:161)
at javax.swing.JComponent.paintComponent(JComponent.java:778)
at javax.swing.JComponent.paint(JComponent.java:1054)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5221)
at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:295)
at javax.swing.RepaintManager.paint(RepaintManager.java:1206)
at javax.swing.JComponent._paintImmediately(JComponent.java:5169)
at javax.swing.JComponent.paintImmediately(JComponent.java:4980)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:770)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:728)
at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:677)
at javax.swing.RepaintManager.access$700(RepaintManager.java:59)
at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1621)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:675)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
...
A: Your code has a big problem that may explain what you observe: you are modifying your table model outside the EDT, which is evil.
Since you are using a SwingWorker, you should try to use it completely correctly, e.g. use its publish API to call model.addRow().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Generated Div cause havoc I'll try and be as adequate as I can describing this problem.
I'm developing a web-application in Vaadin (GWT-like framework) where I make use of modal windows for displaying tables and other information.
The modal windows are in varying sizes but I'd like to use the same CSS classes for all of them for obvious reasons. and therefore I specify size specific parameters outside the CSS and instead in the java code when the modal windows are created. Eg:
public class InventoryAssignSubscription extends Window {
Panel mainPanel = Cf.panel(I18N.get("inventory.assignsubscription.single.header"));
public void init(Object customer) {
setResizable(false);
setModal(true);
setWidth("730px");
center();
mainPanel.addStyleName("m2m-modalwindow-mainpanel");
However, I've discovered a problem.
When I create a Panel component holding all the content in the window its width will fill the content width of the window, but when I look at the markup generated through Firebug I see another component generated, a VerticalLayout inside the Panel that has another width than the Panel. I have no idea how it gets there. And the problem I get is that the VerticalLayout is too big and causes a horizontal scroll in the bottom of the Panel. This is how it looks in Firebug:
The only way I've found to work around this is by setting the max-width of all VerticalLayout's inside the Panel with the m2m-modalwindow-mainpanel CSS class name:
.v-panel-content-m2m-modalwindow-mainpanel .v-verticallayout {
max-width: 1000px;
}
However, this will only work for ONE window, namely the one who's content is displayed in a 1000 pixel width. Windows who are slimmer will never have their VerticalLayout affected by this CSS class, since their width should be way below 1000px.... =(
Does anyone have an idea of how I can work around this..? Maybe somehow when I create the Panel I can tell it in some way what the components (div's) it "generates" should have as a max-width..?
If my problem is too vividly described or if you need more information to help me solve then please don't hesitate to ask!
Thank you!
EDIT: I've added CSS for the Panel padding and an image from Firebug showing the problem. There is a scroll in the bottom of the Panel that unfortunately doesn't show in the image..
CSS
.v-panel-content-m2m-modalwindow-mainpanel {
padding: 15px;
}
Image:
A: Every Panel in Vaadin has a Vertical layout inside by default. The fact that you had set 730 to the Panel's width and the layout is only 704 pixels wide indicates that you have a margin in your panel. Try using the layout tab in Firebug to see what has caused the difference.
A whole lot of effort is put by Vaadin developers to get the sizing right and there shouldn't be anything without an explanation there.
It's a good idea to post your question to the Vaadin's forum.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make hidden div which appears when file is found? I was trying to make hidden div which shows on when .txt file is found.
I want the div to show the content of the .txt file.
Is that possible?
I have tried to make it by using jQuery but without success.
Idea is simple: div box with constant dimensions which shows content of .txt file which is in same folder on server, but when there isn't any .txt file div becomes hidden (for example in jQuery $("p").hide();).
A: As far as I know this is not possible. You can do an ajax call to a php-page which will check if the file exist on the server and returns something, but directly loading/checking using jQuery is in violation of browser security so they should not allow you to do that.
A: This depends on the usage, but say you have your div for the text, you can make that invisible by setting it to display:none in css.
Now you can either try getting the file with an ajax call, or you can use a ajax head call to check if the file exists on the server.
Just getting the file is faster if it exists, as a head call only checks if it's there, and another ajax call would be neccessary to get the content of the file, however a head call is faster it it does not exist as it does'nt get the content of the file.
EDIT: but since the file does not exists, there is nothing to get, so a head call is probably not needed here as a "get" would be faster in both situations, but the example still shows how to check if a file exists on the server, and then do something if it does or does not exist.
It would look like something like this.
$.ajax({
url:'http://www.mysite.com/myfile.txt',
type:'HEAD',
error: function()
{
//file does not exists, no need to do anything
},
success: function()
{
//file exists get the file and put in the textcontainer and make that visible
$.ajax({
url:'http://www.mysite.com/myfile.txt',
success: function(data)
{
$("#textcontainer").show().text(data);
}
}
});
Or the other way around with the textcontainer visible with display:block etc :
$.ajax({
url:'http://www.mysite.com/myfile.txt',
type:'GET',
error: function()
{
//file does not exists, hide the textcontainer
$("#textcontainer").hide();
},
success: function(data)
{
//file exists get the file and put in the textcontainer that is already visible
$("#textcontainer").text(data);
}
});
A: According to http://api.jquery.com/jQuery.get/ you can handle errors:
If a request with jQuery.get() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method.
Please also see http://api.jquery.com/jQuery.ajax/#jqXHR
An example from that page:
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.ajax({ url: "example.php" })
.success(function() { alert("success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
// perform other work here ...
// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Add a column to a sql server table with a asp.net form I am using C# form and need to enter a column name to the "varchar(100)" textbox and submit the form to create a column on the "Products3" table in sql server. I am getting this error "Error Creating column. Incorrect syntax near 'System.Web.UI.WebControls.TextBox'." when I click the Submit button.
I am not sure why the SQL statement does not see the textbox. Please help.
========================== FrontPage ===
<form id="form1" runat="server">
<div>
<br /><br />
<asp:button id="IP_TextBtn" onclick="btnAddColumn_Click" runat="server" text="Submit" />
<br />
<br />
<asp:textbox id="txtIP_TextField" runat="server"></asp:textbox>
<br />
<br />
<asp:Label id="lblResults" runat="server" Width="575px" Height="121px" Font-Bold="True"></asp:Label>
<br />
<br />
</div>
</form>
========================= BackPage ===
// Creating the Method for adding a new column to the database
public virtual void btnAddColumn_Click(object sender, EventArgs args)
{
{
string alterSQL;
alterSQL = "ALTER TABLE Products3 ";
alterSQL += "ADD '" + txtIP_TextField + "' bool()";
SqlConnection con = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand(alterSQL, con);
cmd.Parameters.AddWithValue("@txtIP_TextField ", txtIP_TextField.Text);
int SQLdone = 0;
try
{
con.Open();
SQLdone = cmd.ExecuteNonQuery();
lblResults.Text = "Column created.";
}
catch (Exception err)
{
lblResults.Text = "Error Creating column. ";
lblResults.Text += err.Message;
}
finally
{
con.Close();
}
}
}
A: You're confused about parameterized queries. txtIP_TextField is not a parameter to the query, so adding it to the Parameters collection won't help. Your query should be:
string alterSQL = "ALTER TABLE Products3 ADD @txtIP_TextField BIT";
Edit: It looks like it may not be possible to parameterize this statement. In that case, you will need to use:
string alterSQL = String.Format("ALTER TABLE Products3 ADD {0} BIT",
txtIP_TextField.Text);
However, this is still subject to SQL Injection Attacks, and you will need to "clean" the txtIP_TextField.Text before using it.
A: Use txtIP_TextField.Text
alterSQL += "ADD '" + txtIP_TextField.Text + "' bool()";
Thats the value of your textbox
A: Use this:
string alterSQL;
alterSQL = "ALTER TABLE Products3 ";
alterSQL += "ADD @txtIP_TextField bool()";
SqlConnection con = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand(alterSQL, con);
cmd.Parameters.AddWithValue("@txtIP_TextField ", txtIP_TextField.Text);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DrawRect does not get called in a simple customized UIView In the code below, my drawRect method is never called. Note tht HypnosisView is inherited from UIView. Can some experts here help me out? Thanks a lot!
- (void)drawRect:(CGRect)rect
{
// This code is never getting called....
NSLog(@"in drawRect...");
// Drawing code -- no need to post this since this function is not even getting called
}
@end
Below is the code I created the view and added it to the current window...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
CGRect wholeWindow = CGRectMake(0,0,320,460); //[window bounds];
view = [[HypnosisView alloc] initWithFrame:wholeWindow];
[view setBackgroundColor:[UIColor clearColor]];
[window addSubview:view];
[view setNeedsDisplay];
[self.window makeKeyAndVisible];
return YES;
}
A: The most likely cause is that window is nil. Make sure it's correctly bound in Interface Builder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Incorrect url generated by URL.Action and Html.ActionLink I have routes:
routes.MapRoute(
"NewsRoute",
"News/{newsId}/{newsTitle}",
new {
controller = "News",
action = "News",
newsId = UrlParameter.Optional,
newsTitle = UrlParameter.Optional
}
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Home", id = UrlParameter.Optional } // Parameter defaults
);
and usage:
@Url.Action("News", "News", new { newsId = "", newsTitle = "" })
I want to have "/News" url, but instead "/News/News" is being generated. Default route is used I guess.
So the question is why NewsRoute is skipped?
A: The solution was to split route with 2 optional parameters and action to two separate actions:
routes.MapRoute(
"NewsRoute",
"News", new {
controller = "News",
action = "Index"
}
);
routes.MapRoute(
"Specific News",
"News/{id}/{title}",
new {
controller = "News",
action = "News",
title = UrlParameter.Optional
}
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine I have this section defined in my _Layout.cshtml
@RenderSection("Scripts", false)
I can easily use it from a view:
@section Scripts {
@*Stuff comes here*@
}
What I'm struggling with is how to get some content injected inside this section from a partial view.
Let's assume this is my view page:
@section Scripts {
<script>
//code comes here
</script>
}
<div>
poo bar poo
</div>
<div>
@Html.Partial("_myPartial")
</div>
I need to inject some content inside the Scripts section from _myPartial partial view.
How can I do this?
A: This is quite a popular question, so I'll post my solution up.
I had the same problem and although it isn't ideal, I think it actually works quite well and doesn't make the partial dependant on the view.
My scenario was that an action was accessible by itself but also could be embedded into a a view - a google map.
In my _layout I have:
@RenderSection("body_scripts", false)
In my index view I have:
@Html.Partial("Clients")
@section body_scripts
{
@Html.Partial("Clients_Scripts")
}
In my clients view I have (all the map and assoc. html):
@section body_scripts
{
@Html.Partial("Clients_Scripts")
}
My Clients_Scripts view contains the javascript to be rendered onto the page.
This way my script is isolated and can be rendered into the page where required, with the body_scripts tag only being rendered on the first occurrence that the razor view engine finds it.
That lets me have everything separated - it's a solution that works quite well for me, others may have issues with it, but it does patch the "by design" hole.
A: Following the unobtrusive principle, it's not quite required for "_myPartial" to inject content directly into scripts section. You could add those partial view scripts into separate .js file and reference them into @scripts section from parent view.
A: There is a fundamental flaw in the way we think about web, especially when using MVC. The flaw is that JavaScript is somehow the view's responsibility. A view is a view, JavaScript (behavioral or otherwise) is JavaScript. In Silverlight and WPF's MVVM pattern we we're faced with "view first" or "model first". In MVC we should always try to reason from the model's standpoint and JavaScript is a part of this model in many ways.
I would suggest using the AMD pattern (I myself like RequireJS). Seperate your JavaScript in modules, define your functionality and hook into your html from JavaScript instead of relying on a view to load the JavaScript. This will clean up your code, seperate your concerns and make life easier all in one fell swoop.
A: From the solutions in this thread, I came up with the following probably overcomplicated solution that lets you delay rendering any html (scripts too) within a using block.
USAGE
Create the "section"
*
*Typical scenario: In a partial view, only include the block one time no matter how many times the partial view is repeated in the page:
@using (Html.Delayed(isOnlyOne: "some unique name for this section")) {
<script>
someInlineScript();
</script>
}
*In a partial view, include the block for every time the partial is used:
@using (Html.Delayed()) {
<b>show me multiple times, @Model.Whatever</b>
}
*In a partial view, only include the block once no matter how many times the partial is repeated, but later render it specifically by name when-i-call-you:
@using (Html.Delayed("when-i-call-you", isOnlyOne: "different unique name")) {
<b>show me once by name</b>
<span>@Model.First().Value</span>
}
Render the "sections"
(i.e. display the delayed section in a parent view)
@Html.RenderDelayed(); // writes unnamed sections (#1 and #2, excluding #3)
@Html.RenderDelayed("when-i-call-you", false); // writes the specified block, and ignore the `isOnlyOne` setting so we can dump it again
@Html.RenderDelayed("when-i-call-you"); // render the specified block by name
@Html.RenderDelayed("when-i-call-you"); // since it was "popped" in the last call, won't render anything due to `isOnlyOne` provided in `Html.Delayed`
CODE
public static class HtmlRenderExtensions {
/// <summary>
/// Delegate script/resource/etc injection until the end of the page
/// <para>@via https://stackoverflow.com/a/14127332/1037948 and http://jadnb.wordpress.com/2011/02/16/rendering-scripts-from-partial-views-at-the-end-in-mvc/ </para>
/// </summary>
private class DelayedInjectionBlock : IDisposable {
/// <summary>
/// Unique internal storage key
/// </summary>
private const string CACHE_KEY = "DCCF8C78-2E36-4567-B0CF-FE052ACCE309"; // "DelayedInjectionBlocks";
/// <summary>
/// Internal storage identifier for remembering unique/isOnlyOne items
/// </summary>
private const string UNIQUE_IDENTIFIER_KEY = CACHE_KEY;
/// <summary>
/// What to use as internal storage identifier if no identifier provided (since we can't use null as key)
/// </summary>
private const string EMPTY_IDENTIFIER = "";
/// <summary>
/// Retrieve a context-aware list of cached output delegates from the given helper; uses the helper's context rather than singleton HttpContext.Current.Items
/// </summary>
/// <param name="helper">the helper from which we use the context</param>
/// <param name="identifier">optional unique sub-identifier for a given injection block</param>
/// <returns>list of delayed-execution callbacks to render internal content</returns>
public static Queue<string> GetQueue(HtmlHelper helper, string identifier = null) {
return _GetOrSet(helper, new Queue<string>(), identifier ?? EMPTY_IDENTIFIER);
}
/// <summary>
/// Retrieve a context-aware list of cached output delegates from the given helper; uses the helper's context rather than singleton HttpContext.Current.Items
/// </summary>
/// <param name="helper">the helper from which we use the context</param>
/// <param name="defaultValue">the default value to return if the cached item isn't found or isn't the expected type; can also be used to set with an arbitrary value</param>
/// <param name="identifier">optional unique sub-identifier for a given injection block</param>
/// <returns>list of delayed-execution callbacks to render internal content</returns>
private static T _GetOrSet<T>(HtmlHelper helper, T defaultValue, string identifier = EMPTY_IDENTIFIER) where T : class {
var storage = GetStorage(helper);
// return the stored item, or set it if it does not exist
return (T) (storage.ContainsKey(identifier) ? storage[identifier] : (storage[identifier] = defaultValue));
}
/// <summary>
/// Get the storage, but if it doesn't exist or isn't the expected type, then create a new "bucket"
/// </summary>
/// <param name="helper"></param>
/// <returns></returns>
public static Dictionary<string, object> GetStorage(HtmlHelper helper) {
var storage = helper.ViewContext.HttpContext.Items[CACHE_KEY] as Dictionary<string, object>;
if (storage == null) helper.ViewContext.HttpContext.Items[CACHE_KEY] = (storage = new Dictionary<string, object>());
return storage;
}
private readonly HtmlHelper helper;
private readonly string identifier;
private readonly string isOnlyOne;
/// <summary>
/// Create a new using block from the given helper (used for trapping appropriate context)
/// </summary>
/// <param name="helper">the helper from which we use the context</param>
/// <param name="identifier">optional unique identifier to specify one or many injection blocks</param>
/// <param name="isOnlyOne">extra identifier used to ensure that this item is only added once; if provided, content should only appear once in the page (i.e. only the first block called for this identifier is used)</param>
public DelayedInjectionBlock(HtmlHelper helper, string identifier = null, string isOnlyOne = null) {
this.helper = helper;
// start a new writing context
((WebViewPage)this.helper.ViewDataContainer).OutputStack.Push(new StringWriter());
this.identifier = identifier ?? EMPTY_IDENTIFIER;
this.isOnlyOne = isOnlyOne;
}
/// <summary>
/// Append the internal content to the context's cached list of output delegates
/// </summary>
public void Dispose() {
// render the internal content of the injection block helper
// make sure to pop from the stack rather than just render from the Writer
// so it will remove it from regular rendering
var content = ((WebViewPage)this.helper.ViewDataContainer).OutputStack;
var renderedContent = content.Count == 0 ? string.Empty : content.Pop().ToString();
// if we only want one, remove the existing
var queue = GetQueue(this.helper, this.identifier);
// get the index of the existing item from the alternate storage
var existingIdentifiers = _GetOrSet(this.helper, new Dictionary<string, int>(), UNIQUE_IDENTIFIER_KEY);
// only save the result if this isn't meant to be unique, or
// if it's supposed to be unique and we haven't encountered this identifier before
if( null == this.isOnlyOne || !existingIdentifiers.ContainsKey(this.isOnlyOne) ) {
// remove the new writing context we created for this block
// and save the output to the queue for later
queue.Enqueue(renderedContent);
// only remember this if supposed to
if(null != this.isOnlyOne) existingIdentifiers[this.isOnlyOne] = queue.Count; // save the index, so we could remove it directly (if we want to use the last instance of the block rather than the first)
}
}
}
/// <summary>
/// <para>Start a delayed-execution block of output -- this will be rendered/printed on the next call to <see cref="RenderDelayed"/>.</para>
/// <para>
/// <example>
/// Print once in "default block" (usually rendered at end via <code>@Html.RenderDelayed()</code>). Code:
/// <code>
/// @using (Html.Delayed()) {
/// <b>show at later</b>
/// <span>@Model.Name</span>
/// etc
/// }
/// </code>
/// </example>
/// </para>
/// <para>
/// <example>
/// Print once (i.e. if within a looped partial), using identified block via <code>@Html.RenderDelayed("one-time")</code>. Code:
/// <code>
/// @using (Html.Delayed("one-time", isOnlyOne: "one-time")) {
/// <b>show me once</b>
/// <span>@Model.First().Value</span>
/// }
/// </code>
/// </example>
/// </para>
/// </summary>
/// <param name="helper">the helper from which we use the context</param>
/// <param name="injectionBlockId">optional unique identifier to specify one or many injection blocks</param>
/// <param name="isOnlyOne">extra identifier used to ensure that this item is only added once; if provided, content should only appear once in the page (i.e. only the first block called for this identifier is used)</param>
/// <returns>using block to wrap delayed output</returns>
public static IDisposable Delayed(this HtmlHelper helper, string injectionBlockId = null, string isOnlyOne = null) {
return new DelayedInjectionBlock(helper, injectionBlockId, isOnlyOne);
}
/// <summary>
/// Render all queued output blocks injected via <see cref="Delayed"/>.
/// <para>
/// <example>
/// Print all delayed blocks using default identifier (i.e. not provided)
/// <code>
/// @using (Html.Delayed()) {
/// <b>show me later</b>
/// <span>@Model.Name</span>
/// etc
/// }
/// </code>
/// -- then later --
/// <code>
/// @using (Html.Delayed()) {
/// <b>more for later</b>
/// etc
/// }
/// </code>
/// -- then later --
/// <code>
/// @Html.RenderDelayed() // will print both delayed blocks
/// </code>
/// </example>
/// </para>
/// <para>
/// <example>
/// Allow multiple repetitions of rendered blocks, using same <code>@Html.Delayed()...</code> as before. Code:
/// <code>
/// @Html.RenderDelayed(removeAfterRendering: false); /* will print */
/// @Html.RenderDelayed() /* will print again because not removed before */
/// </code>
/// </example>
/// </para>
/// </summary>
/// <param name="helper">the helper from which we use the context</param>
/// <param name="injectionBlockId">optional unique identifier to specify one or many injection blocks</param>
/// <param name="removeAfterRendering">only render this once</param>
/// <returns>rendered output content</returns>
public static MvcHtmlString RenderDelayed(this HtmlHelper helper, string injectionBlockId = null, bool removeAfterRendering = true) {
var stack = DelayedInjectionBlock.GetQueue(helper, injectionBlockId);
if( removeAfterRendering ) {
var sb = new StringBuilder(
#if DEBUG
string.Format("<!-- delayed-block: {0} -->", injectionBlockId)
#endif
);
// .count faster than .any
while (stack.Count > 0) {
sb.AppendLine(stack.Dequeue());
}
return MvcHtmlString.Create(sb.ToString());
}
return MvcHtmlString.Create(
#if DEBUG
string.Format("<!-- delayed-block: {0} -->", injectionBlockId) +
#endif
string.Join(Environment.NewLine, stack));
}
}
A: This worked for me allowing me to co-locate javascript and html for partial view in same file. Helps with thought process to see html and related part in same partial view file.
In View which uses Partial View called "_MyPartialView.cshtml"
<div>
@Html.Partial("_MyPartialView",< model for partial view>,
new ViewDataDictionary { { "Region", "HTMLSection" } } })
</div>
@section scripts{
@Html.Partial("_MyPartialView",<model for partial view>,
new ViewDataDictionary { { "Region", "ScriptSection" } })
}
In Partial View file
@model SomeType
@{
var region = ViewData["Region"] as string;
}
@if (region == "HTMLSection")
{
}
@if (region == "ScriptSection")
{
<script type="text/javascript">
</script">
}
A: Sections don't work in partial views and that's by design. You may use some custom helpers to achieve similar behavior, but honestly it's the view's responsibility to include the necessary scripts, not the partial's responsibility. I would recommend using the @scripts section of the main view to do that and not have the partials worry about scripts.
A: The first solution I can think of, is to use ViewBag to store the values that must be rendered.
Onestly I never tried if this work from a partial view, but it should imo.
A: You can't need using sections in partial view.
Include in your Partial View.
It execute the function after jQuery loaded.
You can alter de condition clause for your code.
<script type="text/javascript">
var time = setInterval(function () {
if (window.jQuery != undefined) {
window.clearInterval(time);
//Begin
$(document).ready(function () {
//....
});
//End
};
}, 10); </script>
Julio Spader
A: You can use these Extension Methods: (Save as PartialWithScript.cs)
namespace System.Web.Mvc.Html
{
public static class PartialWithScript
{
public static void RenderPartialWithScript(this HtmlHelper htmlHelper, string partialViewName)
{
if (htmlHelper.ViewBag.ScriptPartials == null)
{
htmlHelper.ViewBag.ScriptPartials = new List<string>();
}
if (!htmlHelper.ViewBag.ScriptPartials.Contains(partialViewName))
{
htmlHelper.ViewBag.ScriptPartials.Add(partialViewName);
}
htmlHelper.ViewBag.ScriptPartialHtml = true;
htmlHelper.RenderPartial(partialViewName);
}
public static void RenderPartialScripts(this HtmlHelper htmlHelper)
{
if (htmlHelper.ViewBag.ScriptPartials != null)
{
htmlHelper.ViewBag.ScriptPartialHtml = false;
foreach (string partial in htmlHelper.ViewBag.ScriptPartials)
{
htmlHelper.RenderPartial(partial);
}
}
}
}
}
Use like this:
Example partial: (_MyPartial.cshtml)
Put the html in the if, and the js in the else.
@if (ViewBag.ScriptPartialHtml ?? true)
<p>I has htmls</p>
}
else {
<script type="text/javascript">
alert('I has javascripts');
</script>
}
In your _Layout.cshtml, or wherever you want the scripts from the partials on to be rendered, put the following (once): It will render only the javascript of all partials on the current page at this location.
@{ Html.RenderPartialScripts(); }
Then to use your partial, simply do this: It will render only the html at this location.
@{Html.RenderPartialWithScript("~/Views/MyController/_MyPartial.cshtml");}
A: Pluto's idea in a nicer way:
CustomWebViewPage.cs:
public abstract class CustomWebViewPage<TModel> : WebViewPage<TModel> {
public IHtmlString PartialWithScripts(string partialViewName, object model) {
return Html.Partial(partialViewName: partialViewName, model: model, viewData: new ViewDataDictionary { ["view"] = this, ["html"] = Html });
}
public void RenderScriptsInBasePage(HelperResult scripts) {
var parentView = ViewBag.view as WebPageBase;
var parentHtml = ViewBag.html as HtmlHelper;
parentView.DefineSection("scripts", () => {
parentHtml.ViewContext.Writer.Write(scripts.ToHtmlString());
});
}
}
Views\web.config:
<pages pageBaseType="Web.Helpers.CustomWebViewPage">
View:
@PartialWithScripts("_BackendSearchForm")
Partial (_BackendSearchForm.cshtml):
@{ RenderScriptsInBasePage(scripts()); }
@helper scripts() {
<script>
//code will be rendered in a "scripts" section of the Layout page
</script>
}
Layout page:
@RenderSection("scripts", required: false)
A: If you do have a legitimate need to run some js from a partial, here's how you could do it, jQuery is required:
<script type="text/javascript">
function scriptToExecute()
{
//The script you want to execute when page is ready.
}
function runWhenReady()
{
if (window.$)
scriptToExecute();
else
setTimeout(runWhenReady, 100);
}
runWhenReady();
</script>
A: The goal of the OP is that he wants to define inline scripts into his Partial View, which I assume that this script is specific only to that Partial View, and have that block included into his script section.
I get that he wants to have that Partial View to be self contained. The idea is similar to components when using Angular.
My way would be to just keep the scripts inside the Partial View as is. Now the problem with that is when calling Partial View, it may execute the script in there before all other scripts (which is typically added to the bottom of the layout page). In that case, you just have the Partial View script wait for the other scripts. There are several ways to do this. The simplest one, which I've used before, is using an event on body.
On my layout, I would have something on the bottom like this:
// global scripts
<script src="js/jquery.min.js"></script>
// view scripts
@RenderSection("scripts", false)
// then finally trigger partial view scripts
<script>
(function(){
document.querySelector('body').dispatchEvent(new Event('scriptsLoaded'));
})();
</script>
Then on my Partial View (at the bottom):
<script>
(function(){
document.querySelector('body').addEventListener('scriptsLoaded', function() {
// .. do your thing here
});
})();
</script>
Another solution is using a stack to push all your scripts, and call each one at the end. Other solution, as mentioned already, is RequireJS/AMD pattern, which works really well also.
A: There is a way to insert sections in partial views, though it's not pretty. You need to have access to two variables from the parent View. Since part of your partial view's very purpose is to create that section, it makes sense to require these variables.
Here's what it looks like to insert a section in the partial view:
@model KeyValuePair<WebPageBase, HtmlHelper>
@{
Model.Key.DefineSection("SectionNameGoesHere", () =>
{
Model.Value.ViewContext.Writer.Write("Test");
});
}
And in the page inserting the partial view...
@Html.Partial(new KeyValuePair<WebPageBase, HtmlHelper>(this, Html))
You can also use this technique to define the contents of a section programmatically in any class.
Enjoy!
A: Using Mvc Core you can create a tidy TagHelper scripts as seen below. This could easily be morphed into a section tag where you give it a name as well (or the name is taken from the derived type). Note that dependency injection needs to be setup for IHttpContextAccessor.
When adding scripts (e.g. in a partial)
<scripts>
<script type="text/javascript">
//anything here
</script>
</scripts>
When outputting the scripts (e.g. in a layout file)
<scripts render="true"></scripts>
Code
public class ScriptsTagHelper : TagHelper
{
private static readonly object ITEMSKEY = new Object();
private IDictionary<object, object> _items => _httpContextAccessor?.HttpContext?.Items;
private IHttpContextAccessor _httpContextAccessor;
public ScriptsTagHelper(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var attribute = (TagHelperAttribute)null;
context.AllAttributes.TryGetAttribute("render",out attribute);
var render = false;
if(attribute != null)
{
render = Convert.ToBoolean(attribute.Value.ToString());
}
if (render)
{
if (_items.ContainsKey(ITEMSKEY))
{
var scripts = _items[ITEMSKEY] as List<HtmlString>;
var content = String.Concat(scripts);
output.Content.SetHtmlContent(content);
}
}
else
{
List<HtmlString> list = null;
if (!_items.ContainsKey(ITEMSKEY))
{
list = new List<HtmlString>();
_items[ITEMSKEY] = list;
}
list = _items[ITEMSKEY] as List<HtmlString>;
var content = await output.GetChildContentAsync();
list.Add(new HtmlString(content.GetContent()));
}
}
}
A: I had this issue today. I'll add a workaround that uses <script defer> as I didn't see the other answers mention it.
//on a JS file somewhere (i.e partial-view-caller.js)
(() => <your partial view script>)();
//in your Partial View
<script src="~/partial-view-caller.js" defer></script>
//you can actually just straight call your partial view script living in an external file - I just prefer having an initialization method :)
Code above is an excerpt from a quick post I made about this question.
A: I solved this a completely different route (because I was in a hurry and didn't want to implement a new HtmlHelper):
I wrapped my Partial View in a big if-else statement:
@if ((bool)ViewData["ShouldRenderScripts"] == true){
// Scripts
}else{
// Html
}
Then, I called the Partial twice with a custom ViewData:
@Html.Partial("MyPartialView", Model,
new ViewDataDictionary { { "ShouldRenderScripts", false } })
@section scripts{
@Html.Partial("MyPartialView", Model,
new ViewDataDictionary { { "ShouldRenderScripts", true } })
}
A: I had a similar problem, where I had a master page as follows:
@section Scripts {
<script>
$(document).ready(function () {
...
});
</script>
}
...
@Html.Partial("_Charts", Model)
but the partial view depended on some JavaScript in the Scripts section. I solved it by encoding the partial view as JSON, loading it into a JavaScript variable and then using this to populate a div, so:
@{
var partial = Html.Raw(Json.Encode(new { html = Html.Partial("_Charts", Model).ToString() }));
}
@section Scripts {
<script>
$(document).ready(function () {
...
var partial = @partial;
$('#partial').html(partial.html);
});
</script>
}
<div id="partial"></div>
A: choicely, you could use a your Folder/index.cshtml as a masterpage then add section scripts. Then, in your layout you have:
@RenderSection("scripts", required: false)
and your index.cshtml:
@section scripts{
@Scripts.Render("~/Scripts/file.js")
}
and it will working over all your partialviews. It work for me
A: My solution was to load the script from the layout page. Then in the javacript, check for the presence of one of the elements in the parial view. If the element was present, the javascript knew that the partial had been included.
$(document).ready(function () {
var joinButton = $("#join");
if (joinButton.length != 0) {
// the partial is present
// execute the relevant code
}
});
A: I had the similar problem solved it with this:
@section ***{
@RenderSection("****", required: false)
}
Thats a pretty way to inject i guesse.
A: I have just added this code on my partial view and solved the problem, though not very clean, it works. You have to make sure the the Ids of the objects you are rendering.
<script>
$(document).ready(function () {
$("#Profile_ProfileID").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
$("#TitleID_FK").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
$("#CityID_FK").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
$("#GenderID_FK").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
$("#PackageID_FK").selectmenu({ icons: { button: 'ui-icon-circle-arrow-s' } });
});
</script>
A: assume you have a partial view called _contact.cshtml, your contact can be a legal (name) or a physical subject (first name, lastname). your view should take care about what's rendered and that can be achived with javascript. so delayed rendering and JS inside view may be needed.
the only way i think, how it can be ommitted, is when we create an unobtrusive way of handling such UI concerns.
also note that MVC 6 will have a so called View Component, even MVC futures had some similar stuff and Telerik also supports such a thing...
A: Well, I guess the other posters have provided you with a means to directly include an @section within your partial (by using 3rd party html helpers).
But, I reckon that, if your script is tightly coupled to your partial, just put your javascript directly inside an inline <script> tag within your partial and be done with it (just be careful of script duplication if you intend on using the partial more than once in a single view);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "369"
}
|
Q: JNA: Read Data back from memory to Structure I want to estimate deviceinformations of a printer with JNA.
interface GDI32Ext extends GDI32
{
public static class DEVICEMODE extends Structure
{
public static class ByReference extends DEVICEMODE
implements Structure.ByReference
{
public ByReference()
{
}
public ByReference( Pointer memory )
{
super( memory );
}
}
public DEVICEMODE()
{
}
public DEVICEMODE( int size )
{
super( new Memory( size ) );
}
public DEVICEMODE( Pointer memory )
{
useMemory( memory);
read();
}
public char[] dmDeviceName = new char[32];
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public short dmOrientation = 0;
public short dmPaperSize = 0;
public short dmPaperLength = 0;
public short dmPaperWidth = 0;
public short dmScale = 0;
public short dmCopies = 0;
public short dmDefaultScore = 0;
public short dmPrintQuality = 0;
public short dmColor = 0;
public short dmDuplex = 0;
public short dmYResolution = 0;
public short dmTTOption = 0;
public short dmCollate = 0;
public char[] dmFormName = new char[32];
public WORD dmLogPixels;
public int dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmNup;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
@Override
public String toString()
{
return "DEVICEMODE: dmDeviceName <" +this.dmDeviceName
+"> dmSpecVersion <" +this.dmSpecVersion
....
+"> dmPanningWidth <" +this.dmPanningWidth
+"> dmPanningHeight <" +this.dmPanningHeight
+">\nBytes (" +this.size() +")";
}
}
Execution:
GDI32Ext.DEVICEMODE devMode = new GDI32Ext.DEVICEMODE( (int) dwNeeded );
long dwResult = WinspoolExt.INSTANCE.DocumentProperties( null,
handle, new WString( printerName ), devMode.getPointer(), null,
GDI32Ext.DEFINES.DM_OUT_BUFFER );
debugToFile( "DEVICEMODE.txt", devMode.getPointer().getByteArray( 0, (int) dwNeeded ) );
System.out.println( devMode );
The problem is that the dumped bytes in the File has data, but if i access the devMode-Object, i can see that i dont get valid data.
DEVICEMODE: dmDeviceName <null> dmSpecVersion <0> dmDriverVersion <0> dmSize <0> dmFields <0> dmOrientation <0> dmPaperSize <0> dmPaperLength <0> dmPaperWidth <0> dmScale <0> dmCopies <0> dmDefaultScore <0> dmPrintQuality <0> dmColor <0> dmDuplex <0> dmColor <0> dmYResolution <0> dmTTOption <0> dmCollate <0> dmFormName <null> dmLogPixels <0> dmBitsPerPel <0> dmPelsWidth <0> dmPelsHeight <0> dmNup<0> dmDisplayFrequency <0> dmICMMethod <0> dmICMIntent <0> dmMediaType <0> dmDitherType <0> dmReserved1 <0> dmReserved2 <0> dmPanningWidth <0> dmPanningHeight <0>
How works the coversion from bytedata into a Structure-Object?
UPDATE:
After adding
devMode.read();
i get data back in my Java-Structure Object.
But now i have the Problem, that changes where not "active".
After writing with "DM_IN_BUFFER" and reading again the values had not changed!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Difference between servlet/servlet-mapping and filter/filter-mapping? As part of exploring/learning Struts2, JSP and Servlets, I see from here and there that servlets and servlets-mapping can be used in web.xml. However, Struts2 mentions filters and filter-mapping too for web.xml.
What is the difference between both? Are these mutually exclusive? When should I use which and why? Can someone clarify the concepts? Thanks.
CLARIFICATION
I just got to understand that I needed to understand how Struts2 and Servlets are related: http://www.coderanch.com/t/57899/Struts/Difference-between-servlet-struts
A: Filters are used like Servlet Filters. For example, if you need to do security checks on certain URLs then you can add a filter for those pages. For instance, you can say /secure/pages/*.do needs to be intercepted by securityFilter. Then the doFilter() method of the SecurityFilter class (a class that implements the Filter interface) will handle the security audit before forwarding it to the actual requesting servlet.
Servlets are pretty much the standard stuff. You define a servlet and then let the servlet container know what type of requests needs to be mapped to that servlet.
They are not mutually exclusive. They both can be used at the same time. Think of filter like the way the word means - it "filters" things (logging, security,etc) before proceeding to the next servlet/action.
A: The request lifecycle according to the servlet specification goes through a chain of filters before finally being executed by a servlet.
This is fairly intuitive when you look at the signature for the doFilter method in the Filter interface
doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
That is, in the filter you have access to the request and response and the chain. The contract is that you, as implementer, should invoke the chain either before or after the operations you do in the filter, or not at all if it is desired to not continue execution. Calling chain.doFilter(...) will cause the next filter in the chain of filters with a mapping matching the requested URL to be executed. The final member of the chain is the servlet whose mapping matches the requested URL.
Technically, you can do everything in a filter that you can do in a servlet. You can build your application to do all processing and rendering in a filter and have a blank servlet that does nothing. The main difference is that if there is no servlet mapped against a given URL, the container must respond with a 404 error so there must always be a servlet mapped against any URL you want to serve. You can also only have one servlet mapped against a URL, but you can have any number of filters.
A: Servlet filters implement intercepting filter pattern. While servlet is the ultimate target of web request, each request goes through a series of filters. Every filter can modify the request before passing it further or response after receiving it back from the servlet. It can even abstain from passing the request further and handle it completely just like servlet (not uncommon). For instance caching filter can return result without calling the actual servlet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Partitioning by Year vs. separate tables named Data_2011, Data_2010, etc We are designing a high volume SQL Server application that involves processing and reporting on data that is restricted within a specified year.
Using Partitioning by year comes to mind.
Another suggestion is to programmatically create separate physical table where the suffix of the name is the year and, when reporting is needed across years, to provide a view which is the union of the physical tables.
My gut tells me that this situation is what partitioning is design to handle. Are there any advantages to using the other approach?
A: From an internals perspective, the methods are essentially the same.
Behind the scenes, when you create a date-based partition the SQL engine creates separate physical tables for each partition, then does what is basically a UNION when you query the table itself.
If you use a filter in your query on the partitioned table that corresponds to your partitioning field (DateField let's say), then the engine can go directly to the partition that you need for the data. If not, then it searches each physical table in the logical table as needed to complete the query.
If your queries will involve a date filter (which it sounds like they will from your question) then I can think of no advantage to your "custom" method.
Essentially, the choice you need to make is do you want to be responsible for all the logic and corner cases involved in partitioning, or trust the developers at Microsoft who have been doing this for decades to do it for you?
For my own purposes, if there is a built-in framework for something I want to do then I always try to use it. It is invariably faster, more stable, and less error-prone than a "roll-your-own" solution.
A: Both of the solutions means that you have to do some metadata operations in the db. The question is whether you will do some changes/updates in the historical data? I was working on similar solution - bud instead of a year we were working a half year of the data. In this case we used partitioning by date - we have half year floating window keeping 2 years of historical data + current half year (HTD) in 10 partitions(each partition represents a separate quarter). We were updating the HTD data every day and once a week we were restating some of the historical data. In this case we were hitting only few partitions (the partition id was defined in where clause, the partitioning key was a date_id representing the calendar date in one of our dimensions). The whole table had about 250M of rows. Every half year the process is adjusting the partitioning, but the same you will have to do with the view. Using this approach we can always execute an update against the whole table (using the view you will have to test the the update scenario or run the update against separate tables). We have procedures in place which can truncate / switch out a specified partition of the table so the manipulation is quick.
It is difficult to say which is the best option. But in general I would suggest to use the tables in the case that you really are not changing the history (I would go for 1 partitioned table for history and 1 table for current data)
A: I feel using partitioning with a date driven paritioning key is like using a hammer to drive in a screw...'that must have been why they invented the hammer'...Partitioning is good when you need parallel processes to run as in data marts or you partition on some arbitrary key e.g. and identity column. In your case, the business requirement is simply to keep multiple years of history. In order to use partitioning, the app team would need to create a routine that dynamically generates the partitioning constraint, which is DDL and is the responsibility of the DBA team. The multi-table/union view provides a much simpler soluiton.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Random NSNumber from array I'm trying to make an IBAction pick a random float from an NSMutableArray (10.00, 2.56, 4.25, 1.95).
Here's what I tried:
In the viewDidLoad:
NSMutableArray *numberPicker = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:10.00],
[NSNumber numberWithFloat:2.56],
[NSNumber numberWithFloat:4.25],
[NSNumber numberWithFloat:1.95],
nil];
In the IBAction:
-(IBAction)buttonPressed: (id)sender{
result = [numberPicker objectAtIndex:arc4random() % [numberPicker count])];
Obviously this isn't working, i get an error "Assigning to 'float' from incompatible type 'id'".
Any ideas how to get one of the numbers into "result"?
A: You just change one line to:
result = [[numberPicker objectAtIndex:arc4random() % [numberPicker count])] floatValue];
A: You could write a method randomElement in a category on NSArray
#import "NSArray+RandomUtils.h"
@implementation NSArray (RandomUtils)
-(id)randomElement
{
if ([self count] < 1) return nil;
NSUInteger randomIndex = arc4random() % [self count];
return [self objectAtIndex:randomIndex];
}
@end
or just use the one, I wrote.
You will use it like this:
*
*#import "NSArray+RandomUtils.h"
*Use a property numberPicker @property (retain) NSArray *numberPicker
*viewDidLoad:
self.numberPicker = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:10.00],
[NSNumber numberWithFloat:2.56],
[NSNumber numberWithFloat:4.25],
[NSNumber numberWithFloat:1.95],
nil];
*in your buttonPressed: use
result = [(NSNumber *)[self.numberPicker randomElement] floatValue];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Reopen SQLiteOpenHelper when my application is stopped as "close()" was never explicitly called on database" I'm using the SQLiteOpenHelper. When my application is normally closed, the database is closed normally in the method onDestroy(), too. When it's force closed, the database is left open and later, when my application tries to read the database using getReadableDatabase(), it crashed with the following message:
09-26 13:45:30.995: ERROR/Database(12632): close() was never explicitly called on database
Here is the full LogCat:
09-27 03:10:04.331: ERROR/Database(391): close() was never explicitly called on database '/data/data/myApplication/databases/DownloadDatabase1'
09-27 03:10:04.331: ERROR/Database(391): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
09-27 03:10:04.331: ERROR/Database(391): at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1847)
09-27 03:10:04.331: ERROR/Database(391): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:820)
09-27 03:10:04.331: ERROR/Database(391): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:854)
09-27 03:10:04.331: ERROR/Database(391): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:847)
09-27 03:10:04.331: ERROR/Database(391): at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:544)
09-27 03:10:04.331: ERROR/Database(391): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203)
09-27 03:10:04.331: ERROR/Database(391): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:118)
09-27 03:10:04.331: ERROR/Database(391): at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
I followed the stack trace and I guess the exception is because of the following line of code:
setLocale(Locale.getDefault());
Th code above is from the file SQLiteDatabase.java. Any suggestions on how to solve this problem?
A: Even though it gives that error, you should be able to access the database. Looking at the underlying code, my understanding is that such an error shouldn't cause your program to exit:
http://hi-android.info/src/android/database/sqlite/SQLiteDatabase.java.html
Check the finalize() method there. You will see, it just tries to clean up, it doesn't throw exception.
You must have a problem somewhere else.
A: I would recommend closing the database as soon as you are done working with it. Opening and closing the database each time you need to preform a transaction is not a bad idea either. Unless your application is constantly writing data, you shouldn't lose performance
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: run WebClient.DownloadStringCompleted before loading MainPage_Loaded in silverlight I want to load this event handler before MainPage_Loaded
WebClient wc = new WebClient();
wc.DownloadStringCompleted += new
DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri("./ImageList.xml", UriKind.Relative));
void wc_DownloadStringCompleted(object sender,
System.Net.DownloadStringCompletedEventArgs e){.....}
A: I think this was the question
I want to "load some resources" "Asynchronously" before loading the MainPage!
WebClient wc = new WebClient();
wc.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
wc.DownloadStringAsync(new Uri("./ImageList.xml", UriKind.Relative));
void wc_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e){.....}
Answer
If it is the main page of your application so you can add this code to "app.xaml.cs" in Application_Startup event handler. note that since you are loading the resource asynchronously then you should load the main page in your event handler not Application_Startup unless you don’t care if the Main page got loaded before completion of the resource loading process.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SCALA Lift MongoDB MongoRecord compilation errors I'm attempting to setup a simple DB for the Scala Lift (2.4) framework
Below is my User.scala model.
package code.model
import net.liftweb.mongodb._
import net.liftweb.json.JsonDSL._
import com.mongodb._
class User private() extends MongoRecord[User] with ObjectIdPk[User] {
def meta = User
object name extends StringField(this, 50)
object level extends IntField(this)
}
object User extends User with MongoMetaRecord[User]
When compiling I get 7 errors, but think they are all related to this first one:
[error] C:\Lift2.4\scala_29\conference\src\main\scala\code\model\User.scala:7:
not found: type MongoRecord
Any help is much appreciated, I'm sure I'm not importing something right or have missed something obvious.
Thanks in advance
A: add
import net.liftweb.mongodb.record._
import net.liftweb.mongodb.record.field._
import net.liftweb.record.field._
import net.liftweb.record._
example of model
https://github.com/foursquare/rogue/blob/master/src/test/scala/com/foursquare/rogue/QueryTest.scala
For queries, you can use Rogue: A Type-Safe Scala DSL for querying MongoDB
A: import net.liftweb.mongodb.record._
A: MongoRecord (and MongoMetaRecord) is in net.liftweb.mongodb.record, so you’ll have to add
import net.liftweb.mongodb.record._
and of course take care that these are included with sbt.
A: Have a look at https://github.com/rohit-tingendab/ks-lift, it is a working kick starter for Lift + MongoDB.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make binding between XElement and ListBox ? I hold XElement - that appear as this
<Root>
<child1>1</child1>
<child2>2</child2>
<child3>3</child3>
<child4>4</child4>
</Root>
I want to show this Element + value on some ListBox.
So i define this xaml - but nothing work ...
How can i do it right ?
<ListBox ItemsSource="{Binding XMLProperty}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*.5" />
<ColumnDefinition Width="*.5" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Element}" />
<TextBlock Grid.Column="1" Text="{Binding Value }" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
A: An XElement does not have a IEnumerable interface through which to list its child elements. In order to enumerate the elements you need to call the Elements() method. To assist you could create a value converter:-
public class ElementConverter : IValueConverter
{
public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
XElement source = value as XElement;
if (source != null)
{
return source.Elements();
}
return null;
}
public override object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Now your Xaml should look like:-
<Grid.Resources>
<local:ElementConverter x:Key="conv" />
</Grid.Resources>
...
<ListBox ItemsSource="{Binding XMLProperty, Converter={StaticResources conv}}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Name.LocalName}" />
<TextBlock Grid.Column="1" Text="{Binding Value }" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: NSpredicate with round function I need to use NSPredicate with a round function.
e.g. :
Child* child1 = [self myFirstChild];
NSPredicate *predicate = [NSPredicate predicateWithString:@"round(SELF.age) > 12"];
BOOL twelveOrAlmostTwelve = [predicate evaluateWithObject:child1];
There is no such function in documentation:
http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Predicates.pdf
Any ideas?
Thanks
A: You can use your own defined function in extensions class.
IE:
[NSPredicate predicateWithFormat:@"FUNCTION('12.12345','round:',3) = 12.123"]
and you need to define this method in your category for ie. NSString:
-(NSNumber*) round:(NSString*) precision;
look at the page:
http://funwithobjc.tumblr.com/post/2922267976/using-custom-functions-with-nsexpression
A: You cannot generate arbitrary predicate functions. In this case, however, the answer is trivial:
NSPredicate *predicate = [NSPredicate predicateWithString:@"SELF.age >= 11.5"];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to: Save position/order of UITabBarItems after the have been reordered Okay, I have searched around for a answer to this question and so far come up with none.
Heres my question: I am using the default TabBarApplication provided by Apple. And since I have created 10 tabs it is using the default reordering process. So after I reorder the tabs and quit the app I want to save the position of the tabs to be restored when the app relaunches. How would I do this? Code samples appreciated!
A: The tabItems are stored in an array. You could do something like this (pseudo-code):
* myArray = [tabBar tabBarItems];
* itemNameArray = [[NSMutableArray new] autorelease];
* for (UITabBarItem *item in myArray)
* NSString *itemName = [item title];
* [itemNameArray addObject: itemName];
* [[NSUserDefaults standardUserDefaults] setObject: itemNameArray forKey: @"TabItemNames"]
Then, at app restart, load the array and set-up the tab items in the right order.
A: I found this a little confusing as well. Hopefully my research will help others out...
I think the confusion comes from the fact that UITabBar.items returns an array of just the 4 items visible in the current tabBar. When apple says that you shouldn't mess with the tabBar object, this is what they mean.
The way you read the order of items (and update the order of items) is through the viewControllers parameter of the UITabBarController.
So code would look something like (this is in a class which overrides UITabBarController):
- (UIViewController *)vcWithTabBarTitle:(NSString *)name
{
NSLog(@"looking for UIViewController with tabBarItem.title = %@", name);
for (UIViewController *item in self.viewControllers)
{
if ([item.tabBarItem.title isEqualToString:name])
return item;
}
return nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSArray *itemNames = [userDefaults objectForKey:@"viewControllersOrder"]
if (itemNames != nil && itemNames.count > 0)
{
NSMutableArray *items = [NSMutableArray arrayWithCapacity:self.viewControllers.count];
for (NSString *itemName in itemNames)
{
[items addObject:[self vcWithTabBarTitle:itemName]];
}
[self setViewControllers:items];
}
}
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray *)viewControllers changed:(BOOL)changed
{
if (changed)
{
NSMutableArray *itemNames = [[NSMutableArray alloc] initWithCapacity:viewControllers.count];
for (UIViewController *item in viewControllers)
{
if (item.tabBarItem.title != nil)
{
[itemNames addObject:item.tabBarItem.title];
}
}
[userDefaults setObject:itemNames forKey:@"viewControllersOrder"];
}
}
A: I know this is an old question, but I felt like posting this as it's what I found when looking up how to do this.
So the other answers (as of me writing this) are not incorrect. However they will break instantly when you introduce localisation or have a navigation item that changes it's title dynamically, both of which are very possible.
I ended up using the restoreIdentifier that you can either set in code or in IB to any view controller (or subclass there of).
NOTE: This is implemented within a subclass of UITabBarController.
Save Tab Bar View Controllers order
NSMutableArray *tabBarVCIDs = [NSMutableArray new];
for (UIViewController *viewController in [self viewControllers])
[tabBarVCIDs addObject:[viewController rootRestorationIdentifier]];
[[NSUserDefaults standardUserDefaults] setObject:tabBarVCIDs forKey:@"tabBarVCIDs"];
[[NSUserDefaults standardUserDefaults] synchronize];
Load Tab Bar Items Order
NSMutableArray *tabBarVCIDs = [[NSUserDefaults standardUserDefaults] objectForKey:@"tabBarVCIDs"];
if (tabBarVCIDs)
{
NSMutableArray *viewControllers = [NSMutableArray new];
for (NSString *vcID in tabBarVCIDs)
{
for (UIViewController *viewController in [self viewControllers])
{
if ([[viewController rootRestorationIdentifier] isEqualToString:vcID])
{
[viewControllers addObject:viewController];
break;
}
}
}
[self setViewControllers:viewControllers];
}
rootRestorationIdentifier is a method I put into a category to get the correct restoration identifier even when a view controller is within a navigation controller or split view controller (this is useful with universal apps that might have slightly different layouts).
- (NSString *)rootRestorationIdentifier
{
if ([self isKindOfClass:[UINavigationController class]] || [self isKindOfClass:[UISplitViewController class]])
{
__weak UIViewController *rootVC = [[(UINavigationController *)self viewControllers] firstObject];
return [rootVC rootRestorationIdentifier];
}
return [self restorationIdentifier];
}
You could also use NSPredicate instead of nested for loops, but it's probably not necessary.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Select a value in a language if in another is empty I have a table with key_id, id, text, lang.
I need to retrieve all the text fields (so without limit) in the table in a language (eg. DE), but if in this language the field is empty, I need to retrieve it in English.
Example:
key_id, id text lang
1 1 hi en
2 1 Guten Tag de
3 2 nothing en
4 2 '' de
I need to have as result, searching with language DE:
Guten
nothing -> this is because in deutsch it's empty...
How can I?
A: Your question doesnt make the table structure completely clear so it is hard to write the Sql for you. However, I think what you want to do is select both the default(en) value of the word, AND the current(de) version. It is then a simple matter to supply the chosen value.
select ifnull(de.text, en.text)
from
words de
join words en on
en.id = de.id and
en.lang = 'en'
where de.lang = 'de'
A: You can make use of mysql's non-standard group-by-without-aggregate functionality, which instead of grouping by, it selects the first row for each value in the group by. The inner query first orders the data such that the rows are ordered by language preference for each id.
select * from (
select id, text, lang
from lang_table
order by id, field(lang, 'de', 'en') -- this provides the custom ordering preference. you can add more languages as you like
) x
group by id; -- this captures the first (preferred language) row for each id
A: first i would have separate table for translations like
[t] id text
[t_translation] id language text
select coalesce(t_translation.text, t.text) as translated_text
from t left join t_translation on t.id=t_translation.id where language = 'de'
this way you have fallback if there is no record with 'de' language
(the query is not complete but you get the idea)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can i put part of a div inserted in a div outside? I have 3 divs like this image:
Two of those divs have the same width and height and the last one (red div) should go outside but not all, only a part (10%) I tried margin-left: -10px; but it didn't work.
Thanks.
A: Try using absolute positioning and assigning a z-index.
A: Please do not use absolute positioning when your problem does not require it.
Negative margin should be enough: http://jsfiddle.net/pmc7B/1/
A: You appear to have set overflow: hidden on one of the outer divs. That’s why the inner div is clipped when you apply the negative margin.
A: Give the parent <div> relative position:
<div style="position: relative;">
Then give the red <div> negative left value:
<div style="position: absolute; left: -20px;">
A: I think I see what your trying to do. Have you considered giving the red div a Z index of +1 so it float over the others and acts independantly of them
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Evaluation Order of Subscript Operator Does there exist any order for evaluation of expressions in case of an array.
If an expression E is of the form E1[E2], where E1 & E2 are also expressions, is the order of evaluation of E1 & E2 fixed ?
Here is my code :
#include<stdio.h>
int main(){
int a[5] = {1,2,3,4,5};
(a + printf("1"))[printf("2")];
(printf("3"))[a + printf("4")];
return 0;
}
It's showing output as:
1243
I'v compiled it with gcc.
Thanks.
A: E1[E2] is equivalent of *(E1 + E2).
And the Standard tells that "the order of evaluation of subexpressions and the order in which side effects take place are both unspecified". So, the order of evaluation of E1[E2] is not fixed.
A: N1256:
6.5 Expressions
...
3 The grouping of operators and operands is indicated by the syntax.74) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.
So the short answer is "no"; for an expression like E1[E2], the order in which the subexpressions E1 and E2 are evaluated is not fixed.
A: I hope you only ask this from curiosity and are not depending on this behaviour for something;
I don't have a C standard near me, but I don't see why you couldn't instead break up the operations into two separate statements, adding an explicit sequence point. You and other people might not remember what the correct order was supposed to be in the future, creating a maintenance issue.
int * the_array = E1;
the_array[E2];
//or
int the_index = E2;
E1[the_index];
//is much clearer
A: The evaluation order across the subscript operator is undefined. Let's give another example that isn't so obfuscated.
Issue: Consider the following expression:
f() + g() * h()
The precedence is quite clear; multiplication wins out over addition, as demonstrated by the corresponding parse tree:
+
/ \
/ \
f() *
/ \
/ \
g() h()
the precedence table only tells us how terms are grouped, not the order in which they are evaluated. The only way to make the order predictable is to introduce what the C Standard calls sequence points. For example, the steps:
x = g();
x = x * h();
x = x + f();
result in the same precedence as before, but with the functions being called in the guaranteed order g(), h(), and f().
So in your example, you have to introduce sequence points to ensure that your printf statements are executed in the desired order.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Finding new entries in a MySQL table Is it possible to find out if new entries where made into a MySQL table?
For example a table has 10 records and someone adds 2 new.
How do I write a php line to detect the new records (only) and insert them into another table?
Any help would be appreciated.
A: New is relative. So logically you need some anchor/baseline to determine what new means in your system.
A few ideas:
*
*table has a column 'processes' with a default value of 0, everything which has 0 is new
*table has some time entry, new is when it's younger than time t
*table has a relationship with that other table you mention, every entry in the first table that doesn't have an entry in the second table is new.
*new could also mean the last X autoincrement values.
So you see, in order to get a more precise answer you would need to give more information about what exactly it is that you want to achieve.
A: You would have to implement some sort of control mechanism for this, for example add a column to your table called (as a crude example) added_into_other_table. Then check in your query for all records that have a value of zero for added_into_other_table. Add only these to the new table, then update your original table to set added_into_other_table to 1 for all of the records you just processed so they won't be processed again.
A: You can use triggers to achive this.
http://dev.mysql.com/doc/refman/5.0/en/triggers.html
Syntax will be similar to this one:
CREATE TRIGGER ins_table AFTER INSERT ON first_table
FOR EACH ROW BEGIN
INSERT INTO second_table values(NEW.field1, NEW.field2,..., NEW.fieldn)
END;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NSManagedObject delete not working, can still retrieve the object I am trying to delete a managed object, is there something I am missing?
[managedObjectContext deleteObject:managedObject];
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
return NO;
}
return YES;
When I run this code the object can still be retrieved.
NSManagedObject *objectiveManagedObject = [managedObjectContext objectWithID:objectID];
return (ObjectiveManagedObject *)objectiveManagedObject;
A: What happens if you do
[[self managedObjectContext] setPropagatesDeletesAtEndOfEvent:NO]
first?
A: I note that you've switched between self.managedObjectContext and managedObjectContext. Are you certain these are the same variable? Avoid accessing your ivars directly; use accessors (except in init and dealloc). This avoids all kinds of problems.
Are you certain that managedObject has the ID objectID? They could be two objects that simply appear similar.
A: The context was not being saved properly
A: Given that the previous answers didn't check out, I would say the most likely explanation is that the managed object is the last object in a required relationship. As such, it cannot be deleted until the object on the other end of the relationship is deleted or a second object is added to the relationship.
You might also want to check that the persistent store isn't set to readonly. I don't remember what errors you get when you try to write a readonly store.
Also, you might want to wait a few seconds before testing for the object. Saves are disk operation and therefore relatively slow. It is possible that the save actually fails.
You should be trapping the error return from the save in any case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WPF UserControls interfere with each other Simply put: I have a UserControl that contains a DataGrid and some dependencyproperties to apply binding to the DataGrid.
Let's say I have 2 of these controls on a page. When I select a row in one control, this row is also selected in the other control! This is NOT something that I wish to happen.
Is this a typical WPF/.NET problem, or is it likely to be my mistake?
A: Answer to your question: No, it is not WPF problem, it is definitely your fault. You most likely have problem in the bindings or in the dependency property declarations.
If you want more detailed answer, you will have post more information, such as key parts of code behind and XAML.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Asp.net MVC - Map Claim identity to custom user identity I'm trying to figure where is the best extension point in the ASP.NET MVC3 infrastructure to map custom user informations (loaded from local database) after received the Claim Authentication from Azure AccessControl Service 2.0
I tried to achieved this by overriding the Authenticate method of Microsoft.IdentityModel.Claims.ClaimsAuthenticationManager class :
public class ClaimsTransformationModule : ClaimsAuthenticationManager
{
public override IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal)
{
// Load User from database and map it to HttpContext
// Code here
return base.Authenticate(resourceName, incomingPrincipal);
}
}
However, it seems that this method is called more than once during the page loading request.
Loading custom user informations here could produce a performance issue.
I would like to load them only once per authenticated session.
Is there a better place to do that ?
Perhaps somewhere at a lower level where the IClaimsPrincipal is constructed ?
A: You just need to do an isAuthenticated check:
if (incomingPrincipal.Identity.IsAuthenticated)
{
// Load User from database and map it to HttpContext
// Code here
}
This will only run once after the user is first authenticated.
A: This is only running once when the user is logging in.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
FederatedAuthentication.WSFederationAuthenticationModule.SecurityTokenValidated += WSFederationAuthenticationModule_SecurityTokenValidated;
}
void WSFederationAuthenticationModule_SecurityTokenValidated(object sender, SecurityTokenValidatedEventArgs e)
{
IClaimsPrincipal principal = e.ClaimsPrincipal;
IClaimsIdentity identity = (IClaimsIdentity)principal.Identity;
try
{
//SQL connection / Claims injeciotn
if (principal.Identity.IsAuthenticated)
{
// identity.Claims.Add(new Claim(ClaimTypes.Role, "WebAdmins"));
}
}
catch
{
//Error
}
}
}
A: Any user information which is not coming from the STS is satellite data about the user. So it would be best to represent this with Asp .Net ProfileProvider infrastructure.
Update:
Another thing which you can do is implemeting a simple Custom STS which will add your custom claims coming from your DB, into the incoming claims. Your Custom STS will trust ACS and will take SAML tokens, and it will be trusted by your web applition.
Another thing, which I haven't tried, would be attempting to tamper with the claims coming from STS. One thing which you can give a try is registering to the SecurityTokenValidated event of the WSFederationAuthenticationModule. In this event you can try to add your additional claims into ClaimsPrincipal of the event arg.
This event should be raised before the session token is created, so you sould be looking up db once per login.
cheers,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why ThreadPoolExecutor has BlockingQueue as its argument? I have tried creating and executing ThreadPoolExecutor with
int poolSize = 2;
int maxPoolSize = 3;
ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(2);
If i try 7th,8th... task continuously
threadPool.execute(task);
after the queue reached maximum size it is start throwing "RejectedExecutionException". Means i lost of adding those tasks.
Here then what is the role of BlockingQueue if it is missing the tasks? Means why it is not waiting?
From the definition of BlockingQueue
A Queue that additionally supports operations that wait for the queue
to become non-empty when retrieving an element, and wait for space to
become available in the queue when storing an element.
Why cant we go for linkedlist (normal queue implementation instead of blocking queue)?
A: You're not using BlockingQueue in the way it's intended to be used.
A BlockingQueue is used to implement the producer consumer pattern. Producer thread(s) put items on the queue via the blocking put() method, while consumer thread(s) take items from the queue via the blocking take() method.
put() blocks - meaning if the queue is full, it waits until a consumer has taken an item from the queue before adding it, then returns.
take() blocks - meaning if the queue is empty, it waits until a producer has put an item on the queue before taking it and returning it.
This pattern completely disconnects the producers from consumers, except that they share the queue.
Try using the queue like that: Have an executor run some threads that act as producers and some that act as consumers.
A: The problem occurs because you're task queue is too small and this is indicated by the documentation of the execute method:
Executes the given task sometime in the future. The task may execute in a new thread or in an existing pooled thread. If the task cannot be submitted for execution, either because this executor has been shutdown or because its capacity has been reached, the task is handled by the current RejectedExecutionHandler.
So the first problem is that you're setting your queue size to a very small number:
int poolSize = 2;
int maxPoolSize = 3;
ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(2);
And then you state "If [I] try 7th, 8th... task" then you would get a RejectedExecutionException because you're past the capacity of the queue. There are two ways to resolve your problem (I would recommend doing both):
*
*Increase the size of the queue.
*Catch the exception and re-try adding the task.
You should have something along the lines of this:
public void ExecuteTask(MyRunnableTask task) {
bool taskAdded = false;
while(!taskAdded) {
try {
executor.execute(task);
taskAdded = true;
} catch (RejectedExecutionException ex) {
taskAdded = false;
}
}
}
Now, to address your other questions...
Here then what is the role of BlockingQueue if it is missing the tasks?
The role of the BlockingQueue is to complete the Producer/Consumer pattern and if it's large enough, then you shouldn't see the issues you're encountering. As I mentioned above, you need to increase the queue size and catch the exception then retry executing the task.
Why cant we go for linkedlist?
A linked list is neither thread safe, nor is it blocking. The Producer/Consumer pattern tends to work best with a blocking queue.
Update
Please don't be offended by the following statements, I'm intentionally using more stringent language in order to put emphasis on the fact that your first assumption should never be that there is something wrong with the library you're using (unless you wrote the library yourself and you know that there is a specific problem in it)!
So let's put this concern to rest right now: neither the ThreadPoolExecutor nor the Java library are the problem here. It's entirely your (mis)use of the library that's causing the problem. Javmex has a great tutorial explaining the exact situation you're seeing.
There could be several reasons why you're filling up the queue faster than you're emptying it:
*
*The thread that's adding tasks for executing is adding them too fast.
*The tasks are taking too long to execute.
*Your queue is too small.
*Any combination of the above 3.
There are a bunch of other reasons too, but I think the above would be the most common.
I would give you a simple solution with an unbounded queue, but it would NOT resolve your (mis)use of the library. So before we go blaming the Java library, let's see a concise example that demonstrates the exact problem you're encountering.
Update 2.0
Here are a couple of other questions addressing the specific problem:
*
*ThreadPoolExecutor Block When Queue Is Full?
*How to make ThreadPoolExecutor's submit() method block if it is saturated?
A: The blocking queue is mainly for the Consumers (threads in the pool). The threads can wait for new tasks to become available on the queue, they will be automatically woken up. A plain linked list would not serve that purpose.
On the producer side the default behavior is to throw an exception in case the queue is full. This can be easily customized by implementing your own RejectedExceptionHandler. In your handler you can get hold of the queue and call the put method that will block till more space becomes available.
But this is not a good thing to do - the reason is that if there is a problem in this executor (deadlock , slow processing) it would cause a ripple effect on the rest of the system. For example if you are calling the execute method from a servlet - if the execute method blocks then all the containers threads will be held up and your application will come to a halt. That is probably the reason why the default behavior is to throw an exception and not to wait. Also there is no implementation of the RejectedExceptionHandler that does this - to discourage people from using it.
There is an option (CallersRunPolicy) to execute in the calling thread which can be another option if you want the processing to happen.
The general rule is - it is better to fail processing of one request, rather than bring the whole system down. You might want to read about the circuit-breaker pattern.
A:
The problem occurs because you're task queue is too small
IMHO this doesn't answers the OP question (although Kiril gives more detail after that) because the size of a queue being too small is totally subjective. For example he may be protecting an external resource that can't handle more than two concurrent requests (besides that I think 2 was for make a quick test). Also, what size we could say that is not to small? 1000? What if the execution tries to execute 5000 tasks? The scenario remains because the true question is why the procuder or caller thread is not being blocked if the ThreadPoolExecutor uses a LinkedBlockingQueue?
The role of the BlockingQueue is to complete the Producer/Consumer pattern and if it's large enough, then you shouldn't see the issues you're encountering. As I mentioned above, you need to increase the queue size and catch the exception then retry executing the task.
This is true if you know the maximum number of tasks that could be queued in runtime and you can allocate enough heap for that, but this isn't always the case. The benefit of using bounded queues is that you cant protect yourself against OutOfMemoryError.
The correct answer should be the one from @gkamal.
The blocking queue is mainly for the Consumers (threads in the pool). The threads can wait for new tasks to become available on the queue, they will be automatically woken up. A plain linked list would not serve that purpose.
My two cents:
Developers could have decided that consumer won't block neither and in that case a BlockingQueue will no longer needed (although you still need to use a concurrent collection or handle synchronization manually), but in this case when the worker tries to poll a task from a empty collection you must
*
*Kill the thread (an handle new task creating fresh threads), or
*Do a busy waiting wasting cpu
Since creating new threads is an expensive task (that is way we are using thread pools after all) and do a busy waiting to, the best option is to block that consumer and notify later when a task is available.
Actually, there is a special case where workers won't block (at least not indefinitely), when there are more threads than the configured corePoolSize.
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
We can see these two scenarios in ThreadPoolExecutor (java 1.8)
/**
* Performs blocking or timed wait for a task, depending on
* current configuration settings, or returns null if this worker
* must exit because of any of:
* 1. There are more than maximumPoolSize workers (due to
* a call to setMaximumPoolSize).
* 2. The pool is stopped.
* 3. The pool is shutdown and the queue is empty.
* 4. This worker timed out waiting for a task, and timed-out
* workers are subject to termination (that is,
* {@code allowCoreThreadTimeOut || workerCount > corePoolSize})
* both before and after the timed wait, and if the queue is
* non-empty, this worker is not the last thread in the pool.
*
* @return task, or null if the worker must exit, in which case
* workerCount is decremented
*/
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) : // <---- wait at most keepAliveTime
workQueue.take(); // <---- if there are no tasks, it awaits on notEmpty.await();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
A: From your setting, the request maybe rejected if concurrent more than 5. Because the sequence order will be pool size -> queue -> max pool size.
*
*Inital two threads will be created
*Afterward if request more than 2 are coming, the subsequence request will be put into queue.
*If the queue are full(Which you are set 2), new thread will be created but will not exceed max pool size(Which you are set 3).
*If more request are coming, and all thread/worker are busy and queue are full then request will be rejected(Subject to your rejectPolicy config).
More detail can read from here: https://dzone.com/articles/scalable-java-thread-pool-executor
A: Your question is perfectly legitimate and in this case you should ignore "go read the docs" or other superior comments you received.
Here then what is the role of BlockingQueue if it is missing the
tasks? Means why it is not waiting?
As the 2nd voted answer (not the accepted one) tells you, the use of a BlockingQueue is consistent with the need of consumers to block for work to be available (items in the queue). The blocking nature of the queue is seemingly not used on the enqueue side, and you are right, this is unintuitive and AFAIK undocumented.
A legitimate use-case for the Executor is to have a fixed number of threads (e.g. 1 or 2 or as many as the number of cores of your machine), and yet never drop incoming work items, AND don't accumulate them in the queue. This use-case would be solved with a fixed number of core threads, and a bounded blocking queue that blocks when full. Thereby the system putting backpressure onto upstream systems. This is a perfectly reasonable design decision.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: Extending QString to overload construction I would like to extend the QString class from Qt to provide some convenience for converting to/from various string types.
For example, I would like to be able to write lines like:
MyStringClass myString(_T("Hello World!"));
and get a MyStringClass object that behaves just like a QString. Using just QString, that would have had to be written like:
QString myString = QString::fromWCharArray(_T("Hello World!"));
There's other functionality I would like to add to MyStringClass, but I'm getting hung up on how overload the constructor to accept a wchar_t parameter as in my example. It appears QString's internal data is private, so my derived class can't directly set up the object as necessary (as far as I can tell).
A: You really aren't abstracting anything there, it's a bad idea. If you bite the bullet and fix it now you won't ever have to deal with it again. If you keep deferring it, the cost will increase as you go.
You really want to keep your basic types as simple as possible.
Having 6 different string types is not manageable either, so narrow it down to QString as soon as possible. If you want help converting the types, write some adapter functions. I've used simple things like the below when converting between QString and std::string for convenience.
std::string sstr(const QString &str);
QString qstr(const std::string &str);
I'm sure you can write similar for the other types you mentioned.
If you really want to write your own class to help with the transition, then you should protect yourself from its continued use. The real risk is that despite its intended deprecation, it is used forever. If you allow your new string class in public interfaces, it will be hard to get rid of. At that point its just another string type to handle with the others.
class MyStringClass {
public:
MyStringClass(const std::string &val);
MyStringClass(const char *val);
MyStringClass(const wchar_t *val);
QString getQString() const;
};
This gives an easy way to get what you need in the new code, and doesn't allow implicit conversions. QString is a value object anyway, not sure you could use it the way you want to.
Chances are you won't convert most of the code, but as long as its in private implementation it won't hurt you that often.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Handling unreadable/not found files in MVC (PHP) I'm still writing my simple MVC for learning and eventually make a framework for my applications and now I'm writing the routing class and have faced dilemma. Since this community is big, I wanted to hear different opinions before continue. At some point entered URL might not match any controller or there might be a controller with unreadable file. Now I'm faced with dilemma on how do I notify user of the situation.
First option that I see is throwing an exception. This is easy option but catching exceptions might be a problem and it is not centralized.
Another is calling error controller populating a message error or fixed error.
There might be other options and I would like to hear from you buddies.
A: I went with either including the file or redirecting to error page
if (file_exists($file_path) && is_readable($file_path)) {
//the file is valid, include it
require $file_path;
}else{
redirect_to_error_page(404);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Connect to exchange asyncronously using powershell I have the following code to connect to my office 365 account using powershell:
$Cred=GET-CREDENTIAL
Write-Host "Connecting..."
IMPORT-MODULE MSONLINE
CONNECT-MSOLService -credential $Cred
$s = NEW-PSSESSION -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic -AllowRedirection
$importresults=import-pssession $s
Write-Host "Connected to exchange server"
but since this effectively connects twice, once with new-pssession and once with connect -MSOLService, it ought to be possible to do both simultaneously, e.g.:
$Cred=GET-CREDENTIAL
Write-Host "Connecting..."
IMPORT-MODULE MSONLINE
$j = start-job -scriptBlock { CONNECT-MSOLService -credential $Cred }
$s = NEW-PSSESSION -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Cred -Authentication Basic -AllowRedirection
$importresults=import-pssession $s
wait-job $j
Write-Host "Connected to exchange server"
But this doesn't actually work (I'm guessing it's an issue with the scope of the variables? Is this possible to do/how should I do it?
A: try this:
Start-Job -scriptblock {Param ($cred) CONNECT-MSOLService -credential $Cred} -ArgumentList $cred
A: I've come to the conclusion this probably isn't possible. I believe the problem is that the login commands modify the context they run in but the context is different if they are done inside an asynchronous job.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to position Highcharts dataLabels depending on the value? I'm using Highcharts to display a bar chart, with 2 bars overlaying each other, and a dataLabels at the right of them, displaying the exact value.
The problem here is that when the value is above 80%, the label is overflowing from the chart into the frame, going over some other text, and making them both unreadable.
Here are my plotOptions :
plotOptions: {
bar: {
groupPadding: 0.5,
pointWidth : 30,
borderWidth: 0,
dataLabels: {
enabled: true,
y:-5,
color:"black",
style: {
fontSize: "12px"
},
formatter: function(){
if(this.y > 80)
{
this.series.chart.options.plotOptions.bar.dataLabels.x -= 20;
}
if(this.series.name == "Tests OK")
return "Tests OK : <strong>"+Math.round(this.y*10)/10+"%</strong>";
else
return "<br/>Tests Executed : <strong>"+Math.round(this.y*10)/10+"%</strong>";
}
}
}
}
I thought i could edit the chart options on the go, using this.series.chart.options.plotOptions.bar.dataLabels.x -= 20;, but this doesn't work.
Surely I'm not the first one who has encountered a problem like that. Any idea ?
Thanks
A: Here's what I ended up with. The setTimeout is necessary or the dataLabel property doesn't exist on the point:
formatter: function () {
var point = this.point;
window.setTimeout(function () {
if (point.s < 0) {
point.dataLabel.attr({
y: point.plotY + 20
});
}
});
//this.series.options.dataLabels.y = -6;
var sty = this.point.s < 0 ? 'color:#d00' : 'color:#090;' //other style has no effect:(
return '<span style="' + sty + '">' + Math.abs(this.point.s) + '</span>';
}
A: Although Bhesh's answer solves the problem for x/y positioning, Highcharts ignores any changes to the style property of dataLabels (see the problem here). However, you can override the styles of an individual point by passing it through the data object:
series: [{ data: [29.9, 106, { y: 135, dataLabels: { style: { fontSize: 20 } } }]
example from Highcharts docs
I was able to get dynamic styles by iterating over my data before passing the whole object to Highcharts to render.
A: Looks like it's not possible to do that from within the formatter.
But you could set them after the chart is rendered (loaded). Try something like this
$.each(chartObj.series[0].data, function(i, point) {
if(point.y > 100) {
point.dataLabel.attr({x:20});
}
});
in the load callback (or if you need it in the redraw callback).
See example here.
A: I've been trying to figure some of this out myself... it looks like instead of
this.series.chart.options.plotOptions.bar.dataLabels.x -= 20;
could you use...
this.series.options.dataLabels.x = -20;
... at this point I'm trying to understand if I'm able to discern the location of a dataLabel so that I can reposition it if necessary.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: iphone calculator keyboard I am pretty new to iPhone development, so I don't know if this is even possible, but is it possible to customize a keyboard so it looks like a calculator? I know how to use inputAccessoryView to put buttons on top of the keyboard, but I would like to put the add, multiply, divide and subtract buttons on the side to make it look like a more standard calculator. Is this possible?
Thanks.
A: The Buttons
Check out CodePadawan: iPhone Glossy Buttons for programmatically created calculator buttons.
However, I would suggest using PNG images for the button backgrounds. You can extract the normal button backgrounds (I didn't find selected button background.) from iPhone UI Vector Elements (linked to from iPhone and iPad Development GUI Kits, Stencils and Icons) with Adobe Illustrator by making a selection, copy, new, paste, Object > Artboards > Fit to Selected Art > Save for Web.
CalculatorMemoryButtonBackgroundNormal.png & CalculatorMemoryButtonBackgroundNormal@2x.png
CalculatorOperatorButtonBackgroundNormal.png & CalculatorOperatorButtonBackgroundNormal@2x.png
CalculatorDigitButtonBackgroundNormal.png & CalculatorDigitButtonBackgroundNormal@2x.png
CalculatorEqualButtonBackgroundNormal.png & CalculatorEqualButtonBackgroundNormal@2x.png
The Implementation
*
*How to create a custom keyboard
A: Since you are new to iPhone Application Development, I would say go to Youtube and watch tutorials on iPhone app dev, and it is of great resource. As for your "Calculator" project - visit this tutorial !
A: Not in any simple way. Given how simple this keyboard would be, this is better achieved by building a custom view.
A: You will need a whole replacement "keyboard" with your own buttons and actions to do this. This will be a UIView holding a set of UIButtons. If you want this to pop up like the regular keyboard (as opposed to being on screen all the time like in the calculator app) then set your new view to be the inputView of your text field rather than the inputAccessoryView.
A: Please see Custom iPhone Keyboard
However, it is possible that Apple could reject your app according to various SO posts on the issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Intellij - how do I add a text file to the resources I am reading a *.properties file using properties.load and a file name.
I want to add the properties file to the jar or to the classpath.
*
*How do add a file to the jar?
*How do I read from the jar?
A: Place the file in the source folder, it will be copied to the output and added to the jar together with the classes according to Settings | Compiler | Resource Patterns.
To load the file in your app use something like:
Properties props = new Properties();
InputStream is = this.getClass().getResourceAsStream("/file.properties");
props.load(is);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Does facebook-java-api support app request I'm currently trying to add the facebook apps request from our java server using facebook-java-api (3.0.5-snapshot) (http://code.google.com/p/facebook-java-api/)
But it's seem that it's support everything except the apps request.
I was wondering if anybody manage to make it work event though this api seem to haven't change since 2009.
Am I missing something in the facebook-java-api that does or I have to use a new api or maybe simply call directly the rest request for that notification ?
Edit : While reading the Facebook docs and this question, it seem that the short answer is you can't.
A: We fixed it by using the http://restfb.com/ instead of the old and no longuer updated facebook-java-api (3.0.5-snapshot) (http://code.google.com/p/facebook-java-api/)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Selenium Export test cases as PHP-phpunit is missing in my Selenium IDE 1.2.0? I really in need of converting/exporting my test cases to PHP. But PHP-phpunit formatter in Selenium IDE 1.2.0 is missing. Can you please tell me how can I get it? Its really urgent please.
A: The PHP formatter has been removed starting in IDE 1.2.0, presumably because nobody was maintaining it. You can either go back to IDE 1.1.0 and never upgrade, or you can try the PHP formatter from 1.0.2, which might work. Long term, you've got a decision to make about what language you're going to use instead of PHP.
A: Great news - it's been revived! https://addons.mozilla.org/en-US/firefox/addon/selenium-ide-php-formatters/
Thanks to Dan Chan for taking that on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Jira PHP SOAP updateissue doesnt work I tried updating component for issue in Jira using SOAP in PHP, it didnt throw any exception, it returned isuue but component was never updated.
Any ideas?
here is my sample code:
$myIssue="";
$myIssue['components'][] = array("id" => "10769", "name" => "component name");
$soap->updateIssue($auth,"ISSUEKEY", $myIssue);
It just returns issue without any change to component.
This is what is sent out of php when i print that variable :
Array
(
[components] => Array
(
[0] => Array
(
[id] => 10769
[name] => component name
)
)
)
A: I am not a PHP developer, but I think that this code:
arrayToObject(array("id" => "10769", "name" => "component name")
Results in this:
{
id: '10769',
name: 'component name'
}
Am I right?
Which would result in this being sent to JIRA as the RemoteFieldValue Array:
{components: [{
id: '10769',
name: 'component name'
}]}
If so, I do not think that is what jira is expecting. I believe it is expecting:
[
{id: 'components',value:'component name'}
]
Remember that Java does not have associative arrays. So the construct $myIssue['components'][] doesn't mean anything to Java. Java also does not support multi-dimensional arrays of different types.
Update:
Try this (Or something like it, my code is not tested):
<?php
class RemoteFieldValue {
var $id;
var $values = array();
function __construct($idIn, $valuesIn) {
$this->id = $idIn;
$this->values = $valuesIn;
}
}
$rfv = new RemoteFieldValue('components', array("id" =>"componentid_goes_here"));
$rfvArray = array($rfv);
$soap->updateIssue($auth,"ISSUEKEY", $rfvArray);
?>
When I put together a JIRA service in ColdFusion I implemented each JIRA object (User, Issue, RemoteFieldValue, etc) as a ColdFusion object. I suspect you could also do it with associative arrays and arrays, but I find this cleaner and it makes it easier to adapt to what the JIRA SOAP service expects.
A: The easiest way to update a field is to pass the object
First define the class (generated from the WSDL)
class RemoteFieldValue {
public $id; // string
public $values; // ArrayOf_xsd_string
}
Create object
$remoteField = new RemoteFieldValue ();
$remoteField->id = "12345";
$remoteField->value = "bla";
then call the method
$soap->updateIssue($auth,"ISSUEKEY", $remoteField );
Hope this help.
A: For me updateIssue works in such way (php)
Defining class (from wsdl)
class RemoteFieldValue
{
public $id; // string
public $values; // ArrayOf_xsd_string
}
after that here is a code which updates 'description' field at issue.
public function updateDescription($issue_key, $description)
{
$remoteField = new RemoteFieldValue ();
$remoteField->id = 'description';
$remoteField->values = array($description);
return $this->mSoapClient->updateIssue($this->mToken, $issue_key, array($remoteField));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Methods for categorizing 'plugin' DLLs In my team, we are creating a .NET (WinForms) application that loads additional assemblies (DLLs) as pluggable components.
These actions needed to be classified into product categories, in order to be presented in the GUI in an organized way.
We've just started to implement this feature, so for starters, we keep a master .xml file that maps different assmeblies to categories.
This process is brittle and prone to many errors, and the final version of this feature should automatically create this mapping (somehow).
What we're looking for is some method to map the different DLLs now (and in the future) and keep all of this in sync.
Some suggestions we've had are:
*
*Attributes - mark each assembly with some attribute, and run some
custom tool during build to produce some sort of mapping file,
according to these attributes.
This process will work, however this means static compilation of
category name into the assembly itself, making it impossible to
dynamically update on a client machine after installed.
*Configuration file - Add a configuration file for the assembly (a
practice this is rarely used i believe) and contain the needed
information there in some form.
These are mainly the 2 options i have considered, one is static and the other dynamic (updateable after the app has been deployed).
Although we don't foresee any changes, requiring this mapping to be dynamic, i somehow feel that statically compiling this as an attribute is wrong.
Are there any other good options for meeting such a requirement?
Also, are there any other pros/cons i haven't considered with the presented solutions ?
A: The first questions you should ask here is:
*
*who is the one who must be able to change the assembly<->category mapping?
*can every of your plugin assemblies be associated to an arbitrary category, or does that make no sense / may be a cause of errors?
*is it sufficient when a category change takes place during the install of an update?
Metadata to be build into the assemblies is the right thing, if each assembly can only belong to a defined category (or a defined list of categories) at one point in time, and it may be result in a runtime error if someone changes the category in a wrong way. Updating the category mapping later is not impossible, it is possible whenever you install a new release of your components.
Putting the mapping into separate configuration file or XML file is the right option if someone else should be able to change the actual mapping, without having to install a new release of your software. This may result in the need of having a user-friendly dialog to change the mapping in a not-so-error-prone way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I recognize a mouse click on a line? I have a WPF application. There is a canvas. I draw line when user drag the mouse over the canvas (from mouse down to mouse up). I take initial point, when mouse is pressed down and final point, when user does mouse up. Then I calculate the distance and draw the line in simple mouse down, move and up events.
After drawing many lines on canvas, I click on any one of the line. I want to select the line and show the user that line is selected (like by changing the color of the line). So user can delete it.
Thanks.
A: Here is a working example: (implementing what Bala suggested in his comment)
private void myCanvas_Loaded(object sender, RoutedEventArgs e)
{
Line line = new Line();
line.MouseDown += new MouseButtonEventHandler(line_MouseDown);
line.MouseUp += new MouseButtonEventHandler(line_MouseUp);
line.Stroke = Brushes.Black;
line.StrokeThickness = 2;
line.X1 = 30; line.X2 = 80;
line.Y1 = 30; line.Y2 = 30;
myCanvas.Children.Add(line);
}
void line_MouseUp(object sender, MouseButtonEventArgs e)
{
// Change line colour back to normal
((Line)sender).Stroke = Brushes.Black;
}
void line_MouseDown(object sender, MouseButtonEventArgs e)
{
// Change line Colour to something
((Line)sender).Stroke = Brushes.Red;
}
Considering that you already have the logic to add the lines into canvas,
Simply add the two event handlers (as above) for every line that you add.
A: I would advise you to add a custom MouseDown event handler to your canvas. Indeed, if your lines are very thin, you need to let the user be able to click near a line to select it.
For this, in your custom MouseDown handler, iterate over your lines and do the following:
For each line:
*
*Create a rectangle with the length of the line as width and height = max(lineWidth, 10px),
*Rotate your mouse coordinates around the rectangle center with an angle equals to the line angle (compute it with math.atan2),
*Check if the new mouse coordinates lie inside the rectangle,
*If so, select the current lien and break.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: flot: integration example with fancybox and like? I'm using flot to display a set of graphs on a web page. Now I'm looking for a floating window that's quite popular these days, like those used for showing a gallery.
fancybox looks quite nice and capable. My question is: has anybody used fancybox to display a flot picture and would like to share how easy/hard it was?
Thanks and regards,
A: Pretty easy to combine the two. I coded this up in about 10 mins.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Avoid bitmaps being recycled automatically in android In my application, I am storing some bitmap images in the HashMap.
with the hashmap as a member of a class ImageHolder.
I need the images in the HashMap in my program for further processing on the images.
When I run my application, the bitmap image is automatically recycled and I get
java.lang.IllegalStateException: Can't call getPixels() on a recycled bitmap.
Please help me to avoid the bitmap image being recycled automatically.
Here is code for class ImageHolder :
public class ImageHolder {
private HashMap<String, Bitmap> mImageMap = null;
public ImageHolder() {
mImageMap = new HashMap<String, Bitmap>();
}
/**
* @return the mImageMap
*/
public Map<String, Bitmap> getmImageMap() {
return mImageMap;
}
/**
* @param mImageMap the mImageMap to set
*/
public void setmImageMap(HashMap<String, Bitmap> mImageMap) {
this.mImageMap = mImageMap;
}
}
A: Read the pixels when you load the bitmap and store these information somewhere.
I dont know why you need these pixels, but I can recommend you NOT to store the pixel information over a longer periode of time cause this really eats the memory.
A: Its kind of hard to tell without your whole source code. Most probably you are using the same bitmap in multiple places, like ImageView and the Holder class. If the either causes a recycle, it will affect the other as both are referencing the same object. If you are doing this, you might want to use the bitmap.copy method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Python: Type error when drawing contour plot despite using the search function I've been unable to find an answer. I got two assumptions, but don't know in how far they may apply. Now the problem:
I'd like to plot a contour. For this I've got here the following python code:
import numpy as np
import matplotlib.pyplot as plt
xi=list_of_distance
yi=list_of_angle
x = np.arange(0,54,0.2)
y = np.arange(0,180,2.0)
Z = np.histogram2d(xi,yi,bins=(274,90))
X, Y = np.meshgrid(x, y)
plt.contour(X,Y,Z)
plt.ylabel('angles')
plt.xlabel('distance')
plt.colorbar()
plt.show()
xi and yi are lists containing float values.
x and y are defining the 'intervals' ...for example:
x generates a list with values from 0 to 54 in 0.2 steps
y generates a list with values from 0 to 180 in 2.0 steps
with Z I make use of the numpy function to create 2D-Histograms. Actually this seems to be the spot that causes trouble.
When the function plt.contour(X,Y,Z) is called, the following error message emerges:
... File "/usr/lib/pymodules/python2.7/numpy/ma/core.py", line 2641, in new
_data = np.array(data, dtype=dtype, copy=copy, subok=True, ndmin=ndmin)
ValueError: setting an array element with a sequence.
Now to the assumptions what may cause this problem:
*
*It seems like it expects an array but instead of an numpy-array it receives a list
or
*We got a row that is shorter than the others (I came to that thought, after a collegue ran into such an issue a year ago - there it has been fixed by figuring out that the last row was by 2 elements shorter than all others...)
A: As @rocksportrocker implies, you need to take into account that histogram2d returns the edges in addition to the histogram. Another detail is that you probably want to explicitly pass in a range, otherwise one will be chosen for you based on the actual min and max values in your data. You then want to convert the edges to cell centers for the plot. Something like this:
import numpy as np
import matplotlib.pyplot as plt
n = 1000000 # how many data points
xmin, xmax = 0.0, 54.0 # distances
ymin, ymax = 0.0, 180.0 # angles
# make up some random data
xi=np.random.normal(xmax/2.0, xmax/4.0, n)
yi=np.random.normal(ymax/3.0, ymax/3.0, n)
Z, xedges, yedges = np.histogram2d(xi,yi, bins=(270,90), range=[[xmin, xmax], [ymin, ymax]])
# find the cell centers from the cell edges
x = 0.5*(xedges[:-1] + xedges[1:])
y = 0.5*(yedges[:-1] + yedges[1:])
# promote to 2D arrays
Y, X = np.meshgrid(y, x)
plt.contour(X,Y,Z)
plt.ylabel('angles')
plt.xlabel('distance')
plt.colorbar()
plt.savefig("hist2d.png")
yields a countour plot like this:
but personally I wouldn't use contours in this case, since the histogram is likely to be noisy.
A: Your traceback indicates that the error does not raise from the call to matplotlib, it is numpy which raises the ValueError.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Programmatically start an Eclipse IApplication does anyone know how to programmatically start an Eclipse IApplication?
It is an commandline Application and I want to write unit tests for it.
It should work so:
org.eclipse.equinox.app.IApplication app = new myApp();
try {
app.start(???);
} catch (Exception e) {
e.printStackTrace();
}
The start method requires an IApplicationContext.
Where do I get this?
Thanks a lot for help
A: You launch such applications using the OSGi ApplicationDescriptor service. In Equinox, each of the org.eclipse.core.runtime.applications is turned into an ApplicationDescriptor instance. You then launch an instance using the ApplicationDescriptor.launch(Map) method. The Eclipse Help provides a very broad if brief description, and be sure to read about the application cardinality on the Eclipsepedia.
A: It does not seem the right way to start the application programmatically for unit testing.
Instead, you could write Eclipse plug-in tests, and they can launch the required OSGi container, where you can initialize your tests. Of course, you have to do some manual initialization, that are related to providing the corresponding test suite - but in that case you could manually call your code instead of relying an external launch process.
Take a look at the following FAQ entry http://wiki.eclipse.org/FAQ_What_is_a_PDE_JUnit_test%3F for details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to get halfbrothers/sisters in SPARQL? I have this RDF dataset with a family that has the hasParent realtionship. To search for all brother and sisters pairs I have the following query:
SELECT DISTINCT ?name1 ?name2
WHERE {
?subject1 oranje:hasParent ?object .
?subject2 oranje:hasParent ?object .
?subject1 rdfs:label ?name1 .
?subject2 rdfs:label ?name2 .
FILTER (?subject1 != ?subject2)
}
However, How do I get all the halfbrother/sisters pair? This means: brothers and sisters that have only one parent in common.
Edit: maybe important, the dataset also contains the marriedWith relationship
A: Does this work for you?
SELECT DISTINCT ?name1 ?name2
WHERE {
?child1 oranje:hasParent ?parent , ?otherparent1 .
?child2 oranje:hasParent ?parent , ?otherparent2 .
?child1 rdfs:label ?name1 .
?child2 rdfs:label ?name2 .
FILTER (?child1 != ?child2)
FILTER (?otherparent1 != ?parent)
FILTER (?otherparent2 != ?parent)
FILTER (?otherparent1 != ?otherparent2)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Wordpress footer has body background image overlapping On http://www.teampaulmitchellkarate.com/ the footer where "this website is created by" should continue all the way down and not cut off half Grey(its showing part of my background image).
I've made the BG image smaller but then it cuts off in the middle of the page on the home page.
CSS for footer:
#footer {
background: url("images/footer.gif") repeat-x scroll 50% 0 transparent;
height: auto !important;
min-height: 171px;
overflow: hidden;
}
A: You have the following selector:
#footer .indent {padding:73px 0 20px 13px;}
that should be:
#footer .indent {padding:23px 0 20px 13px;}
A: If you want the white bg of the footer to continue to the bottom of the page, set the background image to repeat along the x and y axis:
#footer {
background: url(images/footer.gif) repeat-x 50% 0%;
min-height: 171px;
height: auto !important;
height: 171px;
overflow: hidden;
}
#footer .indent {
padding: 23px 0 20px 13px;
}
#footer p {
line-height: 22px;
font-size: 14px;
color: #3f3f3f;
}
#footer p a {
text-decoration: none;
color: #333333;
}
#footer p a:hover {
text-decoration: underline;
}
#footer p span a {
color: #000000;
}
/* Footer navigation */
nav.footer {
float:right;
}
nav.footer ul {
margin: 0;
list-style: none;
overflow: hidden;
}
nav.footer ul li {
float: left;
padding: 0 0 0 15px;
line-height: 22px;
font-size: 14px;
color: #3f3f3f;
}
nav.footer ul li a {
text-decoration: none;
color: #3f3f3f;
}
nav.footer ul li a:hover {
text-decoration: underline;
}
This will get the white bg slice of the footer to fill the entire area.
Unrelated, you could trim your images/bg.png down to about 10px in width and save some server bandwidth without losing any quality.
A: Was the height set on your footer set intentionally? You can cut down on the height of your footer and just hide all that empty space quite easily, just set your height on your footer to something like 84px instead of auto and all that empty space will disappear.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: My first try to output my Drupal7 module as a custom block failed This is my first try to create a Drupal module: Hello World.
I need it to have it displayed as a custom block and I found this can be implemented by 2 Drupal7 hooks: hook_block_info() and hook_block_view() inside my my helloworld module. In Drupal 6 was used the deprecated hook_block().
In the actual form it works but it only display the text: 'This is a block which is My Module'. I actually need to display the output of my main function: helloworld_output(), the t variable.
<?php
function helloworld_menu(){
$items = array();
//this is the url item
$items['helloworlds'] = array(
'title' => t('Hello world'),
//sets the callback, we call it down
'page callback' => 'helloworld_output',
//without this you get access denied
'access arguments' => array('access content'),
);
return $items;
}
/*
* Display output...this is the callback edited up
*/
function helloworld_output() {
header('Content-type: text/plain; charset=UTF-8');
header('Content-Disposition: inline');
$h = 'hellosworld';
return $h;
}
/*
* We need the following 2 functions: hook_block_info() and _block_view() hooks to create a new block where to display the output. These are 2 news functions in Drupal 7 since hook_block() is deprecated.
*/
function helloworld_block_info() {
$blocks = array();
$blocks['info'] = array(
'info' => t('My Module block')
);
return $blocks;
}
/*delta si used as a identifier in case you create multiple blocks from your module.*/
function helloworld_block_view($delta = ''){
$block = array();
$block['subject'] = "My Module";
$block['content'] = "This is a block which is My Module";
/*$block['content'] = $h;*/
return $block;
}
?>
All I need now is to display the content of my main function output: helloworld_output() inside the block: helloworld_block_view().
Do you have an idea why $block['content'] = $h won't work? Thanks for help.
A: $h is a variable local to the helloworld_output() function so wouldn't be available in helloworld_block_view().
I'm not sure why you're setting headers in helloworld_output(), you should remove those lines as they will only cause you problems.
After you've removed the two calls to header() in that function simply change your line of code in the helloworld_block_view() function to this:
$block['content'] = helloworld_output();
And the content you set to $h in helloworld_output will be put into the block's content region.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Set_radio codeigniter from database [EDIT REGISTRY] I have following code:
echo form_radio($arr_gen_fem,
($btn_value == 'Editar') ? ( isset($row_new_person) ? $row_new_person->gender: set_value('gender')) : '');
I need display the value from database for edit registry, but this not display.
The problem is only with radio buttons.
A: try putting your condition result into a variable then add the variable as a param.
$result = ($btn_value == 'Editar') ? ( isset($row_new_person) ? $row_new_person->gender: set_value('gender')) : '';
echo form_radio($arr_gen_fem, $result);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JQuery DatePicker -> dateformat, how to output dayNamesMin instead of dayNamesShort? Hi there i am trying to output the selection of a date. Using the D option gives me days like 'Thu' or 'Mon'. When i try to localize this format using the 'nl' localisation, the the output is again nicely in 3 letters such as 'don' or 'maa'
But for parsing the date (using Javascript) into the Dutch language i need to have the 'do' and 'ma' so the dayNamesMin. Is there a way that i can configure JQuery datepicker the correct localized day?
A: Try using the altFormat option of the jQuery UI date picker, this should allow you to do what you want.
A: Strange enough, you cannot specify a date format with dayNamesMin. You can, however, specify dayNamesShort and dayNames in your options. So, for example, you could copy dayNamesMin to dayNamesShort and use D in your date format.
var minDays = $('#datepicker').datepicker('option', 'dayNamesMin');
$('#datepicker').datepicker('option', 'dayNamesShort', minDays);
See this in action: http://jsfiddle.net/william/bBA9F/3/.
Note that, for some reason, the #datepicker div wouldn't be hidden after the two statements above, hence the last statement in the jsfiddle.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: System Setting ties notification volume to ringer volume By default Android treats the Ringer and Notification sounds as one audio stream.
To change this you sould deselect the check box labeled "Use incoming call volume for notifications" on android settings.
Is it possible to do it programmatically?
A: Android - Toggle Notification volume programatically
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: nanosleep() syscall waking up with bus error? I'm looking at a core dump from an embedded MIPS Linux app. GDB is reporting SIGBUS, and the thread handling the signal appears to be sat in a syscall for nanosleep - the higher level code basically called sleep(verylongtime);
Assuming another process didn't send that signal to the app, what would cause this thread to be woken up like this? Has something inside the kernel generated the bus error? Could it have been caused by another thread that blocks such signals? (please excuse any naivety here, I'm not too knowledgeable about signals). Thanks.
A: If si_pid is set to an address, this means your SIGBUS was raised by a fault in the program. Usually this happens when the kernel tries to page in some program text, but encounters an IO error. Stack overflows can also trigger this.
You see si_pid set to an address because si_pid is part of a union, and is aliased with si_address. In particular, si_pid is only valid if si_code == SI_USER. You may be able to get more information from the si_code member:
The following values can be placed in si_code for a SIGBUS signal:
BUS_ADRALN invalid address alignment
BUS_ADRERR nonexistent physical address
BUS_OBJERR object-specific hardware error
BUS_MCEERR_AR (since Linux 2.6.32)
Hardware memory error consumed on a machine check; action required.
BUS_MCEERR_AO (since Linux 2.6.32)
Hardware memory error detected in process but not consumed; action optional.
Note that it is not possible to block kernel-originated SIGBUS signals - if you try to do so, your program will be terminated anyway.
I suspect your debugger may be a bit confused as to the origin of the SIGBUS signal here; it may be attributing it to the wrong thread. You may want to examine the other threads of your process to see if they're doing anything odd. Alternately, you may have encountered an IO error when returning from the nanosleep and paging in the page of code at the return address.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Variables in memory on server once session times out I've created a web site that is used mainly to do reporting on multiple locations and e-mail reports and things like that. Since its dealing with a lot of information I've set it up so it grabs a bunch of information at one time then I go through it with linq and filter it however I need to. When someone actually clicks the logout button then the variables are released and cleaned up.
My questiion is what happens to those variables if the user never actually clicks logout and either lets the session timeout or x's out of the web browser they are using?
If the variables aren't released how do people normally handle that?
Thanks,
Mike
A: If your session times out (it will eventually) then your server will release it's reference to the Session object which holds the reference to the object that you're storing in the SessionState. When there's no reference left for an object it's automatically garbage collected when the garbage collector is run. By the way, if your user clicks logout it doesn't mean the objects are cleared immediately but just that the objects are made available for garbage collection. This way you're not really sure when they will be collected but this allows the garbage collection process to only run if needed and do some extra cleaning when your application is not under heavy load.
A: The way you've described it, it sounds like the best solution is to store the data in cache, so that you can reference it whenever you need to.
Here is a simple example of how to cache a DataSet object:
DataSet ds = RetrieveLotsOfData();
Cache["MyDataSet"] = ds;
Once the data is stored in cache, you can reference it anywhere like this:
DataSet ds = (DataSet)Cache["MyDataSet"];
See this article for an overview of cache management in ASP.NET:
http://www.codeproject.com/KB/web-cache/cachemanagementinaspnet.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Non-JavaScript pop-up for non-JavaScript users? I was wondering if it's possible at all to do something like the following:
Let the website examine whether a visitor has Javascript enabled or not. If not a pop-up will appear telling them to enable JavaScript for a better website view.
It doesn't have to be a pop-up, it could be anything, really.
Is it even possible to do something like that without using JavaScript?
In the worst case scenario I just leave a plain text note in my footer or so.
A: Anything inside a <noscript> block will only be shown to people with JavaScript disabled or unavailable:
<noscript>
Please enable JavaScript to see the awesomeness
</noscript>
A: All you need is noscript tag
<noscript>
Doh! No javascript?
</noscript>
A: You could use <noscript>, but there may be unintended side effects. Instead, Include a <div>, and then remove it from the DOM on document.ready. That way, the message is sure to appear if your script doesn't run for any reason.
A: From my reading here is a way to do it:
in your HTML add a text that tell the user to enable javascript for better view. Then on the load of the page remove the DOM.
source : "Jquery novice to ninja" p.64
In HTML
<p id="no-script"> We recommend that you have JavaScript enabled!</p>
In Javascript
$('#no-script').remove();
A: That's difficult to answer you because Java is not Javascript.
Javascript is a native browser language.
Java is an advanced language which needs plugin to run on browser (applet).
If you talk about javascript, you can use the noscript tag.
If you talk about java, you can use javascript to show a popup because javascript is activated on 99% of browsers.
A: Try this - Visual basic Script (For IE only):
<script type="text/vbscript">
MsgBox("Please Enable Javascript to experience the full quality of this page...")
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Operation on 2 entities - how and where to design? There are interfaces
interface Male {
boolean likes(Female female);
}
interface Female {
boolean likes(Male male);
}
There's also interface
interface GoodCouple {
Male getMale();
Female getFemale();
}
You're given 2 sets:
Iterable<Male> males = ...;
Iterable<Female> females = ...;
And you're asked to build the set of GoodCouples:
Iterable<GoodCouple> couples = XXXXXXXXXXXX(males, females);
The question is, how would you define XXXXXXXXXXXX? It's not about algorithm, it's about architecture: what is XXXXXXXXXXXX? Is it some class' method? What name would you give to that class? What are responsibilities of this class?
If it matters, languages are either C# or Java.
A: class GoodCoupleDetectorImpl : GoodCoupleDetector {
public Iterable<GoodCouple> findGoodCouples(Iterable<Male> males, Iterable<Female> females) { }
}
This way you can use different strategies for finding good couples.
A: It might be part of a GoodCoupleFactory: CreateGoodCouples(males, females)
A: I would put methods like XXXXXXXXXXXX and all other methods not directly belonging to either Male or Female in a class like MaleFemaleUtils or GoodCoupleUtils.
A: Yes, it can be a method in a class. I'd call it MatchMaker and the method FindMatches :)
A: C# Linq Zip
IEnumerable<Male> males = ...;
IEnumerable<Female> females = ...;
IEnumerable<GoodCouples> couples = males.Zip(female, (male, female) => new GoodCouple { male = male, female = female });
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Passenger and Resque - Restarting on Deploy I'm rolling out resque as my scheduler in my newest app, and noticed an interesting little quirk. The app we're building is just a REST API, and isn't being hit all the time. So, what it IS doing all the time is running some scheduled every two minute jobs to update the data it feeds out of the API.
Well, here's the quirk - until the application has been hit over HTTP at least once, the application doesn't restart, and the rescue workers are still working using the old version of the app.
I figure this is because with Passenger, when you just touch the tmp/restart.txt file, it just marks the app so that next time it gets hit by a request, it will restart. But if it DOESN'T get hit, it doesn't, yet, restart! Is there a way around this? Is there a way to tell passenger to restart an app and reload its environment right now, instead of the next time it receives an HTTP request?
A: Nevermind - I was over thinking it, this wasn't the problem at all - I just had a configuration wrong. Sorry!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery: Match a list with less than X items I want add a class to lists, but only if they have 3 or less items:
var ol = $('ol');
var len = ol.children('li').length;
//0 based?
while(len < 2) {
$("ol").addClass("small-list");
}
http://jsfiddle.net/hryZ4/2/
How would I add such a conditional clause?
All I found was something mroe or less unrelated: Fill list up to 10 items
A: This will check and fixup every <ol> on your page:
$('ol').filter(function() {
return ($(this).children('li').length <= 3);
}).addClass('small-list');
i.e. for every <ol> which satisfies the supplied function, add the required class.
See http://jsfiddle.net/alnitak/9uTvT/
A: var ol = $("ol");
ol.each(function() {
if ($(">li", this).length <= 3) {
$(this).addClass("small-list");
}
});
I think you can try this :)
A: you can pass a function to addClass() since jQuery 1.4
$('ol').addClass(function(){
var retClass;
if (this.children.length<=3){
retClass='small-list';}
return retClass;
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: bad reference to MS.Practices.Data I have two project who reference to the same path of:
Microsoft.Practices.EnterpriseLibrary.Data.dll
I use
Database database = DatabaseFactory.CreateDatabase();
one project compiles OK and the other shows error:
Error 1 The type
'Microsoft.Practices.EnterpriseLibrary.Common.Instrumentation.IInstrumentationEventProvider'
is defined in an assembly that is not referenced. You must add a
reference to assembly 'Microsoft.Practices.EnterpriseLibrary.Common,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=null'. <---in file
line.. --> 58 17 ControlPanel.Toolbar
Why might I get this error?
A: Did you try adding the reference to Microsoft.Practices.EnterpriseLibrary.Common.dll to the project with the problem? Is it referenced in the other one with no problems?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Storing org-mode TODOs inside source code I like keeping TODOs inside my source code next to lines that need updating. Can I include these in Org-mode's agenda?
A: You would need to add those files to your org-agenda-files. But this is going to clutter your agenda with all the stuff inside your source files and there is nothing like an org-prog-mode I know of.
It might be easier to invert the process by defining an appropriate org-capture. You can just use the place from which you triggered the capture process and put it as a link in the entry you create. You can then navigate to the place by using C-o when the point is on top of the right entry. You probably also want to use org-refile to get the TODO to the proper subtree for your project.
Actually the default capture template is pretty close to what works for me:
("t" "Task" entry (file+headline "/path/to/org/notes.org" "Tasks") "* TODO %?
%u
%a" :prepend t)
A: A possible solution to this showed up on the mailing list, it was designed to keep track of links to content within C/C++ source code.
http://thread.gmane.org/gmane.emacs.orgmode/47816/focus=48556
If you're using something other than C/C++ it would likely need to be adjusted to be able to properly trace back the links.
It would not directly allow you to insert your TODOs in the source code and have them show up in the agenda, however you could create TODO headlines in an org file, and use the links to match them to the relevant points of your source code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Xcode environment variables for sub projects My current Xcode iOS project uses a number of static libraries. The different code modules in the static libraries have various levels of debug that I can switch on/off with #defines from within that module.
What I want to do is have all the debug default to off in the library then set the debug level from the parent project. I want to do this so any proj that uses the lib has to explicitly turn on debug.
So MainProj uses myLib1 and myLib2 etc. Within myLib1 is a module called fooModule. fooModule has debug code such as:
#if FOOMODULE_DEBUG_LEVEL > 0
//debug code, console logs etc
#endif
I want to be able to define FOOMODULE_DEBUG_LEVEL in the parent project so the library picks it up at build time and compiles appropriately.
I have tried:
#define FOOMODULE_DEBUG_LEVEL 1
in the main project .pch
and I have tried adding FOOMODULE_DEBUG_LEVEL as a user defined environment variable with a value of 1. Neither of which were picked up by the sub project lib.
Is there a way of doing this or am I approaching this in the wrong way?
A: you accomplish this without multiple definitions by creating xcconfig files and then referencing or #include-ing them throughout your projects. so, you could apply Mattias' suggestion and then define the preprocessor defs in the xcconfig. then you have one file to change (and a full rebuild if you require these defs in the pch file, which there are separate settings for).
xcode also lets you assign separate xcconfigs per build configuration.
A: I would edit the schema and add a pre-build shell script to set the proper variables.
When you add a script you can establish from which target you are getting the definitions.
A: Maybe add a define using the "Preprocessor macros" build setting to the targets and or debug/release build configurations where you want to enable debug.
In your case you would double click on on the value column and then click "+" to add a new macro. The marco would be "FOOMODULE_DEBUG_LEVEL=1" which should result in -DFOOMODULE_DEBUG_LEVEL=1 to the compiler.
A: Solution
1) Target > Build Settings > Preprocessor macros. Set environment variable as preprocessor def for target (seems that must be target rather than project), e.g. DEBUG_VARIABLE=1
2) Project > Build phases > Add build phase. Then in the Run Script export the variable:
export DEBUG_VARIABLE
All sub projects now pick up this environment variable.
I think the ideal would be to also use Justin's suggestion of having an .xcconfig file with all the preprocessor macros defined in one place to make it easy to edit them. For the life of me I can't make this work. If I put this in the .xcconfig file:
GCC_PREPROCESSOR_DEFINITIONS = DEBUG_VARIABLE=1 $(inherited)
Then base the debug and/or release build on this configuration the DEBUG_VARIABLE environment variable never gets set.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: MochaUI Post data and MochaUI.updateContent I'm playing around with mochaUI and am having a hard time getting POST data to work correctly. I have a form and a submit button. I am using MochaUI.updateContent to work within panels. In the main panel, I have the form and the following js:
<script type="text/javascript" charset="utf-8">
$('stp1btn').addEvent('click', function(e){
MochaUI.updateContent({
element: $('mainPanel'),
method: 'post',
data: "w=1",
url: '/postFile.php',
title: 'Test Post Stuff durrrrrr',
padding: { top: 8, right: 8, bottom: 8, left: 8 }
});
});
</script>
Which posts to a page which then is supposed to update the same panel. However, I can't get it to post correctly. Even in the above example where the sample data is simply "w=1", what is actually getting posted is "w=1" in addition to what looks like one of the mootools js files included within mochaUI:
This is the Form Data from Firebug:
0:w
1:=
2:1
$family[name]:string
test:function (a,b){return((typeof a=="string")?new RegExp(a,b):a).test(this);
}
contains:function (a,b){return(b)?(b this b).indexOf(b a b)>-1:this.indexOf(a)>-1;}
clean:function (){return this.replace(/\s /g," ").trim();
}
camelCase:function (){return this.replace(/-\D/g,function(a){return a.charAt(1).toUpperCase();});}
hyphenate:function (){return this.replace(/[A-Z]/g,function(a){return("-" a.charAt(0).toLowerCase());
});}[SNIP]
I am using a framework (codeigniter) which disallows query strings thereby preventing the post data from even seeing the destination php file.
The html on the page is all correct.
I've tried surrounding the data with both quotations and apostrophes.
I searched the nether-regions of the internet looking for answers. Found tits instead--so it wasn't a total wash.
If anyone could lend some insight into how/what would be injecting the js into the post data, I would be very grateful.
A: just try this:
$('stp1btn').addEvent('click', function(e){
MochaUI.updateContent({
element: $('mainPanel'),
method: 'post',
data: { w: 1 },
url: '/postFile.php',
title: 'Test Post Stuff durrrrrr',
padding: { top: 8, right: 8, bottom: 8, left: 8 }
});
});
the mootools request does work with an object literal or otherwise for data - even can serialize a form element, so data: document.id("formel") is usually fine.
if the subclassing by mochaui is ok, then it should work.
A: <script type="text/javascript" charset="utf-8">
$('stp1btn').addEvent('click', function(e){
var myRequest = new Request({
url: '/le_formDerp.php',
onSuccess: function(responseText){
MochaUI.updateContent({
element: $('mainPanel'),
content: responseText,
title: 'Test Post Stuff durrrrrr',
padding: { top: 8, right: 8, bottom: 8, left: 8 }
});
},
}).send($('stp1_form').toQueryString());
myRequest.send();
});
</script>
hurrrrrr durrrrrr
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make CustomClass savechanges() working in Linq? I am trying to get Linq going on Northwind and I am really lost..
I have a CustomClass named Ordr with the properties OrderID, EmployeeID, _ShipRegion
I do a simple query:
Dim query = From c In dbcontext.Orders _
Where c.EmployeeID = 2
Select New Ordr With { _
.OrderID = c.OrderID, _
.EmployeeID = c.EmployeeID, _
.Shipregion = c.ShipRegion}
then I bind this query to a DataGridView:
DataGridView1.DataSource = query
Now, when I try to save any changes with dbcontext.SaveChanges() no changes are saved. OrderID is the primary key.
How was I supposed to do it properly without loosing the ability to save changes?
A: From the looks of it, the Entity class is probably called Order and Ordr is just sort of data transfer object. You'll need to save data as an Order object. Example, when you go back to saving, you probably have an updated Ordr class, so convert that into Order class, you might need to attach it to the context or fetch an existing Order based on Id and then update it, and then save the context.
Hope this helps.
Edit in response to the comments:
As an example, you can do this:
var orders = from o in context.Orders
select new Order{Id = o.Id, EmployeeId = o.EmployeeId}; //etc. C#
Then when you want to save, this is of type Order, so you should be able to attach it back to the context and save it.
When you return a lighter weight object like Ordr, I am not sure how you can track it automatically, there might be some way, but I have never used them that way. Usually you use them for read-only purposes and to make the query faster.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Vanilla JavaScript version of jQuery .click So maybe I'm just not looking in the right places but I can't find a good explanation of how to do the equivalent of jQuery's
$('a').click(function(){
// code here
});
in plain old JavaScript?
Basically I want to run a function every time an a tag is clicked but I don't have the ability to load jQuery into the page to do it in the way above so I need to know how to do it using plain JavaScript.
A: element.addEventListener('click', function() { ... }, false);
You have to locate the elements and make a loop to hook up each one.
A: Working Example: http://jsfiddle.net/6ZNws/
Html
<a href="something">CLick Here</a>
<a href="something">CLick Here</a>
<a href="something">CLick Here</a>
Javascript:
var anchors = document.getElementsByTagName('a');
for(var z = 0; z < anchors.length; z++) {
var elem = anchors[z];
elem.onclick = function() {
alert("hello");
return false;
};
}
A: I just stumbled upon this old question.
For new browsers (find support here: https://caniuse.com/?search=querySelectorAll)
My solution would be:
function clickFunction(event) {
// code here
}
for (let elm of document.querySelectorAll("a")) {
elm.addEventListener('click', clickFunction);
}
This is optimized to not create a new function for each element.
This will add an "click" eventListener to each element, so if you do this more than once, several eventListeners for each element will be called.
To replace/set the "click" eventListener use the following code:
for (let elm of document.querySelectorAll("a")) {
elm.onclick = clickFunction;
}
Will work on IE9 and up.
A: This will assign an onclick function to every a element.
var links = document.getElementsByTagName("a");
var linkClick = function() {
//code here
};
for(var i = 0; i < links.length; i++){
links[i].onclick = linkClick;
}
You can see it in action here.
A: Try the following
var clickHandler = function() {
// Your click handler
};
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
var current = anchors[i];
current.addEventListener('click', clickHandler, false);
}
Note: As Ӫ_._Ӫ pointed out this will not work on IE8 and lower as it doesn't support addEventListener.
On IE8 you could use the following to subscribe to onclick. It's not a perfect substitute as it requires everyone to be cooperative but it may be able to help you out
var subscribeToOnClick = function(element) {
if (element.onclick === undefined) {
element.onclick = clickHandler;
} else {
var saved = element.onclick;
element.onclick = function() {
saved.apply(this, arguments);
clickHandler.apply(this, arguments);
}
}
}
for (var i = 0; i < anchors.length; i++) {
var current = anchors[i];
subscribeToOnClick(current);
}
A: document.getElementById('elementID').onclick = function(){
//click me function!
}
A: Here you go:
[].forEach.call( document.querySelectorAll( 'a' ), function ( a ) {
a.addEventListener( 'click', function () {
// code here
}, false );
});
Live demo: http://jsfiddle.net/8Lvzc/3/
(doesn't work in IE8)
Also, I recommend event delegation...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "68"
}
|
Q: Referencing crosstab grand total field in another formula I need to refer the grandtotal field generated in the cross tab - in a formula field.
Is there a way to do it? The database fields can be referenced using table.fieldname but how to identify the grandtotal column?
I then need to show a curve based on the totals vs something else, but identifying the totals in a formula is where I'm stuck.
A: It would probably be easiest to calculate the total again. In the report footer, add a summary field on table.fieldname, and set the summary to Sum.
Or create a formula: Sum({table.fieldname})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is there no built-in Set data type in Haskell? Is there anyone who can explain to me why there's no Set datatype defined in Haskell?
Sidenote:
I'm only learning Haskell as part of a course on logic in which set theory is very important thus it would be really handy to have the notion of a set in Haskell. Having a list and removing duplicates (and possibly sorting) would result in a set as well but I'm curious if there's a particular reason why it's not built-in?
A: It exists as Data.Set. However, as you said, it can be implemented on top of list and so is not necessary to build up the language which, I think, is why it is in a module rather than being part of the definition of the language itself.
A: As other answers indicate, the question "Why is there no Set data type in Haskell?" is misguided: there is a Set data type.
If you'd like to know why Set isn't "built in" to Haskell, you could be asking one of two things.
*
*Why is Set not part of the language specification?
*Why is Set not in Prelude (the functions and data types that are imported by default)?
To answer the former, it is because the language is powerful enough to express the idea of a set without needing to bake it in. Being a language with a high emphasis on functional programming, special syntax for tuples and lists is built in, but even simple data types like Bool are defined in Prelude.
To answer the latter, well, again, with the emphasis on functional programming, most Haskellers tend to use lists. The list monad represents nondeterministic choice, and by allowing duplicates, you can sort of represent weighted choices.
Note how similar list comprehension syntax is to set notation. You can always use Set.fromList to convert a list into a "real" set, if necessary. As a begrudging shout out to Barry, this would be similar to using Python's set() method; Python has list comprehensions as well.
A: On a more philosophical level --- there can't ever be a strict correspondence between the mathematical concept of a set and a Haskell set implementation. Why not? Well, the type system, for starters. A mathematical set can have anything at all in it: {x | x is a positive integer, i < 15} is a set, but so is {1, tree, ham sandwich}. In Haskell, a Set a will need to hold some particular type. Putting Doubles and Floats into the same set won't typecheck.
As others have said, if you need to do some set-like things and don't mind the type restriction, Data.Set exists. It's not in Prelude because lists are usually more practical. But really, from a language design perspective, it doesn't make sense to think of mathematical sets as one datatype among many. Sets are more fundamental than that. You don't have sets, and numbers, and lists; you have sets of numbers, and sets of lists. The power of recursive types tends to obscure that distinction, but it's still real.
There is a place in Haskell, though, where we define arbitrary collections, and then define functions over those collections. The closest analog of the mathematical concept of sets in Haskell is the type system itself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: How to get sign of a number? Is there a (simple) way to get the "sign" of a number (integer) in PHP comparable to gmp_signDocs:
*
*-1 negative
*0 zero
*1 positive
I remember there is some sort of compare function that can do this but I'm not able to find it at the moment.
I quickly compiled this (Demo) which does the job, but maybe there is something more nifty (like a single function call?), I would like to map the result onto an array:
$numbers = array(-100, 0, 100);
foreach($numbers as $number)
{
echo $number, ': ', $number ? abs($number) / $number : 0, "\n";
}
(this code might run into floating point precision problems probably)
Related: Request #19621 Math needs a "sign()" function
A: You can nest ternary operators:
echo $number, ': ', ($number >= 0 ? ($number == 0 ? 0 : 1) : -1 )
This has no problem with floating point precision and avoids an floating point division.
A: Here's a cool one-liner that will do it for you efficiently and reliably:
function sign($n) {
return ($n > 0) - ($n < 0);
}
A: What's wrong with this form?
if ( $num < 0 )
{
//negative
}
else if ( $num == 0 )
{
//zero
}
else
{
//positive
}
or ternary:
$sign = $num < 0 ? -1 : ( $num > 0 ? 1 : 0 );
Not sure of the performance of abs vs value comparison, but you could use:
$sign = $num ? $num / abs($num) : 0;
and you could turn any of them into a function:
function valueSign($num)
{
return $sign = $num < 0 ? -1 : ( $num > 0 ? 1 : 0 );
//or
return $sign = $num ? $num / abs($num) : 0;
}
I suppose you could be talking about gmp_cmp, which you could call as gmp_cmp( $num, 0 );
A: In PHP 7 you should use the combined comparison operator (<=>):
$sign = $i <=> 0;
A: I think that gmp_sign is not very efficient because it expects a GMP or string.
($n ? abs($n)/$n : 0) is mathematically correct, but the division costs time.
The min/max solutions seem to get unnecessary complex for floats.
($n > 0) - ($n < 0) always does 2 tests and one subtraction
($n < 0 ? -1 : ($n > 0 ? 1 : 0) does one or two tests and no arithmetic, it should be most efficient.
But I don't believe that the difference will be relevant for most use cases.
A: I know this is late but what about simply dividing the number by the abs() of itself?
Something like:
function sign($n) {
return $n/(abs($n));
}
Put whatever error handling you want for div by zero.
A: Use strcmpDocs:
echo $number, ': ', strcmp($number, 0), "\n";
A: A variant to the above in my question I tested and which works as well and has not the floating point problem:
min(1, max(-1, $number))
Edit: The code above has a flaw for float numbers (question was about integer numbers) in the range greater than -1 and smaller than 1 which can be fixed with the following shorty:
min(1, max(-1, $number == 0 ? 0 : $number * INF))
That one still has a flaw for the float NAN making it return -1 always. That might not be correct. Instead one might want to return 0 as well:
min(1, max(-1, (is_nan($number) or $number == 0) ? 0 : $number * INF))
A: Here's one without loop:
function sign($number){
echo $number, ': ', $number ? abs($number) / $number : 0, "\n";
}
$numbers = array(-100, 0, 100);
array_walk($numbers, 'sign');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
}
|
Q: Ninject WCF Error OK, I'm at my wits end after hunting this error down for the past two days:
Error activating IUserIssueRepository
No matching bindings are available, and the type is not self-bindable.
Activation path:
2) Injection of dependency IUserIssueRepository into parameter userIssueRepository of constructor of type IssueTrackerService
1) Request for IssueTrackerService
Suggestions:
1) Ensure that you have defined a binding for IUserIssueRepository.
2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
3) Ensure you have not accidentally created more than one kernel.
4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
5) If you are using automatic module loading, ensure the search path and filters are correct.
I know my settings are correct (bindings intact, etc). Here are the relevant wcf service stuff. And yes, of course the assembly references are intact as well.
Global.asax.cs
using Ninject;
using Ninject.Extensions.Wcf;
namespace NextGenIT.Web.Wcf
{
public class Global : NinjectWcfApplication
{
protected override IKernel CreateKernel()
{
return new StandardKernel(new ServiceModule());
}
}
}
ServiceModule.cs
using Ninject.Modules;
using NextGenIT.Core.Domain;
namespace NextGenIT.Web.Wcf
{
public class ServiceModule : NinjectModule
{
public override void Load()
{
this.Bind<IUserIssueRepository>()
.To<SqlUserIssueRepository>();
}
}
}
IssueTrackerService.svc
<%@
ServiceHost
Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory"
Service="NextGenIT.Core.Services.IssueTrackerService"
%>
Edit 1: entire stack trace:
[FaultException`1: Error activating IUserIssueRepository
No matching bindings are available, and the type is not self-bindable.
Activation path:
2) Injection of dependency IUserIssueRepository into parameter userIssueRepository of constructor of type IssueTrackerService
1) Request for IssueTrackerService
Suggestions:
1) Ensure that you have defined a binding for IUserIssueRepository.
2) If the binding was defined in a module, ensure that the module has been loaded into the kernel.
3) Ensure you have not accidentally created more than one kernel.
4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name.
5) If you are using automatic module loading, ensure the search path and filters are correct.
]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +4729827
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +1725
NextGenIT.Services.Contracts.IIssueTrackerService.GetUserIssues(String userId) +0
NextGenIT.Services.Client.IssueTrackerClient.GetUserIssues(String userId) in D:\Projects\TFS\NextGenIssueTracker\branches\2011Updates\NextGenIT.Services.Client\Proxies\IssueTrackerClient.cs:46
NextGenIT.Tests.Integration.WebClient._default.Page_Load(Object sender, EventArgs e) in D:\Projects\TFS\NextGenIssueTracker\branches\2011Updates\NextGenIT.Tests.Integration.WebClient\default.aspx.cs:26
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3064
Edit 2: interface and implementation
IUserIssueRepository.cs
using System.Collections.Generic;
using NextGenIT.Services.Contracts;
namespace NextGenIT.Core.Domain
{
public interface IUserIssueRepository
{
string CreateUser(IUser user);
int CreateIssue(IIssue issue);
int CreateComment(IComment comment);
IUser GetUser(string userId);
IIssue GetIssue(int issueId);
IEnumerable<IIssue> GetIssues(string userId);
IEnumerable<IComment> GetComments(string userId, int issueId);
}
}
SqlUserIssueRepository.cs
using System.Collections.Generic;
using NextGenIT.Services.Contracts;
namespace NextGenIT.Core.Domain
{
public class SqlUserIssueRepository : IUserIssueRepository
{
public string CreateUser(IUser user) { return "1234"; }
public int CreateIssue(IIssue issue) { return 1; }
public int CreateComment(IComment comment) { return 1; }
public IUser GetUser(string userId) { return null; }
public IIssue GetIssue(int issueId) { return null; }
public IEnumerable<IIssue> GetIssues(string userId) { return null; }
public IEnumerable<IComment> GetComments(string userId, int issueId) { return null; }
}
}
A: Update:
At some point I had renamed the project hosting the WCF service. I never thought to check the markup of the global.asax.
Indeed it was inheriting from a file that no longer existed. The project compiled no problem, that's why I never thought to check there!
A: This could be caused by SqlUserIssueRepository not implementing IUserIssueRepository.
Ninject is trying to bind the class to the interface.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Silverlight 4. Need same instance in multiple groups I want to display a class presenting a worker who have different skills.
The datagrid must be able to group by Skills
So worker 1 have skills C# and Java
Worker 2 have skills SQL and C#
My grid should display the following
C#
*
*Worker 1
*Worker2
Java
*
*Worker 1
SQL
*
*Worker 2
(The sort order is not relevant)
A: You can use LINQ to group them how you want:
var WorkersGroupedBySkills =
Workers
.SelectMany(w => w.Skills)
.Distinct()
.Select(s=>new{Skill=s,Workers=Workers.Where(w=>w.Skills.Contains(s))});
Then create the UI to display the higherachy using an Items Control with a data template which contains and expander and within the expander, a grid to show the workers with those skills.
Alternatively there are a number of third party grids with grouping capabilities which may be able to handle the new data model.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: String manipulation in R to create dataframe column I have an R dataframe(df) which includes a factor column, Team
Team
Baltimore Orioles
Kansas City Chiefs
...
I just want to create a new column, nickname, which just refers to the last name
Nickname
Orioles
Chiefs
As a first stage, I have tried splitting the factor like this
df$Nickname <- strsplit(as.character(df$Team), " ")
which produces a list of character fields which I can reference thus
>df$Nickname[1]
[[1]]
[1] "Baltimore" "Orioles"
and
>str(df$Nickname[1])
List of 1
$ : chr [1:2] "Baltimore" "Orioles"
but then I do not know how to proceed. Trying to get the length
length(df$Nickname[1])
gives 1 - which flummoxes me
A: Use a regular expression:
text <- c("Baltimore Orioles","Kansas City Chiefs")
gsub("^.*\\s", "", text)
[1] "Orioles" "Chiefs"
The regex searches for:
*
*^ means the start of the string
*.* means any character, repeated
*\\s means a single white space
gsub finds this pattern and replaces it with an empty string, leaving you with the last word of each string.
A: you just need to unlist the split strings and take the last one
full <- c("Baltimore Orioles","Kansas City Chiefs")
getlast <- function(x){
parts <- unlist(strsplit(x, split = " "))
parts[length(parts)]
}
sapply(full,getlast)
> Baltimore Orioles Kansas City Chiefs
> "Orioles" "Chiefs"
A: How about this?
require(plyr)
ldply(df$Nickname)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iTunes Connect: App name with special characters (german 'umlaute') Today I wanted to submit a new german app with an 'umlaut' in app name: "Börse".
There are plenty of Apps in the AppStore with special characters "Diät, Führerschein" etc.
When I enter the app name a JavaScript onBlur event send the name to a server and then every special charcters are stripped out.
Can anyone confirm this problem? I tested it under OS X Snow Leopard, Windows 7, Chrome, Safari, Firefox. I also disabled JavaScript, but still no luck.
Screenshots:
http://dl.dropbox.com/u/2213241/Bildschirmfoto%202011-09-26%20um%2016.11.31.png
http://dl.dropbox.com/u/2213241/Bildschirmfoto%202011-09-26%20um%2016.11.16.png
Anyone has a workround for this one? I also created a apple support ticket.
A: In the past, I've kept the product name alphanumeric but used the Bundle Display Name in the Info.plist file to use additional/different characters.
I ran into a similar problem a while back with the + character - I couldn't sign any apps with the character in the bundle name. So, I changed the name from Xxx+ to XxxPlus and set the Bundle Display Name to Xxx+. Looked like I wanted it to in the GUI and the signing worked fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is the Javascript date object always one day off? In my Java Script app I have the date stored in a format like so:
2011-09-24
Now when I try using the above value to create a new Date object (so I can retrieve the date in a different format), the date always comes back one day off. See below:
var date = new Date("2011-09-24");
console.log(date);
logs:
Fri Sep 23 2011 20:00:00 GMT-0400 (Eastern Daylight Time)
A: You can convert this date to UTC date by
new Date(Date.UTC(Year, Month, Day, Hour, Minute, Second))
And it is always recommended to use UTC (universal time zone) date instead of Date with local time, as by default dates are stored in Database with UTC. So, it is good practice to use and interpret dates in UTC format throughout entire project.
For example,
Date.getUTCYear(), getUTCMonth(), getUTCDay(), getUTCHours()
So, using UTC dates solves all the problem related to timezone issues.
A: To normalize the date and eliminate the unwanted offset (tested here : https://jsfiddle.net/7xp1xL5m/ ):
var doo = new Date("2011-09-24");
console.log( new Date( doo.getTime() + Math.abs(doo.getTimezoneOffset()*60000) ) );
// Output: Sat Sep 24 2011 00:00:00 GMT-0400 (Eastern Daylight Time)
This also accomplishes the same and credit to @tpartee (tested here : https://jsfiddle.net/7xp1xL5m/1/ ):
var doo = new Date("2011-09-24");
console.log( new Date( doo.getTime() - doo.getTimezoneOffset() * -60000 ) );
A: This through me for a loop, +1 on zzzBov's answer. Here is a full conversion of a date that worked for me using the UTC methods:
//myMeeting.MeetingDate = '2015-01-30T00:00:00'
var myDate = new Date(myMeeting.MeetingDate);
//convert to JavaScript date format
//returns date of 'Thu Jan 29 2015 19:00:00 GMT-0500 (Eastern Standard Time)' <-- One Day Off!
myDate = new Date(myDate.getUTCFullYear(), myDate.getUTCMonth(), myDate.getUTCDate());
//returns date of 'Fri Jan 30 2015 00:00:00 GMT-0500 (Eastern Standard Time)' <-- Correct Date!
A: I believe that it has to do with time-zone adjustment. The date you've created is in GMT and the default time is midnight, but your timezone is EDT, so it subtracts 4 hours. Try this to verify:
var doo = new Date("2011-09-25 EDT");
A: There are several crazy things that happen with a JS DATE object that convert strings, for example consider the following date you provided
Note: The following examples may or may not be ONE DAY OFF depending on YOUR timezone and current time.
new Date("2011-09-24"); // Year-Month-Day
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF.
However, if we rearrange the string format to Month-Day-Year...
new Date("09-24-2011");
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.
Another strange one
new Date("2011-09-24");
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF AS BEFORE.
new Date("2011/09/24"); // change from "-" to "/".
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.
We could easily change hyphens in your date "2011-09-24" when making a new date
new Date("2011-09-24".replace(/-/g, '\/')); // => "2011/09/24".
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.
What if we had a date string like "2011-09-24T00:00:00"
new Date("2011-09-24T00:00:00");
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF.
Now change hyphen to forward slash as before; what happens?
new Date("2011/09/24T00:00:00");
// => Invalid Date.
I typically have to manage the date format 2011-09-24T00:00:00 so this is what I do.
new Date("2011-09-24T00:00:00".replace(/-/g, '\/').replace(/T.+/, ''));
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.
UPDATE
If you provide separate arguments to the Date constructor you can get other useful outputs as described below
Note: arguments can be of type Number or String. I'll show examples with mixed values.
Get the first month and day of a given year
new Date(2011, 0); // Normal behavior as months in this case are zero based.
// => Sat Jan 01 2011 00:00:00 GMT-0700 (MST)
Get the last month and day of a year
new Date((2011 + 1), 0, 0); // The second zero roles back one day into the previous month's last day.
// => Sat Dec 31 2011 00:00:00 GMT-0700 (MST)
Example of Number, String arguments. Note the month is March because zero based months again.
new Date(2011, "02");
// => Tue Mar 01 2011 00:00:00 GMT-0700 (MST)
If we do the same thing but with a day of zero, we get something different.
new Date(2011, "02", 0); // Again the zero roles back from March to the last day of February.
// => Mon Feb 28 2011 00:00:00 GMT-0700 (MST)
Adding a day of zero to any year and month argument will get the last day of the previous month. If you continue with negative numbers you can continue rolling back another day
new Date(2011, "02", -1);
// => Sun Feb 27 2011 00:00:00 GMT-0700 (MST)
A: It means 2011-09-24 00:00:00 GMT, and since you're at GMT -4, it will be 20:00 the previous day.
Personally, I get 2011-09-24 02:00:00, because I'm living at GMT +2.
A: Though in the OP's case the timezone is EDT, there's not guarantee the user executing your script will be int he EDT timezone, so hardcoding the offset won't necessarily work. The solution I found splits the date string and uses the separate values in the Date constructor.
var dateString = "2011-09-24";
var dateParts = dateString.split("-");
var date = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
Note that you have to account for another piece of JS weirdness: the month is zero-based.
A: I encountered this exact problem where my client was on Atlantic Standard Time. The date value the client retrieved was "2018-11-23" and when the code passed it into new Date("2018-11-23") the output for the client was for the previous day. I created a utility function as shown in the snippet that normalized the date, giving the client the expected date.
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
var normalizeDate = function(date) {
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
return date;
};
var date = new Date("2018-11-23");
document.getElementById("default").textContent = date;
document.getElementById("normalized").textContent = normalizeDate(date);
<h2>Calling new Date("2018-11-23")</h2>
<div>
<label><b>Default</b> : </label>
<span id="default"></span>
</div>
<hr>
<div>
<label><b>Normalized</b> : </label>
<span id="normalized"></span>
</div>
A: My solution to parse an ISO date without beeing annoyed by the timezone is to add a "T12:00:00" at the end before parsing it, because when it's noon at Greenwich, well the whole world is on the same day :
function toDate(isoDateString) {
// isoDateString is a string like "yyyy-MM-dd"
return new Date(`${isoDateString}T12:00:00`);
}
Before:
> new Date("2020-10-06")
> Date Mon Oct 05 2020 14:00:00 GMT-1000 (heure normale d’Hawaii - Aléoutiennes)
After:
> toDate("2020-10-06")
> Date Tue Oct 06 2020 12:00:00 GMT-1000 (heure normale d’Hawaii - Aléoutiennes)
A: Just want to add that apparently adding a space at the end of the string will use UTC for creation.
new Date("2016-07-06")
> Tue Jul 05 2016 17:00:00 GMT-0700 (Pacific Daylight Time)
new Date("2016-07-06 ")
> Wed Jul 06 2016 00:00:00 GMT-0700 (Pacific Daylight Time)
Edit: This is not a recommended solution, just an alternative answer. Please do not use this approach since it is very unclear what is happening. There are a number of ways someone could refactor this accidentally causing a bug.
A: If you want to get hour 0 of some date in the local time zone, pass the individual date parts to the Date constructor.
new Date(2011,08,24); // month value is 0 based, others are 1 based.
A: if you need a simple solution for this see:
new Date('1993-01-20'.split('-'));
A: if you're just looking to make sure the individual parts of the date stay the same for display purposes, *this appears to work, even when I change my timezone:
var doo = new Date("2011-09-24 00:00:00")
just add the zeros in there.
In my code I do this:
let dateForDisplayToUser =
new Date( `${YYYYMMDDdateStringSeparatedByHyphensFromAPI} 00:00:00` )
.toLocaleDateString(
'en-GB',
{ day: 'numeric', month: 'short', year: 'numeric' }
)
And I switch around my timezone on my computer and the date stays the same as the yyyy-mm-dd date string I get from the API.
But am I missing something/is this a bad idea ?
*at least in chrome. This Doesn't work in Safari ! as of this writing
A: As most answers are hacky, allow me to propose my very simple hack that worked for me: Set the script's timezone to UTC
process.env.TZ = 'UTC' // this has to be run before any use of dates
With this change, any timezone modifications are neutralized, so as long as you don't need the runner's actual timezone, this is probably the easiest fix.
A:
// When the time zone offset is absent, date-only formats such as '2011-09-24'
// are interpreted as UTC time, however the date object will display the date
// relative to your machine's local time zone, thus producing a one-day-off output.
const date = new Date('2011-09-24');
console.log(date); // Fri Sep 23 2011 17:00:00 GMT-0700 (PDT)
console.log(date.toLocaleDateString('en-US')); // "9/23/2011"
// To ensure the date object displays consistently with your input, simply set
// the timeZone parameter to 'UTC' in your options argument.
console.log(date.toLocaleDateString('en-US', { timeZone: 'UTC' })); // "9/24/2011"
A: Notice that Eastern Daylight Time is -4 hours and that the hours on the date you're getting back are 20.
20h + 4h = 24h
which is midnight of 2011-09-24. The date was parsed in UTC (GMT) because you provided a date-only string without any time zone indicator. If you had given a date/time string w/o an indicator instead (new Date("2011-09-24T00:00:00")), it would have been parsed in your local timezone. (Historically there have been inconsistencies there, not least because the spec changed more than once, but modern browsers should be okay; or you can always include a timezone indicator.)
You're getting the right date, you just never specified the correct time zone.
If you need to access the date values, you can use getUTCDate() or any of the other getUTC*() functions:
var d,
days;
d = new Date('2011-09-24');
days = ['Sun', 'Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat'];
console.log(days[d.getUTCDay()]);
A: Your issue is specifically with time zone. Note part GMT-0400 - that is you're 4 hours behind GMT. If you add 4 hours to the displayed date/time, you'll get exactly midnight 2011/09/24. Use toUTCString() method instead to get GMT string:
var doo = new Date("2011-09-24");
console.log(doo.toUTCString());
A: This probably is not a good answer, but i just want to share my experience with this issue.
My app is globally use utc date with the format 'YYYY-MM-DD', while the datepicker plugin i use only accept js date, it's hard for me to consider both utc and js. So when i want to pass a 'YYYY-MM-DD' formatted date to my datepicker, i first convert it to 'MM/DD/YYYY' format using moment.js or whatever you like, and the date shows on datepicker is now correct. For your example
var d = new Date('2011-09-24'); // d will be 'Fri Sep 23 2011 20:00:00 GMT-0400 (EDT)' for my lacale
var d1 = new Date('09/24/2011'); // d1 will be 'Sat Sep 24 2011 00:00:00 GMT-0400 (EDT)' for my lacale
Apparently d1 is what i want. Hope this would be helpful for some people.
A: The best way to handle this without using more conversion methods,
var mydate='2016,3,3';
var utcDate = Date.parse(mydate);
console.log(" You're getting back are 20. 20h + 4h = 24h :: "+utcDate);
Now just add GMT in your date or you can append it.
var mydateNew='2016,3,3'+ 'GMT';
var utcDateNew = Date.parse(mydateNew);
console.log("the right time that you want:"+utcDateNew)
Live: https://jsfiddle.net/gajender/2kop9vrk/1/
A: I faced some issue like this. But my issue was the off set while getting date from database.
this is stroed in the database and it is in the UTC format.
2019-03-29 19:00:00.0000000 +00:00
So when i get from database and check date it is adding offset with it and send back to javascript.
It is adding +05:00 because this is my server timezone. My client is on different time zone +07:00.
2019-03-28T19:00:00+05:00 // this is what i get in javascript.
So here is my solution what i do with this issue.
var dates = price.deliveryDate.split(/-|T|:/);
var expDate = new Date(dates[0], dates[1] - 1, dates[2], dates[3], dates[4]);
var expirationDate = new Date(expDate);
So when date come from the server and have server offset so i split date and remove server offset and then convert to date. It resolves my issue.
A: Trying to add my 2 cents to this thread (elaborating on @paul-wintz answer).
Seems to me that when Date constructor receives a string that matches first part of ISO 8601 format (date part) it does a precise date conversion in UTC time zone with 0 time. When that date is converted to local time a date shift may occur
if midnight UTC is an earlier date in local time zone.
new Date('2020-05-07')
Wed May 06 2020 20:00:00 GMT-0400 (Eastern Daylight Time)
If the date string is in any other "looser" format (uses "/" or date/month is not padded with zero) it creates the date in local time zone, thus no date shifting issue.
new Date('2020/05/07')
Thu May 07 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
new Date('2020-5-07')
Thu May 07 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
new Date('2020-5-7')
Thu May 07 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
new Date('2020-05-7')
Thu May 07 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
So then one quick fix, as mentioned above, is to replace "-" with "/" in your ISO formatted Date only string.
new Date('2020-05-07'.replace('-','/'))
Thu May 07 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
A: You can use moment library to format the date.
https://momentjs.com/
let format1 = "YYYY-MM-DD"
let date = new Date();
console.log(moment(date).format(format1))
EDIT
The moment is now deprecated, you can use date-fns format method for formatting a date.
import { format } from 'date-fns'
format(new Date(), "yyyy-MM-dd")
A: This solved my problem (thanks to @Sebastiao answer)
var date = new Date();
//"Thu Jun 10 2021 18:46:00 GMT+0200 (Eastern European Standard Time)"
date.toString().split(/\+|-/)[0] ; // .split(/\+|-/) is a regex for matching + or -
//"Thu Jun 10 2021 18:46:00 GMT"
var date_string_as_Y_M_D = (new Date(date)).toISOString().split('T')[0];
//2021-06-10
A: I just wanted to give my 2 cents on this, as this post was very helpful to figure out the issue. I don't think I've seen this solution mentioned, correct me if I'm wrong.
As it has been mentioned numerous times already here, the problem comes mainly from summer/winter time. I noticed that in January, the GMT was +1. If the time is not set, it will always be 00.00.00 (midnight), which results in going on the 23rd hour of the previous day.
If you have a dynamic date and don't care about the hour, you can set the hour using the setHours() method before using it with toISOString().
syntax:
setHours(hoursValue, minutesValue, secondsValue, msValue)
Which means that:
dynamicDate.setHours(12, 0, 0, 0)
dynamicDate.toISOString()
should hopefully work for you as even if the date is one hour ahead/behind it will still be the same day now that we're setting the hour to be noon.
More about setHours() on MDN.
A: You are using the ISO date string format which, according to this page, causes the date to be constructed using the UTC timezone:
Note: parsing of date strings with the Date constructor (and
Date.parse, they are equivalent) is strongly discouraged due to
browser differences and inconsistencies. Support for RFC 2822 format
strings is by convention only. Support for ISO 8601 formats differs in
that date-only strings (e.g. "1970-01-01") are treated as UTC, not
local.
If you format the text differently, such as "Jan 01 1970", then (at least on my machine) it uses your local timezone.
A: Storing yyyy-mm-dd in MySql Date format you must do the following:
const newDate = new Date( yourDate.getTime() + Math.abs(yourDate.getTimezoneOffset()*60000) );
console.log(newDate.toJSON().slice(0, 10)); // yyyy-mm-dd
A: Following Code worked for me. First I converted to date and time string to localeDateString then apply the split function on the returned string.
const dateString = "Thu Dec 29 2022 00:00:00 GMT+0500 (Pakistan Standard Time)";
const date = new Date(dateString).toLocaleDateString().split("/");
const year = new Date(dateString).getFullYear();
const month = new Date(dateString).getMonth();
console.log(new Date(`${date[2]}-${date[0]}-${date[1]}`));
// 2022-12-29T00:00:00.000Z
// Due to timezone issue, the date is one day off.
console.log(new Date("2011-09-24"));
// => 2011-09-24T00:00:00.000Z-CORRECT DATE.
console.log(new Date("2011/09/24"));
// => 2011-09-23T19:00:00.000Z -ONE DAY OFF AS BEFORE.
A: The following worked for me -
var doo = new Date("2011-09-24").format("m/d/yyyy");
A: Using moment you can keep Offset while converting toISOString
let date = moment("2022-03-15").toISOString();
// WRONG OUTPUT 2022-03-14T18:30:00.000Z
let date = moment("2022-03-15").toISOString(true);
// CORRECT OUTPUT 2022-03-15T00:00:00.000+05:30
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "397"
}
|
Q: Dojox charting programmatically using store series I have been trying to get dojo charting working using the programmatic method. I have tried the following but the graph is not showing.
//Requirements
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require('dojox.charting.Chart2D');
dojo.require('dojox.charting.widget.Chart2D');
dojo.require('dojox.charting.themes.PlotKit.blue');
dojo.require('dojox.charting.plot2d.Columns');
dojo.require('dojox.charting.StoreSeries');
dojo.ready(function() {
var data = {"identifier":"MyMonth","label":"MyMonth","items":[{"MyAmount":"98498.67","MyMonth":"1"},{"MyAmount":"114384.10","MyMonth":"2"},{"MyAmount":"125307.86","MyMonth":"3"},{"MyAmount":"87534.38","MyMonth":"4"},{"MyAmount":"90376.60","MyMonth":"5"},{"MyAmount":"96233.60","MyMonth":"6"},{"MyAmount":"112824.29","MyMonth":"7"},{"MyAmount":"119593.06","MyMonth":"8"},{"MyAmount":"95691.64","MyMonth":"9"}]};
var mystore= new dojo.data.ItemFileWriteStore({data: data});
var chart1 = new dojox.charting.Chart2D('testChart').
setTheme(dojox.charting.themes.PlotKit.blue).
addAxis('x', {min: 0, max: 12}).
addAxis('y', { vertical: true, min: 1}).
addPlot('default', {type: 'Columns'}).
addSeries("My Month", new dojox.charting.StoreSeries(mystore, {query:{}}, "MyMonth")).
render();
});
A: Instead of using dojox.charting.StoreSeries, I used the dojox.charting.DataSeries while using the same code and it worked
addSeries("My Month", new dojox.charting.DataSeries(mystore, {query:{}}, "MyMonth")).
Thats it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Primary Key Generated From External System What are the general guidelines for the following scenario:
You need to create a table where the PK is a value that is generated from an external system. It is unique, similar to using a SSN.
Does it make sense for this to be the primary key? Especially considering it will be used in foreign key relationships with two other tables. Or, would it be better to create an auto-incrementing ID field in addition to the unique key, and use the auto-incrementing ID in the table relationships?
A: I would always create my own surrogate primary key, and set the natural identifier as a secondary unique key.
Scott W Ambler has a good comparison of the two strategies here.
A: Personally, I wouldn't trust an ID from an external system. Sure, they'll promise you today that it will be unique, never change and never be reused. But then, some day in the future...
Create your own auto-incrementing ID and use that for the PK and FK relationships. Keep their ID only as a reference.
A: Using your own auto generated Id will give you another field in a table with excess information. If external ID is like SSN I think you will hardly receive duplicates. I choose to make external ID as PK.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Am I presenting my viewControllers correctly? I am developing an app which requires the user to login first before using the rest of the service.
This app is made out of tab bar controller with 4 tab bar items. All these 4 tab bar items has navigation controller.
Right now, I am presenting the loginViewController modally. I implemented a 'Remember Me' feature during login which will the user automatically be logged in the next time he re-launches the app. I do this by saving a indicator using NSUserDefaults and during viewDidLoad, checks for whether did the user opted for 'remember me' and present loginViewController modally if needed.
when the user logs out, I will then present loginViewController modally again and remove the NSUserDefaults. But then this will make the rest of the viewController of the tabBarController remain the same state as before the user logs out, which means when user logs in again it will not be a fresh copy. How do I make sure it's a fresh copy when ever the user logs in? Meaning the textFields and all, should not shown amendments made during previous logins.
All in all, I want to load a fresh copy of the tabBarController viewController whenever the user logs in.
A: iPhone is a "personal" device. It's not a web browser. A browser is different. On iPhone, avoid having an explicit logout if possible, or make it extremely difficult to find the logout button.
Facebook, Twitter, Foursquare all do this. Your phone is always with you and privacy conscious users are going to set a unlock password. Even other wise a lost phone can be wiped remotely (unlike a browser).
Think mobile when developing for a mobile device. Not every functionality you have on your web app needs to be implemented on the mobile device.
Having said that, if you still need a logout mechanism, nsnotifications are the way to go.
A: On pressing the logout button, make sure that you deallocate all active views. When you log back in, create a allocate a fresh set of views.
You can do the check for the login or logout with NSUserDefaults and the whole process have to be logically sync. The only thing you need to be worried about is properly deallocating all views and removing them appropriately when you log back again. Make sure that there are no memory leaks and your view controllers follow Apple's guidelines for Memory Management .
A: This is how I would do it :
viewWillAppear gets called everytime you open the Tab. you can reload view contents in viewWillAppear.
this solutions reloads the view every time user opens the view. there is better way to do this by saving last User State, So everytime user comes on the view, check if UserState (i.e. LoggedIn/LoggedOut) if it matches then no need to reload, if it doesn't reload the view.
A: There are a couple of ways to do this. One is to send an NSNotification on logout and have all the views which need to reload their information observe that notification and do the update.
Another way would be to update each view's data on viewDidAppear. The main downside with this method is that it will update every time, whether they logged out or not.
The notification way works like this:
In the logout view controller:
if (userDidLogout)
{
[[NSNotificationCenter defaultCenter] postNotificationName: USER_LOGOUT_NOTIFICATION];
}
In the view controllers that need to know:
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(updateMyData:) name: USER_LOGOUT_NOTIFICATION object: nil]
//...
- (void) updateMyData: (NSNotification*) note
{
// ...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7556602",
"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.