text stringlengths 8 267k | meta dict |
|---|---|
Q: SSIS: C# Script task: How to change a SQL connection string based on server environment that the dtsx is running on? I have a script task where i change the connection string for a db, however, it is missing one vital piece of information which is the server that the package itself is running on.
is there a way to retrieve the name of the server from a c# script?
i know in sql i can do select @@servername, but i need the package to check the name of the server that it(dtsx) is running on which is not the sql server.
i know this is an odd request, but there are many options, here are the ones that i am researching now:
+Through A Batch CMD whose results i could store in a pkg level variable
+Through a c# script
+SQL if it is possible
any other ways anyone knows of would be greatly appreciated.
EDIT/UPDATE: I found a couple of ways to do this:
C#: public string host = System.Environment.MachineName.ToString();
cmd: hostname ...-->then store in pkg variable
A: While you can use .NET to get the server name, the traditional SSIS way is to use the pre-existing "System::MachineName" package variable (as an aside, note that you might have to click the "Show System Variables" button to see it in the package Variables window.) Assuming SSIS 2008 and C# (2005/VB provides the same variable):
1) Add the variable name "System::MachineName" (without the quotes) to the script task editor ReadOnlyVariables property
2) Inside the script you access the variable like this:
Dts.Variables["System::MachineName"].Value.ToString()
Hope it helps.
Kristian
A: Kristian has the proper solution, use the native variables and skip the convoluted roads you were trying to go down. I didn't want to make such a drastic edit as this to their post but thought screenshots would help beef up the answer.
If you haven't created any variables in your package, this is what your default variable window will look like
Click the grey X icon and that will display the available system variables and their current values. Some values are set at creation time - CreatorName, CreatorComputerName; others change as the result of an event (save auto-increments VersionBuild); while still others change as a result of a package being executed (StartTime, ContainerStartTime, MachineName, etc)
Finally, please also note that some system variables are context dependent. As you can see in the scope, the OnError system variables expose things like ErrorCode, ErrorDescription, etc.
A: Create a new Script Task before your SQL Query tasks. Use a script task to update the ConnectionString like this (assuming your connection name is "SQLConnection":
Dts.Connections("SQLConnection").ConnectionString = "Data Source =" + System.Environment.MachineName.ToString() + ";Initial Catalog =myDataBase; Integrated Security =SSPI;";
I remember the UI being particularly restrictive on where and when this variable is set, but I have done this in the past. Let me know if you encounter issues.
A: I have earlier used an environment variable (windows) which my package reads at the startup and get is connection string from it!
You can use package configuration to achieve this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Implement URL aliases in CakePHP I'm new to CakePHP, though not new at all to MVC frameworks for web development. I'd normally go with Drupal when doing web sites that are not web apps but my employee feels that coding stuff from the ground up is far better than using pre built well tested and working solutions. Sigh.
Anyways, he agreed to at least let me use a framework, and I chose CakePHP because a) I've always wanted to learn it, and b) I love Rails so much I can't honestly go back to Zend once more :) Whatever, I decided to have some Cake so bear with me :)
I set up a whole lot of controllers and stuff implementing all the features of the site, and now I'd need to set up Drupal-like url aliases. Such an alias is something that lets you request http://www.example.com/this-be-me-page and display the same page that you'd have seen if you requested http://www.example.com/pages/42 for example. Or return the same as /article/301 when you type /blog/the-most-excellent-post-ever — I guess you got how it works.
I set up a database and a model such that I can query for the "alias" and retrieve the "internal url", then I'm stuck. It seemed that calling
$html = $this->requestAction($internal_url, array('return'));
would have returned the fully rendered HTML as if my user directly requested $internal_url but it's not the case. I only get the HTML for the action's view, without all the awesome layout stuff.
I'm going this database/controller way because I'd like site's admins to be able to edit the aliases via browser, not by editing some obscure routing directives or the .htacces. It's also much quicker to log in, create a page, set the alias and go out for lunch.
Now: how do I do it?
EDIT Mimicking the behaviour of app/webroot/index.php I wrote this action for my AliasController:
public function parse() {
$alias = $this->request->params['url'];
$record = $this->Alias->findByAlias($alias);
$request = $record['Alias']['request'];
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch(new CakeRequest($request), new CakeResponse(array('charset' => Configure::read('App.encoding'))));
die;
}
Except for the name (it doesn't really parse anything, does it?) it works fine… at least it does what I wanted it to do. But I still feel dirty :) Does anybody have suggestions?
A: Sorry for the late answer.
What you want to do is to re-do the parse method that CakeRoute uses. This way you can do as you want and parse the entry, and even use database to get the id of a slug like url. it is explain in more detail here you can do it like in the example, and add a if clause that if didn't find anything and (is numeric && !empty()) go as usual id...
Hope this works, i test it in 1.3 it SHOULD work in 2.0 since this is a feature NEW to 1.3 so you can create custom routes (i imagine lot of people had the same problem as you do) so i think it's going to work :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Accessing JavaScript function from C# class function? ASP.Net Web Application.
Is it possible to access a JavaScript function located on the master page from a C# class function?
Below is a description of what I'm attempting to do...
When user clicks save button, database procedure called that returns value indicating if it was successful. This value is fed into a C# function which is located in a C# class file. This function determines if the save was successful and has two paths:
Successful Path: Store "Save Successful" in session variable. Call JavaScript function that momentarily displays the message that is stored in the session variable.
Failure Path: Reverse all changes made with this transaction number. Store "Save was unsuccessful" in session variable. Call JavaScript function to display message that is stored in the session variable.
I'd like to use JavaScript to display the message since I have the ability to do it neatly and without requiring the user to click a button.
Thanks for your help! :)
A: Use Ajax. Make a call with JavaScript to a ASP.Net PageMethod and have the return value be the string response ("Success"/"Failure"). Here's an article that will help you accomplish this:
Calling PageMethods With jQuery
Good luck!
A: You can inject JavaScript.
http://msdn.microsoft.com/en-us/library/aa478975.aspx
A: In general, no. I'm not saying that it is impossible, but this is not the normal way.
Let me explain. The C# code runs on the server, and is used to assemble the page and scripts to be delivered to the browser. The browser executes the javascript. (The browser contains a javascript runtime engine to accomplish this.)
You can call C# code from javascript, but only if the C# code is exposed via a web service. (Think [WebMethod]).
The server doesn't normally have a javascript runtime engine to use when creating a page.
I think for your case, the easiest path to a solution would be to display the message directly using the C# code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting unused port number in C dynamically when running server process I am using C and writing a client-server program, and I would like to get an unused port number to run my server process. My server code is like this:
getaddrinfo()
socket()
bind()
listen
while(1)
accept()
I need to provide the unused port addr to the bind() call. But I do not want to pass the port number via command line while starting the server process. The port number should be got via a socket call, and I need to use that to start my client process. Is there any socket call which would help me get an unused port dynamically in C ?
A: Just bind() your socket setting sin_port to 0 in sockaddr_in. System will automatically select unused port. You can retrieve it by calling getsockname().
But I don't have any idea how to pass it to client, except printing it and using as command-line parameter for client program.
A: That would be a huge race condition. Imagine this sequence of events:
*
*Your code uses the (non-existant) getNextFreePort() call.
*Another process creates a new socket without specifying a port, getting "your" number assigned to it.
*You try to bind(), which fails with "address in use".
This is why servers tend to have "well-known" addresses, since that's needed in order for a client to know where it should connect.
Also, unless I'm misunderstadning, you seem to expect the client to be able to call getNextFreePort() when starting, and then magically get the port number that server has already gotten, and used? That doesn't make a lot of sense, so hopefully I'm misunderstanding you.
A: Since you're on Linux/Unix, this is exactly a situation that the RPC portmapper was designed to solve. Your server bind()s to an unused port (port 0), then registers the resulting actual port (fetched with getsockname() with the portmapper by application/service name.
Clients then query portmapper on its known port, asking for what port that named service is actually running on.
portmapper RPC isn't as popular as it used to be
If servers and clients are on the same box:
Another alternative is to use some sort of naming scheme for a shared file (create a temporary file /tmp/servport.xxxxx), replacing xxxxx with the port.
Or you could create a shared memory segment that the server stashes its port into. Clients would attach to the same shared memory, read the port, and connect as normal.
Or your server could create a unix domain socket on a known/shared path, and clients could connect to that, asking for what port the server is on. (obviously you could just do all IPC this way if they are both local!)
Lots of options with IPC...
A: If you bind() to a random or unpredictable address+portnumber, the clients may experience some difficulty finding your server and connecting to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Planning to start Iphone game in Unity engine..Suggestions/Experiences? I am new on unity and iphone game development. I have been instructed to make a game for iphone. After alot of research and google I am now thinking to use Unity3d game engine as it compiles code for almost every device plus no extensive coding.
What do you people suggest am I planning right ?
Is there any issues playing unity game on Iphone ?
Would I need to modify it in Xcode also ?
Pls suggest me abt it. Thnx
A: I have worked with Unity3d, but not for iPhone, but Unity seems to be the right direction because of its simplicity and sheer quality of the engine. Unity3d is great for beginners as well as for low-medium budget game projects. Highly recommended.
By the way this question doesn't belong here, use GameDev SE for non-programming game development issues.
A: The Unity engine is a great choice because it makes it easy to visually assemble your levels. While it does help you organize and integrate your game assets and components, don't think you can get by with minimal coding if you plan to build a game of any kind of scope. You'll still need to code, just not excessively.
A: I started developing iPhone apps with Unity3d as well. First of all, I want to say that deployment with Unity3d is extremely hard compared to making your app with swift, objective-c/objective-c++, and Xcode. Unity3d was easier for me to grip on to and create games with than my experiences with Xcode though. The only part where I would give Unity3d a 0 out of 5 stars is deployment. Some reasons why I say this is resolution, auto-generated Xcode errors, low-quality iPhone deployment help for indie developers, and many other reasons. I created a tilting ball game like a maze game that I wanted to put on the App Store. However, Apple kept rejecting my app due to the horrible build Unity3d made of my project. After 5 continuous tries to put my app on the app store, I decided to go an easier developer way and to head towards learning the foundation programming language of iOS apps, Swift. I would say that Swift was a very horrible experience compared to Unity3d. Unity3d had a very easy C# editor and drag and drop user interface. Xcode didn't have that much though. In Xcode, creating new scenes, making transitions and many other things were a very intimidating task for me. I don't want for you to go with the same problems I did so I would really recommend you starting with Xcode and not going straight to Unity3d. If you do go to Unity3d, remember what I said.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: MySQL Join Improvement I'm having trouble getting MySQL to return a query properly.
Here's my data:
id date value
2 2011-01-04 55.66
2 2011-03-23 22.33
2 2011-04-21 9.44
5 2010-01-04 104.55
5 2011-02-03 38.82
... ... ...
i'm trying to get a query to return:
select t1.id, max(t1.date), t1.value, t2.id, min(t2.date), t2.value
from tab1 as t1, tab1 as t2
where t1.id = t2.id
and t1.date <= '2011-03-31'
and t2.date >= '2011-04-01'
group by t1.id;
But it is taking forever (db has ~ 1mm lines). I've tried various joins but then it seems to ignore the date < and > statements. Basically I want each customers last purchase date and amount before 4/1/2011 and their first purchase and date on or after 4/1/2011. Any suggestions would be great.
A: SELECT t2.*
FROM tab1 t2
INNER JOIN
(SELECT t1.id,
MIN(CASE WHEN t1.date>='2011-04-01' THEN t1.date END) as min_date_1,
MAX(CASE WHEN t1.date<='2011-03-31' THEN t1.date END) as max_date_2
SUM(CASE WHEN t1.date>='2011-04-01' THEN t1.value END) sum_1,
SUM(CASE WHEN WHEN t1.date<='2011-03-31' THEN t1.value END) sum_2
FROM tab1 t1
GROUP BY t1.id)a ON
(a.id = t2.id AND (t2.date = a.min_date_1 OR t2.date = a.max_date_2))
It should work fairly quick assuming you have index on (id, date).
UPDATED Sum added
A: Your query is flawed, the columns t1.value and max(t1.date) do not have a relation to one and other.
You need to rewrite it as follows, if you want to know the total purchases per the date selected.
SELECT st1.id, st1.date, st1.total_value, st2.id, st2.date, st2.total_value
FROM (SELECT t1.id, t1.date, sum(t1.value) as total_value
FROM tab1 t1
WHERE t1.date <= '2011-03-31'
GROUP BY t1.id
HAVING t1.date = MAX(t1.date)
) st1
INNER JOIN (SELECT t2.id, t2.date, sum(t2.value) as total_value
FROM tab1 t2
WHERE t2.date > '2011-03-31'
GROUP BY t2.id
HAVING t2.date = MAX(t2.date)
) st2
ON (st1.id = st2.id)
Make sure you have an index on id and date
Remarks
id is generally understand as a shorthand for the primary key.
Having a field called id that does not a unique index, is confusing and widely considered a code smell.
A: SELECT
td.id
, ta.`date` AS before_date
, ta.value AS value_at_before_date
, tb.`date` AS after_date
, tb.value AS value_at_after_date
FROM
( SELECT DISTINCT id
FROM tabl
) AS td
LEFT JOIN
tabl AS ta
ON ta.tablePK =
( SELECT tablePK
FROM tabl AS a
WHERE `date` < '2011-04-01'
AND a.id = td.id
ORDER BY `date` DESC
LIMIT 1
)
LEFT JOIN
tabl AS tb
ON tb.tablePK =
( SELECT tablePK
FROM tabl AS b
WHERE `date` >= '2011-04-01'
AND b.id = td.id
ORDER BY `date` ASC
LIMIT 1
)
where tablePK is the PRIMARY KEY of the table (I do hope you have one).
An index on (id, date, tablePK) would be helpful for speed.
A: data - query to generate some test data instead of creating a table hold test data.
before_query - retrieves the maximum date <= 2011-03-31 for each customer id
after_query - retrieves the minimum date >= 2011-04-01 for each customer id
Other than my use Oracle's dummy dual table (which I used to generate some test data), I believe I have only used standard SQL syntax.
You will not need to generate the data so that part of they query can be omitted. Wherever data is referenced in the query replace it with your table name.
with
data as (select 2 as id, '2011-01-04' as trans_date, 55.66 as value from dual
union all
select 2 as id, '2011-03-23' as trans_date, 22.33 as value from dual
union all
select 2 as id, '2011-04-21' as trans_date, 9.44 as value from dual
union all
select 5 as id, '2010-01-04' as trans_date, 104.55 as value from dual
union all
select 5 as id, '2011-02-03' as trans_date, 38.82 as value from dual),
before_qry as (select id, max(trans_date) as max_date from data
where trans_date <= '2011-03-31'
group by id),
after_qry as (select id, min(trans_date) as min_date from data
where trans_date >= '2011-04-01'
group by id)
select bq.*, bq_d.value, aq.*, aq_d.value
from before_qry bq inner join after_qry aq on bq.id = aq.id
inner join data bq_d on bq.id = bq_d.id and bq.max_date = bq_d.trans_date
inner join data aq_d on aq.id=aq_d.id and aq.min_date = aq_d.trans_date
For the test data shown in your question this query gives the following results
ID MAX_DATE VALUE ID MIN_DATE VALUE
---------- ---------- ---------- ---------- ---------- ----------
2 2011-03-23 22.33 2 2011-04-21 9.44
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I add draggable and droppable event listeners with jQuery mobile? I'm using jQuery mobile to build a mobile version of my site.
A lot of the features rely on drag/drop.
Since jQuery mobile uses Ajax to load the pages, the event handlers for draggable and droppable aren't added to elements on any page except the first.
How can I work around this without using in-line JS
A: add references to your custom JavaScript files inside the page container div.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using Phantom JS to convert all HTML files in a folder to PNG I've started using Phantom JS on Windows, but I'm having a bit of difficulty finding documentation on its capability (probably the root of my problem).
Using Phantom JS I would like to do the following:
*
*Give it a local machine folder location,
*Have it navigate to that location and identify the list of HTML files,
*Once that list is identified to loop of the the list of HTML files and convert them all to PNG (similar to the way the rasterize.js example works), where the filename gsubs "HTML" with "PNG".
I'm sure this is probably possible, but I wasn't able to find the Phantom JS function call for:
*
*getting the list of files in a folder and
*the format for gsub and grep in Phantom JS.
A: var page = require('webpage').create(), loadInProgress = false, fs = require('fs');
var htmlFiles = new Array();
console.log(fs.workingDirectory);
var curdir = fs.list(fs.workingDirectory);
// loop through files and folders
for(var i = 0; i< curdir.length; i++)
{
var fullpath = fs.workingDirectory + fs.separator + curdir[i];
// check if item is a file
if(fs.isFile(fullpath))
{
// check that file is html
if(fullpath.indexOf('.html') != -1)
{
// show full path of file
console.log('File path: ' + fullpath);
htmlFiles.push(fullpath);
}
}
}
console.log('Number of Html Files: ' + htmlFiles.length);
// output pages as PNG
var pageindex = 0;
var interval = setInterval(function() {
if (!loadInProgress && pageindex < htmlFiles.length) {
console.log("image " + (pageindex + 1));
page.open(htmlFiles[pageindex]);
}
if (pageindex == htmlFiles.length) {
console.log("image render complete!");
phantom.exit();
}
}, 250);
page.onLoadStarted = function() {
loadInProgress = true;
console.log('page ' + (pageindex + 1) + ' load started');
};
page.onLoadFinished = function() {
loadInProgress = false;
page.render("images/output" + (pageindex + 1) + ".png");
console.log('page ' + (pageindex + 1) + ' load finished');
pageindex++;
}
Hope this helps. For more information about the FileSystem calls, check this page out: http://phantomjs.org/api/fs/
Also, I wanted to add, that I believe the FileSystem functions are only available in PhantomJS 1.3 or later. Please make sure to run the latest version. I used PyPhantomJS for Windows but I'm sure this will work without a hitch on other systems as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Backbone.js pushState is not working and gives a 404 error I have been watching the screencast from PeepCode on Backbone.js, and have done the coding with it.
I have finished the first part and now, I have a Router like this:
routes: {
'': 'home',
'blank': 'blank'
}
and also I have this to start the App:
$(function(){
window.App = new BackboneTunes();
Backbone.history.start({pushState: true});
});
Now, if I type http://localhost:9292/#blank in the URL bar, it redirects me to http://localhost:9292/blank, but if I type http://localhost:9292/blank directly, it gives a 404 message.
Is this normal or do I have an error here?
Thanks in advance.
A: For those that thought the above answer was insufficient: What you want to do is enable your server to reroute all urls to your index.html page where Backbone.js will take care of the routing for you. The following steps will let you do this while still keeping the URL the same inside the address bar.
If you're using Apache as your container, you need to enable a mod_rewrite module inside your application's .htaccess file.
Inside your httpd file:
1) Make sure that your "Override" command for your document root is enabled to "Override All" instead of "Override None"
2) Enable the mod_rewrite.so module by uncommenting this line:
LoadModule rewrite_module modules/mod_rewrite.so
Inside your application's .htaccess file (if you don't have one, create one):
1) If you have a IfModule mod_rewrite.c module already written, then copy these lines into one of the modules:
RewriteEngine On
RewriteRule ^/[a-zA-Z0-9]+[/]?$ /index.html [QSA,L]
You should have something that looks like this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^/[a-zA-Z0-9]+[/]?$ /index.html [QSA,L]
</IfModule>
Edit
Note: In Apache 2.2+, you can now use FallbackResource instead of mod_rewrite, it requires fewer lines and accomplishes the same thing.
A: You need to set up your server to return the same page for all of the URLs that Backbone routes to. Right now, it's only serving the page from the root URL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to break apart a string value and re-arrange characters So from what I have found I would have to write a swap method? Only problem is from the codes I have been looking over it is a bit over my head.
I am getting a value from a xml file, for example "20120411" What I would like it to be once passed to another string is April 11, 2012, or at least 04/11/12. I have found simple ways to do this in just about every other language besides java. If its simple enough for someone to show me the code to accomplish this, or point me in the right direction I would appreciate it!
A: Look at using a SimpleDateFormat object. There are many many examples of how to use this in this forum, and so a little searching will bring you riches. If you look this over and still are stuck, then you should consider showing us your attempt and tell us what's not working for you, and we'll likely be able to easily help you.
A format String to try includes "yyyyMMdd". You'd construct your SDF object with this String, parse the xml String and thereby turn it into a Date object. You'd use a second SDF object with a different pattern String, perhaps "MMMM dd, yyyy" to format the Date into a different String. Again, give it a try!
e.g.,
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SdfTest {
public static void main(String[] args) {
SimpleDateFormat sdfInput = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdfOutput = new SimpleDateFormat("MMMM dd, yyyy");
try {
Date date = sdfInput.parse("20120411");
String output = sdfOutput.format(date);
System.out.println(output);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
A: This takes "20080105" and returns "01/05/2008".
StringBuffer b = new StringBuffer(dateStr);
b.append(b.substring(0, 4)).delete(0, 4); // put year at end
b.insert(2, "/");
b.insert(5, "/");
A: If all you want to do it rearrange characters you can do a replace:
String dateString = "20120411".replaceAll("\\d{2}(\\d{2})(\\d{2})(\\d{2})", "$2/$3/$1"); // outputs: 04/11/12
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is an alternative set-like data structure when modifying elements is necessary? STL sets are designed so that it is not possible to modify the elements in the set (with good reason, see stackoverflow). Suppose however I have a structure in which only one of the members acts as the key. Is there an alternative data structure to a set. I really want exactly the behavior of sets except this inability to modify a field or member which is non-key.
A: A few possibilities come to mind:
*
*Adjust your data structures to use std::map instead
*Use the std::set, but remove the element you want to change and replace it with the updated value.
*Design and implement a data structure that satisfies your requirements.
I'd look at the first two options as preferable; the last should be used only if you can't adapt your problem or existing STL containers to meet your needs.
A: Declare the non-key as mutable, then you would be able to modify it.
struct A
{
KeyType key;
mutable NonKeyType nonkey;
//..
};
std::set<A> aset;
//...
const A & a = *aset.begin();
a.nonkey = newValue; //you can modify it even if the object `a` is const.
You've to make sure that nonkey is really a non-key; it must not take part in operator< comparison function.
A: May be it's time to redesign, considering std::map instead of std::set.
instead of
struct A
{
K key;
V val;
};
set<A> a;
consider
std::map<K,V> m;
you can then do
m[k] = v;
A: There is no way to enforce that members of the class used in the ordering predicate are not modified. An modification to members used in the ordering predicate may potentially break the set.
The easy way to trick the compiler into letting you use the set with mutable members is marking the members as mutable:
class Foo
{
std::string myVal1;
mutable std::string myVal2;
public:
bool operator<(const Foo& rhs)const {
return myVal1 < rhs.myVal;
}
};
Then, you have to manually ensure that Foo::operator<() never uses myVal2 in the comparison. This is possible, but is is a Bad Idea (tm). You can mark this specific operator with a huge comment, but you can't automatically duplicate this comment into all custom comparison functions (std::set<> accepts this as a second parameter).
The real way to achieve what you want is to use a std::map<>. Put the "key" part in the key and the "value" part in the value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Find every occurrence of a regex in a file How can I list every occurrence of a regex in a file, where one line can contain the regex multiple times?
Example:
XXXXXXXXXX FOO3 XXXX FOO4 XXX
XXX FOO2 XXXX FOO9 XXXXXX FOO5
The result should be:
FOO3
FOO4
FOO2
FOO9
FOO5
The regex would be /FOO./ in this case.
Grep will return every line that matches at least one time. But that's not what I want.
A: Have you tried the -o option: (grep man page)
-o, --only-matching Show only the part of a matching line that matches
PATTERN.
A: You question is not completely clear, especially since the example data is super generic. But, here are some patterns that might match:
Your pattern matches FOO followed by any character which would match everything to the end of the line. I don't think you want that so try something like this:
/FOO[0-9]+/ - matches FOO followed by one or more numbers.
/FOO[^ ]+/ - matches FOO followed by any character that is NOT a space. This might be the best solution given your example pattern.
/FOO[0-9a-zA-Z]+/ - matches FOO followed by any alphanumeric character
A: Use grep -o FOO. (-o: show only matching)
Your regex could even be extended to only match FOO followed by a number, instead of any character (. will match whitespace too!):
<yourfile grep -o 'FOO[0-9]'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Use of Response.End in an MVC3 Action I'm trying to do something like this article suggests in my MVC3 site. However, I'm not sure I can use the Response.End in my Action.
My question is, how can I return a 401 status code from my Action if the HttpContext.User == null?
public ActionResult WinUserLogOn(string returnUrl) {
var userName = string.Empty;
if (HttpContext.User == null) {
//This will force the client's browser to provide credentials
Response.StatusCode = 401;
Response.StatusDescription = "Unauthorized";
Response.End();
return View("LogOn"); //<== ????
}
else {
//Attempt to Log this user against Forms Authentication
}
A: This should do what you want:
return new HttpUnauthorizedResult();
which will return a HTTP 401 to the browser. See the docs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set size of the loaded image in AS3.0 I'm loading images from xml file. I want the images to have standard width when they are displayed.
Here are the snippets of the code that do the image processing:
var allThumbs:MovieClip = new MovieClip();
addChild(allThumbs);
allThumbs.width = 200;
allThumbs.height = 200;
galleryPane.source = allThumbs;
and here's the one that loades the images:
function loadTheThumbs() {
var c:Number = 0;
while(c < totalCats) {
var thumbLoader:Loader = new Loader();
var thumbRequest:URLRequest = new URLRequest(catImgList[c]);
thumbLoader.load(thumbRequest);
thumbLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, whenThumbLoaded);
function whenThumbLoaded(e:Event):void {
allThumbs.addChild(thumbLoader);
}
c++;
}
}
Everything worked cool before I inserted
allThumbs.width = 200;
allThumbs.height = 200;
this lines, where I wanted to resize the images before they show up in the ScrollPane.
I saw other threads here, but didn't help...
So maybe any ideas how should I do that?
Thanks in advance.
A: function whenThumbLoaded(e:Event):void {
allThumbs.addChild(thumbLoader);
}
you might want to set up the position of the images and the scale here
function whenThumbLoaded(e:Event):void {
thumbloader.x = c * 220;
thumbloader.y = 0;
thumbloader.width = 200;
thumbloader.height = 200;
allThumbs.addChild(thumbLoader);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: QueryPerformanceCounter in D? Is there something (planned) in the D Library to support high precision timers like QueryPerformanceCounter in c++ ? How can I have a portable High precision timer in D ?
Or if it is not available, what would be the highest percision timer in D ?
A: std.datetime has the StopWatch struct for handling precision timing - and it uses QueryPerformanceCounter internally on Windows. On other OSes, it uses whatever the appropriate, high precision monotonic clock is for them.
If what you need is ticks of the system clock rather than a timer specifically, you can call Clock.currSystemTick for the current tick of the system clock (or Clock.currAppTick for the number of system clock ticks since the application started). But StopWatch is what you want if you want a timer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Windows Mobile intercept notifications I know how to intercept regular SMS messages. But sometimes I get some special SMS notifications. Notifications are treated differently, it seems that the MessageInterceptor is unable to intercept such messages.
Is there a way to intercept those notifications?
LATER EDIT:
On some (or all) mobile devices you get these type of messages prompted directly on the screen instead of being only notified that a message has arrived.
A: I think what you need to do is make use of the InterceptionAction property. This property (which is of type InterceptionAction, an enumeration) takes one of two values: Notify and NotifyAndDelete. You may need to use one of these two for your scenario.
The following links may be helpful for you in this regard:
http://msdn.microsoft.com/en-us/library/microsoft.windowsmobile.pocketoutlook.messageinterception.interceptionaction.aspx
http://msmvps.com/blogs/donscf/archive/2006/04/03/89053.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creating virtual directory tree in zip file using dotnetzip I am trying to create a zip file from code, I'm using dotnetzip
I want to create a directory tree in the folder that doesn't exist on disk. How do I do this?
I have tried using AddDirectory but this seems to want to find the directory on disk. I have also tried AddEntry but this requires some content.
My files are stored in a SQL Server using the FileStream option and organised in a hierarchy there.
I wrote this recursive method to do it but the AddDirectory line doesn't work.
private void GetFiles(ZipFile zipFile, Folder folder, string path)
{
zipFile.AddDirectory(folder.FolderName, path);
foreach (var file in folder.Files)
zipFile.AddEntry(file.FileName, file.FileData);
foreach(var subfolder in folder.SubFolders)
{
GetFiles(zipFile, subfolder, path + "\\" + subfolder.FolderName);
}
}
A: You can use AddDirectoryByName to create a new directory in the zipfile instead of importing a directory
A: It seems from their examples page, if you specify the full filel path, it will add an entry in the ZIP corresponding to that path.. therefore you can try just adding the files with full path and skip the AddDirectory step.. At least this is what I could gather from this code sample in their documentation:
Add a set of items to a zip file, specifying a common directory in the zip archive. This example adds entries to a zip file. Each entry is added using the specified pathname.
String[] filenames = { "ReadMe.txt", "c:\\data\\collection.csv", "c:\\reports\\AnnualSummary.pdf"};
using (ZipFile zip = new ZipFile())
{
zip.AddFiles(filenames, "files");
zip.Save("Archive.zip");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Django template variables from {% for %} loop into Javascript This is a Django template iterating through records. Each record contains a div that JS function fills in. In order for JS to know what to do, it needs to get a variable from each for loop iteration and use it. I don't know exactly how to achieve that or if it's possible. Maybe a different approach is needed where ever record triggers a timer in a separate JS object instance, I don't know.
---------- html -----------------------
{% for match in upcoming_matches %}
...
<tr>
<td> Match title </td>
<td> Match time </td>
<td> Starts in: </td>
<tr>
<tr>
<td> {{ match.title }} </td>
<td> {{ match.start_time }} </td>
<td> <div id="matchCountdown"/></td>
<tr>
...
{% endfor %}
------------ JS ---------------------------
$(function () {
var start_date = {{ match.start_date }}; // Obviously I can't access vars from for loop, I could access upcoming_matches but not the ones from for loop
var matchDate = new Date(start_date.getTime()
$('#matchCountdown').countdown({until: matchDate});
});
A: You can also use a {% for %} loop in your javascript portion of the code. If you write this in your html template:
<script type="text/javascript">
$(function() {
{% for match in upcoming_matches %}
var match_date_{{ match.id }} = new Date({{ match.start_date }}).getTime();
$('#matchCountdown_{{ match.id }}').countdown({until: match_date_{{ match.id }});
{% endfor %}
});
</script>
Also, <div id="matchCountdown"/> becomes <div id="matchCountdown_{{ match.id }}"/> in this case.
A: You could output the start_date as an attribute of the matchCountdown . Then in your JavaScript pick it out, process it and output with the Countdown plugin.
Template code: <td><div class="matchCountdown" start="{{ match.start_date }}" /></td>
JavaScript:
$('.matchCountdown').each(function() {
this = $(this);
var start_date = this.attr('start');
var matchDate = new Date(start_date).getTime();
this.countdown({until: matchDate});
});
This method requires only one loop in the template code and one loop in the Javscript to find and enable the items. Also of note, 'matchCountdown' should be a class not an id of the div since it's not unique.
A: Check out jQuery's .data()
Using it you can store data in the DOM like this
<div id="myDiv" data-somedata="myimportantdata"></div>
then you can access it with jQuery like
$("#myDiv").data("somedata");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: iOS - equal the UITextView string on the different viewController How can i equal a UITextView strings with another UItextView on different viewControllers
on ViewController1 :
UItextView *textView1;
on ViewController2 :
UITextView *textView2;
so when user enter some text in "textView" on ViewController2 the string of textView should be equal with textLayer on ViewController1
I don't know how can I relate each other ! with button on ViewController2 something like this :
-(IBAction)Done {
[textView2.Text isEqualToString:textView1];
}
and on the ViewController1 should change the string of textView2 as textView1 something like this:
textView1.string = ViewController2.textView2;
Is there is possible way to do so ?
A: I understand that you wish to reach a viewcontroller objects' variable from other?
see: How to access a UITextView on another ViewController
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: OAuthException / An active access token must be used to query information about the current user When trying:
facebook requestWithGraphPath:@"me/friends"
In my iOS app I get the error
"OAuthException / An active access token must be used to query information about the current user"
I can query my own Facebook data successfully usng requestWithGraphPath:@"me", and I can use the token I have to get data from
https://graph.facebook.com/me/friends?access_token=xxxx
in the browser. But it won't work in the iOS app...
Can anyone help? I tried recreating a new Fb app, as I had been removing my initial test one from my approved apps and I thought that might have caused it, but the result is the same. I am requesting "offline access" in my permissions so the token shouldn't expire.
EDIT: Interestingly querying the FQL user table returns my friend list IDs
A: Although This is an old post but I am answering it for the followers:
Whenever you post something with facebook graph API, You must get permissions for atleat "publish_stream" Plus be sure to post to the Wall when you receive the authorization e.g
if (![SharedFacebook isSessionValid])
{
NSArray *permissions = [[NSArray alloc] initWithObjects:@"offline_access", @"publish_stream", nil];
[SharedFacebook authorize:permissions];///Show the login dialog
/// [self postToWall];///Do not call it here b/c the permissions are not granted yet and you are posting to the wall.
}
else
{
[self postToWall];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Create 5 DIV with 1 DIV in the center I want to create DIV like the picture below. 1 Div on the center and 4 div around the center div. Could anybody help??I've tried but I couldn't do it.
.mid{
width:700px;
height:400px;
margin-left:100px;
background-color:black;
}
.navtop {
width:700px;
height:100px;
display: inline-block;
background-color:red;
}
.navbottom {
width:700px;
height:100px;
background-color:red;
display: inline-block;
}
.navleft {
width:100px;
height:400px;
float:left;
margin-top:100px;
display: inline-block;
background-color:red;
}
.navright {
width:100px;
height:400px;
display: inline-block;
background-color:red;
}
The content will be static. I have a problem with right and bottom div.
A: http://jsfiddle.net/z2qQG/2/
`<style>
#container{width:500px;height:500px;}
#div1{width:300px;height:100px;margin:auto;background:#000;color:#fff;}
#div2{width:100px;height:300px;float:left;background:#000;color:#fff;}
#div3{width:300px;height:100px;margin:auto;background:#000;color:#fff;}
#div4{width:100px;height:300px;float:left;background:#000;color:#fff;}
#div5{width:300px;height:300px;float:left;background:#fff;}
</style>
<div id="container">
<div id="div1">DIV 1</div>
<div id="div4">DIV 4</div>
<div id="div5">DIV 5</div>
<div id="div2">DIV 2</div>
<div id="div3">DIV 3</div>
</div>`
A: <style>
#div1 { height: 100px; width: 300px; margin-left: 100px; background: orange; }
#div4 { height: 300px; width: 100px; float: left; background: red; }
#div5 { height: 300px; width: 300px; float: left; background: blue; }
#div2 { height: 300px; width: 100px; float: left; background: lime; }
#div3 { height: 100px; width: 300px; margin-left: 100px; clear: both; background: aqua; }
</style>
<div id="div1">DIV1</div>
<div id="div4">DIV4</div>
<div id="div5">DIV5</div>
<div id="div2">DIV2</div>
<div id="div3">DIV3</div>
This would be the most obvious way. There are several other ways.
A: CSS-wise I would probably position: relative; DIV 5 and position: absolute; the rest, then moving them out with the top, bottom, left and right properties.
#wrap {margin: 100px; width: 400px; height: 400px; position: absolute; background: black;}
.side {position: absolute; background: red; width: 100%; height: 100%;}
.side.top {height: 100px; top: -100px;}
.side.bottom {height: 100px; bottom: -100px;}
.side.left {width: 100px; left: -100px;}
.side.right {width: 100px; right: -100px;}
<div id="wrap">
<div class="side top"></div>
<div class="side bottom"></div>
<div class="side left"></div>
<div class="side right"></div>
</div>
Example
A: Yup. Fairly simple :)
http://jsfiddle.net/x5FrV/1
.wrap
{
position:relative;
...
}
.border
{
position:absolute;
width:20px;
height:20px;
...
}
.top
{
bottom:100%;
width:100%;
}
.right
{
left:100%;
height:100%;
}
.bottom
{
top:100%;
width:100%;
}
.left
{
right:100%;
height:100%;
}
<div class="wrap">
<div class="top border">1</div>
<div class="right border">2</div>
<div class="bottom border">3</div>
<div class="left border">4</div>
<div class="content">
go team sea slug!
</div>
</div>
A: There are a bunch of ways, so it really depends more on "why" than "how", but if a client said this to me, my first stab would look something like this:
<div id="div5">
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
Content
</div>
with css like:
#div5 {
position: relative;
margin: 3em;
background-color: red;
width: 10em;
height: 10em;
}
#div1,#div2,#div3,#div4 { position: absolute; background-color: black; color: white; }
#div1, #div3 { width: 100%; height: 2em; }
#div1 { top: -2em; }
#div3 { bottom: -2em; }
#div2, #div4 { height: 100%; width: 2em; }
#div2 { right: -2em; }
#div4 { left: -2em; }
Fiddle here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is there a way to tell if a directory specified by the user is a protected directory in Windows 7/Vista with UAC enabled (and not running as admin) There are several points where the user can specify a what directory that data is to be saved to, I would like to be able to notify the user if they have chosen a directory that is being protected by Windows. I can just write a file to see if the OS lets me because UAC will write the file to a different directory.
A: You can try to write a temporary file to the directory. If the directory is UAC protected and you're not running under admin privileges you will get a System.UnauthorizedAccessException error.
Edit:
If @JoeWhite is correct and you are attempting to determine when your application is being affected by UAC Virtualization. I don't believe you can detect that in the application itself. The write calls will be adjusted by the OS automatically without any notice to your application.
You can read more on how UAC Virtualization works at via this article on the Windows Team Blog.
This only affects these specific cases though:
Your application writes to Program Files, Windows directories, or the
system root (typically the C drive) folders
Your application writes to the Windows
registry, specifically to HKLM/Software
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Jquery xml file provides information details page pulls all info instead of selected I am trying to build on some basic ideas. I have an xml file which I have no problems loading onto a list type menu . My xml file has about 300 records and each record contains approviamtely 45 fields. (LASTNAME, FIRSTNAME, ADDRESS, etc).
I can get the list menu created but I cannot manage figure out how to load the details page for only the person picked from the menu list item. I have googled and I am this is complete user error on my part. Any help would be greatly appreciated.
<body>
<script type="text/javascript">
$.ajax({
type: "GET",
url: "COMBINED.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('COMBINED').each(function(){
var id = $(this).attr('ID')
var JPG = $(this).find('JPG', 'FIRSTNAME').text()
var FIRSTNAME = $(this).find('FIRSTNAME').text()
var LASTNAME = $(this).find('LASTNAME').text()
var SCHOOL = $(this).find('SCHOOL').text()
var DISABILITY = $(this).find('DISABILITY').text()
var TITLE = $(this).find('TITLE').text()
$('<li></li>').html('<a href="#DETAILSPAGE"'+id+'">'+FIRSTNAME +' '+ LASTNAME + '<p>'+SCHOOL+ '</p></a>').appendTo('#LIST');
var $divToAppend= $('#DETAILS')
var detailsitem=$('<div></div>').attr('id','#DETAILSPAGE').html("<h1></h1>");
$('<li></li>').html(DISABILITY).appendTo('#DETAILS' )
})
;}
})
</script>
<div data-role="page" id="page" data-theme="b">
<div data-role="header">
<h1>Page One</h1>
</div>
<div data-role="content">
<ul data-role="listview">
<li><a href="#LISTPAGE">Page Two</a></li>
<li><a href="#page3">Page Three</a></li>
<li><a href="#page4">Page Four</a></li>
</ul>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
<div data-role="page" id="LISTPAGE">
<div data-role="header">
<h1>Page Two</h1>
</div>
<div data-role="content">
<ul data-role="listview" id="LIST"></ul>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
<div data-role="page" id="DETAILSPAGE">
<div data-role="header">
<h1>Page Three</h1>
</div>
<div data-role="content" >
<ul data-role="listview" id="DETAILS"></ul>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
</html>
A: Here is what worked:
After setting up variables with the information.
Had some great help from a great book Jay Blanchard's Applied Jquery Book.
$('<li class="memberInfo" name="'+thisID+'"></li>').html(THISMEMBERDETAIL).appendTo('#DETAILS');
$('a').live('click', function(){
/* get the name attribute of the link clicked */
var thisMemberID = $(this).attr('name');
/* if any previous member info was showing, hide it */
$('.memberInfo').hide();
/* show the current member info */
$('li[name="'+thisMemberID+'"]').show();
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c syntax in two different lines? I have this simple question about c syntax. When we write :
printf("hello world
");
compiler produces an error. Why? In this other case:
for (i = 0; i < MAXLINE - 1
&& (c=getchar)) != EOF && c != '\n'; ++i)
everything compiles fine. What is the general rule for all this?
Thank you !
A: A string literal ("...") cannot contain a bare newline.
If you want a newline character in the string, use the \n escape sequence (`"hello world\n")
A: Because you're breaking a string literal, which isn't allowed, in the first example. In the second, you're just wrapping the syntax over multiple lines. For example:
printf("hello world"
);
will compile.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there any math. function which gives sequence of numbers when ever i call it? I have the following function:
function random()
{
var whichProduct = Math.floor(Math.random()*5);
UIALogger.logMessage(whichProduct);
}
random();
This will give a random number in [1,4] whenever i call this function.
I want to know whether there is any other function which will give me a sequence of numbers in order (like: 1, 2, 3, 4, 5) when I call it.
A: Use closure, here is a simple example: Each time you call x() it returns the next number in the sequence(starting at 'startVal'), but it does not compute every number in advance, only when it is called.
function seq(startVal) {
var i = startVal - 1;
return function() {
return i++;
}
}
x = seq(1);
alert(x()); // alert(1)
alert(x()); // alert(2)
alert(x()); // alert(3)
Edit: Made a simple adjustment to pass in a starting value, sequence will begin there.
A: I don't think there is anything built in to the language but you can define your own like so:
var increasingSequence = function(a, b) {
var seq=[], min=Math.min(a,b), max=Math.max(a,b), i;
for (i=min; i<max; i++) {
seq.push(i);
}
return seq;
};
increasingSequence(1, 5); // => [1, 2, 3, 4, 5]
increasingSequence(2, -2); // => [-2, -1, 0, 1, 2]
Note also that Math.random() returns a value in the range [0,1) (that is including zero but not including one), so if you want your random function to return [1,5] then you should implement it like so:
Math.floor(Math.random() * 5) + 1;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I find the next nonalphanumeric or '_' character in a string in AS3? I need to strip a string from another and get the remnants. The string I need to strip is a Twitter username, so it can be variable length, but always starts with an '@' and can only contain alphanumeric characters or underscores.
For example, the original string might be "@username: tweeting about stuff" and I need to get out of that ": tweeting about stuff".
I don't have any experience with Regular Expressions, but I'm lead to believe that it can be done using these?
Thanks in advance for any help!
A: var str:String = "@username: tweeting about stuff";
trace( str.split(':')[0] )// should always be the username
trace( str.split(':')[1] )// unless the tweet had more colons in it this will be the message
A: Use this regex:
var str:String = "@username: tweeting about stuff";
var pattern:RegExp = /(?<=@)[\w\d]+\b/
var matches:Array = str.match(pattern);
trace(matches[0]);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Excel interop libraries incompatible with ASP.NET? I have a simple web application which uses the Excel Interop libraries to read and insert into an Excel spreadsheet. I'm taking my due diligence to ensure that I don't use two dots and to ensure that all COM object references are released by using Marshal.ReleaseComObject() and GC.Collect(), but there is still an EXCEL.EXE process running on my server.
I've created a Windows Forms application that uses the same object releasing process as in my ASP.NET app, and it ends the process successfully. Is there something involved with using the Interop libraries with ASP.NET that I've overlooked?
EDIT: As a shot in the dark, maybe permissions need to be set up in a specific way on the server? I'm using <identity impersonate="true"/> in my web.config file and am a local administrator on the server.
A: I'm not sure this is exactly an answer but I have worked a lot with ASP.NET and Excel Interop and can offer you some of my observations / pointers.
If you use Task Manager you can see which user is still running EXCEL.EXE process - it's most likely the AppPool Identity.
From experience when the app pool recycles this will close Excel.
Also you may notice that if you run your script again a second Excel opens and will close!
For reference, here is my Close Excel code:
xl.Quit();
Marshal.ReleaseComObject(xl);
xl = null;
GC.Collect();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: WCF REST and SOAP Service without WebServiceHostFactory Despite reading a number of posts eg (This one seems popular) I can't seem to expose my service as multiple endpoints that are compatible with both the SOAP and REST protocol - my problem seems to be with the
Factory="System.ServiceModel.Activation.WebServiceHostFactory"
element in the Service code behind page.
If I leave it out, my SOAP endpoint works grand, but my JSON endpoint is not found. If I put the line in, my REST endpoint sings like bird and the the SOAP endpoint is results in "Endpoint not found" on the Service.svc page.
My operations appear to set up in the standard way eg:
[OperationContract]
[WebGet(UriTemplate = "/GetData", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
string GetData();
And the configuration file
<endpoint address="rest" binding="webHttpBinding" contract=".IMeterService" behaviorConfiguration="REST" />
<endpoint address="soap" binding="wsHttpBinding" contract="IMeterService" bindingConfiguration="secureBasic" />
<behavior name="REST">
<webHttp />
</behavior>
How can I achieve this? Is there a way to set up the REST endpoint without the System.ServiceModel.Activation.WebServiceHostFactory attribute?
Thanks in advance.
A: If you don't specify any factory in the .svc file, all the endpoints will come from the web.config file - WCF will try to find a <system.serviceModel / service> element whose name attribute matches the fully-qualified name of the service class. If it doesn't find one, then it will add a default endpoint (using basicHttpBinding, unless you changed the default mapping). That appears to be what you're facing. Confirm that the "name" attribute of the <service> element matches the value of the Service attribute in the .svc file, and you should have the two endpoints working out fine.
Another thing you can try to do is to enable tracing in the service (level = Information) to see which endpoints were actually opened on the service. The image below:
The server for this example is nothing major:
namespace MyNamespace
{
[ServiceContract]
public interface ITest
{
[OperationContract]
string Echo(string text);
}
public class Service : ITest
{
public string Echo(string text)
{
return text;
}
}
}
The Service.svc doesn't have factory specified:
<% @ServiceHost Service="MyNamespace.Service" Language="C#" debug="true" %>
And the web.config defines two endpoints, which are shown in the traces:
<configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel" switchValue="Information, ActivityTracing"
propagateActivity="true">
<listeners>
<add type="System.Diagnostics.DefaultTraceListener" name="Default">
<filter type="" />
</add>
<add name="ServiceModelTraceListener">
<filter type="" />
</add>
</listeners>
</source>
</sources>
<sharedListeners>
<add initializeData="C:\temp\web_tracelog.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
name="ServiceModelTraceListener" traceOutputOptions="Timestamp">
<filter type="" />
</add>
</sharedListeners>
<trace autoflush="true"/>
</system.diagnostics>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="Web">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="MyNamespace.Service">
<endpoint address="basic" binding="basicHttpBinding" bindingConfiguration=""
name="basic" contract="MyNamespace.ITest" />
<endpoint address="web" behaviorConfiguration="Web" binding="webHttpBinding"
bindingConfiguration="" name="web" contract="MyNamespace.ITest" />
</service>
</services>
</system.serviceModel>
</configuration>
Notice that there's an extra listener shown in the listener, it's the "help page" from WCF (the one which tells, when you browse to it, that the service doesn't have metadata enabled).
You can try either to compare this setup with yours, or start with this simple one, then start adding component from yours until you hit the issue. That will help isolate the problem.
Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Can I use a SetTimer() API in a console C++ application? I have a console application that is using a DLL file that uses a SetTimer() call to create a timer and fire a function within itself. The call is below:
SetTimer((HWND)NULL, 0, timer_num, (TIMERPROC)UnSyncMsgTimer)) == 0)
It is expecting to receive timer messages, but this never happens. I assume because mine is a console application and not a standard Windows GUI application (like where the DLL file was originally used). This stops a key part of the DLL files functionality from working.
My application needs to stay a console application, and I cannot change the DLL.
Is there a work around to make this work?
A: You can use CreateTimerQueueTimer function
HANDLE timer_handle_;
CreateTimerQueueTimer(&timer_handle_, NULL, TimerProc, user_object_ptr, 10, 0, WT_EXECUTEDEFAULT);
//callback
void TimerProc(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
{
user_object* mgr = (user_object*) lpParameter;
mgr->do();
DeleteTimerQueueTimer(NULL, timer_handle_, NULL);
timer_handle_ = NULL;
}
A: Timers set using the SetTimer API require a Windows message processing function to be actively running, as that is where the time messages are sent.
If you need a timer thread then you could register a Window class and create a default window message pump (See this article for a short example), but a simpler process would probably be to just spin up a second thread to handle your timing events and send notifications.
A: Have a look at the following example which shows how to use WM_TIMER messages with a console app:
(Credit to the Simple Samples site)
#define STRICT 1
#include <windows.h>
#include <iostream.h>
VOID CALLBACK TimerProc(HWND hWnd, UINT nMsg, UINT nIDEvent, DWORD dwTime) {
cout << "Time: " << dwTime << '\n';
cout.flush();
}
int main(int argc, char *argv[], char *envp[]) {
int Counter=0;
MSG Msg;
UINT TimerId = SetTimer(NULL, 0, 500, &TimerProc);
cout << "TimerId: " << TimerId << '\n';
if (!TimerId)
return 16;
while (GetMessage(&Msg, NULL, 0, 0)) {
++Counter;
if (Msg.message == WM_TIMER)
cout << "Counter: " << Counter << "; timer message\n";
else
cout << "Counter: " << Counter << "; message: " << Msg.message << '\n';
DispatchMessage(&Msg);
}
KillTimer(NULL, TimerId);
return 0;
}
A: Have you considered Waitable Timers or Timer Queues? While it is possible to use SetTimer from a console app, these other facilities might be more appropriate for you.
A:
Using Timer Queues
Creates a timer-queue timer. This timer expires at the specified due
time, then after every specified period. When the timer expires, the
callback function is called.
The following example creates a timer routine that will be executed by
a thread from a timer queue after a 10 second delay. First, the
code uses the CreateEvent function to create an event object
that is signaled when the timer-queue thread completes. Then it
creates a timer queue and a timer-queue timer, using the
CreateTimerQueue and CreateTimerQueueTimer functions,
respectively. The code uses the WaitForSingleObject function to
determine when the timer routine has completed. Finally, the code
calls DeleteTimerQueue to clean up.
For more information on the timer routine, see WaitOrTimerCallback.
Example code from MSDN:
#include <windows.h>
#include <stdio.h>
HANDLE gDoneEvent;
VOID CALLBACK TimerRoutine(PVOID lpParam, BOOLEAN TimerOrWaitFired)
{
if (lpParam == NULL)
{
printf("TimerRoutine lpParam is NULL\n");
}
else
{
// lpParam points to the argument; in this case it is an int
printf("Timer routine called. Parameter is %d.\n",
*(int*)lpParam);
if(TimerOrWaitFired)
{
printf("The wait timed out.\n");
}
else
{
printf("The wait event was signaled.\n");
}
}
SetEvent(gDoneEvent);
}
int main()
{
HANDLE hTimer = NULL;
HANDLE hTimerQueue = NULL;
int arg = 123;
// Use an event object to track the TimerRoutine execution
gDoneEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (NULL == gDoneEvent)
{
printf("CreateEvent failed (%d)\n", GetLastError());
return 1;
}
// Create the timer queue.
hTimerQueue = CreateTimerQueue();
if (NULL == hTimerQueue)
{
printf("CreateTimerQueue failed (%d)\n", GetLastError());
return 2;
}
// Set a timer to call the timer routine in 10 seconds.
if (!CreateTimerQueueTimer( &hTimer, hTimerQueue,
(WAITORTIMERCALLBACK)TimerRoutine, &arg , 10000, 0, 0))
{
printf("CreateTimerQueueTimer failed (%d)\n", GetLastError());
return 3;
}
// TODO: Do other useful work here
printf("Call timer routine in 10 seconds...\n");
// Wait for the timer-queue thread to complete using an event
// object. The thread will signal the event at that time.
if (WaitForSingleObject(gDoneEvent, INFINITE) != WAIT_OBJECT_0)
printf("WaitForSingleObject failed (%d)\n", GetLastError());
CloseHandle(gDoneEvent);
// Delete all timers in the timer queue.
if (!DeleteTimerQueue(hTimerQueue))
printf("DeleteTimerQueue failed (%d)\n", GetLastError());
return 0;
}
This is another example code from MSDN
This is another example from Codeproject
#include <windows.h>
HANDLE hTimer = NULL;
unsigned long _stdcall Timer(void*)
{
int nCount = 0;
while(nCount < 10)
{
WaitForSingleObject(hTimer, 5000);
cout << "5 s\n";
nCount++;
}
cout << "50 secs\n";
return 0;
}
void main()
{
DWORD tid;
hTimer = CreateEvent(NULL, FALSE, FALSE, NULL);
CreateThread(NULL, 0, Timer, NULL, 0, &tid);
int t;
while(cin >> t)
{
if(0==t)
SetEvent(hTimer);
}
CloseHandle(hTimer);
}
Resource:
*
*https://msdn.microsoft.com/en-us/library/windows/desktop/ms682485(v=vs.85).aspx
*https://msdn.microsoft.com/en-us/library/windows/desktop/ms687003(v=vs.85).aspx
A: Very simple timer without Windows
MSG Msg;
UINT TimerId = (UINT)SetTimer(NULL, 0, 0, NULL); // 0 minute
while (TRUE)
{
GetMessage(&Msg, NULL, 0, 0);
if (Msg.message == WM_TIMER)
{
KillTimer(NULL, TimerId);
cout << "timer message\n";
TimerId = (UINT)SetTimer(NULL, 0, 60000, NULL); // one minute.
}
DispatchMessage(&Msg);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Add active class to current page navigation link Hi I need help making my navigation show the active link highlighted on current page. In other words when I click on a link to go to a new page I want to see that link highlighted after the new page is opened. I could handle this with CSS by adding a class to the active link on each page but since there's going to be many pages I would prefer to do this dynamically with JS.
How can I do that with Javascript?... I will appreciate your help, thanks.
Below is the code I'm using feel free to edit as you think convenient.
Here is the HTML, is just a list to structure the navigation
<ul class="menu collapsible">
<li id="main">
<a href="http://google.com">About SfT</a>
<ul class="acitem">
<li><a href="page1.html">page1</a></li>
<li><a href="page2.html">page2</a></li>
<li><a href="http://www.textpattern.com/">Textpattern</a></li>
<li><a href="http://typosphere.org/">Typo</a></li>
</ul>
</li>
<li>
<a id="main" href="#">Your Life</a>
<ul class="acitem">
<li><a href="page3.html">page3</a></li>
<li><a href="">Ruby</a></li>
<li><a href="">Python</a></li>
<li><a href="">PERL</a></li>
<li><a href="http://java.sun.com/">Java</a></li>
<li><a href="http://en.wikipedia.org/wiki/C_Sharp">C#</a></li>
</ul>
</li>
<li>
<a id="main" href="">Your Health</a>
<ul class="acitem">
<li><a href="http://bookalicio.us/">Bookalicious</a></li>
<li><a href="http://www.apple.com/">Apple</a></li>
<li><a href="http://www.nikon.com/">Nikon</a></li>
<li><a href="http://www.xbox.com/en-US/">XBOX360</a></li>
<li><a href="http://www.nintendo.com/">Nintendo</a></li>
</ul>
</li>
<li>
<a id="main" href="#">Your Call</a>
<ul class="acitem">
<li><a href="http://search.yahoo.com/">Yahoo!</a></li>
<li><a href="http://www.google.com/">Google</a></li>
<li><a href="http://www.ask.com/">Ask.com</a></li>
<li><a href="http://www.live.com/?searchonly=true">Live Search</a></li>
</ul>
</li>
</ul>
The CSS (very mininmal, just for the purpose of testing):
body {
font-family: Helvetica, Arial, sans-serif;
font-size: 0.9em;
}
p {
line-height: 1.5em;
}
#main {font-size:2em;}
ul.menu, ul.menu ul {
list-style-type:none;
margin: 0;
padding: 0;
width: 15em;
}
ul.menu a {
display: block;
text-decoration: none;
font-family: Georgia, "Times New Roman", Times, serif;
font-size: 2em;
}
ul.menu li {
margin-top: 1px;
}
ul.menu li a, ul.menu ul.menu li a {
color: #666;
padding: 0.5em;
font-weight: bold;
font-size: 1em;
}
ul.menu li a:hover, ul.menu ul.menu li a:hover {
color: #900;
}
ul.menu li ul li a, ul.menu ul.menu li ul li a {
color: #999;
padding-left: 20px;
}
ul.menu li ul li a:hover, ul.menu ul.menu li ul li a:hover {
color: #900;
}
ul.menu ul.menu li a:hover {
border-left: 0;
padding-left: 0.5em;
}
ul.menu ul.menu {
border-left: 5px #f00 solid;
}
ul.menu a.active, ul.menu ul.menu li a.active, ul.menu a.active:hover, ul.menu ul.menu li a.active:hover {
color: #900;
}
div.panel {
border: 1px #000 solid;
padding: 5px;
margin-top: 1px;
}
ul.menu div.panel a, ul.menu div.panel li a:hover {
display :inline;
color: #090;
margin: 0;
padding: 0;
font-weight: bold;
}
ul.menu div.panel a:hover {
color: #900;
}
.code { border: 1px solid #ccc; list-style-type: decimal-leading-zero; padding: 5px; margin: 0; }
.code code { display: block; padding: 3px; margin-bottom: 0; }
.code li { background: #ddd; border: 1px solid #ccc; margin: 0 0 2px 2.2em; }
.indent1 { padding-left: 1em; }
.indent2 { padding-left: 2em; }
.indent3 { padding-left: 3em; }
.indent4 { padding-left: 4em; }
.indent5 { padding-left: 5em; }
.indent6 { padding-left: 6em; }
.indent7 { padding-left: 7em; }
.indent8 { padding-left: 8em; }
.indent9 { padding-left: 9em; }
.indent10 { padding-left: 10em; }
The JavaScript:
jQuery.fn.initMenu = function() {
return this.each(function(){
var theMenu = $(this).get(0);
$('.acitem', this).hide();
$('li.expand > .acitem', this).show();
$('li.expand > .acitem', this).prev().addClass('active');
$('li a', this).click(
function(e) {
e.stopImmediatePropagation();
var theElement = $(this).next();
var parent = this.parentNode.parentNode;
if($(parent).hasClass('noaccordion')) {
if(theElement[0] === undefined) {
window.location.href = this.href;
}
$(theElement).slideToggle('normal', function() {
if ($(this).is(':visible')) {
$(this).prev().addClass('active');
}
else {
$(this).prev().removeClass('active');
}
});
return false;
}
else {
if(theElement.hasClass('acitem') && theElement.is(':visible')) {
if($(parent).hasClass('collapsible')) {
$('.acitem:visible', parent).first().slideUp('normal',
function() {
$(this).prev().removeClass('active');
}
);
return false;
}
return false;
}
if(theElement.hasClass('acitem') && !theElement.is(':visible')) {
$('.acitem:visible', parent).first().slideUp('normal', function() {
$(this).prev().removeClass('active');
});
theElement.slideDown('normal', function() {
$(this).prev().addClass('active');
});
return false;
}
}
}
);
});
};
$(document).ready(function() {$('.menu').initMenu();});
A: To do this, you'd need to be able to compare some unique element in each link with some other unique element of the page (such as the URL).
Looking at what you have, you might be able to get away with comparing the URLs. You'd have to grab the current' page's location, parse the URL to get the file name (last part of the URL after the last /) and then go through each href of your navigation, parse each one of those, then make a comparison. If there's a match, add a class to that link.
The catch with this is that this isn't the most performant way to handle it. The other issue is if you happen to have two pages on the site with the same file name (which isn't unheard of).
I think uniquely identifying each page with a unique class in the BODY tag is probably the best way to handle it.
So, perhaps your body tag is:
<body class="page-contactus">
And then add a class to your navigation:
<li><a href="contact.html" class="link-contactus">Contact us</a></li>
Then you'd have a block of CSS that will set these on a per-page basis:
.page-contactus .link-contactus {[add active style]}
.page-home .link-home {[add active style]}
.page-etc .link-etc {[add active style]}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Resolving LINQ Parameters that were passed to method in which LINQ Expression is I am working on LINQ to SQL translator. It should translate LINQ queries to SQL. I am focused on creating WHERE part of the query.
I am traversing LINQ Expression tree and then I get to a problem that I can't get to the value of actual parameter passed to the method that contains LINQ call.
NOTE: I am not using LINQ to SQL, nor Entity Framework, nor NHibernate because I simply can't since VB6 Legacy system is in the game.
So what I am trying to achieve is to call somewhere on high level this:
int? parameterForCall = cmb.SelectedValue;
Then I have a method like this and it is in ExpenseDAL class that calls BaseDAL<Expense>.GetAll(X):
public IList<Expense> GetAll(int? parameterForCall)
{
IList<Expense> expenses = BaseDAL<Expense>.GetAll(t => t.Fixed ==
parameterForCall);
}
GetAll method has signature like this:
public static IList<T> GetAll(Expression<Func<T, bool>> predicate = null);
Then I am calling GetCondition method that converts expression to SQL:
private static string GetCondition(Expression predicate = null);
It is a recursive function. In it I get to a situation that I need to get to parameter that I passed to GetAll expression, named parameterForCall.
The problem is that I can write this:
dynamic value = (predicate as ConstantExpression);
And in ImmediateWindow I can see that value.Value is written like this:
{FMC.Proxy.Common.BaseDAL.}
parameterForCall: 19
But I can't get to the value 19. And I want it so I can convert it to value to put to SQL string.
Does anyone know how to get to value 19 so I can use it in the code?
A: You simply have to get the property from the dynamic you already got:
dynamic value = (predicate as ConstantExpression);
int? parameterForCall = value.parameterForCall;
If you don't know the name of the parameter (and perhaps the type) you can use reflection. The parameter you are looking for exists as a public field of the object returned by ConstantExpression.Value. This is not something specified anywhere so use it at your own risk.
This small piece of code demonstrates that:
class Expense { public int Fixed { get; set; } }
void Test(int? parameterForCall) {
Expression<Func<Expense, bool>> predicate = t => t.Fixed == parameterForCall;
var parameter = (
(ConstantExpression) (
(MemberExpression) (
(BinaryExpression) predicate.Body
).Right
).Expression
).Value;
var fieldInfo = parameter.GetType().GetFields().First();
var name = fieldInfo.Name;
var value = fieldInfo.GetValue(parameter);
Console.WriteLine(name + " = " + value);
}
If you execute Test(19) the output is parameterForCall = 19.
A: My answer assumes - and your question supports this assumption - that the predicate passed into GetCondition is of type ConstantExpression.
It isn't trivial to get that value, because parameterForCall is captured in an automatically generated class. You can see that, when you look at the output of (predicate as ConstantExpression).Value.GetType(). In my case, this outputs:
UserQuery+<>c__DisplayClass0
This class in turn has a public field named parameterForCall. Now, you have two possibilities to get that value:
*
*You know the name of that field, because you control the method in which this Expression is created. In that case, you can use this code to get the value:
var constantExpression = (ConstantExpression)predicate;
dynamic autoGeneratedClass = constantExpression.Value;
object value = autoGeneratedClass.parameterForCall;
value.GetType() will return System.Int32 and the value will be a boxed int with the value 19.
*You don't know the name of that field. In that case, it is harder. You could use reflection to get the value of the only public visible field, but if you do this, you would make a lot of assumptions about the automatically generated class.
A: Hope this Stackoverflow answer helps
expression trees linq get value of a parameter?
Basically you might have to compile the expression before being able to programmatically get the property value.
Watch for performance penalty though. Good luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting error while converting C MEX-file into pure c++ i am converting some C mex-files into pure C++. obviously i need to convert mxarrays and mex functions.
as you see in the code, it creates an mxarray at line 60,
mxArray *mxGradient = mxCreateNumericArray(3, out, mxDOUBLE_CLASS, mxREAL);
and at the line 61 assigns it to a pointer with mxgetpr,
double *gradient = (double *)mxGetPr(mxGradient);
at the line 68 it sums the pointer with multiplication of integers,
double *tempGradientVBase = gradient + ( out[0] * out[1]);
i couldn't manage to understand the line 68. what does it means?
i don't know so much about mxarrays and mex files. could anyone please help me?
A: This is C pointer arithmetic.
The code that you pasted is treating gradient as a pointer to the first double in an array of doubles. By gradient + ( out[0] * out[1] ), it means "give me the pointer to the double at index out[0] * out[1] in the array of doubles beginning at gradient". It is equivalent to &gradient[ out[0] * out[1] ].
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C send() to socket and select() function I want to send(socketfd, ...) and I'm using the select() function. Should this file descriptor be in the writefds, or in the readfds?
A: readfds are for sockets you want to read from, writefds for those you want to write to. So writefds in your case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Javascript (jQuery) remove last sentence of long text I'm looking for a javascript function that is smart enough to remove the last sentence of a long chunk of text (one paragraph actually). Some example text to show the complexity:
<p>Blabla, some more text here. Sometimes <span>basic</span> html code is used but that should not make the "selection" of the sentence any harder! I looked up the window and I saw a plane flying over. I asked the first thing that came to mind: "What is it doing up there?" She did not know, "I think we should move past the fence!", she quickly said. He later described it as: "Something insane."</p>
Now I could split on . and remove the last entry of the array but that would not work for sentences ending with ? or ! and some sentences end with quotes like something: "stuff."
function removeLastSentence(text) {
sWithoutLastSentence = ...; // ??
return sWithoutLastSentence;
}
How to do this? What's a proper algorithm?
Edit - By long text I mean all the content in my paragraph and by sentence I mean an actual sentence (not a line), so in my example the last sentence is: He later described it as: "Something insane." When that one is removed, the next one is She did not know, "I think we should move past the fence!", she quickly said."
A: Define your rules:
// 1. A sentence Starts with a Capital letter
// 2. A sentence is preceded by nothing or [.!?], but not [,:;]
// 3. A sentence may be preceded by quotes if not formatted properly, such as ["']
// 4. A sentence may be incorrectly in this case if the word following a quote is a Name
Any additional Rules?
Define your Purpose:
// 1. Remove the last sentence
Assumptions:
If you started from the last character in the string of text and worked backwards, then you'd identify the beginning of the sentence as:
1. The string of text before the character is [.?!] OR
2. The string of text before the character is ["'] and preceded by a Capital letter
3. Every [.] is preceded by a space
4. We aren't correcting for html tags
5. These assumptions are not robust and will need to be adapted regularly
Possible Solution:
Read in your string and split it on the space character to give us chunks of strings to review in reverse.
var characterGroups = $('#this-paragraph').html().split(' ').reverse();
If your string is:
Blabla, some more text here. Sometimes basic html code is used but that should not make the "selection" of the sentence any harder! I looked up the window and I saw a plane flying over. I asked the first thing that came to mind: "What is it doing up there?" She did not know, "I think we should move past the fence!", she quickly said. He later described it as: "Something insane."
var originalString = 'Blabla, some more text here. Sometimes <span>basic</span> html code is used but that should not make the "selection" of the sentence any harder! I looked up the window and I saw a plane flying over. I asked the first thing that came to mind: "What is it doing up there?" She did not know, "I think we should move past the fence!", she quickly said. He later described it as: "Something insane."';
Then your array in characterGroups would be:
["insane."", ""Something", "as:", "it", "described", "later", "He",
"said.", "quickly", "she", "fence!",", "the", "past", "move", "should", "we",
"think", ""I", "know,", "not", "did", "She", "there?"", "up", "doing", "it",
"is", ""What", "mind:", "to", "came", "that", "thing", "first", "the", "asked",
"I", "over.", "flying", "plane", "a", "saw", "I", "and", "window", "the", "up",
"looked", "I", "harder!", "any", "sentence", "the", "of", ""selection"", "the",
"make", "not", "should", "that", "but", "used", "is", "code", "html", "basic",
"Sometimes", "here.", "text", "more", "some", "Blabla,"]
Note: the '' tags and others would be removed using the .text() method in jQuery
Each block is followed by a space, so when we have identified our sentence start position (by array index) we'll know what index the space had and we can split the original string in the location where the space occupies that index from the end of the sentence.
Give ourselves a variable to mark if we've found it or not and a variable to hold the index position of the array element we identify as holding the start of the last sentence:
var found = false;
var index = null;
Loop through the array and look for any element ending in [.!?] OR ending in " where the previous element started with a capital letter.
var position = 1,//skip the first one since we know that's the end anyway
elements = characterGroups.length,
element = null,
prevHadUpper = false,
last = null;
while(!found && position < elements) {
element = characterGroups[position].split('');
if(element.length > 0) {
last = element[element.length-1];
// test last character rule
if(
last=='.' // ends in '.'
|| last=='!' // ends in '!'
|| last=='?' // ends in '?'
|| (last=='"' && prevHadUpper) // ends in '"' and previous started [A-Z]
) {
found = true;
index = position-1;
lookFor = last+' '+characterGroups[position-1];
} else {
if(element[0] == element[0].toUpperCase()) {
prevHadUpper = true;
} else {
prevHadUpper = false;
}
}
} else {
prevHadUpper = false;
}
position++;
}
If you run the above script it will correctly identify 'He' as the start of the last sentence.
console.log(characterGroups[index]); // He at index=6
Now you can run through the string you had before:
var trimPosition = originalString.lastIndexOf(lookFor)+1;
var updatedString = originalString.substr(0,trimPosition);
console.log(updatedString);
// Blabla, some more text here. Sometimes <span>basic</span> html code is used but that should not make the "selection" of the sentence any harder! I looked up the window and I saw a plane flying over. I asked the first thing that came to mind: "What is it doing up there?" She did not know, "I think we should move past the fence!", she quickly said.
Run it again and get:
Blabla, some more text here. Sometimes basic html code is used but that should not make the "selection" of the sentence any harder! I looked up the window and I saw a plane flying over. I asked the first thing that came to mind: "What is it doing up there?"
Run it again and get:
Blabla, some more text here. Sometimes basic html code is used but that should not make the "selection" of the sentence any harder! I looked up the window and I saw a plane flying over.
Run it again and get:
Blabla, some more text here. Sometimes basic html code is used but that should not make the "selection" of the sentence any harder!
Run it again and get:
Blabla, some more text here.
Run it again and get:
Blabla, some more text here.
So, I think this matches what you're looking for?
As a function:
function trimSentence(string){
var found = false;
var index = null;
var characterGroups = string.split(' ').reverse();
var position = 1,//skip the first one since we know that's the end anyway
elements = characterGroups.length,
element = null,
prevHadUpper = false,
last = null,
lookFor = '';
while(!found && position < elements) {
element = characterGroups[position].split('');
if(element.length > 0) {
last = element[element.length-1];
// test last character rule
if(
last=='.' || // ends in '.'
last=='!' || // ends in '!'
last=='?' || // ends in '?'
(last=='"' && prevHadUpper) // ends in '"' and previous started [A-Z]
) {
found = true;
index = position-1;
lookFor = last+' '+characterGroups[position-1];
} else {
if(element[0] == element[0].toUpperCase()) {
prevHadUpper = true;
} else {
prevHadUpper = false;
}
}
} else {
prevHadUpper = false;
}
position++;
}
var trimPosition = string.lastIndexOf(lookFor)+1;
return string.substr(0,trimPosition);
}
It's trivial to make a plugin for it if, but beware the ASSUMPTIONS! :)
Does this help?
Thanks,
AE
A: This ought to do it.
/*
Assumptions:
- Sentence separators are a combination of terminators (.!?) + doublequote (optional) + spaces + capital letter.
- I haven't preserved tags if it gets down to removing the last sentence.
*/
function removeLastSentence(text) {
lastSeparator = Math.max(
text.lastIndexOf("."),
text.lastIndexOf("!"),
text.lastIndexOf("?")
);
revtext = text.split('').reverse().join('');
sep = revtext.search(/[A-Z]\s+(\")?[\.\!\?]/);
lastTag = text.length-revtext.search(/\/\</) - 2;
lastPtr = (lastTag > lastSeparator) ? lastTag : text.length;
if (sep > -1) {
text1 = revtext.substring(sep+1, revtext.length).trim().split('').reverse().join('');
text2 = text.substring(lastPtr, text.length).replace(/['"]/g,'').trim();
sWithoutLastSentence = text1 + text2;
} else {
sWithoutLastSentence = '';
}
return sWithoutLastSentence;
}
/*
TESTS:
var text = '<p>Blabla, some more text here. Sometimes <span>basic</span> html code is used but that should not make the "selection" of the text any harder! I looked up the window and I saw a plane flying over. I asked the first thing that came to mind: "What is it doing up there?" She did not know, "I think we should move past the fence!", she quickly said. He later described it as: "Something insane. "</p>';
alert(text + '\n\n' + removeLastSentence(text));
alert(text + '\n\n' + removeLastSentence(removeLastSentence(text)));
alert(text + '\n\n' + removeLastSentence(removeLastSentence(removeLastSentence(text))));
alert(text + '\n\n' + removeLastSentence(removeLastSentence(removeLastSentence(removeLastSentence(text)))));
alert(text + '\n\n' + removeLastSentence(removeLastSentence(removeLastSentence(removeLastSentence(removeLastSentence(text))))));
alert(text + '\n\n' + removeLastSentence(removeLastSentence(removeLastSentence(removeLastSentence(removeLastSentence(removeLastSentence(text)))))));
alert(text + '\n\n' + removeLastSentence('<p>Blabla, some more text here. Sometimes <span>basic</span> html code is used but that should not make the "selection" of the text any harder! I looked up the '));
*/
A: This is a good one. Why don't you create a temp variable, convert all '!' and '?' into '.', split that temp variable, remove the last sentence, merge that temp array into a string and take it's length? Then substring the original paragraph up until that length
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Install vFrabric tc server (as bundled with STS) into Linux EC2 instance? I have been developing a Spring MVC web app using Springsource Tool Suite (STS). STS comes with vFabric tc server developer edition I believe. When I deploy the .war file into my EC2 Linux AMI instance running tomcat6, there are incompatibilities between tomcat and vFabric.
For example, vFabric will accept objectName.getMethod() whereas it will return an error in tomcat6. I have to change it to objectName.method.
Here is my question. So, when making changes now, I don't use STS anymore and every change I have to package and redeploy which is time consuming. What is a good way around this?
I am thinking of installing the vFrabic tc server in my EC2 linux instance. Will that work? If I do that, theoretically, everything I develop in STS should be 100% compatible when deployed, correct?
Second question. How do I install vFrabic tc server in my EC2 instance?
Thanks!
A: One suggestion would be to develop inside of STS using a Tomcat server instead of tcServer. However, then of course you loose some of the nice capabilities of tcServer.
If no one here can give you a complete answer, I would recommend the SpringSource forums (for STS):
http://forum.springsource.org/forumdisplay.php?32-SpringSource-Tool-Suite
or here for tcServer:
http://forum.springsource.org/forumdisplay.php?64-tc-Server-General
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Color of date tag in org-mode publish to HTML and boxes around text I am using org-mode version 7.4 to organize all of my research notes and then export to HTML so I can create a sort of personal wiki. I just have two questions:
1) Upon export to HTML, the org-mode date stamps appear a very faint gray, is there anyway to change this this color to something more bold? If the fix involves adding a lot of messy CSS tags, is there something I could add to my .emacs file instead? I am hoping to keep my original org file as neat and as legible as possible.
2) Also, what is the best way to add a box around some text in org-mode? I have found that surrounding the text in #+BEGIN_SRC emacs-lisp / #+END_SRC emacs-lisp tags works the same as #+BEGIN_EXAMPLE/#+END_EXAMPLE in that the org-mode features (like using an asterix to mark headings and -,+,. to mark sub-items) do not get evaluated in the block. I am interested in just being able to put a block around the text, but still have the org-mode features such as headings, sub-items, etc., be evaluated.
Thank you for the help, I admit I am a bit of a noob here.
UPDATE: Thank you to Jonathan Leech-Pepin and Juancho for the tips. Part 1 is definitely answered and I apologize for missing it in the manual.
For part 2, I realize I could wrap DIV tags in BEGIN_SRC HTML tags, but I was hopeful that there might be a simpler way of doing this, as it seems like something many people would want to do as a way of highlighting or offsetting text. I was hoping there was something equivalent to the BEGIN_EXAMPLE/END_EXAMPLE tags that I was simply missing. I can use the DIV tags, and will if need be, but it ends up making the original org file look a bit messy and illegible if you end up doing it a lot. So if anyone knows a shortcut, I'd be happy to hear it. I suppose if I knew what I was doing more, I could write my own function, which I may just end up looking into once I'm through my thesis proposal and actually have more free time. :)
Thanks Everyone!!!
A: For point 1)
You can adjust the CSS settings either for a single file or create a custom stylesheet.
The relevant classes for style formatting are listed in the Org Manual - CSS Support
As a test I added (as a single line, the line return is to make it easier to read on the page)
#+STYLE: <style type="text/css"> .timestamp { color: purple; font-weight: bold; }
</style>
to one of my org files and exported. The timestamps were a bold purple, which was much more legible.
A: The HTML exporter in org-mode adds class identifiers extensively, so that you can style your HTML at will.
Have a look at http://orgmode.org/manual/CSS-support.html
You don't need to include your CSS inside the document itself. You can either link to a stylesheet via the #+STYLE directive, or you can customize the default CSS that comes with org-mode.
As for question 2, have a look at an exported org-mode file. There are plenty of div sections that you can style via CSS, like adding a border.
A: As another option if you prefer some trial and error as well as seeing an example vs. a specification is to download some examples and pay attention to what css elements are tweaked.
For example, I was recently trying to change the background color of exported tags in html and found this org-mode mailing list thread. I grabbed a copy of worg-original.css and searched it for the word 'tag':
.tag {
color: #DDD;
font-size: 70%;
font-weight: 500;
}
I didn't like the background and noticed other elements with a background-color property so I played with it and ended up with:
.tag {
color: #000;
background-color: #ccf;
font-size: 85%;
font-weight: 500;
margin: 0 0 0 8em;
}
You can do the same for timestamp properties. I'd suggest finding some things you like and throwing them together in a .css file. From there you can just put the #+style: line in each file (as has already been mentioned):
#+STYLE: <link rel="stylesheet" type="text/css" href="path/to/stylesheet.css" />
This isn't really anything new compared to the other answers; I mainly added it as another approach. I didn't know css, so seeing the list of properties in the org manual (p.author, .timestamp-kwd, .todo) didn't mean much to me. Finding a .css that was specifically designed for org-mode expert, such as those linked in the mailing list above for the org manual and worg were much more helpful since I could see some tangible examples and tweak from there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Why is the constructor for my class not being called in this case? I am creating a new class instance like this:
Cube* cube1;
There is code in the Cube constructor, but it's not being run! Is this usual?
A: You're actually not creating any instance.
the variable you're calling cube1 is a pointer to a Cube.
To create a Cube you should have:
Cube* cube1 = new Cube();
This create a new instance of Cube in heap memory, you should call delete cube1 once you don't use it anymore.
or:
Cube cube1;
This create a new instance of Cube in stack memory, it will be destroyed once it goes out of scope.
PS. you should get a C++ textbook.
A: You're not creating an instance of a Cube; you're creating a pointer to a Cube.
To create a pointer to a new instance of a Cube, you'd want code like this:
Cube* cube1 = new Cube;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Ajax request works in safari, but not in Firefox (Vimeo oembed) I'm trying to get a vimeo embed code via the oembed API (json).
It works fine in safari, but in Firefox, it seems that the json returned is not interpreted correctly, as I get a null value instead of the javascript object (in the success method).
i'd give a link to a jsfiddle example, but the sample doesn't work there, some error about an unallowed origin..
So here is the code:
<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script>
<script type='text/javascript'>
//<![CDATA[
$(window).load(function(){
$.ajax({
url: "http://vimeo.com/api/oembed.json?&format=json&url=http%3A//vimeo.com/2197639",
dataType: "json",
success: function(data) {
$('#output').html(JSON.stringify(data));
},
error: function(errorSender, errorMsg) {
console.log(errorSender);
console.log(errorMsg);
$('#output').html(errorSender + ' ' + errorMsg);
}
});
});
//]]>
</script>
Any ides what could be wrong? Is it something with the json?
Sample json is:
{"type":"video","version":"1.0","provider_name":"Vimeo","provider_url":"http:\/\/vimeo.com\/","title":"Early Morning Qena","author_name":"Oliver Wilkins","author_url":"http:\/\/vimeo.com\/offshoot","is_plus":"1","html":"<iframe src=\"http:\/\/player.vimeo.com\/video\/2197639\" width=\"1280\" height=\"720\" frameborder=\"0\" webkitAllowFullScreen allowFullScreen><\/iframe>","width":1280,"height":720,"duration":229,"description":"Early morning in Quft, near Qena. Shot with EX1 and Letus Extreme 35mm DOF adaptor.\n\nwww.offshoot.tv\n","thumbnail_url":"http:\/\/b.vimeocdn.com\/ts\/271\/854\/27185484_640.jpg","thumbnail_width":640,"thumbnail_height":360,"video_id":2197639}
A: You need to use JSONP because you are trying to perform a cross domain AJAX call. It looks that vimeo supports it. You just need to specify a callback by modifying your url (notice the callback=? parameter that I appended at the end and the format=jsonp):
$.ajax({
url: "http://vimeo.com/api/oembed.json?format=jsonp&url=http%3A%2F%2Fvimeo.com%2F2197639&callback=?",
dataType: "jsonp",
success: function(data) {
$('#output').text(JSON.stringify(data));
},
error: function(errorSender, errorMsg) {
$('#output').text(errorSender + ' ' + errorMsg);
}
});
and here's a live demo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySql Strange Runs Of Command Denied Errors I have an intermittent problem with a MySql database.
Everything runs just fine for long periods of time, but then we suddenly get a run of errors being logged such as this:
MySql.Data.MySqlClient.MySqlException: UPDATE command denied to user
'user'@'ip.add.ress' for table 'tblTable'
The user being reported is the correct user. The same user works just fine almost all the time, but when we get this error we get a load all at once.
I know this is vague, but I have checked that the permissions exist, and indeed the same code, using the same user works almost all the time.
Confirmation: We are not restricting access by IP - it's just a user name and password.
A: Just to close this one out. We solved this issue by granting the same user elevated permissions (i.e. against the MySQL instance as well as the specific database).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calculate number of days remaining I would like to calculate the number of days remaining before a date. In my database I have a timestamp corresponding to the end date. For example Friday 30. I would like to say something like that :
7 days remaining... 6, 5, 4, etc
Can you help me please ?
A: $days = round((timestamp_from_database - time()) / 86400);
A: SELECT DATEDIFF(yourtimestamp, CURDATE()) AS days
doc ref: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_datediff
A: $future = strtotime('21 July 2012'); //Future date.
$timefromdb = //source time
$timeleft = $future-$timefromdb;
$daysleft = round((($timeleft/24)/60)/60);
echo $daysleft;
A: $date1 = new DateTime("2016-01-01"); //current date or any date
$date2 = new DateTime("2016-12-31"); //Future date
$diff = $date2->diff($date1)->format("%a"); //find difference
$days = intval($diff); //rounding days
echo $days;
//it return 365 days omitting current day
A: $date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
http://php.net/manual/ro/function.date-diff.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: regexp matching slug Please help with slug regexp.
I would appreciate if the code will be given in python.
Conditions:
1 #valid
1-1 #valid
1-1-1 #valid (infinite \d-\d)
1- #invalid
-1 #invalid
-1- #invalid
*NOTE 1 = \d
A: I would write it this way:
compiled = re.compile(r'\d(?:-\d)*$')
result = compiled.match(string_to_parse)
A: How about:
re.match(r'\d(?:-\d)*$', s)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: LLVM exceptions; how to unwind at the moment, i'm inserting variables into the beginning of block scope using CreateEntryBlockAlloca:
template <typename VariableType>
static inline llvm::AllocaInst *CreateEntryBlockAlloca(BuilderParameter& buildParameters,
const std::string &VarName) {
HAssertMsg( 1 != 0 , "Not Implemented");
};
template <>
inline llvm::AllocaInst *CreateEntryBlockAlloca<double>(BuilderParameter& buildParameters,
const std::string &VarName) {
llvm::Function* TheFunction = buildParameters.dag.llvmFunction;
llvm::IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
TheFunction->getEntryBlock().begin());
return TmpB.CreateAlloca(llvm::Type::getDoubleTy(buildParameters.getLLVMContext()), 0,
VarName.c_str());
}
Now, i want to add Allocas for non-POD types (that might require a destructor/cleanup function at exit). However, it is not enough to add destructor calls at the end of the exit scope block, since it is not clear how to have them be invoked when a regular DWARF exception is thrown (for the purpose of this argument, lets say that exceptions are thrown from Call points that invoke C++ functions which only throw a POD type, so no, in my case, ignorance is bliss, and i would like to stay away from intrinsic llvm exceptions unless i understand them better).
I was thinking that may be i could have a table with offsets in the stack with the Alloca registers, and have the exception handler (at the bottom of the stack, at the invocation point of the JIT function) walk over those offsets on the table and call destructors appropiately.
The thing i don't know is how to query the offset of the Alloca'ed registers created with CreateAlloca. How can i do that reliably?
Also, if you think there is a better way to achieve this, please enlighten me on the path of the llvm
*
*Technical Comment: the JIT code is being called inside a boost::context which only invokes the JIT code inside a try catch, and does nothing on the catch, it just exits from the context and returns to the main execution stack. the idea is that if i handle the unwinding in the main execution stack, any function i call (for say, cleaning up stack variables) will not overwrite those same stack contents from the terminated JIT context, so it will not be corrupted. Hope i'm making enough sense
A:
The thing i don't know is how to query the offset of the Alloca'ed registers created with CreateAlloca. How can i do that reliably?
You can use the address of an alloca directly... there isn't any simple way to get its offset into the stack frame, though.
Why exactly do you not want to use the intrinsic LLVM exceptions? They really are not that hard to use, especially in the simple case where your code never actually catches anything. You can basically just take the code clang generates in the simple case, and copy-paste it.
Edit:
To see how to use exceptions in IR in the simple case, try pasting the following C++ code into the demo page at http://llvm.org/demo/:
class X { public: ~X() __attribute((nothrow)); };
void a(X* p);
void b() { X x; a(&x); }
It's really not that complicated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: FrameTicks->Automatic in ClickPane causes constant processor activity I discovered that a MatrixPlot in a ClickPane causes one of my processor cores to cycle at about 50% activity if the option FrameTicks -> Automatic is present. I have cut down the code to the following (which doesn't do anything really):
a = ConstantArray[0, {2, 11}];
ClickPane[
Dynamic@
MatrixPlot[a, FrameTicks -> Automatic],
# &
]
Switching to FrameTicks -> None stops the core activity.
To study the processor behavior I let a Clock cycle between None and Automatic every 20 secs (remove the above ClickPane first):
ClickPane[
Dynamic@
MatrixPlot[a, FrameTicks -> ft],
# &
]
Dynamic[ft = {Automatic, None}[[Clock[{1, 2, 1}, 20]]]]
This gives me the following processor activity display:
This is on my Win7-64 / MMA 8.0.1 system.
My questions are:
*
*Is this reproducible on other systems?
*Am I doing something wrong or is this a bug?
*Why does the bare MatrixPlot[a] (without any FrameTicks setting whatsoever) have these odd-looking frame tick choices?
A: Win XP Mma 8.0
The missed peaks correspond to times when the notebook was hidden by another window. Losing focus does not stop the CPU draining.
A: It seems that the Automatic setting of the FrameTicks option changes an internal variable that can be seen by Dynamic. It is apparently (and I think erroneously) not localized. This causes a complete re-evaluation of the argument of the Dynamic.
A workaround would be to add Refresh, which enables the use of TrackedSymbols, so that we can restrict triggering to just the variables we're interested in, in this case array a and the FrameTicks options value ft:
ClickPane[
Dynamic@
Refresh[
MatrixPlot[a, FrameTicks -> ft],
TrackedSymbols -> {a, ft}],
# &
]
Dynamic[ft = {Automatic, None}[[Clock[{1, 2, 1}, 20]]]]
My processor status stays flat at close to zero now.
A: Confirmed also on Mac OS X 10.6, Mathematica 8.0.1.
I thought at first that this was something to do with the kernel having to recalculate where the ticks went, every time FrameTicks->Automatic option was set.
So I tried this and got the same result. Likewise for ArrayPlot.
With[{fta = FrameTicks /.
FullForm[MatrixPlot[a, FrameTicks -> Automatic]][[1, 4]]},
ClickPane[Dynamic@MatrixPlot[a, FrameTicks -> ft], # &]
Dynamic[ft = {fta, None}[[Clock[{1, 2, 1}, 20]]]] ]
But not for this plot - CPU usage barely moved between the two states.:
ClickPane[
Dynamic@Plot[Sin[x], {x, 0, 6 Pi}, Frame -> True,
FrameTicks -> ft], # &]
Dynamic[ft = {Automatic, None}[[Clock[{1, 2, 1}, 20]]]]
I can only surmise that there must be some inefficiency in the way FrameTicks are displayed on these raster-type plot.
In answer to your third question, the odd tick choice doesn't reproduce on my system.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Struts 2 Clarification needed I wonder how struts 2 validation is performed without specifying Validate = true in struts config xml. Can you anyone tell me the flow of Struts 2 validation using validation framework.
A: Validation happens through a combination of the "validation" and "workflow" interceptors. There is no "validate" setup in the Struts 2 config file, because it's unnecessary.
A: Struts core has the validation framework that assists the application to run the rules to perform validation before the action method is executed.
Actions class works as a domain data and it looks for the properties in its Action Mapping File and it searches the field validators in theFileName-Validation.xml and all validators work as per the field defined in validation.xml. If there is any mismatching of data, it picks the message from the validation.xml and displays it to user.
Sample Employee-validation.xml :
<validators>
<field name="name">
<field-validator type="required">
<message>
The name is required.
</message>
</field-validator>
</field>
<field name="age">
<field-validator type="int">
<param name="min">29</param>
<param name="max">64</param>
<message>
Age must be in between 28 and 65
</message>
</field-validator>
</field>
</validators>
This is the sample validation file for Employee model and request will be validated for properties name and age. If name field left empty validation will gives the error message as "The name is required" above the name input box And if the age entered is outside the limit of 29-64 validation will show an error as "Age must be in between 28 and 65" above the age input box.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to compile and run xv6 on windows?
Possible Duplicate:
How to compile and run xv6 on windows?
We are being taught xv6 in our course. Currently we use to login to linux server of our school using putty in windows.
There we make changes in source of xv6 (using vim), then compile and run it in qemu simply
make clean
make
make qemu-nox
It is not always possible to connect to their servers therefore I want to be able to compile and run xv6 withing windows (in some emulator obviously).
What emulator I can use for above kind work? (edit code, compile and run) and how?
A: You should be able to build the xv6 system using cygwin from www.cygwin.org; make sure you install gcc, make and a decent editor (emacs or vim or just use a regular windows editor like notepad++). After that, you can run the resulting image with one of the qemu ports for windows; I found Qemu Manager to be quite easy to use (http://www.davereyn.co.uk/download.htm). You will have to modify the Makefile to point to the proper qemu location.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Very very basic query on programming in C -- displaying int value When I compile this little program instead of displaying "num1:7 , num2: 2",
it displays "num1:-1218690218 , num2:-1217453276". I think I'm not specifying what the program should display so its just giving me the int range instead.
I'm sorry.
#include <stdio.h>
main() {
int num1 = 7, num2 = 2;
printf("num1:%d , num2:%d\n"), num1, num2;
}
EDIT: Thank you so much! The purpose of the exercise was to correct syntax errors, but whenever I compiled it I never got any warnings. That parenthesis is so easy to miss.
A: You've put the closing parenthesis before num1 and num2, so they're not being passed to printf. You need to change this:
printf("num1:%d , num2:%d\n"), num1, num2;
to this:
printf("num1:%d , num2:%d\n", num1, num2);
Yes, the parenthesis is the only change, but it's crucial.
A: You are using the comma operator instead of arguments to a function call. printf will output garbage values but it could have crashed as well.
So it should be:
printf("num1:%d , num2:%d\n", num1, num2);
Notice the )-character.
A: You want to move num1 and num2 inside your parentheses:
printf("num1:%d , num2:%d\n", num1, num2);
The reason is that num1 and num2 are part of the call to the printf function - without them, printf uses random data from elsewhere, giving you those large negative values.
A: Try this:
#include <stdio.h>
main() {
int num1 = 7, num2 = 2;
printf("num1:%d , num2:%d\n", num1, num2);
// ^ num1 and num2 go inside the parentheses
}
A: If that is the actual code then fix it by moving the paren.
printf("num1:%d , num2:%d\n", num1, num2);
A: I think your program should look more like this
int main(){
int num1 = 7, num2 = 2;
printf("num1 : %d num2 : %d\n",num1,num2);
}
A: use a compiler that checks your syntax something like pellesc for windows
#include <stdio.h>
int main(){
int num1 = 7, num2 = 2;
printf("num1:%d , num2:%d\n", num1, num2);
return 0;
}
your printf format was wrong something a c editor would have told you
A: What is happening is that printf is looking at numbers in memory adjacent to the memory the program is working in (the stack). These numbers are there for some other reason when printf just happens to look at them, so it prints them instead of num1 and num2. As others have pointed out, your arguments (num1 and num2) need to be inside of the parentheses so that printf can use them.
A: #include <stdio.h>
int main()
{
//int num1 = 7, num2 = 2; this is static intialisation
//u want it as dynamic u have to use
int num1,num2;
scanf("%d%d",&num1,&num2); //get the values from user
printf("num1:%d , num2:%d\n", num1, num2);
return 0;
}
A: What you wanted was "call printf with this format string, using num1 as the first value to substitute in and num2 as the second value to substitute in; ignore the value that printf returns". (printf normally returns a count of how many bytes it printed; the actual printing is a side effect.)
What you wrote was "call printf with this format string; ignore the value that it returns, and evaluate num1; ignore that value and evaluate num2; ignore that value". This is undefined behaviour: printf hasn't been given any values to substitute in, and will normally blindly reach around in memory for the values that it's expecting to receive (sometimes resulting in a crash) - but the language standard says your program is allowed to do literally anything at this point. Yes, this is a very dangerous language to be working with :)
To pass the values to printf, they need to be within the parentheses, as illustrated in other answers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: move a small circle around a big circle this i an interview question i encountered with HULU.
Given two circles, one has radius 1 and the other has radius 2. Let the small one rotate along the perimeter of the big one. how many circles will the small one rotates when it has moves one round inside the big one? and what about outside?
A: The perimeter of the circle of radius 1 is 2*PI*1 and the other one is 2*PI*2.
Then when the little circles rotates inside it makes 2 round and same thing at the outside... Maybe I don't understand anything...
A: how many diameters of the small circle are in one diameter of the big one?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Threaded timed loops in Perl I'd like to, essentially, have a high-priority thread, that runs at a given interval (here 0.5 ms) and interrupts "everything", executes a short task, and then goes back to 'sleep'; using Ubuntu 11.04 and perl v5.10.1. The problem is, while I'm getting some sort of results, I am not sure whether it's possible to get "tight timing".
I have made three test scripts, in which the 'loop' is basically increasing a counter 10 times, taking timestamps - and then it terminates, and the timestamps are printed (in microseconds).
script 1
The first one is based around a snippet I've found in Perl- How to call an event after a time delay - Perl - however, I cannot get that particular snippet to work; so with some changes, it is:
#!/usr/bin/env perl
# testloop01.pl
use strict;
use warnings;
use Time::HiRes qw ( setitimer ITIMER_VIRTUAL time );
my @tstamps;
my $cnt = 0;
my $numloops = 10;
my $loopperiod = 500e-6; # 0.000500 - 500 us
sub myfunc() {
push(@tstamps, time);
# repeat call for looping
if ($cnt < $numloops) {
$cnt++;
$SIG{VTALRM} = &myfunc; # must have this!
setitimer(ITIMER_VIRTUAL, 1, $loopperiod );
}
}
# take first timestamp at start
push(@tstamps, time);
# start it off
#~ $SIG{VTALRM} = sub { print time, "\n"; }; # no work like this on Linux ?!
$SIG{VTALRM} = &myfunc;
setitimer(ITIMER_VIRTUAL, 1, $loopperiod );
# wait - sleep 2 s
Time::HiRes::sleep(2);
# output results
my ($firstts, $ts, $td);
$firstts = -1; # init
for(my $ix=0; $ix<scalar(@tstamps); $ix++) {
$ts = $tstamps[$ix];
if ($firstts == -1) { # $ix == 0
$firstts = $ts;
$td = 0;
} else { # $ix > 0
$td = $ts - $tstamps[$ix-1];
}
printf "%10d (diff: %d)\n", ($ts-$firstts)*1e6, $td*1e6 ;
}
Executing this reports:
$ ./testloop01.pl
0 (diff: 0)
10 (diff: 10)
25 (diff: 15)
36 (diff: 10)
46 (diff: 10)
57 (diff: 10)
66 (diff: 9)
75 (diff: 8)
83 (diff: 8)
92 (diff: 9)
102 (diff: 9)
118 (diff: 15)
... meaning the loops basically runs as fast as it can, and the asked timing is not honored. I'm guessing, probably ITIMER_VIRTUAL doesn't work on my machine.
script 2
The second script is based around an example in Measurements at Regular Intervals in Perl:
#!/usr/bin/env perl
# testloop02.pl
use strict;
use warnings;
use POSIX qw(pause);
# this does NOT work w/ ITIMER_VIRTUAL
use Time::HiRes qw(setitimer ITIMER_REAL time);
my @tstamps;
my $cnt = 0;
my $numloops = 10;
my $loopperiod = 500e-6; # 0.000500 - 500 us
# take first timestamp at start
push(@tstamps, time);
# how often do we trigger (seconds)?
my $first_interval = $loopperiod;
my $interval = $loopperiod;
# signal handler is empty
$SIG{ALRM} = sub { };
# first value is the initial wait, second is the wait thereafter
setitimer(ITIMER_REAL, $first_interval, $interval);
while (1) {
# wait for alarm from timer
pause;
# do work that takes less than $interval to complete
push(@tstamps, time);
# repeat call for looping
if ($cnt < $numloops) {
$cnt++;
} else {
last;
}
}
Time::HiRes::sleep(2); # helps avoid segfault, but doesn't seem to do anything;
# "it's apparently not safe to use sleep and a timer at
# the same time, as one may reset the other"
# output results
my ($firstts, $ts, $td);
$firstts = -1; # init
for(my $ix=0; $ix<scalar(@tstamps); $ix++) {
$ts = $tstamps[$ix];
if ($firstts == -1) { # $ix == 0
$firstts = $ts;
$td = 0;
} else { # $ix > 0
$td = $ts - $tstamps[$ix-1];
}
printf "%10d (diff: %d)\n", ($ts-$firstts)*1e6, $td*1e6 ;
}
Running it results with:
$ ./testloop02.pl
0 (diff: 0)
717 (diff: 717)
1190 (diff: 473)
1724 (diff: 534)
2206 (diff: 481)
2705 (diff: 499)
3204 (diff: 499)
3705 (diff: 500)
4203 (diff: 498)
4682 (diff: 478)
5206 (diff: 524)
5704 (diff: 498)
... which, I guess, is as tight of a timing possible (with 'self-measurement') on a PC like this. The problem here is, though, that it runs in a single thread context (and usleep doesn't apparently work anymore).
script 3
The third script is an attempt to do the same with threads and usleep:
#!/usr/bin/env perl
# testloop03.pl
use strict;
use warnings;
use Time::HiRes qw ( usleep time );
use threads;
use threads::shared; # for shared variables
my @tstamps :shared;
my $cnt :shared = 0;
my $numloops :shared = 10;
my $loopperiod = 500e-6; # 0.000500 s - 500 us
my $loopperiodus :shared = $loopperiod*1e6; # 500 us
sub myfunc() {
# repeat call for looping
while ($cnt < $numloops) {
push(@tstamps, time);
$cnt++;
usleep($loopperiodus);
}
}
# take first timestamp at start
push(@tstamps, time);
# start it off
my $mthr = threads->create('myfunc');
$mthr->join();
# wait - sleep 2 s
Time::HiRes::sleep(2);
# output results
my ($firstts, $ts, $td);
$firstts = -1; # init
for(my $ix=0; $ix<scalar(@tstamps); $ix++) {
$ts = $tstamps[$ix];
if ($firstts == -1) { # $ix == 0
$firstts = $ts;
$td = 0;
} else { # $ix > 0
$td = $ts - $tstamps[$ix-1];
}
printf "%10d (diff: %d)\n", ($ts-$firstts)*1e6, $td*1e6 ;
}
When I run it, I get something like:
$ ./testloop03.pl
0 (diff: 0)
7498 (diff: 7498)
8569 (diff: 1070)
9300 (diff: 731)
9992 (diff: 691)
10657 (diff: 664)
11328 (diff: 671)
11979 (diff: 650)
12623 (diff: 643)
13284 (diff: 661)
13924 (diff: 639)
... which is somewhat close, but quite a bit off from the demanded period - and I wouldn't call it as tight as the second script either (and in fact, I experimented a bit with this, and my experience is that it can be relatively quickly unstable - even for quite simple tasks - depending on pressure from the OS like GUI updates and such).
So my question is - is there a way to get a "tight" timing in Perl (as in example 2, w/ setitimer) - but in the context of threads (as in example 3; as I'd basically want other stuff done in the main thread while this 'timed loop' is sleeping)? Unfortunately, trying to send the signal to a thread:
...
sub myfunc() {
setitimer(ITIMER_REAL, $loopperiod, $loopperiod);
# repeat call for looping
while ($cnt < $numloops) {
push(@tstamps, time);
$cnt++;
pause;
# usleep($loopperiodus);
# wait for alarm from timer
}
}
# signal handler is empty
$SIG{ALRM} = sub { };
# take first timestamp at start
push(@tstamps, time);
# start it off
my $mthr = threads->create('myfunc');
# first value is the initial wait, second is the wait thereafter
#~ setitimer(ITIMER_REAL, $loopperiod, $loopperiod);
$mthr->join();
...
... won't work:
$ ./testloop04.pl
Maximal count of pending signals (120) exceeded at ./testloop04.pl line 48.
Perl exited with active threads:
1 running and unjoined
-1 finished and unjoined
0 running and detached
EDIT2: example 2 could be used with fork to give an impression of multithreading; however, with forking variables are not shared (and Can't install IPC:Shareable anymore, which would have been the easy way out).
Many thanks in advance for any answers,
Cheers!
EDIT3: Thanks to the answer from @daxim, here is the above with AnyEvent:
#!/usr/bin/env perl
# http://linux.die.net/man/3/anyevent
# http://search.cpan.org/~mlehmann/AnyEvent-6.02/lib/AnyEvent.pm
use 5.010;
use AnyEvent qw();
my @tstamps;
my $cnt = 0;
my $numloops = 10;
my $loopperiod = 500e-6; # 0.000500 - 500 us
my $result_ready = AnyEvent->condvar;
my %events = (
timer => AE::timer(0, $loopperiod, sub {
push(@tstamps, AE::time);
if ($cnt < $numloops) {
$cnt++;
} else {
#~ AE::cv->send; # doesn't exit loop?
$result_ready->broadcast; # exits loop
}
}),
#~ quit => AE::cv->recv,
quit => $result_ready->wait,
);
sleep 1; # this will kick in only after loop is complete!
# output results
my ($firstts, $ts, $td);
$firstts = -1; # init
for(my $ix=0; $ix<scalar(@tstamps); $ix++) {
$ts = $tstamps[$ix];
if ($firstts == -1) { # $ix == 0
$firstts = $ts;
$td = 0;
} else { # $ix > 0
$td = $ts - $tstamps[$ix-1];
}
printf "%10d (diff: %d)\n", ($ts-$firstts)*1e6, $td*1e6 ;
}
Note that on my machine, for 0.5 ms it gives somewhat strange measures (left) - however, already at 1.5 ms, there are some nice results (right):
$ ./testloop05.pl
0 (diff: 0) 0 (diff: 0)
34 (diff: 34) 32 (diff: 32)
117 (diff: 82) 2152 (diff: 2120)
1665 (diff: 1548) 3597 (diff: 1445)
1691 (diff: 25) 5090 (diff: 1492)
3300 (diff: 1609) 6547 (diff: 1456)
3319 (diff: 18) 8090 (diff: 1542)
4970 (diff: 1651) 9592 (diff: 1502)
4990 (diff: 20) 11089 (diff: 1497)
6607 (diff: 1616) 12589 (diff: 1500)
6625 (diff: 18) 14091 (diff: 1501)
A: Threads aren't the only means of multi-programming. In the Perl world, they are one of the worst. Want to try your hand at event loops instead?
use 5.010;
use AnyEvent qw();
my %events = (
timer => AE::timer(0, 0.5, sub {
$now = AE::time;
say sprintf 'now: %f difference: %f', $now, $now - $previous;
$previous = $now;
}),
quit => AE::cv->recv,
);
$ perl testloop-ae.pl
now: 1316799028.264925 difference: 1316799028.264925
now: 1316799028.762484 difference: 0.497559
now: 1316799029.262058 difference: 0.499574
now: 1316799029.762640 difference: 0.500582
now: 1316799030.262207 difference: 0.499567
now: 1316799030.762668 difference: 0.500461
now: 1316799031.262242 difference: 0.499574
now: 1316799031.761805 difference: 0.499563
now: 1316799032.262378 difference: 0.500573
now: 1316799032.761953 difference: 0.499575
now: 1316799033.262513 difference: 0.500560
now: 1316799033.762081 difference: 0.499568
now: 1316799034.262674 difference: 0.500593
now: 1316799034.762256 difference: 0.499582
now: 1316799035.261837 difference: 0.499581
^C
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Big file upload causes browser to hang Small files go smoothly, even when uploading 100 5 Megabyte files at the same time (though it does only handle 5 at a time, queues the rest) but a 150MB file causes the browser to hang several seconds while it initiates.
function start(file) {
var xhr = new XMLHttpRequest();
++count;
var container = document.createElement("tr");
var line = document.createElement("td");
container.appendChild(line);
line.textContent = count + ".";
var filename = document.createElement("td");
container.appendChild(filename);
filename.textContent = file.fileName;
filename.className = "filename";
initXHREventTarget(xhr.upload, container);
var tbody = document.getElementById('tbody');
tbody.appendChild(container);
tbody.style.display = "";
var boundary = "xxxxxxxxx";
xhr.open("POST", "uploader.php");
xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary); // simulate a file MIME POST request.
xhr.setRequestHeader("Content-Length", file.size);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304) {
if (xhr.responseText != "") {
alert(xhr.responseText); // display response.
}
}
}
}
var body = "--" + boundary + "\r\n";
body += "Content-Disposition: form-data; name='upload'; filename='" + file.fileName + "'\r\n";
body += "Content-Type: application/octet-stream\r\n\r\n";
body += $.base64Encode(file.getAsBinary()) + "\r\n";
body += "--" + boundary + "--";
xhr.sendAsBinary(body);
}
A: It IS going to take a non-trivial amount of time to slurp in the file's contents, base64 encode it, and then do your string concatenation. In other words: Behaving as expected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to collect functions results into one array and return this array? My php function looks like that
function generateTour ($lang, $db)
{
echo '<table border="0" cellpadding="0" cellspacing="0" width="100%">';
$title='title_'.$lang;
$txt='txt_'.$lang;
$result = $db->query("SELECT id, $title, $txt FROM 1_table");
$count= $result->num_rows;
$i=1;
while($row=$result->fetch_object())
{
if($i%3==0) echo '<tr>';
echo '<td width="33%">
<div class="tour_item" style="background-image:url(core/content/img/pages/1/slide/'.$row->id.'.png)">
<div class="tour_item_title"><a href="?id='.$row->id.'">';
echo '</a></div><div class="tour_item_text"><a href="?id='.$row->id.'"></div>
</div>';
if($i==$count-1) echo '</td></tr>';
else if($i%3==0) echo '</td></tr><tr>';
$i++;
}
echo '</table>';
}
As you see it echoes result line by line. Not all at once. I want to collect all variables to one array and return this array. Is it possible? how to do it?
Please don't post your ideas about security holes .. etc. I'm filtering $title, $txt varibales against sql injections. (i have array for of possible field names. My filter function checks theese variables' values every time. )
A: $data = array();
while ($row = $result->fetchObject()) {
$data[] = $row;
}
Is the absolutely most basic method of cacheing a result set in an array. You'd just modify this to store your generated html instead.
A: Try this:
function generateTour ($lang, $db)
{
$output = '<table border="0" cellpadding="0" cellspacing="0" width="100%">';
$title='title_'.$lang;
$txt='txt_'.$lang;
$result = $db->query("SELECT id, $title, $txt FROM 1_table");
$count= $result->num_rows;
$i=1;
while($row=$result->fetch_object())
{
if($i%3==0)
{
$output .= '<tr>';
}
$output .= '<td width="33%">
<div class="tour_item" style="background-image:url(core/content/img/pages/1/slide/'.$row->id.'.png)">
<div class="tour_item_title"><a href="?id='.$row->id.'">
</a></div><div class="tour_item_text"><a href="?id='.$row->id.'"></div>
</div>';
if($i==$count-1)
{
$output .= '</td></tr>';
}
else if($i%3==0)
{
$output .= '</td></tr><tr>';
}
$i++;
}
$output .= '</table>';
return $output;
}
Edit:
Now it's easier to read the code. This solution put all content in one variable. You don't need a array.
A: You can use ob_start() and ob_get_clean() to buffer all output into a variable, then output that variable, like this:
ob_start();
print "Hello"; // Prints to buffer instead of screen
$out = ob_get_clean(); // Contains: Hello
echo $out; // Prints: Hello
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: looking for fastest way string to JSONObject in Android I used to use new JSONObject(string) to convert string to JSONObject. however, it is too slow performance-wise. Anybody have the faster solution?
A: Take a look at Jackson. They claim to be faster than any other Java JSON parser. It also parses the data in a stream, lowering memory consumption.
A: I've used Gson with some good success: http://code.google.com/p/google-gson/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Threads and processes? In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system.
This is very abstract!
*
*What would be real world/tangible/physical interpretation of threads?
*How could I tell if an application (by looking at its code) is a single threaded or multi threaded?
*Are there any benefits in making an application multi threaded? In which cases could one do that?
*Is there anything like multi process application too?
*Is technology a limiting factor to decide if it could be made multi threaded os is it just the design choice? e.g. is it possible to make multi threaded applications in flex?
If anyone can could give me an example or an analogy to explain these things, it would be very helpful.
A: *
*What would be real world/tangible/physical interpretation of threads?
Think about a thread as an independent unit of execution that can be executed concurrently (at the same time) on a given CPU(s). A good analogy would be multiple cars driving around independently on the same road. Here a "car" is a thread, and a road is that CPU. So the function of all these cars is somewhat the same: "drive people around", but the kicker is that people should not stand in line to wait for a single car => they can drive at the same time in different cars (threads).
Technically, however, depending on number of CPU cores, and overall hardware / OS architecture there will be some context switching, where CPU would make it seem it happens simultaneously, but in reality it switches from one thread to another.
*How could I tell if an application (by looking at its code) is a single threaded or multi threaded?
This depends on several things, a language the code is written in, your understanding of the language, what code is trying to accomplish, etc.. Usually you can tell, but I do not believe this will solve anything. If you already have access to the code, it's a lot simpler to just ask the developer, or, in case it is an open source product, read documentation, post on user forums to figure it out.
*Are there any benefits in making an application multi threaded? In which cases could one do that?
Yes, think about the car example above. The benefit = at the same time and decoupled execution of things. For example, you need to calculate how many starts are in a known universe. You can either have a single process go over all the stars and count them, or you can "spawn" multiple threads, and give each thread a galaxy to solve: "thread 1 counts all the stars in Milky Way, thread 2 counts all the starts in Andromeda, etc.."
*Is there anything like multi process application too?
That is a matter of terminology, but the cleanest answer would be yes. For example, in Erlang, VM is capable of starting many very lightweight processes very fast, where each process does its own thing. On Unix servers if you do "ps -aux / ps -ef", for example, you'd see multiple "processes" executin, where each process may in fact have many threads doing its job.
*Is technology a limiting factor to decide if it could be made multi threaded os is it just the design choice? e.g. is it possible to make multi threaded applications in flex?
2 threaded application is already multithreaded. You most likely already have 2 or more cores on your laptop / PC, so technology would pretty always encourage you to utilize those cores, rather than limit you. Having said that, the problem and requirements should drive the decision. Not the technology or tools. But if you do decide write a multithreaded application, make sure you understand all the gotchas and solutions to them. The best language I used so far to solve concurrency is Erlang, since concurrency is just built in to it. However, other languages like Scala, Java, C#, and mostly functional languages, where shared state is not a problem would also be a good choice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Android permissions categories and DELETE_PACKAGES and INSTALL_PACKAGES permissions I have an application that requires the DELETE_PACKAGES and INSTALL_PACKAGES permissions. The app is NOT being distributed through the market and requires "unknown sources" to be enabled. When I install this application the install page presents the user with a list of permission categories that include the categories:
*
*Your location
*Network communication
*Storage
*Services that cost you money
*Phone Calls
Are the permissions DELETE_PACKAGES and INSTALL_PACKAGES included in one of these categories? If so, which? If not, is the user not warned about this permission request?
For some background see List of android application categories and permissions
A:
I have an application that requires the DELETE_PACKAGES and INSTALL_PACKAGES permissions.
SDK applications cannot hold these permissions, unless they are part of the firmware.
Are the permissions DELETE_PACKAGES and INSTALL_PACKAGES included in one of these categories?
Probably not, but the user isn't installing your application, as it will be part of the firmware, so the point is presumably moot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Change Background on DragEnter I want to change the background of a framework element when the DragEnter event is fired and revert its background when the DragLeave event is fired. Additionally, I want this applied in a style.
Heres what I have currently:
<EventTrigger RoutedEvent="Button.DragEnter">
<BeginStoryboard x:Name="DragHoverStoryboard">
<Storyboard>
<DoubleAnimation Storyboard.Target="??????????"
Storyboard.TargetProperty="Background"
Duration="0:0:0"
To="{DynamicResource HoverBrush}" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="Button.DragLeave">
<StopStoryboard BeginStoryboardName="DragHoverStoryboard" />
</EventTrigger>
<EventTrigger RoutedEvent="Button.Drop">
<StopStoryboard BeginStoryboardName="DragHoverStoryboard" />
</EventTrigger>
The problem here is that I can't apply target by a name because this style can be applied to any FrameworkElement. How do I apply the target to the element that the Style is attached to?
A: Storyboard.Target is not the problem, just leave it out. However, you need to change the rest of the animation. To animate a color, use a ColorAnimation instead of a DoubleAnimation. Also, the property "Background" does not contain a color but a brush, so animate the property "Background.Color" instead. Here is a working example:
<Style TargetType="Button">
<Setter Property="Background" Value="Red"/>
<Style.Triggers>
<EventTrigger RoutedEvent="Button.DragEnter">
<BeginStoryboard x:Name="DragHoverStoryboard">
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Background.Color"
Duration="0:0:0" To="Green" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="Button.DragLeave">
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="Background.Color"
Duration="0:0:0" To="Red" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: c++ full screen windows 7 I need code to resize my c++ program to fullscreen.
I use Dev-C++
I tried this but it doesn't work on windows 7
keybd_event(VK_MENU,0x36,0,0);
keybd_event(VK_RETURN,0x1c,0,0);
keybd_event(VK_RETURN, 0x1c, KEYEVENTF_KEYUP,0);
keybd_event(VK_MENU, 0x38, KEYEVENTF_KEYUP,0);
A: Don't fake keyboard input when you don't have to. Call ShowWindow().
ShowWindow(MainWindowHandle, SW_MAXIMIZE);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Very Basic std::vector iterating std::vector<Ogre::SceneNode*>::iterator itr;
for(itr=mSelectedObjects.begin();itr!=mSelectedObjects.end();itr++){
itr->showBoundingBox(true); //here
}
I'm getting "expression must have pointer-to-class type" on the marked line, and I'm not sure why. Can anyone help?
A: Replace the erroneous line with:
(*itr)->showBoundingBox(true); //here
Since you're storing pointers, you need to dereference itr twice to get from the iterator to the object (once for the iterator and once for the pointer).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to embed jar in HTML There are a lot of resources on this already but I just can't seem to get it to work. What am I doing wrong? The jar file is at:
http://www.alexandertechniqueatlantic.ca/multimedia/AT-web-presentation-imp.jar
And the code I am using to embed is:
<APPLET ARCHIVE="multimedia/AT-web-presentation-imp.jar"
CODE="ImpViewer.class"
WIDTH=100%
HEIGHT=100%>
</APPLET>
The test page I am using is at:
http://www.alexandertechniqueatlantic.ca/test.php
When I download the jar it runs fine, so I am certain the problem is only with the html embedding. Pleas help!
Also, I get the following error:
java.lang.ClassCastException: ImpViewer cannot be cast to
java.applet.Applet
A: java.lang.ClassCastException: ImpViewer cannot be cast to java.applet.Applet
The 'applet' is not an applet.
BTW - nice UI. Like the way the red splash fades in to the 'Welcome Introductory Workshop' page. Very smooth.
Launch it from a link using Java Web Start (& please don't try and cram such a beautiful UI into a web page).
If the client insists on the GUI being crammed into a web site then (slap them for me &) try this hack.
/*
<APPLET
ARCHIVE="AT-web-presentation-imp.jar"
CODE="ImpViewerApplet"
WIDTH=720
HEIGHT=564>
</APPLET>
*/
import java.awt.*;
import java.applet.*;
import java.util.*;
public class ImpViewerApplet extends Applet {
public void init() {
setLayout(new BorderLayout());
Window[] all = Window.getWindows();
ArrayList<Window> allList = new ArrayList<Window>();
for (Window window : all) {
allList.add(window);
}
String[] args = {};
ImpViewer iv = new ImpViewer();
iv.main(args);
all = Window.getWindows();
for (Window window : all) {
if (!allList.contains(window) && window.isVisible()) {
if (window instanceof Frame) {
Frame f = (Frame)window;
Component[] allComp = f.getComponents();
Component c = f.getComponents()[0];
f.remove(c);
f.setVisible(false);
add(c);
validate();
}
}
}
}
}
The emphasis is on the word 'hack'.
*
*The Frame will flash onto screen before disappearing.
*It will only work at 720x564 px, unlike the java.awt.Frame which was resizable to any size. But then, your '100%' width/height was being a bit optimistic anyway. Some browsers will honour those constraints, others will not.
A: It took a bit of effort, but your ImpViewer class has the following definition:
public class ImpViewer extends ImWindow
implements Printable, Runnable
{
[...]
ImpViewer is NOT an Applet like it needs to be, but is instead an ImWindow. It should inherit from either Applet or perhaps ImApplet.
At either rate, Andrews idea of using Java Web Start is legit. The app you have looks more like a desktop app.
A: An Applet is a Java component which handles the right calls to show up embedded in a web page. The product you have (the JAR file) contains everything necessary to run the program; however, it does not have the correct interface (the applet) for running that program embedded in a web page.
Talk to the author of the product (of if that author is not available, look for documentation) and see if a applet interface is available. Perhaps it is only a matter of using a different class name. If it looks like such an interface is not available, then no one has done the necessary work to make it "embeddable" in a web page. Without knowing your product in more detail, it's not easy to determine if the effort to create an Applet interface into the product is easy or not.
If you don't have the source code, then the amount of effort to develop an Applet interface to what you have is even greater than the unknown amount of effort it would have been with the source code.
There are a few products that do allow applications to be viewed and controlled from a web browser, even when the application in question wasn't designed to be embedded in a web page. These products tend to be expensive and proprietary; but, if it is truly mission-critical (and if it makes enough money) then the expense and effort might be bearable. With such a solution, the web browser actually opens a window into a configured "application server" which launches the application in full screen mode every time the connection is established. Yes, it is an odd architecture; however, such an odd architecture exists purposefully as that's really the only way possible to do some things when the application can't run in other environments.
Look to Citrix for such a solution in the event that you can afford it (remember there's extra windows licenses involved) and you can tolerate it's performance and quirks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Solr dismax boost query not working I have some video titles stored in my solr index. I query based on title but want to have the rating to influence the score. The rating is a typical 5star rating. This rating is stored within solr along with the videos. I tried using the dismax request handler but looks like solr isn't boosting values.
You can see my requestHandler below:
<requestHandler default="true" name="dismax" class="solr.SearchHandler" >
<lst name="dismax">
<str name="defType">dismax</str>
<str name="echoParams">explicit</str>
<float name="tie">0.01</float>
<str name="qf">
title
</str>
<str name="pf">
title
</str>
<str name="mm">
0
</str>
<str name="bq">
rating:1^1.0 rating:2^1.0 rating:3^3.0 rating:4^5.0 rating:5^10.0
</str>
<str name="fl">
*,score
</str>
<int name="ps">100</int>
<str name="q.alt">*:*</str>
</lst>
Hope that someone can help me out!
I run the query with debug,This is the output of the debug. Can't see the rating field in the calculation of score...
4.429465 = (MATCH) weight(title:test in 1894), product of:
0.99999994 = queryWeight(title:test), product of: 4.4294653 =
idf(docFreq=26876, maxDocs=829428) 0.22576088 = queryNorm 4.4294653 =
(MATCH) fieldWeight(title:test in 1894), product of: 1.0 =
tf(termFreq(title:test)=1) 4.4294653 = idf(docFreq=26876,
maxDocs=829428) 1.0 = fieldNorm(field=title, doc=1894)
Some more debug information:
<lst name="debug">
<str name="rawquerystring">test</str>
<str name="querystring">test</str>
<str name="parsedquery">title:test</str>
<str name="parsedquery_toString">title:test</str>
<lst name="explain">...</lst>
<str name="QParser">LuceneQParser</str>
<arr name="filter_queries">
<str/>
</arr>
<arr name="parsed_filter_queries"/>
<lst name="timing">...</lst>
</lst>
A: Seems you have defined the list as dismax instead of defaults -
<requestHandler name="dismax" class="solr.SearchHandler" >
<lst name="defaults">
<str name="defType">dismax</str>
<str name="echoParams">explicit</str>
<float name="tie">0.01</float>
<str name="qf">
title
</str>
<str name="pf">
title
</str>
<str name="mm">
0
</str>
<str name="bq">
rating:1^1.0 rating:2^1.0 rating:3^3.0 rating:4^5.0 rating:5^10.0
</str>
<str name="fl">
*,score
</str>
<int name="ps">100</int>
<str name="q.alt">*:*</str>
</lst>
</requestHandler>
worked fine for me -
<str name="parsedquery">(+DisjunctionMaxQuery((title:itunes)~0.01) DisjunctionMaxQuery((title:itunes)~0.01) rating:1 rating:2 rating:3^3.0 rating:4^5.0 rating:5^10.0)/no_coord</str>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Coalesce/IsNull functionality in LINQ How can I make a property in a class return a certain string if its a certain condition eg/empty
public class Person
{
public string Name{get;set;}
publc string MiddleName{get;set;}
public string Surname{get;set;}
public string Gender{get;set;}
}
List<Person> people = repo.GetPeople();
List<Person> formatted = people.GroupBy(x=>x.Gender).//?? format Gender to be a certain string eg/"Not Defined" if blank
A: people.GroupBy(x=>x.Gender ?? "Not Available").ToList();
Update: (to catch empty strings)
people.GroupBy(x=> String.IsNullOrWhiteSpace(x.Gender) ? "None" : x.Gender).ToList();
A: If this was a local situation, i would fix the null with ?? at the place it's needed.
If a more generic solution is needed, which I recommend. I was go for fix it directly in the getter (or setter, if desired).
private string _gender;
public string Gender
{
get {
string val =
(!string.IsNullOrEmpty(_gender) ? _gender : "[Not decided yet]");
return val;
}
set { _gender = value; }
}
And within a test sample program in it's whole,
public class Nullable
{
public class Person
{
private string _gender;
public string Gender
{
get {
string val =
(!string.IsNullOrEmpty(_gender) ? _gender : "[Not decided yet]");
return val;
}
set { _gender = value; }
}
public string Name { get; set; }
public string MiddleName { get; set; }
public string Surname { get; set; }
}
static void Main()
{
List<Person> p = new List<Person>();
p.Add(new Person() { Name = "John Doe", Gender = "Male" });
p.Add(new Person() { Name = "Jane Doe", Gender = "Female" });
p.Add(new Person() { Name = "Donna Doe", Gender = "Female" });
p.Add(new Person() { Name = "UnDoe", });
// test 1
foreach (var item in p.GroupBy(x => x.Gender))
Console.WriteLine(item.Count() + " " + item.Key);
Console.WriteLine(Environment.NewLine);
//test 2
foreach (var item in p)
Console.WriteLine(item.Name + "\t" + item.Gender);
Console.ReadLine();
}
}
A: Try something like this (I'm using an int for the property type):
public class Widget
{
private int? MyPropertyBackingStore ;
public int MyProperty
{
get
{
int value = 0 ; // the default value
if ( this.MyPropertyBackingStore.HasValue && this.MyPropertyBackingStore > 0 )
{
value = this.MyPropertyBackingStore.Value ;
}
return value ;
}
set
{
this.MyPropertyBackingStore = value ;
}
}
}
Or, since it's a property so it's trivial to control how/what values get set: simply tweak the property value in the settor.
public class Widget
{
private int MyPropertyBackingStore ;
public int MyProperty
{
get
{
return this.MyPropertyBackingStore ;
}
set
{
if ( this.MyPropertyBackingStore.HasValue && this.MyPropertyBackingStore > 0 )
{
this.MyPropertyBackingStore = value ;
}
else
{
this.MyPropertyBackingStore = -1 ;
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Get innerHTML without using innerHTML I know innerHTML is supposed to be icky (and let's not start a debate. We're trying to phase it out at my work), but I need to be able to get the plaintext version of some HTML. Right now I have the lines...
bodycontents = document.getElementById("renderzone").innerHTML;
But I am wondering exactly how I would, say, get the same result WITHOUT innerHTML. I am not afraid of DOM manipulation (I've done a ton of it), so please feel free to be as technical in your answer as you need to be.
A: Retrieving an elements inner HTML content without using the element.innerHTML attribute sounds like an academic pursuit that isn't likely to have a simple solution.
A DOM based approach would require something like recursively walking to retrieve all child nodes and append their text content and serialize the element name and attributes. For example (in JavaScript/DOM pseudo-code):
var getHtmlContent(el, str) {
str += '<' + el.nodeName;
foreach (attr in el.attribute) {
str += attr.name + '="' + escapeAttrVal(attr.value) + '"';
}
str += '>';
foreach (node in el.childNodes) {
if (node.isTextNode()) {
str += node.textContent;
} else {
str += getHtmlContent(node, str);
}
}
str += '</' + el.nodeName + '>';
return str;
}
getHtmlContent(myElement, ''); // '<div id="myElement" class="foo">Text<div...'
A: I think you want this:
someElement.textContent
A: On modern browser the XMLSerializer may help you:
var el = document.getElementById('my-id');
var html_string = new XMLSerializer().serializeToString(el);
console.log(html_string);
<p id="my-id">Greetings Friends</p>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does whitespace in my F# code cause errors? I've been tinkering with the F# Interactive.
I keep getting weird results, but here's one I can't explain:
The following code returns 66, which is the value I expect.
> let f x = 2*x*x-5*x+3;;
> f 7;;
The following code throws a syntax error:
> let f x = 2*x*x - 5*x +3;;
stdin(33,21): error FS0003: This value is not a function and cannot be applied
As you can see, the only difference is that there are some spaces between the symbols in the second example.
Why does the first code example work while the second one results in a syntax error?
A: The error message says that you are trying to call a function x with the argument +3 ( unary + on 3) and since x is not a function, hence the This value is not a function and cannot be applied
A: The problem here is the use of +3. When dealing with a +/- prefix on a number expression white space is significant
*
*x+3: x plus 3
*x +3: syntax error: x followed by the positive value 3
I've run into this several times myself (most often with -). It's a bit frustrating at first but eventually you learn to spot it.
It's not a feature without meaning though. It's necessary to allow application of negative values to functions
*
*myFunc x -3: call function myFunc with parameters x and -3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Android independent services how to? I was wondering if there is a way to create a service that will run as it's own process independent of an activity. I would want to service to run in the foreground so it would not be killed and also accessible to other .apk that wish to use it. How can I do this? I've read so much that its made me a little more confused then I initially was. Any help would be much appreciated.
To clarify. I would like to run a service that can communicate with many .apk's. It is an in-house application with no market value. What I am trying to do is make service that .apk can register there content providers with so all .apk's using this service have a list of all other .apk's content providers to use as pleased.
A: Services are by their nature independent of Activities. You don't need one to run the other. Services always run in the background and usually don't get killed unless they take too many resources.
Depending on the type of interaction you want between the Service and Activities you'll need to define the appropriate intents or maybe use a ContentProvider.
UPDATE:
In the case you described above, simply have each content provider register with service using an intent that specifies the URI needed to access that content provider. The service would then keep a list of all registered content providers and their URI's.
When a new activity wants to get a list of all available ContentProviders it can query the service with an intent asking for a list of providers. The service would then respond with an intent that would contain the list of providers and URIs.
Using this information the individual activities could then decide which content providers they want to interact with.
A:
How can I do this?
You don't, insofar as you do not need it to be "as it's own process". Just start up the service via startService() and have the service call startForeground(). It can be part of the same process as the activity, and the user will be able to navigate away from that activity if desired and the service will remain running.
I would want to service to run in the foreground so it would not be killed
Note that users are still welcome to get rid of your service. startForeground() will reduce the odds of Android getting rid of the service on its own.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Get Devise's model name I have:
devise_for :users
devise_for :admins
Then, on Sign In page, i want to show 'Admin Sign In' title when someone tries to access /admins/sign_in
How it could be done?
A: Use scoped views, they're described in the devise documentation, in the "Configuring views section".
Run:
rails generate devise:views admins
and set the following in config/initializers/devise.rb:
config.scoped_views = true
You can then modify app/views/admins/sessions/new.html.erb, which will only get used when logging in as an admin.
If the view does not exist, it will fall back on app/views/devise/sessions/new.html.erb.
A: If you're just looking to change the title of the page in the admin sign in view you could change the title in your routes file as follows:
devise_for :admins, :path_names => { :sign_in => "Admin Sign In" }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Blocking app from running on iOS 3.2 without blocking it on 3.1 I'd like to release an app that runs on old iPhones - that is, that runs on 3.1 - but blocking it from running on iPad's iOS 3.2.
Game runs perfectly on iPhones with iOS 3.1.3 and newer, and on iPads with iOS 4 and newer. However, some scaling issues occur on iPads with iOS 3.2.
Is it possible to block the app from appearing as compatible with iOS 3.2 on iTunes Store and to block if from installation on iOS 3.2, but still make it run on iOS 3.1.3?
Some clarifications:
*
*We definitely don't want to block iPad users.
*Game fully works on iPhones and iPod Touches with iOS 3.1.3.
*Game fully works on iPads with iOS 4.
*The only combo with issues is iPad with iOS 3.2.
*Runtime solutions are not what we're looking for.
I suspect this is due to Apple's scaling code intended for retina displays accidentally making it into iOS 3.2. While I could certainly spend loads of time pinning down the issues, I don't feel like it. iOS 3.2 has a small user base, and iPad users have no reason to avoid upgrading. At the same time, we're trying not to cut off iPhone 2G, iPhone 3G, iPod Touch 1G and iPod Touch 2G users who cannot upgrade or don't want to upgrade due to slowdowns.
Also, telling users that they just bought an app that won't work on their device would result in bad user experience. Blocking off a specific version of OS from installation via the App Store would be ideal, without blocking all lesser versions, too.
A: Technically you can do that. It's not recommendation to do such!
E.g. in applicationDidFinishLaunching you could do:
if ( [[[UIDevice currentDevice] model] rangeOfString:@"iPad"] != NSNotFound && [[[UIDevice currentDevice] systemVersion] floatValue]==3.2)
exit(0);
There high enough chances Apple will approve that app. Not because they will be happy with your solution but because they will not test your app on iPad with iOS 3.2.
You have no way to allow running app on 3.1 and higher except iPad 3.2. The only legal way I see to prevent your app from being installed on 3.2 - set 3.2.1 as deployment target of your app. If you cannot guarantee your app will work on all devices, move deployment target higher.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Robohelp 8 Changing CHM Title Doesn't Work? I'm generating a Windows .chm file using Robohelp 8. The title bar of the generated .chm file is incorrect and needs to be changed. I've set the project title using File->Project settings, and regenerated the .chm file, but its title bar still has the old text. Is there some other setting I need to make or file I need to rename or delete to get this to work? I'd really like to have the help file reflect the current product name, rather than the old brand...
A: Never mind; found it under Project Setup->Windows->HtmlHelp.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Problem in for-loop for add new input with a number increasing According to the example, i want in each times adding new input with putting number in fields(1, 2, 3), number increasing in each one from new input adding to name[+number increasing here+][] in the input.
Example: this example not worked true
I want this:
if put to "field 1" number 2 we get tow new input that name it is
name[0][], name[1][] in "field 2" put number 3 we get
name[2][], name[3][], name[4][] in "field 3" put number 2 we
get name[5][], name[6][] and etc.
Code(how is, fixed val coming through as a string not an int!?):
var counter = 0;
$('input').live("keyup", function () {
var id = '#'+$(this).closest('b').attr('id');
$(id+' .lee').empty();
var val = int($(this).val());
for (var i = counter; i < val + counter; i++) {
$(id+' .lee').append('<input type="text" name="hi['+i+'][]">');
}
counter = val + counter;
});
A: Edit: I re-read your question and believe I have a solution that has your desired behavior:
The JavaScript:
var counter = 0;
$('input').live('keyup', function(e) {
// bail out if the keypress wasn't a number
if (e.which < 48 || e.which > 57) { return; }
// get the current value of the input
var val = +$(this).val();
// don't do anything if we don't have a valid number
if (isNaN(val)) { return; }
// find and empty .lee
var $lee = $(this).closest('b').find('.lee').empty();
// create inputs
for (var i = 0; i < val; i++) {
$('<input type="text"/>').attr('name', 'hi[' + (counter + i) + '][]')
.appendTo($lee);
}
// update our counter
counter = val + counter;
});
Here's the updated jsFiddle: http://jsfiddle.net/wAwyR/14/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Take disks online/offline I have a program that is doing raw IO to disks within Windows.
All works fine if the target disk is online. However, the default behavior in some Windows OSes is to have new disks initially offline.
I am having a hard time finding the correct API to do this on Windows. The command line equivalent would be something like:
"select disk 2", "online disk" | diskpart
However I need to be able to do this in code. I looked through the DeviceIoControl Win32 API (which I think is right) but cannot determine which control code to use. The fact that I can't find it makes me think I might be missing a better API to use.
A: For future generations, the answer (on Win 2k3/Vista and later) is the Virtual Disk Service (VDS). There's some work getting it all together, especially if you don't use COM objects within .NET that much.
Disk online/offline is done with IVdsDrive::SetStatus. At least it should; I found that I could solve my problem with simply disabling read-only status on my disk. I was able to do this with IVdsDisk::SetFlags with the appropriate flag value.
A: This question has a couple useful links to the Windows API, including the DeviceIOControl method.
After looking through all of the enumerations, I could not find anything related to bringing a disk online, or make any interesting change to the disk beyond formatting/partitions. This is likely because only hot-swappable hard drives are supported by this functionality. The market for hot-swappable hard drives is very small, and the vast majority of those situations there are drivers to support any needed operations. Finally the remainder should be able to use the diskpart tool for whatever is necessary.
You need to look again at your requirements I think. You are running a process that has the rights necessary to online a hard disk, but cannot access a command line program? Here are some suggestions for common reasons to not use a command line program:
*
*Can't have a black screen pop up - tons of solutions to this problem available online
*Security team won't allow it - you are already running the process as an administrator so you trust it, why wouldn't you trust the built in Windows function
*Technical problems preclude calling other processes - I would be interested in how this was managed given the process is running as an administrator
*Coding guidelines such as "Always use the API" - there isn't one due to lack of need
A: Not sure about C#, but I'm using this in C++:
Try calling DeviceIoControl() with IOCTL_DISK_SET_DISK_ATTRIBUTES. The file handle must have read and write access. I think it requires at least Windows 7. It doesn't work on Windows 2003 x64. Windows 8 successfully takes the disk offline and then you can rewrite it from a backup.
BOOL disk_offline(HANDLE h_file, bool enable){
DWORD bytes_returned = 0;
BOOL b_offline = 0;
if(get_size_volume_disk(h_file)){
SET_DISK_ATTRIBUTES disk_attr;
ZeroMemory(&disk_attr, sizeof(disk_attr));
disk_attr.Version = sizeof(SET_DISK_ATTRIBUTES);
disk_attr.Attributes = enable? DISK_ATTRIBUTE_OFFLINE: 0;
disk_attr.AttributesMask = DISK_ATTRIBUTE_OFFLINE;
b_offline = DeviceIoControl(h_file, IOCTL_DISK_SET_DISK_ATTRIBUTES, &disk_attr, disk_attr.Version, NULL, 0, &bytes_returned, NULL);
// Invalidates the cached partition table and re-enumerates the device.
if(!enable) BOOL b_update = DeviceIoControl(h_file, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0, &bytes_returned, NULL);
}
return b_offline;
}
A: Using DeviceIoControl and IOCTL_DISK_IS_WRITABLE control code, it is possible to check if disk is writable. If the disk is offline it returns false. This means that it is possible to determine if disk is offline and it works fine with Windows 2003 and after. However, I could not find any useful IOCTL to bring the disk online on Windows 2003. IOCTL_DISK_SET_DISK_ATTRIBUTES only works with Windows 2008 and after.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Converting from Java String to Windows-1252 Format I want to send a URL request, but the parameter values in the URL can have french characters (eg. è). How do I convert from a Java String to Windows-1252 format (which supports the French characters)?
I am currently doing this:
String encodedURL = new String (unencodedUrl.getBytes("UTF-8"), "Windows-1252");
However, it makes:
param=Stationnement extèrieur into param=Stationnement extérieur .
How do I fix this? Any suggestions?
Edit for further clarification:
The user chooses values from a drop down. When the language is French, the values from the drop down sometimes include French characters, like 'è'. When I send this request to the server, it fails, saying it is unable to decipher the request. I have to figure out how to send the 'è' as a different format (preferably Windows-1252) that supports French characters. I have chosen to send as Windows-1252. The server will accept this format. I don't want to replace each character, because I could miss a special character, and then the server will throw an exception.
A: Use URLEncoder to encode parameter values as application/x-www-form-urlencoded data:
String param = "param="
+ URLEncoder.encode("Stationnement extr\u00e8ieur", "cp1252");
See here for an expanded explanation.
A: Try using
String encodedURL = new String (unencodedUrl.getBytes("UTF-8"), Charset.forName("Windows-1252"));
A: As per McDowell's suggestion, I tried encoding doing:
URLEncoder.encode("stringValueWithFrechCharacters", "cp1252") but it didn't work perfectly. I replayced "cp1252" with HTTP.ISO_8859_1 because I believe Android does not have the support for Windows-1252 yet. It does allow for ISO_8859_1, and after reading here, this supports MOST of the French characters, with the exception of 'Œ', 'œ', and 'Ÿ'.
So doing this made it work:
URLEncoder.encode(frenchString, HTTP.ISO_8859_1);
Works perfectly!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: RValue references, pointers, and copy constructors Consider the following piece of code:
int three() {
return 3;
}
template <typename T>
class Foo {
private:
T* ptr;
public:
void bar(T& t) { ptr = new T(t); }
void bar(const T& t) { ptr = new T(t); }
void bar(T&& t) { (*ptr) = t; } // <--- Unsafe!
};
int main() {
Foo<int> foo;
int a = 3;
const int b = 3;
foo.bar(a); // <--- Calls Foo::bar(T& t)
foo.bar(b); // <--- Calls Foo::bar(const T& t)
foo.bar(three()); // <--- Calls Foo::bar(T&& t); Runs fine, but only if either of the other two are called first!
return 0;
}
My question is, why does the third overload Foo::bar(T&& t) crash the program? What exactly is happening here? Does the parameter t get destroyed after the function returns?
Furthermore, let's assume that the template parameter T was a very large object with a very costly copy constructor. Is there any way to use RValue References to assign it to Foo::ptr without directly accessing this pointer and making a copy?
A: In this line
void bar(T&& t) { (*ptr) = t; } // <--- Unsafe!
you can dereference an uninitialized pointer. This is undefined behavior.
You must call one of the two other version of bar first because you need to create the memory for your object.
So I would do ptr = new T(std::move(t));.
If your type T supports moving the move constructor will get called.
Update
I would suggest something like that. Not sure if you need the pointer type within foo:
template <typename T>
class Foo {
private:
T obj;
public:
void bar(T& t) { obj = t; } // assignment
void bar(const T& t) { obj = t; } // assignment
void bar(T&& t) { obj = std::move(t); } // move assign
};
This would avoid memory leaks which are also quite easy with your approach.
If you really need the pointer in your class foo how about that:
template <typename T>
class Foo {
private:
T* ptr;
public:
Foo():ptr(nullptr){}
~Foo(){delete ptr;}
void bar(T& t) {
if(ptr)
(*ptr) = t;
else
ptr = new T(t);
}
void bar(const T& t) {
if(ptr)
(*ptr) = t;
else
ptr = new T(t);
}
void bar(T&& t) {
if(ptr)
(*ptr) = std::move(t);
else
ptr = new T(std::move(t));
}
};
A: Assuming that you only called foo.bar(three()); without the other two calls:
Why did you think that'd work? Your code is essentially equivalent to this:
int * p;
*p = 3;
That's undefined behaviour, because p isn't pointing to a valid variable of type int.
A: There's no reason for that to fail in that code. ptr will point to an existing int object created by the previous calls to bar and the third overload will just assign the new value to that object.
However, if you did this instead:
int main() {
Foo<int> foo;
int a = 3;
const int b = 3;
foo.bar(three()); // <--- UB
return 0;
}
That foo.bar(three()); line would have undefined behaviour (which does not imply any exception), because ptr would not be a valid pointer to an int object.
A: The "unsafe"thing, here is that, before assigning to ptr a new object, you should worry about the destiny of what ptr actually points to.
foo.bar(three());
is unsafe in the sense that you have to grant -before calling it- that ptr actually point to something. In your case it points to what was created by foo.bar(b);
But foobar(b) makes ptr to point to a new object forgetting the one created by foobar(a)
A more proper code can be
template<class T>
class Foo
{
T* p;
public:
Foo() :p() {}
~Foo() { delete p; }
void bar(T& t) { delete p; ptr = new T(t); }
void bar(const T& t) { delete p; ptr = new T(t); }
void bar(T&& t)
{
if(!ptr) ptr = new T(std::move(t));
else (*ptr) = std::move(t);
}
}
;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to set the default value to the list box using jquery I need to set the this as a default value for my list box can any body help me out.
thanks
$(document).ready(function () {
var targetid = '<%:ViewData["target"] %>';
if (targetid != null) {
$("#lstCodelist").val(targetid); //// I need to set this targetid as default selected value for lstCodelist
}
A: Set n to the index of the item you wish to set as selected.
$("#lstCodelist option").eq(n).attr('selected','selected')
A: This should do it:
$('#foo').val(2)
http://jsfiddle.net/yRXEc/
A: $("#ListBox")[0].selectedIndex = 0
A: It is worked for me. You can try it
$("#foo").val("")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: translating matlab script to R I've just been working though converting some MATLAB scripts to work in R, however having never used MATLAB in my life, and not exactly being an expert on R I'm having some trouble.
Edit: It's a script I was given designed to correct temperature measurements for lag generated by insulation mass effects. My understanding is that It looks at the rate of change of the temperature and attempts to adjust for errors generated by the response time of the sensor. Unfortunately there is no literature available to me to give me an indication of the numbers i am expecting from the function, and the only way to find out will be to experimentally test it at a later date.
the original script:
function [Tc, dT] = CTD_TempTimelagCorrection(T0,Tau,t)
N1 = Tau/t;
Tc = T0;
N = 3;
for j=ceil(N/2):numel(T0)-ceil(N/2)
A = nan(N,1);
# Compute weights
for k=1:N
A(k) = (1/N) + N1 * ((12*k - (6*(N+1))) / (N*(N^2 - 1)));
end
A = A./sum(A);
# Verify unity
if sum(A) ~= 1
disp('Error: Sum of weights is not unity');
end
Comp = nan(N,1);
# Compute components
for k=1:N
Comp(k) = A(k)*T0(j - (ceil(N/2)) + k);
end
Tc(j) = sum(Comp);
dT = Tc - T0;
end
where I've managed to get to:
CTD_TempTimelagCorrection <- function(temp,Tau,t){
## Define which equation to use based on duration of lag and frequency
## With ESM2 profiler sampling @ 2hz: N1>tau/t = TRUE
N1 = Tau/t
Tc = temp
N = 3
for(i in ceiling(N/2):length(temp)-ceiling(N/2)){
A = matrix(nrow=N,ncol=1)
# Compute weights
for(k in 1:N){
A[k] = (1/N) + N1 * ((12*k - (6*(N+1))) / (N*(N^2 - 1)))
}
A = A/sum(A)
# Verify unity
if(sum(A) != 1){
print("Error: Sum of weights is not unity")
}
Comp = matrix(nrow=N,ncol=1)
# Compute components
for(k in 1:N){
Comp[k] = A[k]*temp[i - (ceiling(N/2)) + k]
}
Tc[i] = sum(Comp)
dT = Tc - temp
}
return(dT)
}
I think the problem is the Comp[k] line, could someone point out what I've done wrong? I'm not sure I can select the elements of the array in such a way.
by the way, Tau = 1, t = 0.5 and temp (or T0) will be a vector.
Thanks
edit: apparently my description is too brief in explaining my code samples, not really sure what more I could write that would be relevant and not just wasting peoples time. Is this enough Mr Filter?
A: The error is as follows:
Error in Comp[k] = A[k] * temp[i - (ceiling(N/2)) + k] :
replacement has length zero
In addition: Warning message:
In Comp[k] = A[k] * temp[i - (ceiling(N/2)) + k] :
number of items to replace is not a multiple of replacement length
If you write print(i - (ceiling(N/2)) + k) before that line, you will see that you are using incorrect indices for temp[i - (ceiling(N/2)) + k], which means that nothing is returned to be inserted into Comp[k]. I assume this problem is due to Matlab allowing the use of 0 as an index and not R, and the way negative indices are handled (they don't work the same in both languages). You need to implement a fix to return the correct indices.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: living bytes increase without leak I'm making iPhone development and having (like lot of peoples) problems with memory management.
I'm often using "Instruments" in order to fix memory I have forgot to dealloc.
So I don't have memory leak anymore !
BUT... When I'm using the app the "Live Bytes" in Instruments is always increasing.
At the launch my App is using 4MB and going back and forward few times in my UINavigationView 10MB (still "without" memory leak).
Martin Magakian
A: That would be bloat, not a true leak.
What you want to do is use that Mark Heap button a time or two, then look at the heap shots.
http://www.friday.com/bbum/2010/10/17/when-is-a-leak-not-a-leak-using-heapshot-analysis-to-find-undesirable-memory-growth/ has lots more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Proper syntax for container.dataitem binding to A Href tag I have a Datagrid with an ItemTemplate in it to convert a dataitem to a link. However, when I run the app it errors out with:
FolderID is neither a DataColumn nor a DataRelation for table Table.
Here is the line of code in question:
<b><a href="PerformanceEvaluationSubcontractorRating.aspx?ProjectID='<%#Container.DataItem("ProjectID")%>'&FolderID='<%#Container.DataItem("FolderID")%>'&SubcontractorID='<%#Container.DataItem("OrganizationID")%>'>
<%#Container.DataItem("OrganizationName")%>
</a></b>
What is wrong with the A Href tag?
A: The FolderID column is not present at the datasource. This error has nothing to do with the A Href tag, it is a databinding error. check the schema to retrieve the right column name.
A: Ensure your field is part of your table (ie part of your query to populate the table)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: javascript singleton scope problems with "this" Hi i am beginning using the singleton javascript design pattern, but i have some scope problems. Here i am just experimenting with a small ajax, retrieve and store singleton.
From within a function in the singleton i call another function (this.ready, called when the ajax has retrieved and stored the data) but it seems "this" doesn't refer to the singleton, rather it refers to "Object #XMLHttpRequest" according to chrome debugger, firefox just says it's undefined.
var mag = {
magObj: [], // object to store the retrieved json data
getData: function(){
request = getHTTPObject(), // defined externally
request.onreadystatechange = this.setData;
request.open("POST", "be.php", true);
request.send(null);
},
setData: function(){
if (request.readyState == 4)
{
this.magObj = JSON.parse(request.responseText);
this.ready(); // this line yields the error, seems "this" does not refer to the singleton
}
else if (request.readyState == 1)
{
}
},
ready: function() {
console.log('ready');
},
construct: function(){
this.getData();
},
}
Also if i try to declare the getHTTPObject() as a singleton variable in the top, instead of using global variable i get the error Cannot read property 'readyState' of undefined. Again it's "this" getHTTPObject that seems to be undefined even though i set it at the top:
var mag = {
magObj: [],
request: getHTTPObject(),
getData: function(){
this.request.onreadystatechange = this.setData;
this.request.open("POST", "be.php", true);
this.request.send(null);
},
setData: function(){
if (this.request.readyState == 4) // debugger says this.request is undefined
{
this.magObj = JSON.parse(this.request.responseText);
}
else if (this.request.readyState == 1)
{
}
},
construct: function(){
this.getData();
},
}
A: #1
setData is a callback function for the XMLHttpRequest object. It's therefore run in the scope of the XMLHttpRequest object. Use mag instead of this.
#2
Same as #1: this refers to the XMLHttpRequest, rather than you mag variable.
A: If it is a singleton you could try
var mag = {
magObj: [], // object to store the retrieved json data
getData: function(){
request = getHTTPObject(), // defined externally
request.onreadystatechange = this.setData;
request.open("POST", "be.php", true);
request.send(null);
},
setData: function(){
if (request.readyState == 4)
{
this.magObj = JSON.parse(request.responseText);
mag.ready(); // this line yields the error, seems "this" does not refer to the singleton
}
else if (request.readyState == 1)
{
}
},
ready: function() {
console.log('ready');
},
construct: function(){
this.getData();
},
}
A: To solve the scope problem, you need to use the concepts of closures in javascript. basically a scope where functions have access to properties and methods in the context that created that function.. ok for a more clear explanation.. try initializing your mag object as a function..
var mag = function(){
var magObj = [];
var getData = function(){
//here you'll have access to the magObj collection
};
}
The previous is a classic example of a javascript closure..
Of course you instantiate the mag object simply as a function invocation mag();
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is NSLog causing EXC_BAD_ACCESS? I have a tablecell with a button and I want to hook this in to a method call in my main class.
I have it working, but I need to identify the button pressed. SO I have done the following:
in cellForRowAtIndexPath I do the following:
cell.myBtn.tag = indexPath.row;
[cell.myBtn addTarget:self
action:@selector(viewClick:)
forControlEvents:UIControlEventTouchUpInside];
And I created the selector method like so:
- (void)viewClick:(id)sender
{
UIButton *pressedButton = (UIButton *)sender;
// EXC_BAD_ACCESS when running NSLog
NSLog(@"button row %@",pressedButton.tag);
if(pressedButton.tag == 1)
{
// NSString filename = @"VTS_02_1";
}
}
The problem is I get EXC_BAD_ACCESS when it hits this line: NSLog(@"button row %@",pressedButton.tag);
A: specify %i for int value
you have to use %@ for only object, but int is not object,NSNumber is an object for that you can use %@.
NSLog(@"button row %i",pressedButton.tag);
A: try NSLog(@"button row %d", pressedButton.tag);
tag property is an int not an object.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Remap "te" to "tabedit" in vim I've started using Vim recently, and so far my main issue is with the buffer. I miss my Mac OS-style drawer with all open docs. I recently learned about tabs, and I think that's somewhat of a good solution, at least for when I have only a few files open. Opening a new tab is :tabe <filename>. Is there a way to remap that to :te <filename>?
A: The first thing that came to my mind was a custom command.
command! -complete=file -nargs=1 Te tabedit <args>
Use the command: :Te <filename>
Please see the comments by Peter Rincker in this post.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JasperReports 4.1 + Hibernate 3.6 java.lang.NoSuchFieldError: BOOLEAN Iam getting an error when iam trying to call a report made in iReport 4.1.1.
Session sax = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = sax.beginTransaction();
Map<String, Object> map = new HashMap<String, Object>();
map.put(JRHibernateQueryExecuterFactory.PARAMETER_HIBERNATE_SESSION, sax);
//map.put(, session);
String relativeWebPath = "/reports/factura_template1.jasper";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
JasperPrint print = JasperFillManager.fillReport(new FileInputStream(new File(absoluteDiskPath)),map);
byte[] report = JasperExportManager.exportReportToPdf(print);
We are using Hibernate 3.6 (JPA Annotations) and Jasperreports 4.1.1 as report engine, when i try to call the report i get this exception:
java.lang.NoSuchFieldError: BOOLEAN
at net.sf.jasperreports.engine.query.JRHibernateQueryExecuter.<clinit>(JRHibernateQueryExecuter.java:70)
at net.sf.jasperreports.engine.query.JRHibernateQueryExecuterFactory.createQueryExecuter(JRHibernateQueryExecuterFactory.java:136)
at net.sf.jasperreports.engine.fill.JRFillDataset.createQueryDatasource(JRFillDataset.java:724)
at net.sf.jasperreports.engine.fill.JRFillDataset.initDatasource(JRFillDataset.java:625)
at net.sf.jasperreports.engine.fill.JRBaseFiller.setParameters(JRBaseFiller.java:1238)
at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:869)
at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:118)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:435)
at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:398)
at mx.com.facture.FactureApp.server.ReportExporter.ServletExporter.doGet(ServletExporter.java:198)
Any one else has been in this problem?, how did you solve?
Thank you.
A: Even I was getting the same error...
This is because Hibernate 3.6 has deprecated "org.hibernate.Hibernate.BOOLEAN" (and other similar types).
They have consolidated all the types into "org.hibernate.type.StandardBasicTypes" class.
Solution
Solution is very simple.
1) Download the whole (with source) jasper tar.gz file from JasperReports home site
2) Untar the file (let the location be called $JASPER_SOURCE)
3) vim $JASPER_SOURCE/src/net/sf/jasperreports/engine/query/JRHibernateQueryExecuter.java
4) Add the following line in the top import statements
import org.hibernate.type.StandardBasicTypes;
5) Now from line 71 onwards change all "Hibernate" to "StandardBasicTypes" (till the end of the static block, that is till 84th line)
6) Save and exit the editor
7) Copy the latest hibernate3.jar (3.6.x version) into "$JASPER_SOURCE/lib" location
8) Now do the following ant command from $JASPER_SOURCE location
ant jar
You will get the modified jar in lib/jasperreports-4.x.x.jar location. Use that jar for your project
--------------- OR -------------------
Another solution is to use old hibernate3.jar file (version 3.0.x) with your project
A: Replace your existing hibernate3.jar with that one that exists at JasperReports package.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Dreamweaver/MyBB/MySQl Database? I have MyBB installed on my server and apparently the template sets are stored via MySQL database instead of downloaded to the remote server. I would like to set up a path in Dreamweaver so I can directly edit template sets without having to go into the acp in MyBB. Otherwise, there's really no way to test locally unless I set up a database on my machine and it wouldn't make sense having two databases with the same entries. Has anyone managed to set up an ftp path through Dreamweaver that will link to a MySQL database, or is this not possible? Thanks in advance.
A:
Has anyone managed to set up an ftp path through Dreamweaver that will
link to a MySQL database, or is this not possible?
Not possible. Dreamweaver will let you create a connection to a MySQL database to query it but you cannot affect the database structure from within Dreamweaver's interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is NLTK's naive Bayes Classifier suitable for commercial applications? I need to train a naive Bayes classifier on two corpuses consisting of approx. 15,000 tokens each. I'm using a basic bag of words feature extractor with binary labeling and I'm wondering if NLTK is powerful enough to handle all this data without significantly slowing down run time if such an application were to gain many users. The program would basically be classifying a regular stream of text messages from potentially thousands of users. Are there other machine learning packages you'd recommend integrating with NLTK if it isn't suitable?
A: Your corpora are not very big, so NLTK should do the job. However,I wouldn't recommend it in general, it is quite slow and buggy in places. Weka is a more powerful tool, but the fact that it can do so much more makes it harder to understand. If Naive Bayes is all you plan to use, it would probably be fastest to code it yourself.
EDIT (much later):
Try scikit-learn, it is very easy to use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JavaScript Processing In Selenium And HtmlUnit I'm planning to use HtmlUnit in my Java application to test drive some website but I heard it may not be able to handle complex JavaScript, what is your experience with the level of complex JavaScript that both HtmlUnit and Selenium can handle?
Thank you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Http Post with Blackberry 6.0 issue I am trying to post some data to our webservice(written in c#) and get the response. The response is in JSON format.
I am using the Blackberry Code Sample which is BlockingSenderDestination Sample. When I request a page it returns with no problem. But when I send my data to our webservice it does not return anything.
The code part that I added is :
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
What am i doing wrong? And what is the alternatives or more efficients way to do Post with Blackberry.
Regards.
Here is my whole code:
class BlockingSenderSample extends MainScreen implements FieldChangeListener {
ButtonField _btnBlock = new ButtonField(Field.FIELD_HCENTER);
private static UiApplication _app = UiApplication.getUiApplication();
private String _result;
public BlockingSenderSample()
{
_btnBlock.setChangeListener(this);
_btnBlock.setLabel("Fetch page");
add(_btnBlock);
}
public void fieldChanged(Field button, int unused)
{
if(button == _btnBlock)
{
Thread t = new Thread(new Runnable()
{
public void run()
{
Message response = null;
String uriStr = "http://192.168.1.250/mobileServiceOrjinal.aspx"; //our webservice address
//String uriStr = "http://www.blackberry.com";
BlockingSenderDestination bsd = null;
try
{
bsd = (BlockingSenderDestination)
DestinationFactory.getSenderDestination
("name", URI.create(uriStr));//name for context is name. is it true?
if(bsd == null)
{
bsd =
DestinationFactory.createBlockingSenderDestination
(new Context("ender"),
URI.create(uriStr)
);
}
//Dialog.inform( "1" );
ByteMessage myMsg = bsd.createByteMessage();
//myMsg.setStringPayload("I love my BlackBerry device!");
myMsg.setMessageProperty("querytpe","myspecialkey");//here is my post data
myMsg.setMessageProperty("uname","myusername");
myMsg.setMessageProperty("pass","password");
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
// Send message and wait for response myMsg
response = bsd.sendReceive(myMsg);
if(response != null)
{
BSDResponse(response);
}
}
catch(Exception e)
{
//Dialog.inform( "ex" );
// process the error
}
finally
{
if(bsd != null)
{
bsd.release();
}
}
}
});
t.start();
}
}
private void BSDResponse(Message msg)
{
if (msg instanceof ByteMessage)
{
ByteMessage reply = (ByteMessage) msg;
_result = (String) reply.getStringPayload();
} else if(msg instanceof StreamMessage)
{
StreamMessage reply = (StreamMessage) msg;
InputStream is = reply.getStreamPayload();
byte[] data = null;
try {
data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
} catch (IOException e) {
// process the error
}
if(data != null)
{
_result = new String(data);
}
}
_app.invokeLater(new Runnable() {
public void run() {
_app.pushScreen(new HTTPOutputScreen(_result));
}
});
}
}
..
class HTTPOutputScreen extends MainScreen
{
RichTextField _rtfOutput = new RichTextField();
public HTTPOutputScreen(String message)
{
_rtfOutput.setText("Retrieving data. Please wait...");
add(_rtfOutput);
showContents(message);
}
// After the data has been retrieved, display it
public void showContents(final String result)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
_rtfOutput.setText(result);
}
});
}
}
A: HttpMessage does not extend ByteMessage so when you do:
((HttpMessage) myMsg).setMethod(HttpMessage.POST);
it throws a ClassCastException. Here's a rough outline of what I would do instead. Note that this is just example code, I'm ignoring exceptions and such.
//Note: the URL will need to be appended with appropriate connection settings
HttpConnection httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
OutputStream out = httpConn.openOutputStream();
out.write(<YOUR DATA HERE>);
out.flush();
out.close();
InputStream in = httpConn.openInputStream();
//Read in the input stream if you want to get the response from the server
if(httpConn.getResponseCode() != HttpConnection.OK)
{
//Do error handling here.
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Use JSONP to load an html page I'm trying to load an external page using JSONP, but the page is an HTML page, I just want to grab the contents of it using ajax.
EDIT: The reason why I'm doing this is because I want to pass all the user information ex: headers, ip, agent, when loading the page rather than my servers.
Is this doable? Right now, I can get the page, but jsonp attempts to parse the json, returning an error: Uncaught SyntaxError: Unexpected token <
Sample code:
$.post('http://example.com',function(data){
$('.results').html(data);
},'jsonp');
I've set up a jsfiddle for people to test with:
http://jsfiddle.net/8A63A/1/
A: I've got three words for you: Same Origin Policy
Unless the remote URL actually supports proper JSONP requests, you won't be able to do what you're trying to. And that's a good thing.
Edit: You could of course try to proxy the request through your server …
A: If you really just want to employ the client to snag an HTML file, I suggest using flyJSONP - which uses YQL.. or use jankyPOST which uses some sweet techniques:
jankyPOST creates a hidden iframe and stuffs it with a form (iframe[0].contentWindow.document.body.form.name).
Then it uses HTML5 (watch legacy browsers!) webMessaging API to post to the other iframe and sets iframe's form elements' vals to what u specified.
Submits form to remote server...done.
Or you could just use PHP curl, parse it, echo it, so on.
IDK if what exactly ur using it for but I hope this helps.
ALSO...
I'm pretty sure you can JSONP anything that is an output from server code. I did this with ClientLogin by just JSONPing their keyGen page and successfully consoleLogged the text even though it was b/w tags. I had some other errors on that but point is that I scraped that output.
Currently, I'm trying to do what you are so I'll post back if successful.
A: http://en.wikipedia.org/wiki/JSONP#Script_element_injection
Making a JSONP call (in other words, to employ this usage pattern),
requires a script element. Therefore, for each new JSONP request, the
browser must add (or reuse) a new element—in other words,
inject the element—into the HTML DOM, with the desired value for the
"src" attribute. This element is then evaluated, the src URL is
retrieved, and the response JSON is evaluated.
Now look at your error:
Uncaught SyntaxError: Unexpected token <
< is the first character of any html tag, probably this is the start of <DOCTYPE, in this case, which is, of course, invalid JavaScript.
And NO, you can't use JSONP for fetching html data.
A: I have done what you want but in my case I have control of the server side code that returns the HTML.
So, what I did was wrapped the HTML code in one of the Json properties of the returned object and used it at client side, something like:
callback({"page": "<html>...</html>"})
The Syntax error you are facing it's because the library you're using expects json but the response is HTML, just that.
A: I don't think this is possible. JSONP requires that the response is rendered properly.
If you want another solution, what about loading the url in an iframe and trying to talk through the iframe. I'm not 100% positive it will work, but it's worth a shot.
A: First, call the AJAX URL manually and see of the resulting HTML makes sense.
Second, you need to close your DIV in your fiddle example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: Can't read achievements for certain users I'm experiencing some inconsistent behaviour when trying to read achievements from my app. I have 3 tests accounts, 2 of which I can read achievements. However the 3rd account always returns an empty array. All 3 accounts have the publish_action permission and I've tried using both the user and app access_token. Here's the query:
https://graph.facebook.com/{uid}/achievements?access_token={app_access_token}
or
https://graph.facebook.com/{uid}/achievements?access_token={user_access_token}
Now I know the 3rd account has achievements as I get an error when I try to give it an achievement it already has and the game ticker correctly shows the achievements it has earned.
A: Make sure the third user has granted "user_activities" extended permissions so that the activities can be read, not just published. You can verify this by calling /me/permissions.
A: Have you checked the facebook layout regarding achievements in your app? since in my FB account I can roll over my own achievements and I get a full list of the achievements configured with each game and in other acocunt that info is not available. The other distinctive feature is I see my thumbnail picture over the main facebook bar (the blue one next to log in)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: textField:shouldChangeCharactersInRange:replacementString: How can I correct this code. I want only numbers and range should be not exceed to 10.
My code is
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 10) ? NO : YES;
static NSCharacterSet *charSet = nil;
if(!charSet) {
charSet = [[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet] retain];
}
NSRange location = [string rangeOfCharacterFromSet:charSet];
return (location.location == NSNotFound);
}
A: The problem here is that anything after the first return is not executed.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 10) ? NO : YES;
// unreachable!
So you are just checking the length but not whether the input is numerical. Change this line:
return (newLength > 10) ? NO : YES;
with this one:
if (newLength > 10) return NO;
and it should work. You can also optionally change this:
[NSCharacterSet characterSetWithCharactersInString:@"0123456789"]
with this:
[NSCharacterSet decimalDigitCharacterSet]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sqlite3 / Webpy: "no such column" with double left join I am trying to do Sqlite3 query via webpy framework.The query works in SQLiteManager. But with web.db i get "sqlite3.OperationalError no such column a.id".
Is this a webpy bug?
import web
db = web.database(dbn='sqlite', db='data/feed.db')
account = 1
query='''
SELECT a.id, a.url, a.title, a.description, a.account_count, b.id subscribed FROM
(SELECT feed.id, feed.url, feed.title, feed.description, count(account_feed.id) account_count
FROM feed
LEFT OUTER JOIN account_feed
ON feed.id=account_feed.feed_id AND feed.actived=1
GROUP BY feed.id, feed.url, feed.title, feed.description
ORDER BY count(account_feed.id) DESC, feed.id DESC)
a LEFT OUTER JOIN account_feed b ON a.id=b.feed_id AND b.account_id=$account'''
return list(self._db.query(query,vars=locals()))
Traceback is here:http://pastebin.com/pUA7zB9H
A: Not sure why you are getting the error "no such column a.id", but
it may help to
*
*use a multiline string (easier to read),
*use a parametrized argument for account (Was $account a Perl-hangover?)
query = '''
SELECT a.id, a.url, a.title, a.description, a.account_count, b.id subscribed
FROM ( {q} ) a
LEFT OUTER JOIN account_feed b
ON a.id=b.feed_id
AND b.account_id = ?'''.format(q=query)
args=[account]
cursor.execute(query,args)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Code equivalent of android:cropToPadding In my android app, I create thumbnails in xml this way:
<ImageView android:id="@+id/my_thumbnail
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@color/white"
android:padding="2dp"
android:scaleType="fitXY"
android:cropToPadding="true" />
This creates a white border around the thumbnail - and looks quite nice.
Now, in another place in the code I need to create the thumbnails in the code, not XML (this is an Adapter class for GridView - to create a grid of thumbnails). I can set all parameters as required, however I cannot find a way to set the cropToPadding in the code. As a result, the thumbnail are drawn over the padding and it looks really ugly.
How do I set this cropToPadding thing in the code?
BTW, the app must work on Android 1.6.
Edit
Following a suggestion from userSeven7s, I add this style to my XML containing other styles:
<style name="GridImage">
<item name="android:background">@color/white</item>
<item name="android:padding">2dp</item>
<item name="android:cropToPadding">true</item>
<item name="android:typeface">monospace</item>
</style>
(Note that the file contains <resources> root element and contains a couple of other <style> elements. Yet all of the other ones are only referenced form layout xml files.)
I then added this code inside my grid view adapter:
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
XmlPullParser parser = mContext.getResources().getXml(R.style.GridImage);
AttributeSet attributes = Xml.asAttributeSet(parser);
imageView = new ImageView(mContext, attributes);
// ... some more initialisation
} else {
imageView = (ImageView) convertView;
}
// ... code to create the bitmap and set it into the ImageView goes here
}
This compiles fine (i.e. R.style.GridImage exists). However when I run this code, the app crashes with Resources.NotFoundException on getXml(R.style.GridImage).
Any suggestions?
A: If you try the solution with AttributeSet and attributes.getAttributeCount() always returns 0, then just about the only solution left is this hack using reflection:
Field field = ImageView.class.getDeclaredField("mCropToPadding");
field.setAccessible(true);
field.set(imageView, true);
Using this you probably can't be sure it will work in other android firmware versions.
Anyway the missing setter is probably just forgotten, so that justifies the hack for me.
A: You can get the thumbnails from the ImageView itself. Call getDrawingCache() on each imageview to get the bitmap used for drawing.
new Update :
Create a xml myimage_attrs.xml in xml folder and add all the imageview attributes you need to it.
<?xml version=”1.0″ encoding=”utf-8″?>
<item name=”android:layout_height”>10dp</item>
<item name=”android:layout_width”>10dp</item>
<item name="android:background">@color/white</item>
<item name="android:padding">2dp</item>
<item name="android:cropToPadding">true</item>
<item name="android:typeface">monospace</item>
....
Then create a AttributeSet out of the xml and pass it to the ImageView constructor.
XmlPullParser parser = resources.getXml(R.xml.myimage_attrs);
AttributeSet attributes = Xml.asAttributeSet(parser);
ImageView imgv = new ImageView(context, attributes);
A: For the benefit of others, here's what finally did work (thanks to userSeven7s for pushing me in the right direction).
I created grid_image.xml file with the following content:
<?xml version="1.0" encoding="utf-8"?>
<style>
<item name="android:layout_height">50dp</item>
<item name="android:layout_width">50dp</item>
<item name="android:background">@color/white</item>
<item name="android:padding">2dp</item>
<item name="android:cropToPadding">true</item>
<item name="android:scaleType">fitXY</item>
</style>
Then in my Adapter for the grid view, I put the following code:
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
XmlPullParser parser = mContext.getResources().getXml(R.xml.grid_image);
AttributeSet attributes = null;
int state = XmlPullParser.END_DOCUMENT;
do {
try {
state = parser.next();
if (state == XmlPullParser.START_TAG) {
if (parser.getName().equals("style")) {
attributes = Xml.asAttributeSet(parser);
break;
}
}
} catch (Exception ignore) {
//ignore it - can't do much anyway
} while(state != XmlPullParser.END_DOCUMENT);
if(attributes == null)
imageView = new ImageView(mContext);
else
imageView = new ImageView(mContext, attributes);
//the rest of initialisation goes here
} else {
imageView = (ImageView) convertView;
}
//set image into the imageview here
return imageView;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Inserting Clobs in Oracle with JDBC is very slow Hi i am trying to insert a clob using the jdbc, through a maven plugin. But it is taking about 10 minutes to insert. This is exceptionally slow, and i was wondering if there was another way to do it. The clob needs to have line breaks. My insert is being called from a sql file and it looks like this:
INSERT INTO SCHEMANAME.ATABLENAME VALUES (1,1,'ASTRING','ANOTHERSTRING','STRING WITH LINEBREAKS
BLAH BLAH
BLAH BLAH
BLAH BLAH
BLAH','FINALSTRING',sysdate);
A: Pull AWR and ADDM reports and see what the insert is waiting on. Take manual snapshots if needed to get several data points to check against.
10 minutes to insert a single row indicates that there is locking/blocking/waiting going on inside your DB.
A: If you are wondering if there was another way to do it, could you try to insert a null value to the CLOB column at first, and do a update with the CLOB column after the first insert?
A: The CLOB is certainly not the problem here. The enormously long time of 10 minutes indicates that some sort of time-out is involved. Two of them come to mind:
*
*The network connection is unreliable and it takes a long time to transmit a few bytes.
*Two database sessions are trying to insert or update the same row in Oracle. If the first one is able to do the insert or update but doesn't commit the connection, the second one will be blocked until the first on commits, rolls back or ends the session.
The second one is more likely.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jquery AJAX XMLHTTPRequest has no useful information in error state I'm running into brick wall after brick wall. I have an application that is making an AJAX call, but seems to never hit the server. Instead, jQuery returns with an error status in the XMLHTTPRequest object. If my XMLHTTPRequest object returned is called xhr, here is the relevant information:
xhr.statusText == "error"
xhr.readyState == 0
xhr.status == 0
xhr.responseText == undefined
This has been working in the past, and this problem seems to have come on with no prompting. Also, I have tried in both IE and Firefox, and Firefox seems to work fine. The problem only exists in IE8, where I am using compatibility mode.
Does anyone have any idea what could be going on here? Any insight would be greatly appreciated. Thanks.
A: Using the GET method for my AJAX call, the problem was that the number of ID's being passed to the controller ran up against IE7's (stupid) limit of 2048 characters. So I changed the method to a POST, and that seems to have resolved the problem.
I should post a new question about what to do when you encounter a situation where you need to use a GET, but need to pass down an indefinite number of ID's to assist you in calculating the value(s) returned.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get Url.Action inside extension method I'm using MVC3 (VB) with the Razor view engine, and I'm using the Chart helper to create a number of charts. I've got this code working:
In the view:
<img src="@Url.Action("Rpt002", "Chart", New With {.type = "AgeGender"})" alt="" />
which triggers this action in the Chart controller:
Function Rpt002(type As String) As ActionResult
Dim chart As New System.Web.Helpers.Chart(300, 300)
'...code to fill the chart...
Return File(chart.GetBytes("png"), "image/png")
End Function
Because I have a number of charts on a number of views, I wanted to put the creation of the img into a helper function. I thought the following would work:
<System.Runtime.CompilerServices.Extension>
Public Function ReportChart(htmlHelper As HtmlHelper, action As String, type As String) As MvcHtmlString
Dim url = htmlHelper.Action(action, "Chart", New With {.type = type})
Return New MvcHtmlString(
<img src=<%= url %> alt=""/>
)
End Function
When I try that though, I get the following error:
OutputStream is not available when a custom TextWriter is used.
I thought calling "htmlHelper.Action" would just generate the URL so I could add it to the img, but it's actually triggering the action. How do I get the equivalent of "Url.Action" from within the extension method?
A: Simply instantiate an UrlHelper and call the Action method on it:
Dim urlHelper as New UrlHelper(htmlHelper.ViewContext.RequestContext);
Dim url = urlHelper.Action(action, "Chart", New With {.type = type})
Also I would recommend you to use a TagBuilder to ensure that the markup that you are generating is valid and that the attributes are properly encoded:
<System.Runtime.CompilerServices.Extension> _
Public Shared Function ReportChart(htmlHelper As HtmlHelper, action As String, type As String) As IHtmlString
Dim urlHelper = New UrlHelper(htmlHelper.ViewContext.RequestContext)
Dim url = urlHelper.Action(action, "Chart", New With { _
Key .type = type _
})
Dim img = New TagBuilder("img")
img.Attributes("src") = url
img.Attributes("alt") = String.Empty
Return New HtmlString(img.ToString())
End Function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Spoon-library acts different on localhost then on webhosting I have a problem regarding the spoon-library (www.spoon-library.com). I have a folder with subfolders, each subfolder is a 'reference' from my dad his company. (although its translated to my native language). Each of the 'reference' subfolder contains images.
I am reading the names of al subfolders and the images that are in that specific folder and save it to an array. With the use of spoon-library i am nesting these in template variable in my tpl files. So basically I print the <h2></h2> with the project's title (the subfolder name), and all his images (so that they can be viewed through lightbox).
On my localhost and my website (provider A) it works, but when i upload it to my dad his hosting (provider B) it doens't work.
ex.
http://davyloose.be/electroloose/projecten.php -> it works.
http://electro-loose.be/projecten.php -> it doens't work.
The code is identical.
Example of the array with the data that i get through the folders (note, i get the same data on both webspace):
Array (
[0] => Array (
[title] => Apotheek Beerlandt
[images] => Array (
[0] => Array ( [url] => beerlandt 2.JPG )
[1] => Array ( [url] => beerlandt 3.JPG )
[2] => Array ( [url] => beerlandt 1.JPG )
)
)
)
This is entered in the following 'html' code (template file):
{iteration:referenties}
<h2>{$referenties.title}</h2>
<div id="imageslide">
{iteration:referenties.images}
<a href="/images/referenties/{$referenties.title}/{$referenties.images.url}" rel="lightbox[{$referenties.title}]"><img src="/images/referenties/{$referenties.title}/thumbs/{$referenties.images.url}" /></a>
{/iteration:referenties.images}
</div>
{/iteration:referenties}
Note: references in my native language is 'referenties'.
It seems that on my dad his webhosting a '.' changed to '->', although i'm not really sure (as in 'I can't believe that).
The php version on my localhost and my webhosting are PHP5.3.5, the version on my dad his hosting is 5.1.2.
I hope you guys can help me out on this one :).
PS: I know i can fix this with the use of an sql database. And i'm going to do that in the near future, but for now i just want to know why this error is occurring.
Thanks in advance!
Edit: I just enabled the display_errors in my php.ini and now i see the following error 'Notice: Undefined variable: count in /var/www/html/test/spoon/template/compiler.php on line 913' (and also on some other lines). Still, it's a mystery why it works on my localhost and not on my dad his host.
A: I'm the author of Spoon Library. I believe the issue lies with the differences in the PHP versions. The $count parameter that the notices are talking about were added in PHP5.1, but for some reason they don't seem to work exactly as expected in the PHP version on your dad's host.
I'd recommend to try and get the hosting to use at least PHP5.2, because there are another few issues that might occur within other spoon packages because of this.
If you need any more help you can always find me on twitter(@spoonlibrary) or e-mail me (davy@spoon-library.com)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ForkJoin Framework Quicksort -- Collections does anyone know if a version of the QuickSort algorithm exists which uses the ForkJoin Framework introduced in Java7 and takes Collections as input? I've found some wich simply sort Integer-arrays and I'm currently rewriting it for use with Collections, but I don't want to reinvent the wheel so I just decided to ask if anyone knows of a version which uses Collections.
Edit: I've implemented it for Lists, but not tested so far. I'm going to post it on codereview.stackexchange.com.
kind regards,
Johannes
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Drupal Views- Filtering by multiple taxonomy terms I have a View set up to display featured Article nodes. For each node there are 2 taxonomy vocabs to use. The first is 'Featured' with a term 'Yes'; the second is 'Section' with terms: Home, Info, Blog etc. If a node has the term Yes (Featured vocab) and the term Blog (Section vocab) then if you were to browse to domain.com/blog then you would see that featured content.
The view is set up to accept the first argument in the url to determine which section of the site you are viewing (Views argument: Taxonomy term). This works as expected.
Lastly, I am filtering by node type (Article) and then the taxonomy vocab (Featured) which is where my view is failing to return content. If I remove the taxonomy vocab filter it displays correctly for each section although it is displaying all Article nodes.
Could the issue be that the argument and filter are different taxonomy vocabs?
Here's the SQL query:
SELECT node.nid AS nid,
node.type AS node_type,
node.vid AS node_vid,
node_data_field_article_images.field_article_images_data AS node_data_field_article_images_field_article_images_data,
node.title AS node_title,
node.created AS node_created
FROM node node
LEFT JOIN content_field_article_images node_data_field_article_images ON node.vid = node_data_field_article_images.vid
LEFT JOIN term_node term_node ON node.vid = term_node.vid
LEFT JOIN term_data term_data ON term_node.tid = term_data.tid
WHERE (node.status <> 0) AND (node.type in ('article')) AND (node_data_field_article_images.field_article_images_list <> 0) AND (term_data.vid in ('20')) AND (term_data.name = 'home')
ORDER BY node_created DESC
Here's my view:
$view = new view;
$view->name = 'marquee_slideshow_dev';
$view->description = 'Marquee on homepage and landing pages';
$view->tag = '';
$view->view_php = '';
$view->base_table = 'node';
$view->is_cacheable = FALSE;
$view->api_version = 2;
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('fields', array(
'title' => array(
'label' => '',
'alter' => array(
'alter_text' => 0,
'text' => '',
'make_link' => 0,
'path' => '',
'link_class' => '',
'alt' => '',
'prefix' => '',
'suffix' => '',
'target' => '',
'help' => '',
'trim' => 0,
'max_length' => '',
'word_boundary' => 1,
'ellipsis' => 1,
'html' => 0,
'strip_tags' => 0,
),
'empty' => '',
'hide_empty' => 0,
'empty_zero' => 0,
'link_to_node' => 0,
'exclude' => 0,
'id' => 'title',
'table' => 'node',
'field' => 'title',
'relationship' => 'none',
'override' => array(
'button' => 'Override',
),
),
));
$handler->override_option('sorts', array(
'created' => array(
'order' => 'DESC',
'granularity' => 'second',
'id' => 'created',
'table' => 'node',
'field' => 'created',
'relationship' => 'none',
),
));
$handler->override_option('arguments', array(
'name' => array(
'default_action' => 'default',
'style_plugin' => 'default_summary',
'style_options' => array(),
'wildcard' => 'all',
'wildcard_substitution' => 'All',
'title' => '',
'breadcrumb' => '',
'default_argument_type' => 'php',
'default_argument' => '',
'validate_type' => 'none',
'validate_fail' => 'not found',
'glossary' => 0,
'limit' => '0',
'case' => 'lower',
'path_case' => 'lower',
'transform_dash' => 1,
'add_table' => 0,
'require_value' => 0,
'id' => 'name',
'table' => 'term_data',
'field' => 'name',
'validate_user_argument_type' => 'uid',
'validate_user_roles' => array(
'2' => 0,
'7' => 0,
'8' => 0,
'4' => 0,
'6' => 0,
'5' => 0,
),
'relationship' => 'none',
'default_options_div_prefix' => '',
'default_argument_fixed' => '',
'default_argument_user' => 0,
'default_argument_image_size' => '_original',
'default_argument_php' => '$path = explode(\'/\', drupal_get_path_alias($_GET[\'q\']));
$is_front = $_GET[\'q\'] == \'<front>\' || $_GET[\'q\'] == variable_get(\'site_frontpage\', \'<front>\');
$arg0 = arg(0);
if ($is_front) {
return \'home\';
} else if ($arg0 = \'node\' && arg(1) != \'add\' && arg(2) != \'edit\' && arg(2) != \'delete\' && $path[0] != \'\') {
return $path[0];
}
',
'validate_argument_node_type' => array(
'activitystream' => 0,
'image' => 0,
'contenttab' => 0,
'content_about_fedex_content_page' => 0,
'content_about_fedex_home_page' => 0,
'content_about_fedex_landing_page' => 0,
'content_access_article' => 0,
'content_access_article_index' => 0,
'content_access_content_page' => 0,
'content_access_landing_page' => 0,
'content_block' => 0,
'content_case_study' => 0,
'content_document' => 0,
'content_event' => 0,
'content_executive_viewpoint' => 0,
'content_feature' => 0,
'content_fedex_fact' => 0,
'content_fedex_video_page' => 0,
'content_great_place_to_work' => 0,
'content_location' => 0,
'content_opco_overview' => 0,
'content_our_commitment_content_p' => 0,
'content_our_commitment_landing_p' => 0,
'content_region_overview' => 0,
'content_resources' => 0,
'content_sag' => 0,
'content_small_business' => 0,
'page' => 0,
'slideshow_image' => 0,
'story' => 0,
),
'validate_argument_node_access' => 0,
'validate_argument_nid_type' => 'nid',
'validate_argument_vocabulary' => array(
'14' => 0,
'18' => 0,
'17' => 0,
'11' => 0,
'10' => 0,
'15' => 0,
'9' => 0,
'3' => 0,
'16' => 0,
'8' => 0,
'5' => 0,
'2' => 0,
'7' => 0,
'19' => 0,
'1' => 0,
'12' => 0,
'13' => 0,
),
'validate_argument_type' => 'tid',
'validate_argument_transform' => 0,
'validate_user_restrict_roles' => 0,
'image_size' => array(
'_original' => '_original',
'thumbnail' => 'thumbnail',
'preview' => 'preview',
'icon' => 'icon',
),
'validate_argument_php' => '',
'override' => array(
'button' => 'Override',
),
),
));
$handler->override_option('filters', array(
'status' => array(
'operator' => '=',
'value' => '1',
'group' => '0',
'exposed' => FALSE,
'expose' => array(
'operator' => FALSE,
'label' => '',
),
'id' => 'status',
'table' => 'node',
'field' => 'status',
'relationship' => 'none',
),
'type' => array(
'operator' => 'in',
'value' => array(
'article' => 'article',
),
'group' => '0',
'exposed' => FALSE,
'expose' => array(
'operator' => FALSE,
'label' => '',
),
'id' => 'type',
'table' => 'node',
'field' => 'type',
'relationship' => 'none',
),
'vid' => array(
'operator' => 'in',
'value' => array(
'20' => '20',
),
'group' => '0',
'exposed' => FALSE,
'expose' => array(
'operator' => FALSE,
'label' => '',
),
'id' => 'vid',
'table' => 'term_data',
'field' => 'vid',
'relationship' => 'none',
),
));
$handler->override_option('access', array(
'type' => 'none',
));
$handler->override_option('cache', array(
'type' => 'none',
));
$handler->override_option('empty_format', '3');
$handler->override_option('items_per_page', 0);
$handler->override_option('use_pager', 'mini');
$handler->override_option('distinct', 0);
$handler->override_option('style_options', array(
'grouping' => '',
));
$handler = $view->new_display('block', 'Home Page', 'block_1');
$handler->override_option('block_description', '');
$handler->override_option('block_caching', -1);
A: hope you have a node which has terms from both the vocabulary ..
its difficult to solve it from exported view..
what you can do is provide the sql query which view is generating check it or post it over here..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Encrypt Data in one "slot" in database I read over a great tutorial on how to encrypt the data using a symmetrical key in one column.
Click here to view it.
This has helped me set up a column for encryption, which is what I need. My problem is that I will constantly be updating rows in my database - so copying over one whole original column to the encrypted columm like the tutorial shows doesn't work. Is there a way that I can insert a value that is given to me (using C#/asp) and direclty encrypt it as I insert it into the database, rather than having to place it in one column and copying it over, and then dropping the other column?
A: Just call EncryptByKey on your data to encrypt You don't need another column. In this case it has to be included in your SQL which should be a parameterized query or a stored procedure.
Insert into Whatever
YourEncryptedData
Values ( EncryptByKey(...))
You may have top open your key first depending on your implementation.
http://msdn.microsoft.com/en-us/library/ms174361.aspx
A: You need to have the certificate open do do the encryption. This is from the page you linked to:
OPEN SYMMETRIC KEY TestTableKey
DECRYPTION BY CERTIFICATE EncryptTestCert
UPDATE TestTable
SET EncryptSecondCol = ENCRYPTBYKEY(KEY_GUID('TestTableKey'),SecondCol)
Inserting works the same:
OPEN SYMMETRIC KEY TestTableKey
DECRYPTION BY CERTIFICATE EncryptTestCert
INSERT INTO TestTable (FirstCol, EncryptSecondCol)
VALUES (6, ENCRYPTBYKEY(KEY_GUID('TestTableKey'),'Sixth'))
You can execute the open key command before doing your insert or create a stored procedure to do the insert.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Issue when using a custom font - "native typeface cannot be made" I'm trying to use a font I found on the internet, but the problem is that I get an FC with "native typeface cannot be made".
Here is the code in the getView of my ListVIew:
holder.tv_SuraName =(TextView)convertView.findViewById(R.id.Start_Name);
holder.tv_SuraName.setTypeface(Typeface.createFromAsset(mContext.getAssets(), "suralist_font.ttf"));
Can anyone tell me why can I use the custom rom? You can get it HERE .. the file is .ttf
A: I had this same problem, I created mine in assets>fonts>whatever.ttf and was getting the same error. I added the fonts extension (fonts/whatever.ttf) and it fixed the problem in every case.
holder.tv_SuraName =(TextView)convertView.findViewById(R.id.Start_Name);
holder.tv_SuraName.setTypeface(Typeface.createFromAsset(mContext.getAssets(), "fonts/suralist_font.ttf"));
A: My problem was incorrect placement of the assets folder.
When using Android Studio the assets folder should be inside of the source sets e.g.
src/main/assets/
Found in this answer
A: The font file is either corrupt or unsupported for some reason. You can drop it on the SD card and load it from file, to make sure it's not a problem with your assets.
A: There are basically 4 things that can cause this:
*
*You use the wrong extension
*You have to place the fonts in the assets folder and not inside assets/fonts/
*You misspelled the fonts
*The fonts need to be lowercase (in my case the solution was to rename MyFont.ttf to myfont.ttf, strange)
A: Double check the extension isn't in caps, ie. suralist_font.TTF
Fonts often come seem to come that way and it might be overlooked.
A: Rather old thread, but I want to add one more reason this can happen: You have to set the content view before calling typeface. See example below
Does not work:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView title = (TextView)findViewById(R.id.tvTitle);
Typeface font = Typeface.createFromAsset(this.getAssets(), "fonts/whatever.ttf");
title.setTypeface(font);
setContentView(R.layout.main);
}
Does work!
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // <-- call before typeface
TextView title = (TextView)findViewById(R.id.tvTitle);
Typeface font = Typeface.createFromAsset(this.getAssets(), "fonts/whatever.ttf");
title.setTypeface(font);
}
A: I am using android studio, in my case problem was with the path of assets folder, in Eclipse path for assets folder is res/assets/ but in Android Studio its src/main/assets/
So, i just move my font file to this path and finally problem solved.
A: Either your font file is corrupt else you making some mistake in spelling while calling your file name. I had same issue, it was because file name specified in asset folder was
roboto_black.ttf
and while declaring in java file, i have been spelling it as:
roboto_blak.ttf
If your .ttf files are in asset folder,then use:
Typeface type_bold = Typeface.createFromAsset(getAssets(), "roboto_black.ttf");
Else if it is in fonts folder, then use:
type_bold = Typeface.createFromAsset(getAssets(), "fonts/roboto_black.ttf");
Hope it helps!
A: As CommonsWare states in this answer
I would guess that there is a problem with the font itself. That error
will be triggered when native code in the OS attempts to load the
typeface.
Anyway try this one:
holder.tv_SuraName = (TextView)convertView.findViewById(R.id.Start_Name);
Typeface Font = Typeface.createFromAsset(this.getAssets(),"suralist_font.ttf");
holder.tv_SuraName.setTypeface(Font);
A: Hope this will help
Typeface.createFromAsset leaks asset stream: http://code.google.com/p/android/issues/detail?id=9904
A: I had the same problem with COMIC.TTF from comic sans ms of Windows.
Since the original file I placed in assets/fonts folder was in uppercase as spelt above, I had to type it exactly in uppercase.
Typeface.createFromAsset(getAssets(), "fonts/COMIC.TTF");
it turns out the problem was caused by the lower case:
Typeface.createFromAsset(getAssets(), "fonts/comic.ttf");
A: Please note that this is due to either a corrupt file or you have placed the file in the wrong folder.
According to Android documentation here
main/assets/
This is empty. You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.
Therefore your folder structure should be yourmodule/main/assets (e.g. a***pp/main/assets*** )
A: What worked for me was first changing my font name to only lower case and underscore: from Amatic-Sc.ttf to amatic_sc.ttf.
Then in the set.TypeFace method change assets/fonts/amatic_sc.ttf to just fonts/amatic_sc.ttf.
A: I've been debugging forever on this error in Android Studio. Clean and rebuilding the project after adding the fonts to the assets directory fixed the issue for me.
A: Just did a build --> clean and it started rendering .
A: I had same issue which happened on Android 4.0.3-4.0.4 (100% reproducible on emulator IceCreamSandwich mips 4.0.3).
The problem was that TTF fonts, that I had, were not correct, despite almost all Android versions were able to load those TTF font. So I used https://cloudconvert.com/woff-to-ttf (since I had woff files as well) to make new TTF fonts, which solved my problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "51"
} |
Q: If using Xcode to make an iOS calculator, how would I add a decimal button? How to add a decimal button so I don't have to do whole numbers? If i wanted any decimal number like 1.2 or 100.4 or 3.0 or anything like that, how would I add it to the calculator I'm making?
A: You're not giving me much information in your question. How do the other buttons work?
If I was making a calculator I would have a label at the top showing the current reading. On press of a number button I would update the label with the number at the end.
For a decimal button you just add a . to the end of the label. You might want to have a global variable BOOL hasDecimalPlace and set it to true so you know if there is already a decimal place. Just remember to set it to false again when you clear the view or do a calculation or similar.
A: - (IBAction)Decimal:(id)sender{
NSString *currentText = Text.text;
if ([currentText rangeOfString:@"." options:NSBackwardsSearch].length == 0) {
Text.text = [Text.text stringByAppendingString:@"."];
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Eclipse IDE - Is it possible to have detached windows not always on top? Basically I have multiple monitors for development with Eclipse. I detach some of the windows such as the "Console" view so that I can have it fill my monitor. This is great as I can fill up my screens.
However in some cases I also want to have my browser in front while I'm coding since there's some documentation I need to look at. I can't figure out how to do this without creating another perspective...
A: The answer appears to be that you can't...
A: In Eclipse Luna I had the problem that floating windows were not coming up while setting the focus on the main IDE window. It happened after I changed from 32 to 64bit using the same workspace. The windows were opened and closed correctly.
What solved the problem was reintegrating the floating windows into the main IDE window and recreated floating windows again.
A: You can open a new window (Window|New Window) and drag your views into this window instead of detaching them. New windows are not connected with the main one and you can control their visibility as you wish.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Why does concurrent GC sometimes cause ExecutionEngineException (per MSDN)? According to MSDN, there is a "tip" stating that a .NET application running under heavy load with concurrent garbage collection (either <gcConcurrent enabled="true"/> or unspecified, since it's the default behavior) may throw an ExecutionEngineException. Is anyone aware of a Microsoft KB article or other source that provides additional background on this?
We have experienced this directly with an NHibernate 3.2-based Windows Service application, which will invariably crash after at most a few hours of operation. We were able to track down the exception to the ISession.Flush() call.
There's a thread on nhusers reporting what appears to be the same problem. His suggested workaround, which was to disable concurrent GC, has worked for us so far, although switching to server-mode GC (<gcServer enable="true"/>), which implicitly disables concurrent GC, also did the trick.
Before submitting this to MS as a bug, I'd like to find out if anyone out there has additional information on the concurrent GC instablity that the tip mentions.
A: I suspect this occurs when the application is under heavy load because when concurrent GC is enabled, the GC tries to do it's work without pausing your application. If the GC encounters a situation where it tries to move memory around during the compaction phase of a GC cycle and isn't able to move the memory or isn't able to correctly update the application pointers, that could cause the runtime to throw this exception since it would end up putting your application into a potentially invalid state.
As @casperOne pointed out in his comment, this exception is marked as obsolete in .NET 4.0 although that doesn't necessarily mean the GC still can't get itself into the same state that caused it to throw the exception in .NET 3.5. If the GC did get itself into that same state, the runtime will issue a FailFast command and terminate rather than throwing an exception.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: What is the best way to CRUD dynamically created tables? I'm creating(ed) an ASP.NET application (SQL Server backend) that allows the user (a business) to create their own tables and fields. They will all be child tables of a parent table (non-dynamic) and have proper PK/FK relationships (default fields when the table is created).
However, I don't like my current method of updating/inserting and selecting the fields. I was going to create an SP that was passed the proper keys and table names, then have it return the proper SQL statement. I'm thinking that it might make more sense to just pass the name/value pairs of fields/values and have an SP actually process them. Is this the best way to do it? If so, I'm not good at SP's so any examples of how?
A: I don't have a lot of experience with the EAV model, but it does sound like it might be a good idea for implementing what you're trying to achieve. However, if you already have a system in place, an overhaul could be very expensive.
If the queries you're making against the user tables are basic CRUD operations, what about just creating CRUD stored procs for each table? E.g. -
Table:
acme_orders
Stored Procs:
acme_orders_insert
acme_orders_update
acme_orders_select
acme_orders_delete
... [other necessary procs]
I have no idea what the business needs are for these tables, but I imagine that whatever you're doing currently could be translated into doing the same thing with stored procs.
A:
I was going to create an SP that was passed the proper keys and table names, then have it >return the proper SQL statement. I'm thinking that it might make more sense to just pass the >name/value pairs of fields/values and have an SP actually process them.
Assuming you mean the proc would generate and then execute the SQL (sometimes known as dynamic SQL) this can work, but it probably performs slower than static / compiled SQL, as in normal procs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: "Unresolved overloaded function type" while trying to use for_each with iterators and function in C++ //for( unsigned int i=0; i < c.size(); i++ ) tolower( c[i] );
for_each( c.begin(), c.end(), tolower );
I am trying to use a for_each loop in place of the for loop for an assignment.
I am unsure why I am getting this error message:
In function âvoid clean_entry(const std::string&, std::string&)â:
prog4.cc:62:40: error: no matching function for call to âfor_each(std::basic_string<char>::iterator, std::basic_string<char>::iterator, <unresolved overloaded function type>)â
A: Write:
for_each( c.begin(), c.end(), ::tolower );
Or :
for_each( c.begin(), c.end(), (int(*)(int))tolower);
I've faced this problem so many times that I'm tired of fixing this in my code, as well as in others' code.
Reason why your code is not working : there is another overloaded function tolower in the namespace std which is causing problem when resolving the name, because the compiler is unable to decide which overload you're referring to, when you simply pass tolower 1. That is why the compiler is saying unresolved overloaded function type in the error message, which indicates the presence of overload(s).
So to help the compiler in resolving to the correct overload, you've to cast tolower as
(int (*)(int))tolower
then the compiler gets the hint to select the global tolower function, which in other ways, can be used by writing ::tolower.
1. I guess you've written using namespace std in your code. I would also suggest you to not to do that. Use fully-qualified names in general.
By the way, I think you want to transform the input string into lower case, if so, then std::for_each wouldn't do that. You've to use std::transform function as:
std::string out;
std::transform(c.begin(), c.end(), std::back_inserter(out), ::tolower);
//out is output here. it's lowercase string.
A: 1) You have using namespace std; somewhere in your code. The danger of importing the entire std namespace is that you don't necessarily know what you are getting. In this case, you have imported overloads of std::tolower.
Never type using namespace std;, even if your textbook or your instructor tells you to.
2) Since you are restricted from using std::transform, you could modify the string in place using std::for_each:
#include <cctype>
#include <algorithm>
#include <string>
#include <iostream>
void
MakeLower(char& c)
{
c = std::tolower(c);
}
int
main ()
{
std::string c("Hello, world\n");
std::for_each(c.begin(), c.end(), MakeLower);
std::cout << c;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to rename a single column in a data.frame? I know if I have a data frame with more than 1 column, then I can use
colnames(x) <- c("col1","col2")
to rename the columns. How to do this if it's just one column?
Meaning a vector or data frame with only one column.
Example:
trSamp <- data.frame(sample(trainer$index, 10000))
head(trSamp )
# sample.trainer.index..10000.
# 1 5907862
# 2 2181266
# 3 7368504
# 4 1949790
# 5 3475174
# 6 6062879
ncol(trSamp)
# [1] 1
class(trSamp)
# [1] "data.frame"
class(trSamp[1])
# [1] "data.frame"
class(trSamp[,1])
# [1] "numeric"
colnames(trSamp)[2] <- "newname2"
# Error in names(x) <- value :
# 'names' attribute [2] must be the same length as the vector [1]
A: This is an old question, but it is worth noting that you can now use setnames from the data.table package.
library(data.table)
setnames(DF, "oldName", "newName")
# or since the data.frame in question is just one column:
setnames(DF, "newName")
# And for reference's sake, in general (more than once column)
nms <- c("col1.name", "col2.name", etc...)
setnames(DF, nms)
A: This is a generalized way in which you do not have to remember the exact location of the variable:
# df = dataframe
# old.var.name = The name you don't like anymore
# new.var.name = The name you want to get
names(df)[names(df) == 'old.var.name'] <- 'new.var.name'
This code pretty much does the following:
*
*names(df) looks into all the names in the df
*[names(df) == old.var.name] extracts the variable name you want to check
*<- 'new.var.name' assigns the new variable name.
A: Try:
colnames(x)[2] <- 'newname2'
A: This is likely already out there, but I was playing with renaming fields while searching out a solution and tried this on a whim. Worked for my purposes.
Table1$FieldNewName <- Table1$FieldOldName
Table1$FieldOldName <- NULL
Edit begins here....
This works as well.
df <- rename(df, c("oldColName" = "newColName"))
A: You can use the rename.vars in the gdata package.
library(gdata)
df <- rename.vars(df, from = "oldname", to = "newname")
This is particularly useful where you have more than one variable name to change or you want to append or pre-pend some text to the variable names, then you can do something like:
df <- rename.vars(df, from = c("old1", "old2", "old3",
to = c("new1", "new2", "new3"))
For an example of appending text to a subset of variables names see:
https://stackoverflow.com/a/28870000/180892
A: This can also be done using Hadley's plyr package, and the rename function.
library(plyr)
df <- data.frame(foo=rnorm(1000))
df <- rename(df,c('foo'='samples'))
You can rename by the name (without knowing the position) and perform multiple renames at once. After doing a merge, for example, you might end up with:
letterid id.x id.y
1 70 2 1
2 116 6 5
3 116 6 4
4 116 6 3
5 766 14 9
6 766 14 13
Which you can then rename in one step using:
letters <- rename(letters,c("id.x" = "source", "id.y" = "target"))
letterid source target
1 70 2 1
2 116 6 5
3 116 6 4
4 116 6 3
5 766 14 9
6 766 14 13
A: I think the best way of renaming columns is by using the dplyr package like this:
require(dplyr)
df = rename(df, new_col01 = old_col01, new_col02 = old_col02, ...)
It works the same for renaming one or many columns in any dataset.
A: colnames(trSamp)[2] <- "newname2"
attempts to set the second column's name. Your object only has one column, so the command throws an error. This should be sufficient:
colnames(trSamp) <- "newname2"
A: You could also try 'upData' from 'Hmisc' package.
library(Hmisc)
trSamp = upData(trSamp, rename=c(sample.trainer.index..10000. = 'newname2'))
A: If you know that your dataframe has only one column, you can use:
names(trSamp) <- "newname2"
A: The OP's question has been well and truly answered. However, here's a trick that may be useful in some situations: partial matching of the column name, irrespective of its position in a dataframe:
Partial matching on the name:
d <- data.frame(name1 = NA, Reported.Cases..WHO..2011. = NA, name3 = NA)
## name1 Reported.Cases..WHO..2011. name3
## 1 NA NA NA
names(d)[grepl("Reported", names(d))] <- "name2"
## name1 name2 name3
## 1 NA NA NA
Another example: partial matching on the presence of "punctuation":
d <- data.frame(name1 = NA, Reported.Cases..WHO..2011. = NA, name3 = NA)
## name1 Reported.Cases..WHO..2011. name3
## 1 NA NA NA
names(d)[grepl("[[:punct:]]", names(d))] <- "name2"
## name1 name2 name3
## 1 NA NA NA
These were examples I had to deal with today, I thought might be worth sharing.
A: I would simply change a column name to the dataset with the new name I want with the following code:
names(dataset)[index_value] <- "new_col_name"
A: I find that the most convenient way to rename a single column is using dplyr::rename_at :
library(dplyr)
cars %>% rename_at("speed",~"new") %>% head
cars %>% rename_at(vars(speed),~"new") %>% head
cars %>% rename_at(1,~"new") %>% head
# new dist
# 1 4 2
# 2 4 10
# 3 7 4
# 4 7 22
# 5 8 16
# 6 9 10
*
*works well in pipe chaines
*convenient when names are stored in variables
*works with a name or an column index
*clear and compact
A: I like the next style for rename dataframe column names one by one.
colnames(df)[which(colnames(df) == 'old_colname')] <- 'new_colname'
where
which(colnames(df) == 'old_colname')
returns by the index of the specific column.
A: colnames(df)[colnames(df) == 'oldName'] <- 'newName'
A: Let df be the dataframe you have with col names myDays and temp.
If you want to rename "myDays" to "Date",
library(plyr)
rename(df,c("myDays" = "Date"))
or with pipe, you can
dfNew <- df %>%
plyr::rename(c("myDays" = "Date"))
A: I found colnames() argument easier
https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/row%2Bcolnames
select some column from the data frame
df <- data.frame(df[, c( "hhid","b1005", "b1012_imp", "b3004a")])
and rename the selected column in order,
colnames(df) <- c("hhid", "income", "cost", "credit")
check the names and the values to be sure
names(df);head(df)
A: I would simply add a new column to the data frame with the name I want and get the data for it from the existing column. like this:
dataf$value=dataf$Article1Order
then I remove the old column! like this:
dataf$Article1Order<-NULL
This code might seem silly! But it works perfectly...
A: We can use rename_with to rename columns with a function (stringr functions, for example).
Consider the following data df_1:
df_1 <- data.frame(
x = replicate(n = 3, expr = rnorm(n = 3, mean = 10, sd = 1)),
y = sample(x = 1:2, size = 10, replace = TRUE)
)
names(df_1)
#[1] "x.1" "x.2" "x.3" "y"
Rename all variables with dplyr::everything():
library(tidyverse)
df_1 %>%
rename_with(.data = ., .cols = everything(.),
.fn = str_replace, pattern = '.*',
replacement = str_c('var', seq_along(.), sep = '_')) %>%
names()
#[1] "var_1" "var_2" "var_3" "var_4"
Rename by name particle with some dplyr verbs (starts_with, ends_with, contains, matches, ...).
Example with . (x variables):
df_1 %>%
rename_with(.data = ., .cols = contains('.'),
.fn = str_replace, pattern = '.*',
replacement = str_c('var', seq_along(.), sep = '_')) %>%
names()
#[1] "var_1" "var_2" "var_3" "y"
Rename by class with many functions of class test, like is.integer, is.numeric, is.factor...
Example with is.integer (y):
df_1 %>%
rename_with(.data = ., .cols = is.integer,
.fn = str_replace, pattern = '.*',
replacement = str_c('var', seq_along(.), sep = '_')) %>%
names()
#[1] "x.1" "x.2" "x.3" "var_1"
The warning:
Warning messages:
1: In stri_replace_first_regex(string, pattern, fix_replacement(replacement), :
longer object length is not a multiple of shorter object length
2: In names[cols] <- .fn(names[cols], ...) :
number of items to replace is not a multiple of replacement length
It is not relevant, as it is just an inconsistency of seq_along(.) with the replace function.
A: library(dplyr)
rename(data, de=de.y)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7531868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "446"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.