text stringlengths 8 267k | meta dict |
|---|---|
Q: HTML objects not visible to JavaScript in Firefox 6 Is there any reason why I'm not able to see object values from JavaScript using Firefox, but IE and Chrome see them without problem?
For example:
<div>
<input type="text" id="clientID" />
<input type="submit" id="search" value="Submit" class="submitButton" />
</div>
JavaScript:
<script type="text/javascript">
$(document).ready(function () {
$("#searchDisputes").click(function () {
if(clientID.value.toString() != "") {
//do something
}
}
}
</script>
Firefox tells me that clientID does not exist, however IE and Chrome work just fine.
I am able to access it using jQuery $("#clientID"), but before changing a good bit of code around, I would like to understand why this doesn't work in Firefox, but works ok in other browsers.
A: You are assuming that giving an element an id will create a global variable with the same name as the id containing a reference to the element. There is no reason browsers should do this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Going through a Pivot control really fast crashes I have a pivot control and a button which does selectedIndex++ and when the selectedIndex has gone passed the last entry it will open up a messagebox asking the user if they want to quiz.
But during testing if you spam the button it will create a 0x8000ffff error when you open the MessageBox.
How do I stop this from happening? is it something to do with the ui thread being too busy or continuing to move the pivot? is the button event still running after I try to navigate out of the page?
this is what the code that does the selectedIndex++
void gotoNextQuestion()
{
if (quizPivot.SelectedIndex < App.settings.currentTest.Questions.Count() - 1)
{
//xScroll -= scrollAmount;
//moveBackground(xScroll);
if (!stoppedPaging)
{
quizPivot.SelectedIndex++;
}
//App.PlaySoundKey("next");
}
else
{
if (App.settings.testMode == App.TestModes.TrainingRecap)
{
MessageBoxResult result;
if (countAnsweredQuestions() == App.settings.currentTest.Questions.Count())
{
stoppedPaging = true;
result = MessageBox.Show("You have reviewed every training question, would you like to go back to the main menu?", "Training Over", MessageBoxButton.OKCancel);
stoppedPaging = false;
if (result == MessageBoxResult.OK)
{
positionableSpriteRadioButton.IsAnswered -= new Action<bool>(Answers_IsAnsweredCompleted);
spriteRadioButton.IsAnswered -= new Action<bool>(Answers_IsAnsweredCompleted);
App.settings.currentTest = null;
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
return;
}
}
}
else
{
MessageBoxResult result;
if (countAnsweredQuestions() == App.settings.currentTest.Questions.Count())
{
stoppedPaging = true;
result = MessageBox.Show("You have answered all of the questions, are you sure you want to finish?", "Are you sure you want to finish?", MessageBoxButton.OKCancel);
stoppedPaging = false;
}
else
{
checkFinishConditions();
}
}
quizPivot.SelectedIndex = 0;
//App.PlaySoundKey("begin");
}
App.settings.currentTest.currentQuestion = quizPivot.SelectedIndex;
}
A: Well, one thing is for sure
positionableSpriteRadioButton.IsAnswered -= new Action<bool>(Answers_IsAnsweredCompleted);
That isn't going to work. You're creating a new Action every time. So nothing will have the same reference id, and thus nothing will be removed.
Instead you should remove the Action<bool> and simply subscribe/unsubscribe with
positionableSpriteRadioButton.IsAnswered -= Answers_IsAnsweredCompleted;
And when you subscribe
positionableSpriteRadioButton.IsAnswered += Answers_IsAnsweredCompleted;
That way you can actually remove it again.
But I would recommend you not to use a pivot for this type of "wizard". It's abuse of the control, and going to give a really poor user experience.
Also, just because you navigate to another page, it doesn't mean the code stops running. All code in the same expression is executed, unless you add a return statement after the call to NavigationService.Navigate.
Also, always make sure that Navigation is on the UI thread by wrapping all calls to NavigationService.Navigate in a call to Dispatcher.BeginInvoke.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: javascript/jQuery Array concatenation? I have some simple jQuery code:
var response = Array()
$('.task-list').each(function() {
response.concat(response,$('#' + this.id).sortable('toArray'));
}
);
console.log(response);
The problem I'm having is that I think I'm using concat improperly- the result is an empty array. When I use array push, it works correctly.
A: You have to set response to the newly formed array, as described in the specification. You currently don't use the return value at all.
The specification says that for .concat, the array is not altered, but the new array is returned:
When the concat method is called with zero or more arguments item1, item2, etc., it returns an array containing the array elements of the object followed by the array elements of each argument in order.
Compare with .push, which says the current array is altered, and that something else is returned instead (the new length):
The arguments are appended to the end of the array, in the order in which they appear. The new length of the array is returned as the result of the call.
So:
response = response.concat($('#' + this.id).sortable('toArray'));
A: Concat returns the concatenated array, you want this instead
response = response.concat($('#' + this.id).sortable('toArray'));
Simple example
var a = [1,2];
var b = [3,4];
a = a.concat( b ); // result is [1,2,3,4] which is correct
If you do the following
a = a.concat( a , b ); // result is [1, 2, 1, 2, 3, 4] not what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can resharper jump to the file that contains the unit tests? Is it possible to somehow link or use some convention so I can jump between my unit tests for a given class?
Also, creating short cuts for jumping between the interface, the implementations?
(keyboard shortcuts)
Example:
IUserService
UserService
UserServiceTests
It would be great if I can somehow link these together so I can jump to any of these files while in any one of them currently.
A: I just implemented that feature in TestLinker, which is a ReSharper 2016.1 extension. It is available to install from the ReSharper Gallery.
A:
Is it possible to somehow link or use some convention so I can jump between my unit tests for a given class?
To jump between unit tests for a given class, launch ReSharper's Find Usages on the class name, and as soon as you have results in the Find Results tool window, group them in a way that helps focus on usages in a particular part of your code base - for example, by project and type. This will let detect usages in your test project. From there, you can quickly jump from Find Results to actual usages in code. As an alternative, you can use ReSharper's Go to Usages of Symbol that works in a similar way but displays search results in a pop-up menu instead of flushing them to Find Results.
If your test classes contain metadata showing which business logic they're covering, this would help even better in differentiating the usages you need. For example, if you're using MSpec, test classes are marked with the Subject attribute: [Subject(typeof (MyCoveredClass))] This is handy because usages within this attribute are very visible, and navigating to them leads you directly to declarations of your test classes:
With NUnit and MSTest, this is a bit more complicated as their attributes take strings as parameters, like this: [TestProperty("TestKind", "MyCoveredClass")]. In order to find such a usage of MyCoveredClass, you'll have to use ReSharper's Find Usages Advanced and turn on the Textual occurrences option.
Also, creating short cuts for jumping between the interface, the implementations?
As to jumping within an inheritance chain, ReSharper provides multiple options to do that, including Type Hierarchy (ReSharper > Inspect > Type Hierarchy) and Go to Implementation (ReSharper > Navigate > Go to Implementation):
A: As has already been mentioned you can do this using the TestCop ReSharper plugin (gallery link).
It ties the class under test to the test fixture by using regular expressions to identify class names and namespaces. You can customise these to fit your needs, but I found there to be a fair amount of trial and error to get this right on existing code.
Once it's all set up you can go back and forth with a keyboard shortcut. It can also do things like create the TestFixture or the class for you.
A: ReSharper doesn't have a specific Goto Test/Code feature other than navigating through the list of usages.
However, TestDriven.NET has this feature which uses naming conventions to find the Test/Code peer such that you can flip back and forth.
Also, creating short cuts for jumping between the interface, the
implementations?
ReSharper has this feature. Using the Visual Studio scheme:
*
*Alt + Home navigates to the class' base, in case there are more than one a context menu will list them
*Alt + End navigates down the inheritance hierarchy and behaves like Alt + Home
Ctrl + U and Ctrl + Alt + B respectively is the equivalent for the ReSharper 2.x / IDEA scheme.
A: i don't think this is going to be possible with just resharper. as far as resharper is concerned, your unit test is just another usage of UserService.
also, all of the different unit testing frameworks specify things differently, so it'd be tough to know. for instance, doing bdd would yield test class names almost entirely unrelated to the class(es) being tested.
you might be able to write an extension to do this, maybe using attributes or something? not sure.
A: You can use the ReSharper Extension TestCop
This plugin is designed for use with mstest & nunit but should work with any other unittest framework that requires you to assign a test Attribute.
A: With ReSharper and NUnit, to jump from test to subject, you can use the TestOf property of the TestFixture attribute. Just Ctrl + Click on MyClass in the test file:
[TestFixture(TestOf = typeof(MyClass))]
public class MyClassTest
To jump from subject to test, use the ReSharper Find usage command.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: ObjectDataSource - Can your load methods reside in a different class to the entity? I have the following class model:
public class Person
{
public string Name;
public int Age;
}
public class PersonService
{
public List<Person> GetAll() {...}
}
I'm displaying the data on an ASP.Net web page by binding an ObjectDataSource (ODS) to a GridView.
If I point the 'ODS.TypeName = PersonService' then it gives an "Object does not match target type." error on loading data.
If I point the 'ODS.TypeName = Person' then it can't find the GetAll() method to load data.
Is it possible to bind the ODS to this model (i.e. separate classes for the method and type)?
Edit: I've double checked Type and Select method names are correct (and fully qualified). I made a separate quick test project to prove ODS works with the above model - it does. The only difference now, is that the broken project is using an Entity defined by EF 4.1 - would that cause a problem?
A: TypeName needs to be set to PersonService in your example. There is no need to provide the ODS with the exact type of object bound to the grid's rows (Person in your example), as neither ASP.NET data binding nor the ODS/grid will really care. Concerning your error, try to fully qualify the service, e.g., My.Namespace.PersonService, and make sure to set SelectMethod on the ODS accordingly.
A: I think you want to create a PersonList class that exposes a list of Person object and which has a method uses PersonService to populate/return a list.
A: enter image description here
Just right click on your project and select "Disable Lightweight Solution Load"
it will work. there is no other issue
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When parsing a MongoDB object (using Mongoose), how come I can't get item elements? IndexedTweets.find(searchParameters, function(err, indexedTweetsResults) {
var chunkSize, count, resultArray, size;
if (err != null) {
return console.log("Error!");
} else {
size = indexedTweetsResults.length;
count = 0;
chunkSize = 100;
resultArray = [];
indexedTweetsResults.forEach(function(tweet) {
console.log(tweet.user);
});
}
});
That's my code. My result looks like:
{ text: 'stuff',
user:
{ display_name: '...',
screen_name: '...'},
}
So why can't I get tweet.user? It just returns undefined.
A: If you are just getting back a string of JSON from mongo, you'll need to call JSON.parse(). If that's not the case then you should provide more code because it's not clear what the issue is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Make Emacs ESS follow R style guide I've been using Emacs/ESS for quite a while, and I'm familiar with Hadley's R style recommendations. I'd like to follow these conventions in ESS, like those nice spaces around operators, space after comma and after if statement, before curly braces, etc.
Did anyone even bothered to follow this style guide at all? IMHO, official style recommendations are quite modest, and they say nothing about the style whatsoever. Google R style guide are too similar with the ones I use when I code in JavaScript, so it's a no-no.
Long story short: is there anyone with (e)LISP skills willing to implement (Hadley's) style guide for ESS?
A: The good point of Hadley's guide is spaceing around operators (except maybe around /)
There is a smart-operator package which implements it for almost every operator.
This is my setup (uncoment operators which you want to use):
(setq smart-operator-mode-map
(let ((keymap (make-sparse-keymap)))
(define-key keymap "=" 'smart-operator-self-insert-command)
;; (define-key keymap "<" 'smart-operator-<)
;; (define-key keymap ">" 'smart-operator->)
;; (define-key keymap "%" 'smart-operator-%)
(define-key keymap "+" 'smart-operator-+)
;; (define-key keymap "-" 'smart-operator--)
;; (define-key keymap "*" 'smart-operator-*)
;; (define-key keymap "/" 'smart-operator-self-insert-command)
(define-key keymap "&" 'smart-operator-&)
(define-key keymap "|" 'smart-operator-self-insert-command)
;; (define-key keymap "!" 'smart-operator-self-insert-command)
;; (define-key keymap ":" 'smart-operator-:)
;; (define-key keymap "?" 'smart-operator-?)
(define-key keymap "," 'smart-operator-,)
;; (define-key keymap "." 'smart-operator-.)
keymap)
"Keymap used my `smart-operator-mode'.")
See also a nice discussion on R styles here.
[edit] I am also using the defacto camelCase style of R code for globals. The underscore-separated names for local variables - it's easy to differentiate.
There is a special subword mode in emacs which redefines all editing and navigation commands to be used on capitalized sub-words
(global-subword-mode)
A: Having the same style preference of the OP, I jumped here and I thank @lionel for your valid suggestions, but I had an issue coming from setting RStudio style in ~/emacs.d/init.el with:
(ess-set-style 'RStudio)
Emacs/ESS refused to apply the style (4-space indent instead of the 2-space, not discussing style here :) ).
My advice for the novice, using the following hook in your ~/emacs.d/init.el:
(add-hook 'find-file-hook 'my-r-style-hook)
(defun my-r-style-hook ()
(when (string-match (file-name-extension buffer-file-name) "[r|R]$")
(ess-set-style 'RStudio)))
will do the trick.
A: I don't write Elisp, and I disagree with Hadley about the stylistic merits of underscores. Moreover, Hadley is still lost in the desert of not using the OneTrueEditor so we can expect no help from him on this on this issue.
But if you are open to follow R Core rather than Hadley, below is what the R Internals manual, section 8. "R Coding Standards" recommends. To me, it is R Core who defines R style first and foremost. Google's and Hadley's styles are nice secondary recommendations.
Anyway, back to Elisp. The following has served we well for many years, and I do like the fact that the basic R behaviour is similar to the Emacs C++ style as I happen to look at code in both modes a lot.
[...]
It is also important that code is written in a way that allows
others to understand it. This is particularly helpful for fixing
problems, and includes using self-descriptive variable names,
commenting the code, and also formatting it properly. The R Core Team
recommends to use a basic indentation of 4 for R and C (and most
likely also Perl) code, and 2 for documentation in Rd format. Emacs
(21 or later) users can implement this indentation style by putting
the following in one of their startup files, and using customization
to set the c-default-style' to"bsd"' and c-basic-offset' to4'.)
;;; ESS
(add-hook 'ess-mode-hook
(lambda ()
(ess-set-style 'C++ 'quiet)
;; Because
;; DEF GNU BSD K&R C++
;; ess-indent-level 2 2 8 5 4
;; ess-continued-statement-offset 2 2 8 5 4
;; ess-brace-offset 0 0 -8 -5 -4
;; ess-arg-function-offset 2 4 0 0 0
;; ess-expression-offset 4 2 8 5 4
;; ess-else-offset 0 0 0 0 0
;; ess-close-brace-offset 0 0 0 0 0
(add-hook 'local-write-file-hooks
(lambda ()
(ess-nuke-trailing-whitespace)))))
(setq ess-nuke-trailing-whitespace-p 'ask)
;; or even
;; (setq ess-nuke-trailing-whitespace-p t)
;;; Perl
(add-hook 'perl-mode-hook
(lambda () (setq perl-indent-level 4)))
(The `GNU' styles for Emacs' C and R modes use a basic indentation of
2, which has been determined not to display the structure clearly
enough when using narrow fonts.)
I think the only additions I regularly make are to follow the last commented-out snippet:
;; or even
(setq ess-nuke-trailing-whitespace-p t)
You can of course turn off the underscore toggle if you really need to code with underscores.
A: With the development version of ESS (to be released in September 2015), just add to your ess-mode-hook:
(ess-set-style 'RStudio)
RStudio also has a 'Vertically align arguments' checkbox that is set by default. If you want to reproduce the behaviour when this setting is unchecked (as in Hadley's code), you'll need to change ess-offset-arguments to prev-line:
(setq ess-offset-arguments 'prev-line)
Please file an issue on https://github.com/emacs-ess/ESS if you find an important discrepancy between ESS and RStudio indentation.
A: One more component of the style guide which hasn't been covered here so far
is indentation when a function runs over multiple lines. The style guide
says to use indentation like
long_function_name <- function(a = "a long argument",
b = "another argument", # X
c = "another long argument") {
# As usual code is indented by two spaces.
}
but using any of the default styles seems to indent line X by some fixed
number of spaces rather than up to the (. The solution is to set
ess-arg-function-offset to some non-number, e.g.
(set 'ess-arg-function-offset t)
This should be placed in a mode hook similar to @Dirk Eddelbuettel's answer. Also it must go after any calls to ess-set-style or it will be overridden.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Live CallStack in Visual Studio 2010 Is it possible to make a 'Live' callstack window? To see the Call Stack as the application runs, automatically getting updated?
This would be great to view what happends under the hood while running my web application.
A: Runtime Flow (developed by me) shows a call stack of a running .NET application updated in real time. You can see all function calls up to the moment in a call stack tree.
A: I doubt it... even if it was available, then the update rate on it would be so fast that you wouldn't be able to see anything. Just put Trace statements in the functions you're interested in.
Trace.WriteLine("Foo::Bar()");
You can view the Trace results in your Output window as you're debugging. If you have the need for more advanced tracing, then use the dotTrace profiler or any other .NET profiler.
A: This would be technically possible but it would be essentially an unusable feature. In a normal running application the call stack changes ... easily thousands of times a second. There is simply no way for the UI to keep up with that kind of throughput in a meaningful way. If it simply painted every version on the screen it would just appear as a blur to you and bde useless.
A: Every single method call? There might be hundreds or thousands, or hundreds of thousands of call stack changes per second. You can't do it in Visual Studio 2010. You can suspend a Thread object and get a stack trace from that and output but performance will be terrible (unusable).
It sounds like you might want a profiler instead.
A: I have two suggestions:
*
*There's a new feature in Visual studio 16.9 that is called "New Dynamic Instrumentation Profiling for .NET"
There's some details here: https://devblogs.microsoft.com/visualstudio/new-dynamic-instrumentation-profiling/
*There is this free Profiler called "codetack" which helps
analyzing code execution. If I remember it correctly, it can show
real-time analysis. https://www.getcodetrack.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: ASP.net Menu CSS parent node selected style without URL I know this has been asked countless times before, and they all seem to be resolved by this approach, Although I can't seem to get it to work for my situation.
I'm moving away from CSSFriendly as it is not supported in .net 4 (unless I render it as 3.5), and I'm close to mimicing the functionality using the default CSS styling, although I'm stuck on one issue - Parent selected.
I've read a few solutions on SO and .net forums, although I still can't get it to work for my situation, here is my predicment:
I have an asp.net 4 Menu in a masterpage together with a SiteMapDataSource which loads from a site map. When clicking on the child node, I want its parents CSS to change as well.
Here is a simplified version of my sitemap
<siteMapNode Parent - hidden/no url>
<siteMapNode Home - url="~/" >
<siteMapNode Item - no url >
<siteMapNode Item-child1 - url = "~/child"/>
<siteMapNode Item-child2 - url = "~/child2"/>
</siteMapNode>
</siteMapNode>
All the CSS styling works fine, however I have a horizontal menu which before the ul li css would change as the CSS attribute was "selected". However now, the .net 4 implementation only selects the menu item you select.
I've tried to manually select the parent on the MenuItemDataBound hook, although this does 2 things:
*
*Applys "selected" to the 'a' tag (I need to style the ul li)
*Deselects the sub menu item (I can't have both items selected)
Heres the CSS:
.elfabMenu{position:relative;}
.elfabMenu ul li a.popout{padding:0px !important; background-image:none !important;}
.elfabMenu ul{display:block;width:961px!important;margin:0;padding:0}
.elfabMenu ul li{font-family:Arial,Helvetica,sans-serif;font-size:13.5px;background:url(../images/menu_sep.png) no-repeat scroll left bottom transparent;text-decoration:none;color:#000;line-height:38px;padding:10px 23px 0}
.elfabMenu ul li li{background-image:none!important;width:230px;border-bottom:1px solid #000;border-top:1px solid #121212;padding:0;background-color:#0E0E0E;color:#ffffff}
.elfabMenu ul li li a{color:#ffffff; padding:5px 0 5px 15px}
.elfabMenu ul li li:hover{background-color:#000!important}
.elfabMenu ul li li a.selected{background-color:#000!important}
.elfabMenu ul li a.selected{background-image:none!important}
.elfabMenu ul li li.has-popup{background:url(../images/primary-menu-current-children.gif) no-repeat scroll 210px 20px #0E0E0E !important}
.elfabMenu ul li ul li ul.level3 {margin-top:-1px!important}
Heres the databound method:
void ElfabMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
if (SiteMap.CurrentNode != null)
{
if (e.Item.Selected == true)
{
e.Item.Selected = true;
e.Item.Parent.Selectable = true;
e.Item.Parent.Selected = true;
}
}
}
Hopefully I'm just overlooking something here, but its driving me mad! Would very much appretiate someones help.
Cheers,
Rocky
Update
By design the ASP.net menu can only have one menuitem selected at a time. This is always applied to the <a> tag of the menuitem list. I've changed the menu to incorporate this design, and decided that having the menu parent node selected and not its children is good enough, as I looks like a javascript/page rendering hack is required.
Instead what I do is find the current selected node, use recursion to find the parent and select it. Heres the code for anyone wanting to do the same:
protected void ElfabMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
if (SiteMap.CurrentNode != null)
{
if (e.Item.Selected)
{
MenuItem parent = MenuParent_Recursion(e.Item);
parent.Selectable = true;
parent.Selected = true;
}
}
}
static MenuItem MenuParent_Recursion(MenuItem item)
{
if (item.Parent == null)
{
return item;
}
return MenuParent_Recursion(item.Parent);
}
A: Slight modification of this worked for me.
if (SiteMap.CurrentNode != null)
{
if (e.Item.Selected)
{
if (e.Item.Depth == 1)
{
e.Item.Parent.Selectable = true;
e.Item.Parent.Selected = true;
}
if (e.Item.Depth == 2)
{
e.Item.Parent.Parent.Selectable = true;
e.Item.Parent.Parent.Selected = true;
}
if (e.Item.Depth == 3)
{
e.Item.Parent.Parent.Parent.Selectable = true;
e.Item.Parent.Parent.Parent.Selected = true;
}
}
}
Not sure why my depths were one lower, maybe because I have ShowStartingNode="False" on my site map.
A: This probably isn't the real issue, but it seems that even if you get the selected class onto the li, you don't yet have a css declaration (eg li.selected {...}) that does anything with it.
A: Answering my own question - By design the ASP.net menu can only have one menuitem selected at a time. This is always applied to the tag of the menuitem list. I've changed the menu to incorporate this design, and decided that having the menu parent node selected and not its children is good enough, as I looks like a javascript/page rendering hack is required.
Instead what I do is find the current selected node, use recursion to find the parent and select it. Heres the code for anyone wanting to do the same:
protected void ElfabMenu_MenuItemDataBound(object sender, MenuEventArgs e)
{
if (SiteMap.CurrentNode != null)
{
if (e.Item.Selected)
{
MenuItem parent = MenuParent_Recursion(e.Item);
parent.Selectable = true;
parent.Selected = true;
}
}
}
static MenuItem MenuParent_Recursion(MenuItem item)
{
if (item.Parent == null)
{
return item;
}
return MenuParent_Recursion(item.Parent);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: RDLC rendered to PDF ignores Strikethrough formatting So, I have a local .rdlc file with some text formatted using strikethrough formatting. My issue is quite simple to explain, but I do not know if it is just a limitation of PDF, or a bug with the .rdlc exporting to PDF.
When I write this code:
var localReport = new LocalReport();
...
byte[] pdf = localReport.Render("PDF");
System.IO.File.WriteAllBytes("MyReport.pdf", pdf);
None of the strike-through formatted text transfers over the the .pdf file properly.
If instead, I export to Word using .Render("Word"), the strikethrough does work on the .doc format. So, I know it isn't a problem with the .rdlc report itself.
Has anyone encountered this? Any solutions or workarounds?
A: I found this: http://social.msdn.microsoft.com/Forums/en-US/sqlreportingservices/thread/b35ca474-046d-4a38-a765-6c38c3d33105/
which suggests that missing strikethrough in PDFs was a known limitation. (But as mentioned in comments to the question, I couldn't reproduce with 2008r2.)
The two workarounds given there look painful.
(A) finding a font which itself as the strikethrough built into each
glyph/character. (B) trying to mimic a strikethrough using a line
report item. Note that for (B) overlapping items are supported only in
PDF, Print & TIFF formats.
I suppose if it were mine, I would play around with option B if the text is a small amount. Also, it may be worth test some of the html passthrough enabled when a placeholder is set to render as HTML. Maybe using a strikethrough style there would work?
A: While exporting RDLC report on word, I faced this issue. So while fetching data I replaced style for Strike formatting with strike tag from HTML and it worked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Blackberry Network connection Trying to connect via Wi-Fi and I have an issue with the OS6 cd variable is null but it works on OS5
This is the url Strng: https://api3.popfax.com/index.php?service=Popfax;interface=wifi;interface=wifi
public ServiceConnectionBlackBerry(String s) throws IOException {
ConnectionFactory cf = new ConnectionFactory();
ConnectionDescriptor cd = cf.getConnection(s);
if (cd!=null){
connection = (HttpConnection) cd.getConnection();
}else {
System.out.println("Strng: "+s);}
}
can someone help please.
A: When using ConnectionFactory you should not append any connection information to your URL. So instead you should just pass https://api3.popfax.com/index.php?service=Popfax to your method.
A: Open a Wi-Fi HTTPS connection may help you.
thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem with like it button and public permissions I'm a web developer and i'm having problems using the "like it" button
I put the buttom on my site as a counter of votes of a special contest. People can only click the like buttom if they are fan of my Facebook page.
The problem is that people can't vote if they haven't public permissions on his facebook, cause i can't know if they are or not fans of my page.
Is there a solution?
A: if you rely on information that you are not certain that you can obtain then sadly there is no solution.
Since what you are doing is beyond a simple like button What you may want to try is open a facebook application and request from your users the user_likes permission. You can read more about it here. I have photo albums on the "highest privacy setting" - only me. Yet when I request a list of my photo albums through one of my applications (with the required permissions of course) I get back ALL of my albums.. This might have been a temporary issue that was solved - but in any case - I saw this behavior and I thought it might be relevant to this post :)
Additionally you should look at the Promotions Guidelines specifically this point :
You must not use Facebook features or functionality as a promotion’s registration or entry mechanism. For example, the act of liking a Page or checking in to a Place cannot automatically register or enter a promotion participant.
I had some problems with facebook on this issue - you are not allowed to require someone to "like" a page in order to participate in an activity that is not directly connected to that page.
From what I understand you are requireing people to like your page on facebook beofore voting on your site... If this IS the case then facebook might very well start taking action and closing your page/app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FieldError on ManyToMany after upgrading to Django 1.3 Just been updating to Django 1.3 and come across an odd error. I'm getting the following error from some code which works with version 1.2.7.
FieldError: Cannot resolve keyword 'email_config_set' into field. Choices are: id, name, site, type
The odd thing being email_config_set is a related name for a ManyToMany field. I'm not sure why django is trying to resolve it into a field.
The error occurs deep inside django:
Traceback (most recent call last):
File "./core/driver.py", line 268, in run
self.init_norm()
File "./driver/emailevent/background.py", line 130, in init_norm
self.load_config()
File "./driver/emailevent/background.py", line 71, in load_config
events = list(config.events.select_related())
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/manager.py", line 168, in select_related
return self.get_query_set().select_related(*args, **kwargs)
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/fields/related.py", line 497, in get_query_set
return superclass.get_query_set(self).using(db)._next_is_sticky().filter(**(self.core_filters))
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/query.py", line 550, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/query.py", line 568, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/sql/query.py", line 1194, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/sql/query.py", line 1069, in add_filter
negate=negate, process_extras=process_extras)
File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/sql/query.py", line 1260, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'email_config_set' into field. Choices are: id, name, site, type
Any pointers or tips would be welcome.
A: The problem in this case was due to dynamic models, and their creation order. More specifically, some models which were dynamically created after others, were not defined when the _meta caches were filled, and therefore lead to errors. Clearing the caches or changing the creation order resolves this problem.
See also https://groups.google.com/d/msg/django-users/RJlV5_ribZk/P6tv4QlJN4EJ
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DataContract with inheritance? I have a class with a list of objects that is serialized and deserialized:
[DataContract]
public class Manager
{
[DataMember]
public BigBase[] enemies;
}
The class with subclasses:
[DataContract]
[KnownType(typeof(Medium))]
[KnownType(typeof(Small))]
public class BigBase
{
[DataMember]
public bool isMoving;
}
[DataContract]
public class Medium : BigBase
{
}
[DataContract]
public class Small: BigBase
{
}
Now whats strange when deserializing the enemies array will contain correctly deserialized BigBase classes but each Medium and Small class doesnt have the correct value for isMoving.
A: You need to put KnownType attribute on Manager:
[DataContract]
[KnownType(typeof(Medium))]
[KnownType(typeof(Small))]
public class Manager
{
[DataMember]
public BigBase[] enemies;
}
Because it's the Manager which has an array of BigBase whose elements might be the derived classes as well. So the DataContractSerializer will know what to expect from the array when serializing and deserializing Manager object (and it's all DataMember).
A: [DataContract]
public class Medium : BigBase
{
[DataMember]
public string UpgradedName;
}
I dont see that in this test Code. I think your serialization code is wrong.
Sample calls:
Manager test = new Manager();
Medium medium = new Medium() {isMoving = true,Name = "medium", UpgradedName = "mediaum name"};
//some items in array
test.enemies = new BigBase[] {medium,new Small{isMoving = false},new Small{isMoving = true}, new BigBase {Name = "bigbase", isMoving = true}, new BigBase {Name = "bigbase2", isMoving = true}, new BigBase {Name = "bigbase3", isMoving = true}} ;
DataContractSerializer serializer = new DataContractSerializer(typeof (Manager));
FileStream writer = new FileStream("test123.txt", FileMode.Create);
serializer.WriteObject(writer, test);
writer.Close();
writer = new FileStream("test123.txt", FileMode.Open);
Manager deserializedmanager = serializer.ReadObject(writer) as Manager;
//verify serialized object
Console.WriteLine("medium object:"+ (deserializedmanager.enemies[0] as Medium).UpgradedName);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Is it possible to read cookies of a visitor? AdSense use javascript to catch the keywords of current page to display relevant ads. But I was recently noticed that it will show ads related to my browsing history too. It seems that the javascript code can read my cookie (in general I mean, e.g. list of domains visited) to display relevant ads.
Is it practically possible to read cookies of a visitor?
A: No, it isn't possible to do so directly due to the same origin policy. (If it were possible, then you could make a page that stole the session of anyone on any domain!)
However, many websites include code from ad providers (read Google) on their page -- so that Google knows that you have visited website X because website X allows Google code to run when someone visits it. When you later visit website Y and it asks Google to display some ads on its behalf, what happens is no mystery.
Google knows all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery show function applies inline-block sometimes and block others? I have a script right now where a certain element is shown and hidden often (similar to a tip).
I have noticed that sometimes the inline style says 'display: inline-block' and sometimes it says 'display: block'. The documentation as far as I can see only notes that it will use 'block'.
What appears to be happening, is it's using display: inline-block when the positioning is relative/static and is using display: block when the element is position: fixed but it sets this when the page is loaded and keeps it.
Therefore I have different behaviour if the page is loaded normally compared to if it's loaded while scrolled partway down, because a function applies a style with position: fixed when it's not in view (so that it will always be visible)
$(function() {
checkUrlEdit();
$(window).scroll(function () {
checkUrlEdit();
});
$('a').hover(
function(){
if(!editObj && !imageUpload){
$('#urlEdit').show();
$('#urlEdit').val($(this).attr('href'));}
},
function(){
if(!editObj && !imageUpload){
$('#urlEdit').hide();}
}
);
});
function checkUrlEdit(){
if (!isScrolledIntoView('#urlEditor')) {
$('#urlEdit').addClass('floating');
} else {
$('#urlEdit').removeClass('floating');
}
}
function isScrolledIntoView(node)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var nodeTop = $(node).offset().top;
var nodeBottom = nodeTop + $(node).height();
return ((nodeBottom >= docViewTop) && (nodeTop <= docViewBottom)
&& (nodeBottom <= docViewBottom) && (nodeTop >= docViewTop) );
}
CSS:
#urlEdit.floating {
position: fixed;
top: 10px;
z-index: 99;
}
A: If you don't like the way this is functioning, you can always write your own show/hide plugins with your own custom logic applied. Put this code in your JavaScript:
$.fn.extend({
myShow: function() {
return this.css('display','block');
},
myHide: function() {
return this.css('display', 'none');
}
});
A: straight from from the jquery documentation:
With no parameters, the .show() method is the simplest way to display
an element:
$('.target').show();
The matched elements will be revealed immediately, with no animation.
This is roughly equivalent to calling .css('display', 'block'), except
that the display property is restored to whatever it was initially. If
an element has a display value of inline, then is hidden and shown, it
will once again be displayed inline.
the best way in this situation is, imo, to create a class, a corresponding css rule, and use addClass/removeClass instead of show/hide.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: access 2007 what is the max char for list box My Access 2007 app uses SQL as the back end. On a form we have list boxes. List boxes will not display the data if the data type is varchar (max). We are using 255, but this is not enough. Could someone tell me if there is a way to show more char's in a list box than 255.
Thanks
A: AFAIK, there is no way to make a list box display more than 255 characters.
As a workaround, you could display the text in a text box control. A text box can hold up to 65,535 characters. (on the Access Blog: Access 2007 Limits)
Include a primary key as the bound column in your list box's rowsource, and display as much of the text as is reasonable. Then, in the form's On Current event and the list box's After Update event, retrieve the full text string associated with the list box's current primary key value and load that string into the text box.
You can use the DLookup Function for this.
Me.BigTextBox = DLookup("text_field", "YourTable", _
"pkey_field = " & Me.ListBoxName)
If the pkey_field is text rather than numeric data type, enclose the literal value with quote marks.
Me.BigTextBox = DLookup("text_field", "YourTable", _
"pkey_field = '" & Me.ListBoxName & "'")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CreateCompatibleBitmap and CreateDIBSection (Memory DC's) from what I've read here it seems that most of the Windows GDI functions are accelerated. So for instance a call to BitBlt or AlphaBlend uses hardware acceleration if available. It also mentions that the contents of a window are kept only in video memory. Now this is all good and true for a window DC, but how can I use a memory DC that resides in video card memory? And once we've accomplished that how to obtain direct access to the pixels, I think that would involve 1. temporary copying the data to system memory 2. alter the pixel data 3. copy back to video memory.
I've tried two approaches, both allocate system memory as I can see in the task manager...
*
*CreateCompatibleBitmap
HDC hDC = GetDC(NULL);
m_hDC = CreateCompatibleDC(hDC);
m_hBmp = CreateCompatibleBitmap(hDC, cx, cy);
ReleaseDC(NULL, hDC);
m_hOldBmp = (HBITMAP)SelectObject(m_hDC, m_hBmp);
and then call to obtain the bits
GetBitmapBits(...)
according to various comments this should indeed create the compatible bitmap in video memory, but why can I still see an increase in system memory (even when I don't call GetBitmapBits)?
*CreateDIBSection
HDC hDC = GetDC(NULL);
m_hDC = CreateCompatibleDC(hDC);
BITMAPINFO bmi;
memset(&bmi, 0, sizeof(BITMAPINFO));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biWidth = cx;
bmi.bmiHeader.biHeight = -cy; // top-down
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biCompression = BI_RGB;
m_hBmp = CreateDIBSection(hDC, &bmi, DIB_RGB_COLORS, (void**)&m_pBits, NULL, NULL);
ReleaseDC(NULL, hDC);
m_hOldBmp = (HBITMAP)SelectObject(m_hDC, m_hBmp);
in this case we receive the pointer to the bits immediately (m_pBits) so it's obvious that these reside in system memory...
Or is it a copy that is kept in system memory for both methods? But if I change the bits in system memory a call to BitBlt would still have to check/copy from system memory again... not very optimized IMHO.
EDIT: I've also tried creating memory DC's by using the BeginBufferedPaint and GetBufferedPaintBits. It allocates system memory as well, so in that respect I suppose it's just a wrapper for the above methods but caches the DC's so a next call doesn't necessarily has to recreate a memory DC. See Raymond Chen's article.
EDIT #2: I guess the actual question is: Am I doing the memory DC creation correct in method 1 or 2 to get hardware accelerated GDI operations? To me it all seems fast, and both methods provide the same speed too, so there's not really a way to check it...
A: Memory DCs are not created on a device. They are designed to put GDI output into memory.
From Memory Device Contexts on MSDN:
To enable applications to place output in memory rather than sending
it to an actual device, use a special device context for bitmap
operations called a memory device context. A memory DC enables the
system to treat a portion of memory as a virtual device.
If you want hardware accelerated 2d graphics, you should consider using Direct2D.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Adding/Deleting Data with Many-to-Many Relationship I'm trying to use Entity Framework 4.0 to add and remove records with a many-to-many relationship. I've scoured the web but am just not finding a meaningful example.
As an example, let's say I have a Drivers and Vehicles table with a junction table VehicleDrivers.
Drivers
*
*DriverID
*...
Vehicles
*
*VehicleID
*...
VehicleDrivers
*
*DriverID
*VehicleID
My questions are:
*
*How would I write EF statements to add a new vehicle and related driver?
*How would I write EF statements to delete an existing vehicle and any related drivers?
Thanks for any tips.
A: Something like this:
How would I write EF statements to add a new vehicle and related
driver?
For existing driver:
using (var context = new MyContext(...))
{
var newVehicle = new Vehicle { ... };
var existingDriver = context.Drivers.First(d => d.Name == "Jim");
newVehicle.Drivers.Add(existingDriver);
context.Vehicles.AddObject(newVehicle);
context.SaveChanges();
}
For new driver:
using (var context = new MyContext(...))
{
var newVehicle = new Vehicle { ... };
var newDriver = new Driver { ... };
newVehicle.Drivers.Add(newDriver);
context.Vehicles.AddObject(newVehicle);
context.SaveChanges();
}
How would I write EF statements to delete an existing vehicle and any
related drivers?
using (var context = new MyContext(...))
{
var existingVehicle = context.Vehicles.First(v => v.Name == "Ford");
context.Vehicles.DeleteObject(existingVehicle);
context.SaveChanges();
}
Nothing more to do here because the related entries in the join table with all drivers linked to the deleted vehicle will be deleted as well due to enabled cascading delete in the database.
Edit
If you want to delete the drivers as well (and not only the links) in a many-to-many relationship you need to check first if the driver isn't linked to another vehicle:
using (var context = new MyContext(...))
{
var existingVehicle = context.Vehicles.Include("Drivers")
.First(v => v.Name == "Ford");
foreach(var driver in existingVehicle.Drivers.ToList())
{
if (!context.Drivers.Any(d => d.DriverId == driver.DriverId
&& d.Vehicles.Any(v => v.VehicleId != existingVehicle.VehicleId)))
context.Drivers.DeleteObject(driver);
}
context.Vehicles.DeleteObject(existingVehicle);
context.SaveChanges();
}
A: What I usually do is use the key field and place it into the object I'm saving. This does not work well when you are modifying several new objects at the same time however.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Apache Reverse proxy with proxy authentication I have the following setup
Box A (192.168.8.180 - running apache reverse proxy)
Box B (192.168.8.100:808 - Proxy server to connect to internet)
Due to internal reasons, The IP of box A is redirected to http://xyz.mydomain.com/. The reverse proxy uses the proxy running in Box B to connect to internet.
The setup works fine when the proxy does not need any authentication. But When the proxy at Box B needs authentication, all my request to the reverse proxy fails with the following error.
<h1>Unauthorized ...</h1>
<h2>IP Address: 192.168.8.180:1799<br>
MAC Address: <br>
Server Time: 2011-09-21 20:32:16<br>
Auth Result: </h2>
Here is my apache configuration
<VirtualHost *:80>
ServerName xyz.mydomain.com
ProxyRequests Off
ProxyPreserveHost Off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyRemote * http://192.168.8.100:808/
ProxyPass / http://xyz.mydomain.com/
ProxyPassReverse / http://xyz.mydomain.com/
RequestHeader set Authorization "Basic cGFuZGlhbjpwYW5kaWFu"
<Location />
Order allow,deny
Allow from all
</Location>
ErrorLog "logs/myerror.log"
CustomLog "logs/myaccess.log" common
</VirtualHost>
Any ideas?
access log says the following
127.0.0.1 - - [21/Sep/2011:20:24:55 +0530] "GET / HTTP/1.1" 407 142
127.0.0.1 - - [21/Sep/2011:20:24:57 +0530] "GET / HTTP/1.1" 407 142
192.168.8.180 - - [21/Sep/2011:20:25:33 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:32:07 +0530] "GET / HTTP/1.1" 407 142
192.168.8.180 - - [21/Sep/2011:20:32:14 +0530] "GET / HTTP/1.1" 407 142
192.168.8.180 - - [21/Sep/2011:20:32:15 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:33:58 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:35:03 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:35:16 +0530] "GET / HTTP/1.1" 407 142
192.168.8.227 - - [21/Sep/2011:20:35:24 +0530] "GET / HTTP/1.1" 407 142
The proxy credentials are correct. verified with browser.
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Need help resizing this HTML frame Ok so I've NEVER worked with frames before but a higher power has forced my hand this time.
What I need to be able to do is resize the 'footer.html' frame within this template.
<html>
<head>
<title>Store Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<frameset cols="*,1034,*" frameborder="NO" border="0" framespacing="0">
<frame name="sideblanks" scrolling="NO" src="blank_left.html">
<frameset rows="135,*,25" frameborder="NO" border="0" framespacing="0">
<frame name="top" scrolling="NO" noresize src="top_nav.html" >
<frameset cols="200,*" frameborder="NO" border="0" framespacing="0">
<frame name="meny" noresize scrolling="NO" src="menu_1.html">
<frame name="content" src="content.html">
</frameset>
<frame name="chart" scrolling="NO" noresize src="footer.html">
</frameset>
<frame name="sideblanks" scrolling="NO" src="blank_right.html">
</frameset>
<noframes>
<body bgcolor="#FFFFFF" text="#000000">
</body>
</noframes>
</html>
I feel like a complete novice again. I don't like it, I'm scared.
Any help would be great.
A: Adjust the numeric values here:
<frameset rows="135,*,25" frameborder="NO" border="0" framespacing="0">
A: you have used "rows" and "columns" you can set the height of the frame with rows or with CSS.
if you need to dynamically alter the height of the frame you might be able to do this with javascript or JQuery but you have to reference it as parent. to make sure you are in the right window.
when are you wanting the height of the frame to change?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use SIGNAL and SLOT without deriving from QObject? OR other way to formulate my question (though it didn't solve my problem): 'QObject::QObject' cannot access private member declared in class 'QObject'
I need SIGNALs and SLOTS functionality in my class, but I assume it is not possible without to derive from QObject?
class MyClass
{
signals:
importantSignal();
public slots:
importantSlot();
};
The Problem seems to be that I need to derive from QObject to use signals and slots ... but I need the default contructor of MyClass. But I can't construct them because of the following feature of QObject:
No Copy Constructor or Assignment Operator.
I tried a lot ...
So my shoul Class look like that:
#include <QObject>
class MyClass: public QObject
{
Q_OBJECT
public:
explicit MyClass(QObject *parent = 0); //autogenerated by qtcreator for QObject derived class
MyClass(const MyClass * other);
signals:
importantSignal();
public slots:
importantSlot();
};
I need the default contructor of MyClass.
So is there any possibility do avoid the "'QObject::QObject' cannot access private member declared in class 'QObject'" error?
Or as an alternative is there any possibility to use signals and slots without QObject?
I'm glad for any advice.
A: If you want to implement event-driven functionality using a signals/slots pattern, but do not want to work inside the confines of Qt (i.e., you want to use your class inside of STL containers, etc. that require copy-constructors), I would suggest using Boost::signal.
Otherwise, no, you can't possibly do what you're wanting without deriving from QObject since that base class is what handles the Qt runtime signals/slots functionality.
A: You cannot use Qt's signal/slot mechanisms without using QObject/Q_OBJECT.
You theoretically could create a dummy QObject and compose it into your class. The dummy would then forward the slot calls to your class. You will probably run in to issues with lifetime management, for the reasons that Liz has described in her comment.
A: Since Qt5 you can just connect to any function
connect(&timer, &QTimer::finished,
&instanceOfMyClass, &MyClass::fancyMemberFunction);
A: If you want a copyable object with QObject features you need membership (by pointer) rather than inheritence.
You can derive a class Handler from QObject where Handler's slots call SomeInterface virtual functions on its parent.
struct NonQObjectHandler {
virtual ~ NonQObjectHandler () {}
virtual void receive (int, float) = 0;
};
class Handler : public NonQObjectHandler {
struct Receiver;
std :: unique_ptr <Receiver> m_receiver;
void receive (int, float); // NonQObjectHandler
public:
Handler ();
Handler (const Handler &); // This is what you're really after
};
class Handler :: Receiver : public QObject {
Q_OBJECT
private:
NonQObjectHandler * m_handler;
private slots:
void receive (int, float); // Calls m_handler's receive
public:
Receiver (NonQObjectHandler *);
};
Handler :: Handler ()
: m_receiver (new Receiver (this))
{
}
Handler :: Handler (const Handler & old)
: m_receiver (new Receiver (this))
{
// Copy over any extra state variables also, but
// Receiver is created anew.
}
Handler :: Receiver :: Receiver (NonQObjectHandler * h)
: m_handler (h)
{
connect (foo, SIGNAL (bar (int, float)), this, SLOT (receive (int, float)));
}
void Handler :: Receiver :: receive (int i, float f)
{
m_handler -> receive (i, f);
}
A: In Qt5, you use QObject::connect to connect signal with slot:
/*
QMetaObject::Connection QObject::connect(
const QObject *sender,
const char *signal,
const char *method,
Qt::ConnectionType type = Qt::AutoConnection) const;
*/
#include <QApplication>
#include <QDebug>
#include <QLineEdit>
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
QLineEdit lnedit;
// connect signal `QLineEdit::textChanged` with slot `lambda function`
QObject::connect(&lnedit, &QLineEdit::textChanged, [&](){qDebug()<<lnedit.text()<<endl;});
lnedit.show();
return app.exec();
}
The result:
A: Just because QObject is not copyable doesn't mean that you have to copy it when your class is copied, or assigned to, etc. Specifically, all you need to do is to insulate your class from QObject's copy and assignment operators (because they are deleted).
Typically, you'd factor out the "copyable non-copyable QObject" into a separate class:
// main.cpp
#include <QObject>
#include <QVariant>
class CopyableQObject : public QObject
{
protected:
explicit CopyableQObject(QObject* parent = nullptr) : QObject(parent) {}
CopyableQObject(const CopyableQObject& other) { initFrom(other); }
CopyableQObject(CopyableQObject&& other) { initFrom(other); }
CopyableQObject& operator=(const CopyableQObject& other)
{
return initFrom(other), *this;
}
CopyableQObject& operator=(CopyableQObject&& other)
{
return initFrom(other), *this;
}
private:
void initFrom(const CopyableQObject& other)
{
setParent(other.parent());
setObjectName(other.objectName());
}
void initFrom(CopyableQObject& other)
{
initFrom(const_cast<const CopyableQObject&>(other));
for (QObject* child : other.children())
child->setParent( this );
for (auto& name : other.dynamicPropertyNames())
setProperty(name, other.property(name));
}
};
You can copy whatever attributes you desire between the QObject instances. Above, the parent and object name are copied. Furthermore, when moving from another object, its children are reparented, and dynamic property names are transferred as well.
Now the CopyableQObject adapter implements all the constructors that will allow derived classes to be copy-constructible, copy-assignable, move-constructible and move-assignable.
All your class needs to do is derive from the adapter class above:
class MyClass : public CopyableQObject
{
Q_OBJECT
public:
Q_SIGNAL void signal1();
Q_SIGNAL void signal2();
};
We can test that it works:
int main()
{
int counter = 0;
MyClass obj1;
MyClass obj2;
Q_SET_OBJECT_NAME(obj1);
QObject::connect(&obj1, &MyClass::signal1, [&]{ counter += 0x1; });
QObject::connect(&obj1, &MyClass::signal2, [&]{ counter += 0x10; });
QObject::connect(&obj2, &MyClass::signal1, [&]{ counter += 0x100; });
QObject::connect(&obj2, &MyClass::signal2, [&]{ counter += 0x1000; });
Q_ASSERT(counter == 0);
emit obj1.signal1();
emit obj1.signal2();
Q_ASSERT(counter == 0x11);
QObject obj3(&obj1);
Q_ASSERT(obj3.parent() == &obj1);
const auto name1 = obj1.objectName();
obj2 = std::move(obj1);
Q_ASSERT(obj3.parent() == &obj2);
Q_ASSERT(obj2.objectName() == name1);
emit obj2.signal1();
emit obj2.signal2();
Q_ASSERT(counter == 0x1111);
}
#include "main.moc"
This concludes the complete, compileable example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Zend_Controller_Router_Route_Regex not working I'm trying to use the Zend_Controller_Router_Route_Regex in an application but it doesn't seem to be working at all.
I've set up a very basic instance:
$route = new Zend_Controller_Router_Route_Regex(
'/developer/test/(d+)',
array('controller' => 'developer', 'action' => 'module','module'=>'topic')
);
$router->addRoute('apiModule2', $route);
and the corresponding action:
public function moduleAction()
{
$this->view->module = 'topic';
}
However, every time I visit localhost/developer/test/1, I get a No Route Matched exception.
I believe this is all set up properly because if I use the same exact code changing only Zend_Controller_Router_Route_Regex to Zend_Controller_Router_route and the match url to match against to 'developer/test/1' it all works perfectly.
Any ideas what could be going on?
Thanks!
A: The correct route to match
http://localhost/developer/test/1
is
$route = new Zend_Controller_Router_Route_Regex(
'developer/test/(\d+)',
array('controller' => 'developer', 'action' => 'module','module'=>'topic')
);
You should not have leading slash(before the developer) and d+ should be \d+.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Highchart plot points are being displayed incorrectly I've never had this happen before and I'm at a loss as to why this is happening. As you can see, even though point A's datapoints is lower then B's, it is appearing above it(first screen shot). What's weird is that when I hide line B (2nd screen shot), line A correctly moves to the right position.
I put together a jsfiddle to demonstrate this issue:
http://jsfiddle.net/qwfZ9/1813/
And the code below:
var chart = new Highcharts.Chart({
chart:{
renderTo:"ChartArea",
defaultSeriesType:"line",
zoomType:"x",
plotBackgroundColor:"#c8c8c8",
backgroundColor:"#d5d5d5"
},
title:{
text:"TEST"
},
series:[{
name:"A",
data:[21,21,21,21,23,23,26,24,24,24,24,26,26,21,19,19,19,23,23,23,21,22,22,22,21,16],
pointStart:1314316800000,
pointInterval:86400000,
stack:0,
type:"line",
multiplier:1,
dashStyle:"solid",
color:"#AA4643"
},{
name:"B",
data:[51,51,51,51,52,53,50,47,47,47,47,46,46,42,41,41,41,67,65,66,50,53,52,53,64,59],
pointStart:1314316800000,
pointInterval:86400000,
stack:0,
type:"line",
multiplier:1,
dashStyle:"solid",
color:"#89A54E"}],
plotOptions:{
series:{
stacking:"normal",
borderColor:"black",
shadow:false,
borderWidth:0},
area:{
stacking:"normal",
shadow:false,
fillOpacity:0}},
LastUpdated:0,
colors:["#000000"],
yAxis:{
title:{
text:"Test Counts"
},
labels:{
rotation:0,
align:"right"
},
plotOptions:[{color:"#000000",
width:2,
value:0,
id:"plotline-1"}],
startOnTick:true,
showFirstLabel:true,
stackLabels:{
enabled:true,
style:{
color:"black"}},
min:0,
max:100},
xAxis:{
title:{
text:"Time"},
type:"datetime",
maxZoom:86400000,
tickInterval:86400000,
labels:{
rotation:-40,
align:"right",}},
credits:{
enabled:false},
ZoomTypeChanger:null,
yExtreme:null});
A: Removing stacking:"normal" from your series value for plotOptions seems to fix the issue:
plotOptions:{
series:{
// stacking:"normal",
borderColor:"black",
shadow:false,
borderWidth:0},
area:{
stacking:"normal",
shadow:false,
fillOpacity:0}},
You may want to file a bug report if the documentation does not suggest that there is some reason for the shift.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: dataSize({}) for mongodb mongomapper and rails im trying to get the size of a single collection, fs.chunks, but cant seem to run the command successfully.
in console, this is what I need:
db.fs.chunks.dataSize({})
in Rails im trying stuff like:
= MongoMapper.database.collection('fs.chunks').dataSize({})
= MongoMapper.database.collection('fs.chunks').runCommand('dataSize({})')
any advice is appreciated.
A: Does MongoMapper.database.collection('fs.chunks').stats give you the information you want?
{
"ns" => "app-test.fs.chunks",
"count" => 6,
"size" => 4160,
"avgObjSize" => 693.333333333333,
"storageSize" => 8192,
"numExtents" => 1,
"nindexes" => 1,
"lastExtentSize" => 8192,
"paddingFactor" => 1.58,
"flags" => 1,
"totalIndexSize" => 8192,
"indexSizes" => { "_id_" => 8192 },
"ok" => 1.0
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to fix square boxes in pdf? while going through my pdf for regular expressions, and in many places i see that some characters are replaced by square boxes which is some ASCII code
Is there any way i can fix this?
i have checked this link
http://www.tableausoftware.com/support/knowledge-base/square-boxes
http://acrobatusers.com/tutorials/text-matching-regular-expressions
and others but did not find any solution... aatched is how the square boxes look...
A: As stema said, this has nothing to do with regular expressions.
Neither is it about some "pdf escape sequences", as PDF uses binary safe text encodings.
These square blocks are usually shown in place of some characters that doesn't have a representation in the chosen font. Often, it happens that the typesetting software replaces some quotes or other characters with a 'nicer' Unicode alternative; but the font doesn't have those characters.
You could try to copy/paste the text from the PDF into some other document and replace the font, or even use some PDF editing tools (enfocus PitStop is one of the most popular; it's cheap but not free) to replace the font with another more complete.
A: At first, this has nothing to do with regex, except that the document you are writing is about regular expressions.
I assume, the sequence that is replaced by a square is \s, isn't it?
I think the problem here is that some regular expression shortcuts are interpreted as escape sequences in the pdf creation process and therefor not printed literally.
You don't write how you create your pdf, but I would assume that will be OK when you escape the backslashes, when you want to print them literally.
So when you want to see a \s in the pdf, type \\s in your source format. (If you have somewhere a escaped backslash you want to print like \\ then write \\\\).
A: Javier's answer is nearly complete. But let me add this:
You'll have a small chance to get Acrobat Reader display the square boxes using a "substitute" font by toggling a certain setting in its application preferences.
IIRC, the setting is called 'Use local fonts'. You can usually find it in the Page display section of the preferences settings, but over the different releases Adobe kept adding, removing or re-locating different settings...
Background info: If you have NOT enabled Use local fonts, then you require the Reader to only use the PDF-embedded fonts for displaying all text. In case the font is embedded, but misses some required glyphs, enabling said setting may find the required font on your system to render the text, or the Reader may use its built-in Multiple Master fonts which will try to fake the look of the original glyph, more or less....
A: *
*Copy and paste the text to another word sheet.
*Select the text that contains the squares.
*Control + space.
*Choose the font that you want for your text again.
*Save the word as a pdf again.
.- Voila: it is done!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Element order in BlockingCollection<> I have a Download Queue implemented with BlockingCollection<>. Now I want to prioritize some Download once in a while. I thought it might be great to move some elements 'up' the Collection, like in a list, but there is no method like Remove()/AddFirst() or Move().
What's the preferred way of arranging items in a BlockingCollection<> ?
A: BlockingCollection<T> works by wrapping an internal IProducerConsumerCollection<T>. The default is to use a ConcurrentQueue<T> internally, but you can provide your own implementation via this constructor.
If you provide your own threadsafe collection, you can use any collection type you want. This would allow to you prioritize elements as needed.
While there are no built-in collections that will implement your desired functionality, you could probably wrap a pair of ConcurrentQueue<T> collections into a class that implements IProducerConsumerCollection<T>. This would allow you to have "high priority" and "low priority" elements.
A: There is no way to implement a priority queue directly on top of a BlockingCollection<T>. A BlockingCollection<T> is best viewed as a strict queue for which no reordering can be achieved.
However you could use a combination of a priority queue and a BlockingCollection<T> to achieve the same effect. Lets assume for a second you implemented a simple PriorityQueue<T> which correctly orders your downloads. The following could be used to add priority to the handling of the receiving side
class DownloadManager {
private PriorityQueue<Download> m_priorityQueue;
private BlockingCollection<Download> m_downloadCollection;
public bool TryGetNext(ref Download download) {
PumpDownloadCollection();
if (m_priorityQueue.IsEmpty) {
download = null;
return false;
}
download = m_priorityQueue.Dequeue();
return true;
}
private void PumpDownloadCollection() {
T value;
while (m_downloadCollection.TryTake(out value)) {
m_priorityQueue.Enqueue(value);
}
}
Note: PriorityQueue<T> is not a type that actually exists in the .Net Framework. It's something you'd need to write yourself based on the priority scheduling of downloaded items.
A: Reed is correct in telling you that you need to implement the IProducerConsumerCollection<T>. However, there is a class that can help you. It's not built in, but it's featured on MSDN. Just pass this ConcurrentPriorityQueue to your BlockingCollection.
This is how I used it:
private readonly BlockingCollection<KeyValuePair<int, ICommand>> _commands
= new BlockingCollection<KeyValuePair<int, ICommand>>(
new ConcurrentPriorityQueue<int, ICommand>());
The ICommand is an interface in my project.
Now this allows you to add items like this:
_actions.Add(new KeyValuePair<int, ICommand>(1, command1));
_actions.Add(new KeyValuePair<int, ICommand>(2, command2));
_actions.Add(new KeyValuePair<int, ICommand>(1, command3));
Items with a lower integer value as priority will be executed first. In the above example:
command1
command3
command2
When looping over your BlockingCollection, you will no longer get the single elements (ICommand in my case), but a KeyValuePair. This might require some code changes of course. A nice thing is that you have its original priority:
foreach (var command in _queue)
{
var priority = command.Key;
var actualCommand = command.Value;
}
A: Unfortunately there is no way to rearrange the queue in the manner you desire. What you really need is a PriorityBlockingCollection implemented as a priority queue, but alas that does not exist either.
What you can do is exploit the TakeFromAny method to get the priority behavior you want. TakeFromAny will dequeue the first available item from an array of BlockingCollection instances. It will give priority to queues listed first in the array.
var low = new BlockingCollection<object> { "low1", "low2" };
var high = new BlockingCollection<object> { "high1", "high2" };
var array = new BlockingCollection<object>[] { high, low };
while (true)
{
object item;
int index = BlockingCollection<object>.TakeFromAny(array, out item);
Console.WriteLine(item);
}
The example above will print:
high1
high2
low1
low2
It forces you to use to multiple queues so it is not the most elegant solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Building release version of a project with Android NDK r6 I am compiling helloworld example of Android NDK r6b using cygwin and Windows Vista. I have noticed that the following code takes between 14 and 20 mseconds on my Android phone (it has an 800mhz CPU Qualcomm MSM7227T chipset, with hardware floating point support):
float *v1, *v2, *v3, tot;
int num = 50000;
v1 = new float[num];
v2 = new float[num];
v3 = new float[num];
// Initialize vectors. RandomEqualREAL() returns a floating point number in a specified range.
for ( int i = 0; i < num; i++ )
{
v1[i] = RandomEqualREAL( -10.0f, 10.0f );
if (v1[i] == 0.0f) v1[i] = 1.0f;
v2[i] = RandomEqualREAL( -10.0f, 10.0f );
if (v2[i] == 0.0f) v2[i] = 1.0f;
}
clock_t start = clock() / (CLOCKS_PER_SEC / 1000);
tot = 0.0f;
for ( int k = 0; k < 1000; k++)
{
for ( int i = 0; i < num; i++ )
{
v3[i] = v1[i] / (v2[i]);
tot += v3[i];
}
}
clock_t end = clock() / (CLOCKS_PER_SEC / 1000);
printf("time %f\n", tot, (end-start)/1000.0f);
On my 2.4ghz notebook it takes .45 msec (timings taken when the system is full of other programs running, like Chrome, 2/3 ides, .pdf opens etc...). I wonder if the helloworld application is builded as a release version. I noticed that g++ get called with
-msoft-float.
Does this means that it is using floating point emulations?
What command line options i need to use in order to build an optimized version of the program? How to specify those options?
This is how g++ get called.:
/cygdrive/d/android/android-ndk-r6b/toolchains/arm-linux-androideabi-4.4.3/prebu
ilt/windows/bin/arm-linux-androideabi-g++ -MMD -MP -MF D:/android/workspace/hell
oworld/obj/local/armeabi/objs/ndkfoo/ndkfoo.o.d.org -fpic -ffunction-sections -f
unwind-tables -fstack-protector -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_
5E__ -D__ARM_ARCH_5TE__ -Wno-psabi -march=armv5te -mtune=xscale -msoft-float -f
no-exceptions -fno-rtti -mthumb -Os -fomit-frame-pointer -fno-strict-aliasing -f
inline-limit=64 -ID:/android/workspace/helloworld/jni/boost -ID:/android/workspa
ce/helloworld/jni/../../mylib/jni -ID:/android/android-ndk-r6b/sources/cxx-stl/g
nu-libstdc++/include -ID:/android/android-ndk-r6b/sources/cxx-stl/gnu-libstdc++/
libs/armeabi/include -ID:/android/workspace/helloworld/jni -DANDROID -Wa,--noex
ecstack -fexceptions -frtti -O2 -DNDEBUG -g -ID:/android/android-ndk-r6b/plat
forms/android-9/arch-arm/usr/include -c D:/android/workspace/helloworld/jni/ndk
foo.cpp -o D:/android/workspace/helloworld/obj/local/armeabi/objs/ndkfoo/ndkfoo.
o && ( if [ -f "D:/android/workspace/helloworld/obj/local/armeabi/objs/ndkfoo/nd
kfoo.o.d.org" ]; then awk -f /cygdrive/d/android/android-ndk-r6b/build/awk/conve
rt-deps-to-cygwin.awk D:/android/workspace/helloworld/obj/local/armeabi/objs/ndk
foo/ndkfoo.o.d.org > D:/android/workspace/helloworld/obj/local/armeabi/objs/ndkf
oo/ndkfoo.o.d && rm -f D:/android/workspace/helloworld/obj/local/armeabi/objs/nd
kfoo/ndkfoo.o.d.org; fi )
Prebuilt : libstdc++.a <= <NDK>/sources/cxx-stl/gnu-libstdc++/libs/armeabi
/
cp -f /cygdrive/d/android/android-ndk-r6b/sources/cxx-stl/gnu-libstdc++/libs/arm
eabi/libstdc++.a /cygdrive/d/android/workspace/helloworld/obj/local/armeabi/libs
tdc++.a
SharedLibrary : libndkfoo.so
/cygdrive/d/android/android-ndk-r6b/toolchains/arm-linux-androideabi-4.4.3/prebu
ilt/windows/bin/arm-linux-androideabi-g++ -Wl,-soname,libndkfoo.so -shared --sys
root=D:/android/android-ndk-r6b/platforms/android-9/arch-arm D:/android/workspac
e/helloworld/obj/local/armeabi/objs/ndkfoo/ndkfoo.o D:/android/workspace/hellow
orld/obj/local/armeabi/libstdc++.a D:/android/android-ndk-r6b/toolchains/arm-lin
ux-androideabi-4.4.3/prebuilt/windows/bin/../lib/gcc/arm-linux-androideabi/4.4.3
/libgcc.a -Wl,--no-undefined -Wl,-z,noexecstack -lc -lm -lsupc++ -o D:/androi
d/workspace/helloworld/obj/local/armeabi/libndkfoo.so
Install : libndkfoo.so => libs/armeabi/libndkfoo.so
mkdir -p /cygdrive/d/android/workspace/helloworld/libs/armeabi
install -p /cygdrive/d/android/workspace/helloworld/obj/local/armeabi/libndkfoo.
so /cygdrive/d/android/workspace/helloworld/libs/armeabi/libndkfoo.so
/cygdrive/d/android/android-ndk-r6b/toolchains/arm-linux-androideabi-4.4.3/prebu
ilt/windows/bin/arm-linux-androideabi-strip --strip-unneeded D:/android/workspac
e/helloworld/libs/armeabi/libndkfoo.so
Edit.
I have run the commnad adb shell cat /proc/cpuinfo. This is the result:
Processor : ARMv6-compatible processor rev 5 (v6l)
BogoMIPS : 532.48
Features : swp half thumb fastmult vfp edsp java
CPU implementer : 0x41
CPU architecture: 6TEJ
CPU variant : 0x1
CPU part : 0xb36
CPU revision : 5
Hardware : GELATO Global board (LGE LGP690)
Revision : 0000
Serial : 0000000000000000
I don't understand what swp, half thumb fastmult vfp edsp and java means, but i don't like that 'vfp'!! Does it means virtual-floating points? That processor should have a floating point unit...
A: You are right, -msoft-float is a synonym for -mfloat-abi=soft (see list of gcc ARM options) and means floating point emulation.
For hardware floating point the following flags can be used:
LOCAL_CFLAGS += -march=armv6 -marm -mfloat-abi=softfp -mfpu=vfp
To see what floating point unit you really have on your device you can check the output of adb shell cat /proc/cpuinfo command. Some units are compatible with another: vfp < vfpv3-d16 < vfpv3 < neon - so if you have vfpv3, then vfp also works for you.
Also you might want to add the line
APP_OPTIM := release
into your Application.mk file. This setting overrides automatic 'debug' mode for native part of application if the manifest sets android:debuggable to 'true'
But even with all these settings NDK will put -march=armv5te -mtune=xscale -msoft-float into the beginning of compiler options. And this behavior can not be changed without modifications in NDK sources (these options are hardcoded in file $NDKROOT\toolchains\arm-linux-androideabi-4.4.3\setup.mk).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java TCP Server-Client Design Solution I'm in the process of developing a highly object-oriented solution, (i.e., I want as little coupling as possible, lots of reusability and modular code, good use of design patterns, clean code, etc). I am currently implementing the client-server aspect of the application, and I am new to it. I know how to use Sockets, and how to send streams and receive them. However, I am unsure of actually how to design my solution.
What patterns (if any) are there for TCP Java solutions? I will be sending lots of serialized objects over the network, how do I handle the different requests/objects? In fact, how do I handle a request itself? Do I wrap each object I'm sending inside another object, and then when the object arrives I parse it for a 'command/request', then handle the object contained within accordingly? It is this general design that I am struggling with.
All the tutorials online just seem to be bog-standard, echo servers, that send back the text the client sent. These are only useful when learning about actual sockets, but aren't useful when applying to a real situation. Lots of case statements and if statements just seems poor development. Any ideas? I'd much rather not use a framework at this stage.
Cheers,
Tim.
A: Consider using a higher level protocol then TCP/IP, don't reinvent the wheel. rmi is a good option and you should be able to find good tutorials on it.
A: I suggest you either use RMI, or look at it in details so you can determine how you would do things differently. At a minimum I suggest you play with RMI to see how it works before attempting to do it yourself.
A: If high performance and low latency aren't main requirements then just use existing solutions.
And if you decide to use rmi than consider using J2EE with EJB - it'll provide you a transaction management on top of rmi.
Otherwise if you need extremely low latency take a look on sources of existing solutions that use custom protocols on top of tcp.
For example OpenChord sends serialized Request and Response objects and Project Voldemort uses custom messages for its few operations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inserting a ModelValidator into a Model's Validators in ASP.NET MVC3 I'm currently trying to programmatically insert a ModelClientValidationStringLengthRule ModelValidator via a custom attribute, and wishing to avoid adding to the AdditionalValues dictionary in order to make use of existing functionality.
This is due to using a CMS, and wanting to control the length of the string via the CMS rather than within a model.
I assume I would do this in the OnMetadataCreated event in the custom attribute, however I cannot see how to add to the ModelValidator collection, only get them via GetValidators...
Anyone have any ideas?
Thanks in advance,
Dave
A: Rather than adding a custom attribute, you want to inject a validator based upon a condition.
You can use the class I detail in this answer to inject your validator based upon the conditions in your CMS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Re-ordering y-axis on a horizontal barchart in lattice package I'm relatively new to R, and I wondered if anyone could help me with a barchart I'm trying to create with the lattice package. I've managed to create the plot below (can't post because I'm a new user). Each panel represents the abundance of a separate species, while the bars represent the stacked abundances of larval stages of each species at specific depths. The problem is that I'd like to present the depths in a more intuitive way, with 0 m at the top of each panel, and 90 m at the bottom - this means 'flipping' the axis along with the bars. I created this plot using the following code:
# create a new column for Species and Depth as factors
stn8_9$Depth_mF<-as.factor(stn8_9$Depth_m)
stn8_9$SpeciesF<-as.factor(stn8_9$Species)
# log root transform data
stn8_9$logAbundance_per_m3<-(stn8_9$Abundance_per_m3)^(1/4)
# now create chart
barchart(Depth_mF~logAbundance_per_m3 | SpeciesF,
data=stn8_9[stn8_9$SpeciesF!="CYP" & stn8_9$Stn==9,],
horiz=TRUE, ylab="depth (m)",xlab="Abundance (#/m3)",
main="Station 9", origin=0,
col=c("red","orange","yellow","green","blue","purple"),
stack=TRUE, groups=stn8_9$Stage,
key=
list(title="Stage", cex.title=1,text=list(c("1","2","3","4","5","6")),
space="right", rectangles=list(size=2,border="white",
col=c("red","orange","yellow","green","blue","purple"))))
The dataset is provided at the bottom (hope it's in the right format)
I understand that barchart turns my 'depth' values into factors, and I have tried using reorder() and relevel(), and have managed to get the axis labels to flip, but the bars remain in the same place (not sure why). I'd like the '0 m' bar at the top, and the '90 m' bar at the bottom - can anyone please help?
Dataset:
dput(stn8_9)
structure(list(Stn = c(9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L), Depth_m = c(90L, 90L, 90L, 90L, 90L, 90L, 90L,
90L, 90L, 90L, 90L, 90L, 90L, 90L, 90L, 90L, 90L, 90L, 90L, 90L,
90L, 90L, 90L, 90L, 90L, 90L, 60L, 60L, 60L, 60L, 60L, 60L, 60L,
60L, 60L, 60L, 60L, 60L, 60L, 60L, 60L, 60L, 60L, 60L, 60L, 60L,
60L, 60L, 60L, 60L, 60L, 60L, 40L, 40L, 40L, 40L, 40L, 40L, 40L,
40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L,
40L, 40L, 40L, 40L, 40L, 40L, 20L, 20L, 20L, 20L, 20L, 20L, 20L,
20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L,
20L, 20L, 20L, 20L, 20L, 20L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 70L, 70L, 70L, 70L, 70L, 70L, 70L, 70L, 70L, 70L, 70L,
70L, 70L, 70L, 70L, 70L, 70L, 70L, 70L, 70L, 70L, 70L, 70L, 70L,
70L, 70L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L,
40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L, 40L,
40L, 40L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L,
20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L,
20L, 20L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), Species = structure(c(1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 5L,
5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L,
6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 1L, 1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 5L, 5L, 5L,
5L, 5L, 6L, 6L, 6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L,
6L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 5L, 5L, 5L, 5L, 5L,
6L, 6L, 6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L,
3L, 3L, 3L, 3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 1L,
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 5L,
5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L,
6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L), .Label = c("BB",
"BC", "CH", "CYP", "SB", "VS"), class = "factor"), Stage = c(2L,
3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 7L, 2L,
3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L,
4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 7L, 2L, 3L, 4L, 5L, 6L, 2L, 3L,
4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L,
5L, 6L, 7L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L,
5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 7L, 2L, 3L, 4L,
5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L,
6L, 2L, 3L, 4L, 5L, 6L, 7L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L,
6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L,
7L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L,
2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 7L, 2L, 3L, 4L, 5L, 6L,
2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L,
3L, 4L, 5L, 6L, 7L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L,
3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 7L, 2L,
3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L,
4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 7L, 2L, 3L, 4L, 5L, 6L, 2L, 3L,
4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L,
5L, 6L, 7L, 2L, 3L, 4L, 5L, 6L, 2L, 3L, 4L, 5L, 6L), Abundance_per_m3 = c(0,
0, 0, 1.267024758, 1.267024758, 0, 0, 0, 0, 0, 5.068099033, 0,
0, 0, 0, 25.34049517, 0, 0, 3.801074275, 0, 0, 2.534049517, 7.60214855,
12.67024758, 6.335123791, 0, 0, 0, 0, 3.044963144, 4.059950858,
2.029975429, 1.014987715, 4.059950858, 5.074938573, 7.104914002,
3.044963144, 0, 2.029975429, 0, 0, 30.44963144, 0, 0, 4.059950858,
2.029975429, 0, 11.16486486, 4.059950858, 11.16486486, 2.029975429,
1.014987715, 0, 0, 0, 0, 0, 9.899386594, 4.949693297, 15.83901855,
16.82895721, 10.88932525, 3.959754638, 6.929570616, 0, 0, 0,
24.74846649, 0, 0, 5.939631957, 0, 0.989938659, 1.979877319,
0.989938659, 1.979877319, 0.989938659, 1.979877319, 0, 0, 0,
0, 0, 17.89544764, 1.988383071, 9.941915354, 5.965149212, 7.953532283,
0, 15.90706457, 3.976766141, 1.988383071, 0, 23.86059685, 1.988383071,
9.941915354, 1.988383071, 0, 0, 0, 9.941915354, 61.63987519,
51.69795984, 9.941915354, 0, 0, 0, 0, 0, 28.83473086, 48.05788476,
33.64051933, 14.41736543, 0, 4.805788476, 38.44630781, 4.805788476,
0, 0, 28.83473086, 19.2231539, 28.83473086, 43.25209628, 33.64051933,
0, 72.08682714, 163.3968082, 692.0335406, 321.9878279, 86.50419257,
0, 0, 0, 0, 0, 19.85102993, 9.925514965, 9.925514965, 29.7765449,
0, 9.925514965, 39.70205986, 19.85102993, 0, 0, 29.7765449, 9.925514965,
29.7765449, 9.925514965, 19.85102993, 0, 29.7765449, 178.6592694,
744.4136224, 416.8716286, 49.62757483, 0, 0, 0, 0, 0, 11.25305392,
3.215158262, 12.86063305, 16.07579131, 8.037895656, 19.29094957,
6.430316525, 4.822737393, 0, 0, 51.4425322, 1.607579131, 3.215158262,
1.607579131, 1.607579131, 1.607579131, 1.607579131, 8.037895656,
6.430316525, 1.607579131, 1.607579131, 0, 0, 0, 0, 0, 30.07822022,
12.03128809, 15.03911011, 15.03911011, 9.023466065, 13.5351991,
6.015644043, 0, 1.503911011, 0, 27.07039819, 0, 6.015644043,
3.007822022, 0, 1.503911011, 9.023466065, 25.56648718, 16.54302112,
15.03911011, 6.015644043, 0, 0, 0, 4.939940207, 0, 39.51952166,
14.81982062, 4.939940207, 4.939940207, 4.939940207, 0, 4.939940207,
4.939940207, 0, 0, 29.63964124, 4.939940207, 4.939940207, 14.81982062,
0, 0, 29.63964124, 197.5976083, 568.0931238, 261.816831, 54.33934228,
0, 0, 0, 10.62671701, 0, 21.25343402, 10.62671701, 21.25343402,
21.25343402, 31.88015104, 0, 0, 0, 0, 0, 10.62671701, 31.88015104,
0, 31.88015104, 21.25343402, 0, 138.1473212, 244.4144913, 371.9350954,
212.5343402, 31.88015104, 0, 0, 0, 69.50153499, 19.85758143,
39.71516285, 29.78637214, 79.4303257, 49.64395357, 79.4303257,
9.928790713, 39.71516285, 89.35911642, 9.928790713, 0, 29.78637214,
79.4303257, 19.85758143, 178.7182328, 148.9318607, 99.28790713,
317.7213028, 615.5850242, 1211.312467, 327.6500935, 69.50153499
), Depth_mF = structure(c(7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), .Label = c("5", "10", "20", "40", "60",
"70", "90"), class = "factor"), SpeciesF = structure(c(1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 5L, 5L,
5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L,
6L, 6L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L,
3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 1L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 5L, 5L, 5L, 5L,
5L, 6L, 6L, 6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
3L, 3L, 3L, 3L, 3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L,
5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L,
6L, 6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L,
3L, 3L, 3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 5L, 5L,
5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L,
6L, 6L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L,
3L, 4L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L), .Label = c("BB",
"BC", "CH", "CYP", "SB", "VS"), class = "factor"), logAbundance_per_m3 = c(0,
0, 0, 1.06095331789381, 1.06095331789381, 0, 0, 0, 0, 0, 1.50041457128417,
0, 0, 0, 0, 2.24364310060701, 0, 0, 1.39629309072760, 0, 0, 1.26169323444953,
1.6604816781224, 1.88667144022303, 1.58649525090772, 0, 0, 0,
0, 1.32097777276068, 1.41948299515758, 1.19363816214162, 1.00372605177853,
1.41948299515758, 1.50092052805914, 1.63263727001607, 1.32097777276068,
0, 1.19363816214162, 0, 0, 2.34906757441938, 0, 0, 1.41948299515758,
1.19363816214162, 0, 1.82794602415898, 1.41948299515758, 1.82794602415898,
1.19363816214162, 1.00372605177853, 0, 0, 0, 0, 0, 1.77378946506859,
1.49157320259098, 1.99495023677811, 2.02541630374003, 1.81656207258872,
1.41064284060004, 1.62246964847031, 0, 0, 0, 2.23042217070931,
0, 0, 1.56113292684677, 0, 0.99747511829459, 1.18620450786389,
0.99747511829459, 1.18620450786389, 0.99747511829459, 1.18620450786389,
0, 0, 0, 0, 0, 2.05676958572452, 1.18747647396250, 1.77569149802404,
1.562806928309, 1.67934533442396, 0, 1.99708942036914, 1.41215547164577,
1.18747647396250, 0, 2.21014275343154, 1.18747647396250, 1.77569149802404,
1.18747647396250, 0, 0, 0, 1.77569149802404, 2.80198262342921,
2.68144165217603, 1.77569149802404, 0, 0, 0, 0, 0, 2.31728246613553,
2.63294121550744, 2.40832821053419, 1.94859451890365, 0, 1.48061165227674,
2.49008206159717, 1.48061165227674, 0, 0, 2.31728246613553, 2.09390107914848,
2.31728246613553, 2.56449460796253, 2.40832821053419, 0, 2.91382843883587,
3.57528685520031, 5.12898921614741, 4.23603815839925, 3.04971523426329,
0, 0, 0, 0, 0, 2.11079356271994, 1.77495874023182, 1.77495874023182,
2.33597707218005, 0, 1.77495874023182, 2.5101707230885, 2.11079356271994,
0, 0, 2.33597707218005, 1.77495874023182, 2.33597707218005, 1.77495874023182,
2.11079356271994, 0, 2.33597707218005, 3.65600169507374, 5.2234035271001,
4.51856552762811, 2.65418238899045, 0, 0, 0, 0, 0, 1.83154502725781,
1.33906170112536, 1.89371921865949, 2.00236428275782, 1.68378094745549,
2.09574482014368, 1.59242170246783, 1.48191537399859, 0, 0, 2.67812340235484,
1.12601218427985, 1.33906170112536, 1.12601218427985, 1.12601218427985,
1.12601218427985, 1.12601218427985, 1.68378094745549, 1.59242170246783,
1.12601218427985, 1.12601218427985, 0, 0, 0, 0, 0, 2.34187135068818,
1.86242173581786, 1.96927122377906, 1.96927122377906, 1.73317871692943,
1.91807754972377, 1.56610376120967, 0, 1.10740258963914, 0, 2.28099146904783,
0, 1.56610376120967, 1.31693103877130, 0, 1.10740258963914, 1.73317871692943,
2.24862878114404, 2.01675761776174, 1.96927122377906, 1.56610376120967,
0, 0, 0, 1.49083789392989, 0, 2.50728048152353, 1.96205300969286,
1.49083789392989, 1.49083789392989, 1.49083789392989, 0, 1.49083789392989,
1.49083789392989, 0, 0, 2.33328739913925, 1.49083789392989, 1.49083789392989,
1.96205300969286, 0, 0, 2.33328739913925, 3.74925881222597, 4.88207990404496,
4.02253091444491, 2.71505476657560, 0, 0, 0, 1.80550950406603,
0, 2.14712474844036, 1.80550950406603, 2.14712474844036, 2.14712474844036,
2.37618413862639, 0, 0, 0, 0, 0, 1.80550950406603, 2.37618413862639,
0, 2.37618413862639, 2.14712474844036, 0, 3.42835366591009, 3.95395514204289,
4.39153946529161, 3.8181877309365, 2.37618413862639, 0, 0, 0,
2.88734446548044, 2.11096769918679, 2.51037780725583, 2.33616978566337,
2.98535914973356, 2.65440135387150, 2.98535914973356, 1.77510517087316,
2.51037780725583, 3.07457234475636, 1.77510517087316, 0, 2.33616978566337,
2.98535914973356, 2.11096769918679, 3.65630330777027, 3.49338864171756,
3.15663297601737, 4.22193539810782, 4.98106273377854, 5.899484260135,
4.25453963683082, 2.88734446548044)), .Names = c("Stn", "Depth_m",
"Species", "Stage", "Abundance_per_m3", "Depth_mF", "SpeciesF",
"logAbundance_per_m3"), row.names = c(NA, -286L), class = "data.frame")
A: I hope I'm reading you correctly, as I saw only meters from 5 up to 90, none with 0. But if you simply make that variable an ordered factor with the values ordered "in reverse" you'll get what I think you describe:
d$Depth_mF <- factor(d$Depth_m,
levels = rev(sort(unique(d$Depth_m))),
ordered = TRUE)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I get jquery datepicker to format dates before displaying them? I would have thought this would be a common problem, but I haven't been able to find anything about it...
Basically, I have a jquery datepicker linked up to an input field which paths to a java Date object. Everything works just fine, but the datepicker initially displays a String like this:
Thu Sep 01 00:00:00 MDT 2011
As soon as I pick a date it formats it to the default, is there a way to make it format before the initial display?
A: I handle this a couple ways depending on the framework if any you are using.
*
*Use a static method call to format the date to how you need it displayed using a simple date format method to return a string value
*Add an additional get method to your object (ie getDateFormatted) that simply does the same function as number 1 from the "host" object.
Again it depends on the framework, if any, that you are using on how to implement the tag structure on the page.
UPDATE Based on JSTL Solution
JSP
<input type="text" class="datepicker" name="date" value="${bean.getDateFormatted()}" />
JAVA BEAN
This will have an additional getter method for returning a formatted date string instead of the java date object. You are essentially getting the toString() version on your JSP anyway.
public String getDateFormatted() {
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
return df.format(this.date);
}
Here is some additional information on how to set up date format options using Java:
Class SimpleDateFormat
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: FlexNativeMenu with robotlegs I an using the Robotlegs framework and I am busy with an AIR desktop application and I want to use FlexNativeMenu. THe problem is that I am not able to create a view class based on mx.controls.FlexNativeMenu for dependency injection. When not using Robotlegs the code is pretty straightforward - any help will be appreciated. Thanks.
A: generally you can use whatever you want to a view. The problem is that the mediator's onRegister method will be called only if your view dispatches ADDED_TO_STAGE event. And because FlexNativeMenu doesn't fire this event your mediator is not working (http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/controls/FlexNativeMenu.html#eventSummary)
A: for RobotLegs v2
If you're trying to inject into the FlexNativeMenu (hereinafter referred to FNM), you can try something like this (I'd do this in your IConfig implementor):
injector.injectInto( fnmInstance );
If you are trying to inject an instance of FNM (say in it's mediator):
[Inject]
public var view:MyFNMClass;
If you are trying to attach a mediator to the FNM instance you do something like this in your IConfig implementor:
//requires that you map the FNM (assuming you're subclassing it)
mediatorMap.map( MyFNMClass ).toMediator( MyFNMClassMediator );
//else where where you decide to wire it up
mediatorMap.mediate( fnmInstance );
The "gotcha" is this: There isn't a very pretty way to access the FNM prior to injection. I grabbed it like so:
//very nasty I know
var fnm:MyFlexNativeMenu = FlexGlobals.topLevelApplication.myMenu;
code
Made a git repo - https://github.com/jusopi/RobotLegs-v2-FlexNativeMenu-example
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Splitting Plate Information? How can I break this string for licence plates v/s states?
I have unique VIN Numbers in my database for every vehicle.
VIN varchar2(100)
Make varchar2(100)
Model varchar2(100)
Year varchar2(4)
PlateInfo varchar2(1000)
The objective is to take the string in the PlateInfo field and split it to states and the license plates.
There are vehicles who have had more than 24 owner / plate changes.
The string in plate info typically looks like this.
MA~CT~DE~NJ~NJ~~~~~~VEG-1825~AX7547~117824~NEG-1012~BEG-1011~~
This needs to split into two columns StateId, PlateId
MA:VEG-1825
CT:AX7547
DE:117824
NJ:NEG-1012
NJ:BEG-1011
I was able to do this making an assumption that the number of occurrences for the tilde "~" character will always be an even number.
However when I ran this against the database, I found there are several vehicles where the information looks like this.
CT~DC~DE~MA~MD~NY~RI~VA~WA~WV~
My client wants me to put this in a state column with a null column for the plate. How can I achieve this? Would it be fair to make the assumption that each 2 character is a state, then validate it against the 50 states?
A: Without knowing the specifications of how things are stored, it's difficult (or impossible) to provide accurate guidance.
That being said, it looks like you have 10 state entries, then up to 10 plates per record. If this is the case, you should be able to just use string.Split, not remove empty entries, and treat the first 10 items as states, and any remaining as matching plates.
A: Assuming that your input string is a list of 10+ items where each item is terminated by a ~, e.g.
"0~1~2~3~4~5~6~7~8~9~"
"0~1~2~3~4~5~6~7~8~9~10~11~12~13~14~15~16~17~18~19~"
you can remove the last ~ and split the string by ~:
var parts = input.TrimEnd('~')
.Split('~');
The states seem to be the first 10 non-empty elements (see @Reed Copsey's answer):
var states = parts.Take(10)
.Where(s => s != "");
The plates seem to be the second 10 elements, which need to be padded with nulls if necessary:
var plates = parts.Skip(10)
.Take(10)
.Concat(Enumerable.Repeat<string>(null, 10));
Then zip the states and the plates as follows:
foreach (var item in states.Zip(plates, (state, plate) => new { state, plate }))
{
Console.WriteLine("{0,-10} {1}", item.state, item.plate);
}
Example 1:
MA VEG-1825
CT AX7547
DE 117824
NJ NEG-1012
NJ BEG-1011
Example 2:
CT <null>
DC <null>
DE <null>
MA <null>
MD <null>
NY <null>
RI <null>
VA <null>
WA <null>
WV <null>
A: Assumption:
There are no legal plates that consist of only two characters. If vanity plates like that are a possibility (I am not in the USA), you will have to take appropriate measures.
Pseudocode:
*
*Split the string at the ~ delimiter
*Remove empty entries from the results -- you now have a lot of tokens which are either states or plate numbers
*All the 2-length strings are states
*All the rest are plates
*Combine them
Example code:
public static void Main()
{
var inputs = new[]
{
"MA~CT~DE~NJ~NJ~~~~~~VEG-1825~AX7547~117824~NEG-1012~BEG-1011~~",
"CT~DC~DE~MA~MD~NY~RI~VA~WA~WV~"
};
foreach(var input in inputs)
{
var plates = GetPlates(input);
Console.Out.WriteLine("Input string: " + input);
foreach(var plate in plates)
{
Console.Out.WriteLine(string.Format("{0} : {1}", plate.Key, plate.Value));
}
}
}
static KeyValuePair<string, string>[] GetPlates(string input)
{
var tokens = input.Split(new[] { '~' }, StringSplitOptions.RemoveEmptyEntries);
var states = tokens.Where(t => t.Length == 2).ToArray();
var plates = tokens.Where(t => t.Length != 2)
.Select(s => s.Replace("-", string.Empty));
return states.Zip(plates.Concat(Enumerable.Repeat<string>(null, states.Length)),
(state, plate) => new KeyValuePair<string, string>(state, plate)).ToArray();
}
Output:
Input string: MA~CT~DE~NJ~NJ~~~~~~VEG-1825~AX7547~117824~NEG-1012~BEG-1011~~
MA : VEG1825
CT : AX7547
DE : 117824
NJ : NEG1012
NJ : BEG1011
Input string: CT~DC~DE~MA~MD~NY~RI~VA~WA~WV~
CT :
DC :
DE :
MA :
MD :
NY :
RI :
VA :
WA :
WV :
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Strange behaviour with Xcode and iphone I've stumbled upon what seems like an impossible situation with an iphone app. I have three boolean variables which all are NO (false) and then I test in an if statement whether they is at least one of them as YES (true).
Well, as you can see in the screenshot, the debugger steps inside the if clause and eventually adds the value of BOTTOM_HEIGHT to the height variable. This seems absolutely backwards, have I found a quantum boolean or something? (jk)
Here is the screenshot:
I have already tried to clear the project, Reset the contents and settings of the simulator and even deleted the Derived Data from the xcode build folder in case it was caching old code and nothing seems to work.
----- Update ------
Ok, it seems that it works ok but the variables after debugging with the ideas provided by Maverick1st aren't being reported correctly and hasAvatar, hasRating and haOpinions are always shown as NO. I've figured out that the problem with the result being incorrect is on the offer which is a NSManagedObject is never null despite setting as null when I initialize the object and when I log it I get this:
2011-09-22 10:00:03.889 11870.com[2613:207] offer: (null)
This object gets initialized in a separate project in the workspace that gets added as a static library and I think I've deleted the library's build files so that they get generated again. In fact, I know it since otherwise it would give me a compilation error since on previous version of the library we didn't have the offer property.
I'm gonna do further investigation to see if I find why is this happening.
PS: can someone reedit my post, since it doesn't let me post images yet, thanks
A: Have you tried formulating explicitly with (hasEdit == YES)-terms?
A: Try to write the statement
if(hasRating ││ hasAvatars ││ hasOpinions)
as seperate if statements.
---------Edit----------
Ok, so maybe it will work like this way. This is at least how i do those kind of things.
BOOL b_oneOfTheThreeIsTrue;
if(hasRating)
b_oneOfTheThreeIsTrue = true;
if(hasAvatars)
b_oneOfTheThreeIsTrue = true;
if(hasOpinions)
b_oneOfTheThreeIsTrue = true;
Still good to debug and you can check for the one variable in your if statement.
if(b_oneOfTheThreeIsTrue)
doSomething;
A: Ok, after further investigation I found that there were several problems.
*
*With the quantum booleans the debugger for the simulator was going "bananas" when running the release build. When running on debug it works as expected.
*The offers never being null turned to be a problem with CoreData returning a NSNull object. I found the solution here: if statement fails with variable from CoreData managed object
*Another problem I didn't report is that the height of the cell weren't correct but I just reduced one of the measures used to calculate the total height as a workaround since it looks like the offset was constant.
Thanks for all the responses, it was really helpful.
PS: Should I select this answer as correct or wait for voting? Quite new poster here :)
Update:
I finally got to the source of the issue for the third problem ans why it was returning a reference to [NSNull null] instead of nil as it does with the rest of relationships in CodeData.
The secondary project that handles the DAO operations had no target and the target dependency got lost somehow when changing from Xcode 3.2 to Xcode 4.0 a couple of months back. It wasn't giving me a problem with the selector since the model was being copied in a different way.
Well, apparently CodeData has 2 different null states for objects: NSNull for when the object has not been set and nil when you give the value nil (Which I tent to do in the parse and hence it didn't return NSNull before)
Anywho, all seems to be working more or less as expected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Sort a list of hungarian strings in the hungarian alphabetical order I am working at the moment with some data in hungarians.
I have to sort a list of hungarians strings.
According to this Collation Sequence page
Hungarian alphabetic order is: A=Á, B, C, CS, D, DZ, DZS, E=É, F, G,
GY, H, I=Í, J, K, L, LY, M, N, NY, O=Ó, Ö=Ő, P, Q, R, S, SZ, T, TY,
U=Ú, Ü=Ű, V, W, X, Y, Z, ZS
So vowels are treated the same (A=Á, ...) so in the result you can have some like that using Collator :
Abdffg
Ádsdfgsd
Aegfghhrf
Up to here, no problem :)
But now, I have the requirement to sort according to the Hungarian alphabet
A Á B C Cs D Dz Dzs E É F G Gy H I Í J K L Ly M N Ny O Ó Ö Ő P (Q) R S
Sz T Ty U Ú Ü Ű V (W) (X) (Y) Z Zs
A is considered different than Á
Playing with the Strength from Collator doesnt change the order in the output. A and Á are still mixed up.
Is there any librairies/tricks to sort a list of string according to the hungarian alphabetical order?
So far what I am doing is :
*
*Sort with Collator so that the C/Cs, D,DZ, DZS... are sorted correctly
*Sort again by comparing the first characters of each word based on a map
This looks too much hassle for the task no?
List<String> words = Arrays.asList(
"Árfolyam", "Az",
"Állásajánlatok","Adminisztráció",
"Zsfgsdgsdfg", "Qdfasfas"
);
final Map<String, Integer> map = new HashMap<String, Integer>();
map.put("A",0);
map.put("Á",1);
map.put("E",2);
map.put("É",3);
map.put("O",4);
map.put("Ó",5);
map.put("Ö",6);
map.put("Ő",7);
map.put("U",8);
map.put("Ú",9);
map.put("Ü",10);
map.put("Ű",11);
final Collator c = Collator.getInstance(new Locale("hu"));
c.setStrength(Collator.TERTIARY);
Collections.sort(words, c);
Collections.sort(words, new Comparator<String>(){
public int compare(String s1, String s2) {
int f = c.compare(s1,s2);
if (f == 0) return 0;
String a = Character.toString(s1.charAt(0));
String b = Character.toString(s2.charAt(0));
if (map.get(a) != null && map.get(b) != null) {
if (map.get(a) < map.get(b)) {
return -1;
}
else if (map.get(a) == map.get(b)) {
return 0;
}
else {
return 1;
}
}
return 0;
}
});
Thanks for your input
A: I found a good idea, you can use a RuleBasedCollator.
Source: http://download.oracle.com/javase/tutorial/i18n/text/rule.html
And here is the Hungarian rule:
< a,A < á,Á < b,B < c,C < cs,Cs,CS < d,D < dz,Dz,DZ < dzs,Dzs,DZS
< e,E < é,É < f,F < g,G < gy,Gy,GY < h,H < i,I < í,Í < j,J
< k,K < l,L < ly,Ly,LY < m,M < n,N < ny,Ny,NY < o,O < ó,Ó
< ö,Ö < ő,Ő < p,P < q,Q < r,R < s,S < sz,Sz,SZ < t,T
< ty,Ty,TY < u,U < ú,Ú < ü,Ü < ű,Ű < v,V < w,W < x,X < y,Y < z,Z < zs,Zs,ZS
A: By stream you can sort like below:
public List<String> sortBy(List<String> sortable) {
Collator coll = Collator.getInstance(new Locale("hu","HU"));
return sortable.stream()
.sorted(Comparator.comparing(s -> s, coll))
.collect(Collectors.toList());
}
A: Will any of the solutions result in ordering the strings (names) 'Czár' and 'Csóka' as Czár, Csóka? This would be the correct order, since CS in Csóka is considered one letter and is after C.
However, recognizing double-character consonants is impossible even with a list of all Hungarian words, since there might be cases, where two words could look exactly the same character by character, but in one there are two consonants together, while in the other there are two characters reprezenting one letter at the very same place.
A: Change the order of your map.
Put the numeric representation as the key and the letter as the value. This will allow you to use a TreeMap which will be sorted by key.
You can then just do map.get(1) and it will return the first letter of the alphabet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: how to turn boost::asio socket into C++/CLI .Net socket? What I want is simple - code sample of creating new C++/CLI .Net socket from boost asio socket. How to create such thing?
Here is pseudo code of what I would like to do:
.net::socket a;
boost::asio::socket b;
a.assign(b.nativeWin32Socket());
BTW: Here is how to turn C++/CLI .Net socket into boost::asio socket.
A: You can't 'detach' a Boost.ASIO socket. You can use the native_handle() member function to get a SOCKET handle from the asio::socket object, but you must ensure that the asio::socket object isn't destructed until you're done with the SOCKET. It continues to hold ownership of the native SOCKET and will close it when it's destructor is called.
Like André suggested, you could duplicate the socket handle. However, I wouldn't consider duplicating this socket safe, because Boost.ASIO automatically associates the native SOCKET handle with an I/O completion port. If the .NET Socket wrapper or some other code attempts to associate the duplicated socket with a different I/O completion port, an error will occur. I know that the .NET 2.0 Socket class does, in fact, associate the SOCKET handle with an I/O completion port for asynchronous operations. This may have changed in more recent versions, however.
A: You can probably use the PROTOCOL_INFO structure returned by WSADuplicateSocket(), convert it to its SocketInformation equivalent and then use the appropriate socket constructor to get a shared socket with a different handle.
The "Remarks" section in the documentation on WSADuplicateSocket() depicts the usual control flow involved in socket duplication. I think this flow is somewhat equivalent to the SocketInformation Socket::DuplicateAndClose() and Socket(SocketInformation) pair of calls.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Connect device for debugging with Android? I need to connect my device (Sony S) to eclipse for debugging. How can I do this?
I've got it plugged in, and set up for development with debugging mode turned on.
I have adb devices to see if its there and it isnt.
I am on OSX 10.6
A: In Linux, the solution is to do the following:
$ ./adb kill-server
$ sudo ./adb devices
So please try to open a terminal window and change to the directory where you have adb.
Try to execute the same commands I've written above and let me know if it works for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why can't I print ("puts") in heroku console? I have a Rails app deployed to heroku and need to munge some data in heroku console. To help me do this I've created cmd.rb in my lib directory with some methods in it. Here's what it looks like:
class Cmd
def self.hello
puts "Hello World"
end
def self.create_member
# real code with multiple "puts" statements here
end
end
And here's what I get when I try to run this in heroku console:
$ heroku console
Ruby console for myapp.heroku.com
>> puts User.count
515
=> nil
>> 3.times {|i| puts i}
0
1
2
=> 3
>> require "#{Rails.root}/lib/cmd"
=> true
>> Cmd
=> Cmd
>> Cmd.hello
=> nil
There's a notable lack of "Hello World" in the above. Now I can see the output if I do this in another terminal window:
heroku logs --tail
But there's a lot of noise in that output, and I'd like to be able to see things incrementally.
A: I think it may be because of the way Heroku implemented the console:
On Bamboo, heroku rake and heroku console were implemented as special-cased execution paths, with output delivered over HTTP. This approach has a number of weaknesses, such as timeouts and non-interactivity on rake tasks.
So, one solution might be to upgrade to Cedar: http://devcenter.heroku.com/articles/cedar
Another solution could be to disable the rails_log_stdout functionality. I didn't figure out how to do that, but opening a ticket may get a solution.
Also, you may be able to filter the log results. See 'Filtering': http://devcenter.heroku.com/articles/logging
A: I think you should try to use Rails.logger instead of the method 'puts'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Scrolling up when resizing colorbox First, sorry if I don't use correct words, but my english is not the best, and my problem is kind of complicated to explain, for me.
So, I am using Colorbox from JQuery, and I display a long content in the colorbox, so there is a scrollbar on the windows (but not the colorbox). But I dynamically add content to the colorbox, so I have to resize the colorbox. The problem is that when I resize the colorbox, the all window is scrolling up to the top of the colorbox, and I would just like the content to be added, but the position of the user shouldn't change.
So is it possible the resize a colorbox without beeing bring back to the top of the page ?
(If you don't understand anything I said, tell me, and I will try my best to make me understanable)
Thanks !!
A: Assuming the new content is getting added at the end of the div, I think you could just capture the scroll position before content is added:
var scrollposition = $("#yourcontentdiv").scrollTop();
// add content here
$("#yourcontentdiv").scrollTop(scrollposition);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ways to utilise java thread to perform concurrent execution During the exam I had following question:
"What is a Java thread and how are multiple threads handled by a single
processor core?
[2 marks]
(a) Describe the two ways in which a class may utilise a thread to
perform concurrent execution. [6 marks]
(b) How does Java’s synchronized keyword help with concurrent thread
execution? [2 marks]"
Could anyone make a respond to point a?
I wrote that by calling this thread's start() method and by passing this thread to executor? Is it correct?
A: Since it looks like beginner stuff, I would probably go with "subclassing Thread" and "implementing Runnable and passing that to a Thread".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ruby Rails Routing error Currently, I have a table of companies, and each company has a table to store their funding data with a date and a money value, I can create new data in rails console with
Fund.create :date_of_record=>"2010-01-02", :company_id=>"1", :money=>"2003"
when I go to the company page(e.g. company_id=1), I'm able to view the data I entered from console, and edit, update them, but when I click to add a new funds data I'm getting
No route matches {:controller=>"funds", :company_id=>#<Fund id: nil, date_of_record: nil, company_id: 1, money: nil, created_at: nil, updated_at: nil>}
my create funds from db:
class CreateFunds < ActiveRecord::Migration
def change
create_table :funds do |t|
t.datetime :date_of_record
t.references :company
t.integer :money
t.timestamps
end
add_index :funds, :company_id
end
end
my funds/new.html:
<% form_for ([@company, @fund]) do |f| %>
<p>
<%= f.label :date_of_record %><br />
<%= f.text_field :date_of_record %>
</p>
<p>
<%= f.label :money %><br />
<%= f.text_field :money %>
</p>
<p>
<%= f.submit "Create" %>
</p>
<% end %>
<%= link_to 'Back', company_funds_path(@fund) %>
my funds_controller:
def new
@company = Company.find(params[:company_id])
@fund = @company.funds.build
end
def create
@company = Company.find(params[:company_id])
@fund = @company.funds.build(params[:fund])
if @fund.save
redirect_to company_fund_url(@company, @fund)
else
render :action => "new"
end
end
etc..
my models/company.rb:
class Company < ActiveRecord::Base
has_many :empnumbers
has_many :funds
end
my models/fund.rb:
class Fund < ActiveRecord::Base
belongs_to :company
end
my routes.rb :
resources :companies do
resources :funds
end
Thank you for you help!!
A: = link_to 'Back', company_funds_path(@fund)
Probably should be
= link_to 'Back', company_funds_path(@company)
# => /companies/:company_id/funds
A: Correct. You should do the same thing for adding funds to a given company. You pass @company to new_company_fund_path(@company)
<%= link_to 'add fund', new_company_fund_path(@company) %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Serialize property of type ICollection while using Entity Framework I have a class as shown below
public class Survey
{
public Survey()
{
SurveyResponses=new List<SurveyResponse>();
}
[Key]
public Guid SurveyId { get; set; }
public string SurveyName { get; set; }
public string SurveyDescription { get; set; }
public virtual ICollection<Question> Questions { get; set; }
public virtual ICollection<SurveyResponse> SurveyResponses { get; set; }
}
The above code gives me following exception
Cannot serialize member 'SurveyGenerator.Survey.Questions' of type
'System.Collections.Generic.ICollection
When i convert the ICollection to List it serializes properly
Since it is POCO of Entity Framework, i cannot convert ICollection to List
A: From the looks of your class the ICollection properties are defining foreign key relationships? If so, you wouldn't want to be publicly exposing the collections.
For example: If you are following the best practices guide for developing Entity Framework models, then you would have a separate class called "Question" which would wire up your two class together which might look like the following:
public class Question
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public virtual Survey Survey { get; set; }
}
If this was the case, you could quite possibly go round in circles calling the Question -> Survey -> ICollection -> Question
I had a similar incident using EF, MVC3 to implement a REST service and couldn't serialize the ICollection<> object then realised I didn't need to as I would be calling the object separately anyway.
The updated class for your purposes would look like this:
public class Survey
{
public Survey()
{
SurveyResponses=new List<SurveyResponse>();
}
[Key]
public Guid SurveyId { get; set; }
public string SurveyName { get; set; }
public string SurveyDescription { get; set; }
[XmlIgnore]
[IgnoreDataMember]
public virtual ICollection<Question> Questions { get; set; }
[XmlIgnore]
[IgnoreDataMember]
public virtual ICollection<SurveyResponse> SurveyResponses { get; set; }
}
I hopes this helps you out.
A: Change the ICollection<T> to a List<T>
public class Survey
{
public Survey()
{
SurveyResponses=new List<SurveyResponse>();
}
[Key]
public Guid SurveyId { get; set; }
public string SurveyName { get; set; }
public string SurveyDescription { get; set; }
public virtual List<Question> Questions { get; set; }
public virtual List<SurveyResponse> SurveyResponses { get; set; }
}
A: If you don't mind adding a reference to the assembly System.Runtime.Serialization, you can utilize this code which will serialize an object with ICollection without needing to change the object's implementation. The code below is outputting to string. You can use the stream however you'd like.
private string ConvertClassToXMLString<T>(T classObject)
{
using (var stream = new MemoryStream())
{
var serializer = new DataContractSerializer(classObject.GetType());
serializer.WriteObject(stream, classObject);
return Encoding.UTF8.GetString(stream.ToArray());
}
}
A: I used Matthew Merryfull solution and it works.
Since I am using EF designer for entity generation each time I update my models I would loose manual changes. I had to change *.tt which is used for generation of models. I edited few lines:
public string NavigationProperty(NavigationProperty navigationProperty)
{
var enbleWebService = string.Empty;
if(navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ){
enbleWebService = string.Format("[XmlIgnore]{0}[IgnoreDataMember]{0}", Environment.NewLine);
}
var endType = _typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType());
return string.Format(
CultureInfo.InvariantCulture,
"{5} {0} {1} {2} {{ {3}get; {4}set; }}",
AccessibilityAndVirtual(Accessibility.ForProperty(navigationProperty)),
navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
_code.Escape(navigationProperty),
_code.SpaceAfter(Accessibility.ForGetter(navigationProperty)),
_code.SpaceAfter(Accessibility.ForSetter(navigationProperty)),
_code.Escape(enbleWebService));
}
public string NavigationProperty(NavigationProperty navigationProperty)
{
var enbleWebService = string.Empty;
if(navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ){
enbleWebService = string.Format("[XmlIgnore]{0}[IgnoreDataMember]{0}", Environment.NewLine);
}
var endType = _typeMapper.GetTypeName(navigationProperty.ToEndMember.GetEntityType());
return string.Format(
CultureInfo.InvariantCulture,
"{5} {0} {1} {2} {{ {3}get; {4}set; }}",
AccessibilityAndVirtual(Accessibility.ForProperty(navigationProperty)),
navigationProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many ? ("ICollection<" + endType + ">") : endType,
_code.Escape(navigationProperty),
_code.SpaceAfter(Accessibility.ForGetter(navigationProperty)),
_code.SpaceAfter(Accessibility.ForSetter(navigationProperty)),
_code.Escape(enbleWebService));
}
Also check this article in case you run into problem with serialization http://geekswithblogs.net/danemorgridge/archive/2010/05/04/entity-framework-4-wcf-amp-lazy-loading-tip.aspx
A: For me the issue was not having a default constructor. Example:
List MyVar; // MyClass needs a public constructor
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: How to upload to remote machine with JSPSmartUpload? I am able to upload files to local machine using JSPSmartUpload, but I am not able to upload to a remote machine. It throws the following exception:
com.jspsmart.upload.SmartUploadException:File can't be saved(1120).
java.io.FileNotFoundException:./Manfile.csv(No such file or directory)SBL
How can I solve it? I am using Tomcat.
A: You need to map/mount the remote disk on the local machine so that it's available the usual java.io.File way. If mapping/mounting is not an option, then the only option left is setting up a FTP server on the remote machine and use a FTP client to send it. Apache Commons Net has a FTP client.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create a new class instance when variable is used Its' hard to explain what i mean so here an example.
class mysql {
public function __construct(){
//connect to db and select table
}
....
}
class Index Extends perent_class {
public $mysql;
public function no_mysql_required(){
//this function might be called and no mysql is required
}
public function mysql_required(){..} // this needs mysql.
public function mysql_required2(){..} // this needs mysql.
public function mysql_required3(){..} // this needs mysql.
}
Option 1:$this->mysql = new mysql(); add this to all function that need the connection to mysql, but two of these function could be called and that would creates two connection to mysql which is bad.
Option 2:if( !is_object($this-mysql) ) $this->mysql = new Mysql(); This will only create one mysql object at once and solves the problem, but it creates very repetitive code in the function(s). Creating & Calling a function $this->start_mysql() would be repetitive too.
So what i really want is whenever i call $this->mysql->function(); even tho its not created yet, to create the "$this->mysql = new Mysql" somehow in the Index perent_class automatically and once created, not to recreate it when a new function call is made. I might be doing this wrong and if there a better solution to what I'm doing, please post it.
Thank you.
A: What you want to do is use a singleton pattern for the mysql class. This way you don't have unnecessary connections open. So it would roughly look like this
Your mysql class
class Mysql{
private function __construct(){ }
private static $instance;
.
.
public static function singleton(){
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
And you would now use it like this in your other classes.
$mysql = Mysql::singleton();
A: If I understood your question correctly, it seems like you're wanting to use the 'Singleton' design pattern. This allows you to only create one instance of a class; attempting to create a second instance only returns the original instance. Here's a code extract:
<?php
class mysql {
private static $mysql;
public $testProperty;
private function __construct() { } // Declared private so cannot instantiate objects in client code.
public static function instance() {
if (!isset(self::$mysql)) {
self::$mysql = new self();
}
return self::$mysql;
}
}
?>
By using this pattern, a call to mysql::instance(); will return a new instance of the mysql object if one has not been created. If it has been created, it will return the same instance. Thus, you only ever have one instance of the object. Test it out by making several calls to mysql::instance():
$instance1 = mysql::instance();
$instance1->testProperty = 'abc';
var_dump($instance1->testProperty);
$instance2 = mysql::instance();
var_dump($instance2->testProperty);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: type mistmach for notmodified enum while loading Fixtures I'm using @ApplicationStart job to fill dev db with some values, but i'm encountering strange behavoiur after i clear it with:
Fixtures.deleteDatabase()
Some of my models have a field which is enumeration, each time when it tries to read object from yaml it stops on one of these models with enumerations and fires exception some thing like this:
play.exceptions.JavaExecutionException: Parameter value [OPEN] was not matching type [enumerations.OrderStatus]
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:229)
at Invocation.HTTP Request(Play!)
Caused by: java.lang.IllegalArgumentException: Parameter value [OPEN] was not matching type [enumerations.OrderStatus]
at org.hibernate.ejb.AbstractQueryImpl.registerParameterBinding(AbstractQueryImpl.java:360)
at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:435)
at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:72)
at play.db.jpa.JPQL.bindParameters(JPQL.java:169)
at play.db.jpa.JPQL.find(JPQL.java:46)
at models.Order.find(Order.java)
at controllers.Application._prepare(Application.java:52)
...
I'm not modifing enum. it is "all the way" the same.
What im doing wrong?
ps.Enum is not mapped to db, i think that it could be root of problem but than could you advise how to do it right way from architectual point of view? i'm almost newbie in hibernate/jpa
Upd1
it happens ocassionaly on onloading, here is one of models in yaml where it crashes (as you see nothing odd here):
models.users.GenUser(usr3):
name: V
phoneNumber: "1234567890"
email: v@mail.com.not
login: v
password: "123"
userStatus: ACTIVE
here 'userStatus' is an enum with possiblevalues ACTIVE, BANNED, and others.
i found only one solution - trop table(s) for model and let hibernate to recreate it(them). but sometimes due to relations it is easier to drop whole db and it is very annyoing ;(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to close the Channel for Writing We are using Netty 3.2.3 version and want to close the channel from writing according to a certain calculation.
We are closing the channel by:
channel.setInterestOps(channel.getInterestOps() | Channel.OP_WRITE);
and re-opening it by:
channel.setInterestOps(channel.getInterestOps() & Channel.OP_WRITE);
But according to the performance something is wrong.
the calculation is the same as we are doing serReadable true/false,
that is working fine.
A: Channel.OP_WRITE is for information only. Netty uses it to signal whether the I/O thread can write data to the channel immediately. If channel.isWritable() is false then Netty will queue any further data until it can be accepted by the channel. If you continue to write data when isWritable() is false then you may eventually encounter an OutOfMemoryError.
I assume you don't want to actually close the channel, just stop writing to it. The correct approach is to either check channel.isWritable() after each send, or receive ChannelStateEvent (possibly by overriding SimpleChannelUpstreamHandler.channelInterestChanged()) and pause whatever application process you have that is writing data to the channel.
In either case you'll want to receive ChannelStateEvent to know when you can start writing to the channel again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UniQuery - How to find the largest length of a field in a file I'm trying to figure out how to find the largest length of records for a field in a file on a Unix-based Unidata database in a Manage2000 (M2k) MRP system. I currently have the "Using Uniquery" and "Uniquery Command Reference" both for v7.2 and the closest that I have found is using "LIKE" and "UNLIKE", but it isn't working exactly like I was hoping.
Basically, we have an QUOTES file with a "Part_Nbr" dictionary and I need to find the length of the largest "Part_Nbr" record in the file. The dictionary field maximum length is 19 characters. In doing a random listing of records, I see some records have data length of 7 characters and some have 13 characters, but I need to find the largest data length.
Thanks in advance for your help and suggestions.
Best Regards,
--Ken
A: First I will clarify some terms so that we are speaking the same language. You are appear to be using field and record interchangeably.
A FILE (aka TABLE for SQL folk, 'QUOTES' in this case) contains 0 or more RECORDS. Each record is made up of multiple ATTRIBUTES (aka FIELD). You can reference these attributes using dictionary items (which can also create derived fields)
In this case you want to find the longest length of data accessed via the Part_Nbr dictionary, correct?
Assuming this is correct, you can do it as follows
Use a dictionary Item
Step 1: Create a I-type dictionary item (derived field). Let us call it Part_Nbr_Len. You can do this at the command line using UNIENTRY DICT QUOTES Part_Nbr_Len as per the image below.
*
*Type = I (aka Derived Field)
*LOC = LEN(Part_Nbr) (The field is the number of 1 byte characters in the Part_Nbr field)
*FORMAT = 5R (Right-aligned makes it treat this field as a number for sorting purposes)
*SM = S (This field is a single value)
Step 2: List the file in descending order by Part_Nbr_Len and optionally as I have done, also list the actual Part_Nbr field. You do this by the following command.
LIST QUOTES BY.DSND Part_Nbr_Len Part_Nbr_Len Part_Nbr
Temporary command-line hack
Alternatively, if you don't want something permanent, you could do a bit of a hack at the command line:
list QUOTES BY.DSND EVAL "10000+LEN(Part_Nbr)" EVAL "LEN(Part_Nbr)" Part_Nbr
Okay, let's break it down:
*
*list -> May or may not be important that this is lowercase. This enables you to use 'EVAL' regardless of your account flavor.
*EVAL -> Make a derived field on the fly
*10000+LEN(Part_Nbr) -> Sorting of derived field is done by ASCII order. This means 9 would be listed before 15 when sorting by descending order. The + 10000 is a hack that means ASCII order will be the same as numeric order for numbers between 0 and 9999 which should cover the possible range in your case
*EVAL "LEN(Part_Nbr)" -> Display the actual field length for you.
EDIT
Solve via code for MultiValued lists
If you have a MultiValued (and/or Sub-MultiValued) attribute, you will be required to use a subroutine to determine the length of the largest individual item. Fortunately, you can have a I-type dictionary item call a subroutine.
The first step will be to write, compile and catalog a simple UniBASIC subroutine to do the processing for you:
SUBROUTINE SR.MV.MAXLEN(OUT.MAX.LEN, IN.DATA)
* OUT.MAX.LEN : Returns the length of the longest MV/SMV value
* IN.ATTRIBUTE : The multivalued list to process
OUT.MAX.LEN = 0
IN.DATA = IN.DATA<1> ;* Sanity Check. Ensure only one attribute
IF NOT(LEN(IN.DATA)) THEN RETURN ;* No Data to check
LOOP
REMOVE ELEMENT FROM IN.DATA SETTING DELIM
IF LEN(ELEMENT) > OUT.MAX.LEN THEN OUT.MAX.LEN = LEN(ELEMENT)
WHILE DELIM
REPEAT
RETURN
To compile a program it must be in a DIR type file. As an example, if you have the code in the 'BP' file, you can compile it with this command:
BASIC BP SR.MV.MAXLEN
How you catalog it depends upon your needs. Their are 3 methods:
*
*DIRECT
*LOCAL -> My suggestion if you only want it in the current account
*GLOBAL -> My suggestion if you want it to work across all accounts
If you have the program compiled in the 'BP' file, the catalog commands for the above would be:
*
*CATALOG BP SR.MV.MAXLEN DIRECT
*CATALOG BP SR.MV.MAXLEN LOCAL
*CATALOG BP SR.MV.MAXLEN
After the subroutine has been cataloged, you will need to have the LOC field (attribute 2) of the dictionary item Part_Nbr_Len (as per first part of this answer) updated to call the subroutine and pass it the field to process:
SUBR("SR.MV.MAXLEN", Part_Nbr)
Which gives you:
A: This is a fantastic answer. With more recent versions of Unidata there's a slightly easier, more efficient way to check for the longest MV field though.
If the DICT item becomes:
SUBR('-LENS', Part_Nbr);SUBR('SR.MV.MAXLEN',@1)
The basic program can become simpler and just find the MAXIMUM value of the multivalued list of lengths:
SUBROUTINE SR.MV.MAXLEN(OUT.MAX.LEN, IN.DATA)
OUT.MAX.LEN=MAXIMUM(IN.DATA)
RETURN
Too bad there's no '-MAXIMUMS' built in function to skip the basic program entirely! It's worth reading section 5.9 of the UniQuery docs at:
Rocket Software Uniquery Docs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Tutorial for multi core CPU usage in c++ in unix I would like to know if someone can point me any library or tutorial to work with measurements. In a first moment, CPU usage, but latter I will need network (I've already found libcap, is this good?) and memory usages also.
I believe that each of then will be a different library or project, so thanks in advance.
I am currently working in a database monitoring system for UNIX system, in C++.
PS.: is there a way to access the htop programmatically from c++?
Pedro
A: Look into the /proc filesystem. It contains a bunch of plain-text files with system statistics. /proc/stat has cpu info, and /proc/net/* has network info.
Additionally, /proc/<pid>/* contains information about a specific process.
A: This is what I was looking for: http://developer.gnome.org/libgtop/stable/libgtop-white-paper.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting a specific index in Regular Expression Ex: (test 1 test 2 test 3) I would like to match the second 'test' Getting a specific index in Regular Expression Ex: (test 1 test 2 test 3) I would like to match the second 'test',
I'm using PHP preg_match
I tried to use preg_match_all but that is a slow function and I need high performance on this.
for example I have a HTML
I would like to match the third match
$str = "<span>1</span><span>2</span><span>3</span>";
preg_match('/<span>(\d+)<\/span>/',$str,$matches);
print_r($matches);
Something like: '/(\d+)</span>[2]/'
Thank you guys very much.
A: preg_match_all is your best bet less xml parsing.
This will also work, but is very ugly:
/(?:<span.+?span>){2}<span>(\d+)<\/span>/
function regbuild($num) {
return "/(?:<span.+?span>){". --$num ."}<span>(\d+)<\/span>/"
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mod_rewrite - all to index except static folder I've been trying and trying and can't find the solution, which surely is pretty easy. I have rule
RewriteEngine on
RewriteRule (.*) index.php [L]
So it redirects all urls to index.php, now I want all files expect this in static folder to be redirected, so urls like domain.com/static/... would not be redirected. I tried for example:
RewriteEngine on
RewriteCond %{REQUEST_URI} !^static$
RewriteRule (.*) index.php [L]
or
RewriteEngine on
RewriteRule static/(.*) static/$1 [L]
RewriteRule (.*) index.php [L]
And some other variations but nothing seems to work...
A: In your regex, use a negative look-ahead
RewriteEngine on
RewriteCond %{REQUEST_URI} ^(?!/static/).+ [NC]
RewriteRule (.*) index.php [L]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MySQL database design problem I have design problem, which I would love to get a hand with. I normally don't have problems with designing databases, but this one gives me some trouble. :)
I'm making a program which is basically a task-manager, where you can create Activities and Events. An Activity may or may not have an Event associated with it, and an Event will have one to many associations.
How do I design the Event database? Since every Event can have more than one association, will I need to make a table for each Event? Where the tablename is it's unique name? I'm completely blank.
Thanks
A:
Since every Event can have more than one association, will I need to make a table for each Event?
No. You need some version of:
Activity
--------
ActivityID
ActivityDescription
Event
-----
EventID
EventDescription
EventActivity
-------------
EventID
ActivityID
Then, to list an Event with all its Activities:
SELECT * from Event
LEFT OUTER JOIN EventActivity ON Event.EventID = EventActivity.EventID
LEFT OUTER JOIN JOIN Activity ON Activity.ActivityID = EventActivity.ActivityID
You need the LEFT OUTER JOIN instead of the usual INNER JOIN in case there are no Activities for the event.
A: Well starting with the obvious:
Event(evid PK, event details)
Activity(actid PK, activity details)
EventActivityRelationship(evid FK, actid FK) -- both make the primary key together
-- where PK is primary key and FK is foreign key
Then to make a link between an event and an activity, all you need to do is to add the two ID's together to the relationship table.
And keep in mind, relational databases (basically anything that's not NoSQL) grow downward (they gain rows), never horizontally (never in columns or tables) as you add more data. That will help you make intuitive database designs.
A: Using @egrunin answer, if you need to get all activities and events you can use:
SELECT a.ActivityID, e.EventID
FROM Activity a
LEFT JOIN EventActivity ea
ON a.ActivityID = ea.ActivityID
LEFT JOIN Event e
ON ea.EventID = e.EventID
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP File Handling with UTF-8 Special Characters It seems that File Handling in PHP doesn't work with certain characters (e.g. €) encoded UTF-8 if the path is hardcoded and the php-file saved as UTF-8.
Is it possible to make it work with all (or most western characters)? Is there a library which makes it possible maybe? Because I couldn't find any.
For example a folder named äöü&()éèàâêûô@$+ç%&=!£_;{[]}~´¢¬§°#@¦…€` in windows won't work with is_dir().
A: For Windows the solution is to convert filename / folder name to Windows-1252 encoding:
$dir = 'فارسی';
$dir = iconv(mb_detect_encoding($dir, "auto"), 'Windows-1252', $string);
mkdir($dir);
A: (Note: this answer was added to the answer by the original user, and has been moved here to better fit the site format.)
Ok, I have found a solution. I haven't tested it fully yet, I'm not sure if it's foolproof yet and I don't know if this is the best practise but encoding the string back to ANSI seems to do the trick (at least for the string I posted).
$string = iconv(mb_detect_encoding($string, "auto"), 'Windows-1252', $string);
I guess this should work with the default setting of most western windows computers.
A: I'd refuse to work with such a folder too! :-)
Jokes apart, you might try to save the file as UTF-16, as this is supposed to be the encoding Windows uses internally.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to separate CSS positioning from CSS styling? Let me explain what I want. I have the following (partial) HTML.
<ul>
<li class="positioncommunity"><a href="#">community</a></li>
<li class="positionsolutions"><a href="#">solutions</a></li>
<li class="positionmeetings"><a href="#">meetings</a></li>
</ul>
<div id="tab_content">
</div>
community, solutions and meetings are three tabs in the html page. I want to change the "tab_content" div based on which tab a user clicks.
I also want the user to know which tab he is in. So, I want to highlight the tab element. Here is where I am running into the problem. I have the following css for the tab elements.
#leftPan ul li.positioncommunity{padding:20px 0 0 53px;}
#leftPan ul li.positionsolutions{padding:20px 0 0 100px;}
#leftPan ul li.positionmeetings{padding:20px 0 0 40px;}
You can see that I have three CSS classes to position the tab elements. Now, how do I apply a background image to the tab element without changing the CSS class. Specifically, I am looking for a design pattern to separate CSS styling of elements from CSS positioning. Please help me with a NEAT solution to the above problem. I am sure it is a very common problem, but I cannot find a satisfactory solution.
A: The most right way is to use additional class for it. Anyway you can set the backgound in javascript (you will have click handler). Without javascript you can't implement it. Css can't react to the click event.
http://jsfiddle.net/KDyky/
ul li { float:left; }
ul li a { margin:2px; padding:3px 7px; display:block; }
$('ul li a').click(function() {
$('ul li a').css({ background: 'none' });
$(this).css({ background: 'green' });
return false;
});
for the background use your image.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to duplicate .doc page I have a microsoft word document with single page. I need to make more pages is that document that is the same as first page.
A: If you add a reference to Microsoft Word, you can use Microsoft.Office.Interop.Word to edit and create word documents. The easiest way to copy pages is probably to create a new file and then insert the original file as many times as you need pages.
using Microsoft.Office.Interop.Word;
object missing = System.Reflection.Missing.Value;
object StartPoint = 0;
ApplicationClass WordApp = new ApplicationClass();
Document WordDoc = WordApp.Documents.Add(ref missing, ref missing,
ref missing, ref missing);
Range MyRange = WordDoc.Range(ref StartPoint, ref missing);
Then use InsertFile with your original file as many times as you need pages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Perl -- do {read file} until regex found. Finds match but does not break out of the loop I wanna read a file to extract a few lines of information. I have created a do .. until to ignore the file lines until I reach the part I'm actually interested in, which contains the word V2000. i prefer to use a general regex rather than look for V2000.
The match is found but it doesn't break out the do .. until loop and therefore I'm unable to extract the info that comes right after that
Does anyone know why?
do {$line = <IN_SDF>;} until ($line =~ m/V\d+/);
and the rest of the code is:
my @aline = split ('', $line);
my $natoms = $aline[0];
my $out= shift;
do{
<IN_SDF>;
@aline = split ('', $_);
print OUT_3D $aline[3]."\t".$aline[0]."\t".$aline[1]."\t".$aline[2]."\n";
} until --$natoms == 0;
A: Are you assuming that a bare
<IN_SDF>
will load the next line from that filehandle into $_? That is incorrect. You only get that behavior with a while expression:
while (<IN_SDF>) is equivalent to while (defined($_=<IN_SDF>))
If you mean
$_ = <IN_SDF>
then say so.
For the first part of your question, this idiom:
while ($line = <IN_SDF>) {
last if $line =~ m/V\d+/;
}
is preferable to
do {
$line = <IN_SDF>
} until $line =~ m/V\d+/;
because the latter expression will go into an infinite loop when you run out of input (and $line becomes undefined).
A: Let me get this straight.
*
*You want to scan input until you see a line with a 'V' followed by any number anywhere in the line.
*Then you want to break up the line by characters
*And assign the first character in the line to $natoms, which is a single digit telling you how many lines to scan.
*And then you want to scan each of those lines and display the first 4 characters.
Is that correct?
As for your breaking out of the loop problem, when I ran a version of that code, it worked fine for me. With strict or without.
A: I ran across this while trying to parse a broken, single line 50MB XML file. I wrote my own sub to do this although I don't know if it works for the original poster:
sub ReadNext($$) {
my ($hh, $pattern) = @_;
my ($buffer, $chunk, $chunkSize) = ('', '', 512);
while(my $bytesRead = read($hh, $chunk, $chunkSize) > 0) {
$buffer .= $chunk;
if ($buffer =~ $pattern) {
my ($matchStart, $matchEnd) = (@-, @+);
my $result = substr($buffer, $matchStart, $matchEnd - $matchStart);
my $pos = tell($hh);
# Rewind the stream to where this match left off
seek($hh, ($pos -= length($buffer)-$matchEnd), 0);
return $result;
}
}
undef;
}
open(my $fh, $ARGV[0]) or die("Could not open file: $!");
while(my $chunk = ReadNext($fh, qr/<RECORD>.+?<\/RECORD>/)) {
print $chunk, "\n";
}
close($fh);
Which for me prints out every RECORD element from the XML with a newline.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: In a multithreaded app, can 2+ threads access the same function if the function does not modify/read data or modifies/reads temporary data? I can't seem to find an answer anywhere on Google. I basically want to know if 2 threads can access normal/member functions like these at the same time and not result in undefined behavior or do I have to use a mutex?
void foo(void)
{
float x(133.7);
float y(10);
std::cout << std::endl << (x * y);
}
void foobar(void)
{
std::cout << std::endl << 1/1;
}
A: I am pretty sure your code doesn't have undefined behaviour.
That said, you are using shared data, namely std::cout.
So if you expect std::cout << std::endl << (x * y) to be executed as a single operation (e.g. to prevent bits of output from different threads getting interleaved on stdout), you are going to have to use locks.
A:
I basically want to know if 2 threads can access normal/member functions like these at the same time and not result in undefined behavior or do I have to use a mutex?
Yes. You only need the synchronization if the threads will be using shared data. Synchronization is more about protecting the state, not the code itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to call a jar file in java program? Hi everybody..
i have a java program to convert Html to text file...
but i want to call a stanford-postagger jar file to my java pgm..
could anybody help me..
HERE IS MY JAVA PROGRAM TO CONVERT HTML TO TXT
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.StringTokenizer;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.File;
public class conv {
public static void main(String[] args) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader("C:/1.html"));
String line;
while ( (line=br.readLine()) != null)
{
sb.append(line);
}
try
{
String nohtml = sb.toString().replaceAll("\\<.*?>","");
PrintStream out = new PrintStream(new FileOutputStream("C:/Out.txt"));
StringTokenizer st = new StringTokenizer(nohtml);
while (st.hasMoreTokens())
{
out.println(st.nextToken().toString());
}
Scanner scan = new Scanner(System.in);
System.out.print("Enter File Name:");
String file_Name = "C:/"+scan.nextLine();
//System.out.print("Enter Starting Word:");
String start_word = "Good";
//System.out.print("Enter Final Word:");
String end_word = "Views,";
conv file = new conv();
String word = file.showLines(file_Name, start_word,end_word);
System.out.println(">>>");
if(word.length()>1)
{
//System.out.println(word);
String[] words = word.split("\\,");
for (String str : words)
{
System.out.println(str);
try
{
PrintStream out1 = new PrintStream(new
FileOutputStream("c:/sampleoutput.txt"));
for (String astr : words)
{
out1.println(astr);
}
out1.println();
out1.close();
}
/*StringTokenizer stg = new StringTokenizer(word, ".");
File newFile = new File("c:/newWords.txt");
try {
BufferedWriter writer= new BufferedWriter(new FileWriter(newFile,true));
while(stg.hasMoreTokens()) {
String val = stg.nextToken().trim()+".";
System.out.println(val);
writer.append(val);
writer.newLine();
}
writer.close();
}*/
catch (Exception e)
{
// e.printStackTrace();
System.out.println(e);
}
}
}
else
System.out.println("### Not Found");
}
catch(Exception ex)
{
System.out.println(ex);
}
}
public String showLines(String fileName, String start, String end) {
String word = "";
try {
Scanner scan = new Scanner(new File(fileName));
while(scan.hasNext())
{
if(scan.next().equals(start))
{
word = start;
while(scan.hasNext())
{
String test = scan.next();
word = word +" "+ test;
if(test.equals(end))
break;
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return word;
}
}
A: Just put the jar file in your classpath and import the required Class in your program.
A: Add the jar file to your classpath and call the main() function in it.
A: In order to use a jar, aka, to be able to import the classes of an external jar in the classes of your own project you have to place that jar in the class path. Putting it in the classpath boil down to multiple options:
*
*either you declare a CLASSPATH system environment variable, and in there you specify a folder where your external jar will be placed, this way when you compile your code the jar will be available in the compiler
*you declare the classpath folder containg the external jar at compile time using the "classpath" flag:
javac -classpath /path/to/dir/with/jars/ MyMainClass
A: Once a jar file is included in your project lib directory, any class within the jar can be called/imported as though they were your own. You will not be able to edit the included files, but you will have full access to their functionality.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: How to add a "Page x of y" footer to Word2007 doc as I am generating it using C# I looked here and here and here
I tried this:
private void AddFooters()
{
foreach (Word.Section wordSection in this.WordDoc.Sections)
{
object fieldEmpty = Word.WdFieldType.wdFieldEmpty;
object autoText = "AUTOTEXT \"Page X of Y\" ";
object preserveFormatting = true;
wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Fields.Add(
wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range,
ref fieldEmpty, ref autoText, ref preserveFormatting);
}
}
And this:
private void AddFooters()
{
foreach (Word.Section section in this.WordDoc.Sections)
{
Word.Range footerRange = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
this.WordDoc.ActiveWindow.Selection.TypeText("Page ");
footerRange.Fields.Add(footerRange, Word.WdFieldType.wdFieldPage);
this.WordDoc.ActiveWindow.Selection.TypeText(" of ");
footerRange = section.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
footerRange.Fields.Add(footerRange, Word.WdFieldType.wdFieldNumPages);
footerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
}
}
I recorded this VBA macro, but it does not seem to be helpful.
Sub Macro1()
'
' Macro1 Macro
'
'
WordBasic.ViewFooterOnly
ActiveDocument.AttachedTemplate.BuildingBlockEntries("Bold Numbers 3"). _
Insert Where:=Selection.Range, RichText:=True
End Sub
Nothing that I tried quite worked for me entirely (I got somewhat close).
Let me know if something about the question is not clear.
A: Ya, got it working.
// objects I use in the code below
// instanciate wordapp as the Word application object
Microsoft.Office.Interop.Word.Application wordapp = new Microsoft.Office.Interop.Word.Application();
// create missing object for compatibility with C# .NET 3.5
Object oMissing = System.Reflection.Missing.Value;
// define worddoc as the word document object
Microsoft.Office.Interop.Word.Document worddoc = wordapp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
// define s as the selection object
Microsoft.Office.Interop.Word.Selection s = wordapp.Selection;
// code for the page numbers
// move selection to page footer (Use wdSeekCurrentPageHeader for header)
worddoc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;
// Align right
s.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
// start typing
worddoc.ActiveWindow.Selection.TypeText("Page ");
// create the field for current page number
object CurrentPage = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;
// insert that field into the selection
worddoc.ActiveWindow.Selection.Fields.Add(s.Range, ref CurrentPage, ref oMissing, ref oMissing);
// write the "of"
worddoc.ActiveWindow.Selection.TypeText(" of ");
// create the field for total page number.
object TotalPages = Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages;
// insert total pages field in the selection.
worddoc.ActiveWindow.Selection.Fields.Add(s.Range, ref TotalPages, ref oMissing, ref oMissing);
// return to the document main body.
worddoc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
That last line returns to the main document.
It't not the best and most "fancy" c#, but it works for me. C# .Net 3.5, Office 2007.
A: This is in VB but I tried this and it worked for me, although here you'd have to supply the current and total for page numbers. I'm sure there is a better solution :/
WordBasic.viewfooteronly
Selection.EndKey Unit:=wdStory
Selection.ParagraphFormat.Alignment = wdAlignParagraphRight
Selection.TypeText Text:="Page " & current & " of " & total
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
A: This link helped in solving this problem
https://social.msdn.microsoft.com/Forums/vstudio/en-US/a044ff2d-b4a7-4f19-84f4-f3d5c55396a8/insert-current-page-number-quotpage-x-of-nquot-on-a-word-document?forum=vsto
This is how I solved it in VB.NET:
Dim aDoc As Word.Document
aDoc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter
aDoc.ActiveWindow.ActivePane.Selection.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight
aDoc.ActiveWindow.Selection.TypeText("Page ")
Dim CurrentPage = Word.WdFieldType.wdFieldPage
aDoc.ActiveWindow.Selection.Fields.Add(aDoc.ActiveWindow.Selection.Range, CurrentPage, , )
aDoc.ActiveWindow.Selection.TypeText(" of ")
Dim TotalPageCount = Word.WdFieldType.wdFieldNumPages
aDoc.ActiveWindow.Selection.Fields.Add(aDoc.ActiveWindow.Selection.Range, TotalPageCount, , )
aDoc.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument
A: I just solved my header problem. The header is composed of two lines. The first line is the plain text "SLUŽBENI LIST BiH", and the second line should contain the issue number (text Broj), page number (Strana), - subtitle - date of issue Daywk var, day var, month var, year var. The subtitle must be in italics.
Here is my solution.
Imports Microsoft.Office.Interop.Word
Imports Word = Microsoft.Office.Interop.Word
Dim headerRange As Word.Range = Section.Headers(Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages).Range
headerRange.Font.Size = 9
headerRange.Text = "SLUŽBENI GLASNIK BiH" & vbCrLf
headerRange.Font.Italic = False
headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter
headerRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
headerRange.Text = "Broj " & Br_Gl & " - Strana "
headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify
headerRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
headerRange.Fields.Add(headerRange, CurrentPage)
After adding the page number field, the following text would push the page number all the way to the right to the end. I think it's because after adding the field range positioner doesn't stay behind but in front of the field. The following line solved my problem.
headerRange.MoveEnd(Word.WdUnits.wdCharacter, 1)
headerRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
headerRange.Text = vbTab & " - O g l a s n i k j a v n e n a b a v k e - "
headerRange.Font.Italic = True
headerRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
headerRange.Text = vbTab & DanObjL & ", " & DanObj & ". " & Mjesec & ". " & Godina & "."
headerRange.Font.Italic = False
headerRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
I hope this can make someone's life easier, and if anyone has a more elegant solution, I'd like to learn.
Cheers!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: sending values to self using jquery-ajax may i get the jquery-ajax equivalent of this code? thanks
<html>
<head></head>
<body>
<?php
/* if the "submit" variable does not exist, the form has not been submitted - display initial page */
if (!isset($_POST['submit'])) {
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Enter your age: <input name="age" size="2">
<input type="submit" name="submit" value="Go">
</form>
<?php
}
else {
/* if the "submit" variable exists, the form has been submitted - look for and process form data */
// display result
$age = $_POST['age'];
if ($age >= 21) {
echo 'Come on in, we have alcohol and music awaiting you!';
}
else {
echo 'You're too young for this club, come back when you're a little older';
}
}
?>
</body>
</html>
A: Phew, I just whipped this up:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#go").click(function() {
var age = $("#age").val();
if(age >= 18) {
document.getElementById('pre').style.display = 'none';
document.getElementById('post_good').style.display = 'block';
} else {
document.getElementById('pre').style.display = 'none';
document.getElementById('post_bad').style.display = 'block';
}
})
})
</script>
<body>
<div id="pre">
<form action="" method="post">
Enter your age: <input name="age" size="3" maxlength="2" id="age">
<input type="button" name="submit" value="Go" id="go">
</form>
</div>
<div id="post_good" style="display:none;">
Come on in, we have alcohol and music awaiting you!
</div>
<div id="post_bad" style="display:none;">
Sorry, You're too young!
</div>
</body>
</html>
I assume that you were looking for a solution that doesn't require a new pageload.
I don't want to just give you the answer without an explanation:
The page simply contains all the information you wish to display, but keeps it hidden in a div. When you enter your age, the jquery simply 'unhides' the correct div.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Spaces, Apostrophe, and Ampersand in MySQL Enum Values I am creating a MySQL Table, and one of column's type is ENUM.
I have several different ENUM values. Some of them are two or more words, e.g. Hugo Boss.
Other ENUM values have an apostrophe in them, e.g. Men's, or other characters, e.g. &.
My question is two part:
*
*It is ok to have one or more spaces in an ENUM value (two words, or more)?
*Are apostrophes, ampersands, and other such characters, allowed in ENUM values? And if they are, how would I go about placing them?
A: Seems so:
MySQL [files]> create temporary table t(foo ENUM('123', '1&2', '3\'4'));
Query OK, 0 rows affected (0.17 sec)
MySQL [files]> show create table t\G
*************************** 1. row ***************************
Table: t
Create Table: CREATE TEMPORARY TABLE `t` (
`foo` enum('123','1&2','3''4') COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
1 row in set (0.09 sec)
MySQL [files]> insert into t values (0), (1), (2), (3);
Query OK, 4 rows affected, 1 warning (0.12 sec)
Records: 4 Duplicates: 0 Warnings: 1
MySQL [files]> show warnings;
+---------+------+------------------------------------------+
| Level | Code | Message |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'foo' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.11 sec)
MySQL [files]> select * from t;
+------+
| foo |
+------+
| |
| 123 |
| 1&2 |
| 3'4 |
+------+
4 rows in set (0.09 sec)
MySQL [files]>
Note: The warning means that I have used a value which was not allowed - I tried to insert 3, which is not defined as value for the ENUM.
So it works perfectly - as with any other strings in MySQL. You only have to take care that you treat them correctly - either as hex values, or use mysql_real_escape_string() or prepared statements. This provides for correct communication of "critical" values such as \\, ', " etc.
For example, if I have a string which contains "3'4", and I want to define it as a part of an enum, I create the query by putting one of 0x332734 or '3\'4' to the appropriate place. '3\'4' is obtained as a result of mysql_real_escape_string("3'4") in the used programming language.
NUL characters are not allowed as ENUM components as they would be in data strings - the used string is terminated before, though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: java download multiple files using threads I am trying to download multiple files that matches a pattern using threads. The pattern could match 1 or 5 or 10 files of diff sizes.
lets say for simplicity sake the actual code that would download the file is in downloadFile() method and fileNames is the list of filenames that match the pattern. How do I do this using threads. Each thread will download only one file. Is it advisable to create a new thread inside the for loop.
for (String name : fileNames){
downloadFile(name, toPath);
}
A: Yes, you certainly could create a new thread inside the for-loop. Something like this:
List<Thread> threads = new ArrayList<Thread>();
for (String name : fileNames) {
Thread t = new Thread() {
@Override public void run() { downloadFile(name, toPath); }
};
t.start();
threads.add(t);
}
for (Thread t : threads) {
t.join();
}
// Now all files are downloaded.
You should also consider using an Executor, for example, in a thread pool created by Executors.newFixedThreadPool(int).
A: You really want to use an ExecutorService instead of individual threads, it's much cleaner, likely more performant and will enable you to change things more easily later on (thread counts, thread names, etc.):
ExecutorService pool = Executors.newFixedThreadPool(10);
for (String name : fileNames) {
pool.submit(new DownloadTask(name, toPath));
}
pool.shutdown();
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
// all tasks have now finished (unless an exception is thrown above)
And somewhere else in your class define the actual work horse DownloadTask:
private static class DownloadTask implements Runnable {
private String name;
private final String toPath;
public DownloadTask(String name, String toPath) {
this.name = name;
this.toPath = toPath;
}
@Override
public void run() {
// surround with try-catch if downloadFile() throws something
downloadFile(name, toPath);
}
}
The shutdown() method has a very confusing name, because it "will allow previously submitted tasks to execute before terminating". awaitTermination() declares an InterruptedException you need to handle.
A: Yes you can create the Threads inline.
for (final String name : fileNames){
new Thread() {
public void run() {
downloadFile(name, toPath);
}
}.start();
}
A: Use Executor, Try this.
ExecutorService exec= Executors.newCachedThreadPool()
for (String name : fileNames){
exec.submit(new Runnable()
{
public void run()
{
downloadFile(name, toPath);
}
});
}
If you want say three download running concurrently, you can use:
Executors.newFixedThreadPool(3)
A: All the Above mentioned approach creates Threads but the actual Concurreny is not achieved.
ExecutorService pool = Executors.newFixedThreadPool(5);
final File folder = new File("YOUR_FILES_PATH");
int l = folder.listFiles().length;
System.out.println("Total Files----"+folder.listFiles().length);
long timeStartFuture = Calendar.getInstance().getTimeInMillis();
pool.execute(new DownloadFile(folder,0,l/2));
pool.execute(new DownloadFile(folder,(l/2),l));
pool.shutdown();
try {
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long timeEndFuture = Calendar.getInstance().getTimeInMillis();
long timeNeededFuture = timeEndFuture - timeStartFuture;
System.out.println("Parallel calculated in " + timeNeededFuture + " ms");
The above program is used to achieve concurreny and please modify as per your requirement.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: How to delete parent entity and set null in child FK column in hibernate? Here is example:
@Entity(name="Cat")
public class Cat
{
@ManyToOne
@JoinColumn(name="FoodId",nullable=true)
public Food getFood()
{
// code
...
}
@Entity(name="Food")
public class Food
{
@OneToMany(mappedBy="food",cascade=?
public List<Cat> getCats()
{
// other code
...
}
I want to delete some food entity, so cat.foodId column set to null value for cats, who had this food.
Food fish=new Food()
Cat bazillio=new Cat()
bazillio.food=fish
context.remove(fish)
if (bazilio.food==null) success()
Cascade.ALL in my understanding will delete all cats with this food (or not?) So how solve this task?
A: Load all cats whose food is fish, set each cat's food to null, and then delete the food. You'll need to deal with concurrent inserts of new cats with the food you're deleting. They could make the "delete food" transaction fail.
A: One of the relation should be marked as inverse. I suppose that would be Food.getCats()
Cascade on the Food-to-Cat relation should be None as Cats are independent of the Food entity justified by the nullable on Cat.getFood().
Deleting the food would then be as simple as Ryan specified..
*
*loading cats where food is set to the specified food
*setting the cat.food to null
*saving cat instances and deleting the food instance (can be carried out in any order)
A: It's the programmer responsibility to maintain that consistency.
From JPA 2 Spec:
Note that it is the application that bears responsibility for
maintaining the consistency of runtime relationships—for example, for
insuring that the “one” and the “many” sides of a bidirectional
relationship are consistent with one another when the application
updates the relationship at runtime.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to load correctly my class? I have a class defined in a an external pair of files, let's name them engine.h and engine.m . Also, it was given to me the file "engineListener.h".
this is how they look:
File engine.h:
@interface coreEngine: NSObject {
NSString *displaydValue;
id <coreEngineListener> listener;
}
-(coreEngine*)initWithListener:(id <coreEngineListener>) _listener;
//...
File engine.m
//imports here
@interface coreEngine()
-(Boolean) MyOperation: ... ... (etc)
@end
File engineListener.h
//imports here...
@class coreEngine;
@protocol coreEngineListener <NSObject>
@required
-(void) someVariable:(coreEngine *)source;
@end
Now, in my myController.h I have this:
//... imports and include ...
@interface myController : NSObject
{
coreEngine *PhysicsEngine;
}
- (IBAction)doSomething:(id)sender;
And in the myController.m this is what I have:
-(id) init
{
NSAutorelease *pool = [[NSAutoreleasePool alloc] init];
coreEngine *PhysicsEngine = [[coreEngine alloc] init];
[PhysicsEngine release];
[pool drain];
return self;
}
- (IBAction)doSomething:(id)sender
{
[PhysicsEngine MyOperation:Something];
}
The thing now is: the code compiles correctly, but the "[PhysicsEngine MyOperation:Something]" is doing nothing. I'm sure I'm instantiating my class wrongly. The NSObject defined in "engine.h engine.m and enginelistener.h" that I have to load was not made by me, and I have no means to modify it.
I've tried doing some dummy/random things based on what I've seen around on the internet, without knowing 100% what I was doing. I'm not even close to be familiar with ObjectiveC or C/C++, so be gentle with me. I'm totally noob on this subject.
I'm using Xcode 4, and I have also access to XCode 3.2.6
How should I load my class properly?
Any advice is welcome.
Thanks
A: Your interface should have:
PhysicsEngine *coreEngine;
and MyController.m init:
PhysicsEngine *coreEngine = [[PhysicsEngine allow] init];
I would be surprised if your code would compile at all.
Also, the convention is that classes are capitalised, and variables are not. There are probably more things to comment on, but you should start with that.
A: Your class's -init should look something like this:
- (id)init
{
self = [super init];
if (self != nil)
{
coreEngine = [[PhysicsEngine alloc] initWithListener:self]; // I assume you don't have a property declared
}
return self;
}
This follows a standard design pattern for initializing classes. You actually do the initialization by calling -init on super. Afterwards, if self was initialized properly (as it almost always will be), you create your PhysicsEngine object. Note that your class needs to conform to the PhysicsEngineListener protocol and implement -someVariable:.
// Declares protocol conformance
@interface MyController : NSObject <PhysicsEngineListener>
// In MyController.m
- (void)someVariable:(PhysicsEngine *)source
{
// Do whatever this is supposed to do
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Circular definition in C What I've written is:
typedef enum _MyStatus
{
MY_STATUS_OK = 0,
MY_STATUS_GENERAL_ERROR = -1,
} MyStatus;
typedef MyStatus (*MyCallback)(MySettings *settings);
typedef struct _MySettings
{
MyCallback callback;
} MySettings
However, it wouldn't compile as when defining MyCallback it doesn't know of MySettings. If I swapped MySettings and MyCallback, it would be the other way round: MySettings wouldn't know of MyCallback.
How generally is this sort of problem handled in C?
Thanks!
A: How about putting this line at the top:
typedef struct _MySettings MySettings;
This C FAQ: How can I define a pair of mutually referential structures? might be of use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Prime numbers c# I´m sorry but I have to ask a very simple question.
My problem is that I want to generate the prime numbers until a maximum number.
here´s my code:
for (int i = 2; i <= max - 1; i++)
{
System.Threading.Thread.Sleep(1000);
if (Progress != null)
{
if (max%i == 0)
Console.WriteLine(i);
}
}
My code doesn´t work and I don´t know why..
Can you please help me?
A: Hint 1: Algorithm optimization
You don't need to go all the way to the max number. You need only to go to its square root.
Think with me with this example: if 100 is divided by 50, it was first caught as being divided by 2. So you only need to go up to 10, any divisor you find after that, its counterpart would have been found before.
But this is only how you optimally find whether a specific number is prime or not.
Hint 2: IsNumberPrime() Method
First of all, you have to have a method to determine whether a specific number is prime or not. Keep in mind hint 1 here.
Hint 3: Doing It Right This Time
After you have followed hints 1 and 2, now you can loop and determine the highest prime number lower then your max number.
Conclusion
Sorry, no code here, just general orientation. Doing your homework for you will not help you. This answer will.
A: While you can check every number for primality, that's a waste of work. There are many numbers which you don't even have to consider. Even numbers except 2, for one. There are more tricks, such as something about multiples of 6 (google it)
If you want to generate prime numbers, use an algorithm that generates prime numbers. Seems obvious, right? But an algorithm that tests for primality is not in that category. The Sieve of Eratosthenes is nice, the Sieve of Atkin is nicer.
If you're going to check number for primality anyway (but seriously, don't), trial division is the worst sane algorithm to do so unless your numbers are always tiny (say, smaller than 10k). Use the deterministic version of the Miller Rabin test with known upper bounds (not the full one, because you DO have known upper bounds, otherwise you'd be generating all PositiveInfinity primes).
A: I'm just gonna be stupid and give you some code I wrote for an informatics class some time ago. Everything is ulong because it was first designed as a prime number check for some waaaaaaayy too high numbers.
ulong min = 0;
ulong max = 100000;
ulong i = 0;
ulong sqrt = 0;
ulong j = 0;
bool prime = true;
for (i = min; i <= max; i += 2)
{
prime = true;
sqrt = Math.Sqrt(i) + 1;
if (i % 2 == 0) prime = false;
else for (j = 3; j < sqrt; j += 2)
{
if (i % j == 0)
{
prime = false;
break;
}
}
if(prime)
{
Console.WriteLine(i);
}
}
It is slightly edited so I'm not entirely sure if this will work as expected, but it can't be too hard to edit it yourself.
A: Method to check if a number is prime:
bool IsPrime(int number)
{
for (int i = 2; i < sqrt(number); i++)
{
if (number%i == 0) return false;
}
return true;
}
Call this method for all integers up to max:
for (int crt = 1; crt <= max; crt++)
{
if (IsPrime(crt))
{
Console.WriteLine(crt);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Magento - Fatal error: spl_autoload() after adding to cart. I have just started experiencing this problem:
The site is fine until I add something to my cart at which point I start to receive the following error at the bottom of the page:
Fatal error: spl_autoload() [<a href=’function.spl-autoload’>function.spl-autoload</a>]: Class Mage could not be loaded in /blah/blah/app/code/core/Mage/Core/functions.php on line 244
The logged in user also gets logged out and they can not log back in again.
I’ve seen a couple of forum posts that talk about this possibly being a problem with memory but my hosts (Rackspace) assure me that the memory is fine (i’ve got 16GB of RAM).
So I’m stuck.
I don't think I've changed any code to cause this. But I'm not sure.
Thanks!
A: I deleted the sessions in var/session/ and the problem was solved and it's working fine.
A: Ok. So it appears that I am storing SimpleXml Objects in the session. It seems that this is a no no...
I have removed that code and all is working ok.
I still don't know why it works fine on my development server though but at least it's working.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS positioning The blocks are not alongside, they are one under the other. i want either A1-A2-A3 to be alongside or A1-A4, A2-A5,A3-A6 to alongside. i will be appreciateed if you can help me. this is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SGKM</title>
<style type="text/css">
body {
margin:0 auto;
}
body {
font:13px/22px Arial;
color:#444;
}
.container {
width:100px;
}
.container2 {
width:200px;
}
a {
color:#000;
}
.stage {
height:150px;
width:200px;
border:1px solid #f0f0f0;
background:#fafafa;
margin:60px auto;
}
.docIcon {
background: #eee;
background: -webkit-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%);
background: -moz-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%);
background: -o-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%);
background: -ms-linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%);
background: linear-gradient(top, #ddd 0, #eee 15%, #fff 40%, #fff 70%, #eee 100%);
border: 1px solid #ccc;
display: block;
width: 40px;
height: 56px;
}
</style>
</head>
<body>
<div class="stage">
<center><h2>Sahne</h2></center>
</div>
<div class="container">
<center><a href="#" class="docIcon">A<br>1</a></center>
<center><a href="#" class="docIcon">A<br>2</a></center>
<center><a href="#" class="docIcon">A<br>3</a></center>
</div>
<div class="container2">
<center><a href="#" class="docIcon">A<br>4</a></center>
<center><a href="#" class="docIcon">A<br>5</a></center>
<center><a href="#" class="docIcon">A<br>6</a></center>
</div>
</body>
</html>
A: Have a look at : http://jsfiddle.net/DavidLaberge/cuDFu/
the key is a float:left; in your class container
A: Change the containers to:
.container{}
.container2{
clear:both;
}
And add float:left; to .docIcon
You can also drop the center elements, and add a text-align:center; style.
This will give you a layout with a row of A1, A2, and A3, and then a row beneath with A4 through A6.
Example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: cannot compile c codes using microsoft visual studio c++ 2008 express edition I have a c codes which can be compiled in Linux using gcc. But when I try to compile it using microsoft visual studio c++ 2008 express edition, using the ide, it shows the error
vec.obj : error LNK2005: _INIT_SETA already defined in a.obj
fatal error LNK1169: one or more multiply defined symbols found
I checked the header files, and all of them have the preprocessor guard to prevent the header to be included multiple times, e.g.
#ifndef _vec_h_
#define _vec_h_
Then I tried compiling it in visual studio command prompt,
cl main.c
It can be compiled. What is the problem?
A: "one or more multiply defined symbols found" is a linker error rather than a compiler error. It occurs when two or more object files contain a definition for the same symbol. In this case, both vec.obj and a.obj somehow both contain an entry for the _INIT_SETA symbol, so you need to figure out how the sources for vec.obj and a.obj each introduce an _INIT_SETA symbol into their respective translation units (compilations).
Note that _INIT_SETA is the compiler-generated symbol for the C identifier INIT_SETA. Perhaps a definition of INIT_SETA was inlined via macro expansion? In this case, the declaration of INIT_SETA likely needs to be declared static.
The presence of a "multiple symbol" issue does not affect compilation of the source files; rather the linking step will fail because the linker does not know which _INIT_SETA entry to link with.
A: The error you posted indicates the existence of a vec.c and a.c (assuming you're not trying to link in pre-existing object files), both of which define INIT_SETA. This is a linker error, not a compilation error.
cl main.c only compiles the file to an object file, there is no linking going on. If you try to link all your object files together using (link.exe) from the command line, you'll still get the same error. Search the two files listed in the error for multiple definitions of the INIT_SETA symbol.
One possible solution could be to declare it extern in one of the two files using it, then the two files would share the same instance.
If both files need to have private copies, you should take out any extern INIT_SETA declarations appearing in the header files (and add static to the definitions in each source file).
A: I checked the header files, and all of them have the preprocessor guard to prevent the header to be included multiple times
This only prevents the preprocessor from including a single header file multiple times in a single compilation unit (cpp file). So you still have that header included in both cpp files, and that header defines a _INIT_SETA object. The problem is avoided if headers contain only declarations, and not definitions. (No function-code, and no global variables.)
Hpp file:
#ifndef _vec_h_
#define _vec_h_
class vector {
function(); //function prototype. No definition
}; //class declaration. No instantiation
extern vector myvector; //variable declaration. No instantiation
#endif //_vec_h_
Cpp file:
#include "vec.h"
vector::function() {} //function definition only in this cpp file
vector myvector; //variable instantiation only in this cpp file
The only exceptions are usually templates, which goes entirely in the header file, and the linker figures it out itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SSRS Date Culture Error I've got a strange error when trying to pass date parameters to SSRS.
All of the dates are retrieved using a DatePicker and validated so that only real dates are allowed.
However passing dates in the format dd/mm/yyyy causes SSRS to throw TypeMissmatchException if the day is 13 or higher.
I'm assuming this is due to the culture of SSRS being set to EN-US, is it possible to change this? or do I need to convert all dates that I send SSRS into American format.
A: The easiest way is to send dates in military format yyyy-mm-dd if possible as that is always interpreted correctly regardless of culture settings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Read XML posted via cURL into an array for potential DB insert I am receiving XML POSTED via curl, and can successfully write the posted XML to a file, so I know that its being posted successfully.
I really need to access the posted XML and create an array as soon as it is received, so I can set up variables and prepare the posted XML for a database Insert.
Can anyone show an example of how I would access the XML, received as:
$postXML = trim(file_get_contents('php://input'));
Which is:
<?xml version="1.0" encoding="UTF-8" ?>
<data>
<first_name>Larry</first_name>
<last_name>Jones</last_name>
<url>www.somewhere.com</url>
</data>
I need to access <first_name>, <last_name> and <url> and create as variables for processing and DB inserts.
Any help is very much appreciated!
A: Use simplexml
Load the XML string with:
$xml = simplexml_load_string($postXML);
Then access the data you want:
$first_name = (string)$xml->first_name;
$last_name = (string)$xml->last_name;
$url = (string)$xml->url;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Stop a script (without fatal error) after a certain amount of query/parse time I have a script that pulls from an external database and stores the data in a local database. I'm setup on a shared-server environment so I'm not able to let the script run for longer than two minutes, yet it would take around 5-10 minutes to run to completion.
Can I have the script stop its foreach loop after one and a half minutes, so I can redirect to the same script but with a different database offset to pick up where it left?
I can do the last part of that using a GET query string, but I'm unsure how to time it.
A: The easiest way would be to set a time() at the start of your script and check the difference in your foreach loop.
$start = time(); // Returns time in seconds
foreach($bigdata as $row) {
if(time()-$start > 100) { // Stop 20 seconds before 120 sec limit
// Some code for exiting the loop...
break;
}
}
A: $total_time = 0;
$start_time = microtime(true);
while($total_time < 60)//run while less than a minute
{
//DoSomething;
echo $total_time."\n";
sleep(5);//wait amount in seconds
$total_time = microtime(true) - $start_time ;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to reload UITableViews after returning from a dismissmodalView I have an app that loads three tables with data from arrays that are loaded from core data on startup. The user can tap a button to pull up another page with which they can edit the stored information. When they are finished, their changes are stored and committed back to core data and the user is returned to the home page to hopefully view their changes.
However, the data is not reloaded into the tables. I've tried [srcTableView reloadData]; with no luck.
The way it works is that the tables are populated from arrays that are loaded from core data when called from viewWillAppear. I can see that the right information is being stored in the array, but the array, but when the reloadData method is called, there is no change.
When the app is restarted however, the appropriate data IS in the tables.
I'm guessing it's some sort of instance issue, where the instance of the tables that I'm reloading is not the instance that is displaying...somehow or another.
I'm not really sure how to tell.
-Added
I've tried the reloadData to no effect.
Here's some code:
Instantiating tables
In -loadView
setTable = [[[MPIViewController alloc] initWithFrame:CGRectMake(kFrameX, 0, 1024, 768) TableData1:Data1 TableData2:Data2 TableData2:Data3]autorelease];
Opening second view:
-(IBAction)OpenOptions:(id)sender{
// Create the modal view controller
MPIViewController *viewController = [[MPICreateViewController alloc] initWithNibName:@"MPICreateViewController" bundle:nil];
// We are the delegate responsible for dismissing the modal view
viewController.delegate = self;
// Create a Navigation controller
UINavigationController *navController = [[UINavigationController alloc]
initWithRootViewController:viewController];
// show the navigation controller modally
[self presentModalViewController:navController animated:YES];
// Clean up resources
[navController release];
[viewController release];
}
- (void)didDismissModalView {
// Dismiss the modal view controller
[self dismissModalViewControllerAnimated:YES];
}
I've created the protocol for the modalViewControllerDelegate as well.
Not sure what code would be most effective to post other than this.
A: Your view controller will get a -viewWillAppear: message when the modal view controller covering it is about to be dismissed. That’s usually where you should put a call to -reloadData. In other words:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[srcTableView reloadData];
}
You need to make sure, though, that srcTableView is actually being set somewhere; from the looks of it, you’re instantiating another view controller—MPIViewController—in your -loadView, which is unorthodox and probably not what you want to be doing.
A: you can use the `[srcTableView reloadData]; in viewWillAppear method
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SSRS Report Server Issue User Accounts I need to know if there is a way to change the configuration or a command to turn off/disable SSRS's integration to active directory accounts? I want to be able to add users on the Security tab that do not have a domain/computer login. I understand there is a CustomSecurity feature that you can enable (such as Forms Auth) but I don't want to utilize that whole process. I can access my reports view the following code:
try
{
myReq.UseDefaultCredentials = true;
myReq.Credentials = new NetworkCredential(Properties.Settings.Default.myReportViewerUser, Properties.Settings.Default.MyReportViewerPassword);
HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
if (myResp.StatusCode == HttpStatusCode.OK)
{
this.iReports.Attributes["src"] = "http://myserver/Reports/Pages/Report.aspx?ItemPath=%2fUser+Reports%2fFacility+User%27s+Report";
}
}
I want to be able to create users in SSRS that correspond back to the Groups we have setup for our website (which is using FormsAuth) without creating a local logon or domain logon to the server machine. If I could do this it would isolate those logins from having any other access but to SSRS reports. The SSRS user created would correspond back to group thus specifying which reports that person would have access to run.
Has anyone worked on a similar situation? Please advise!
Thanks
A: There isn't such a thing as an "SSRS User." SSRS relies on other components to provide authentication. The CustomSecurity feature that you mention is the way to allow SSRS to authenticate against a provider other than Windows authentication.
(All due respect, but the statement "I understand there is a CustomSecurity feature that you can enable (such as Forms Auth) but I don't want to utilize that whole process." sounds a bit like "I know there's a way to do this, but I don't want to do it.")
From http://msdn.microsoft.com/en-us/library/ms152825.aspx
We recommend that you use Windows Authentication if at all possible. However, custom
authentication and authorization for Reporting Services may be appropriate in the
following two cases:
*
*You have an Internet or extranet application that cannot use Windows accounts.
*You have custom-defined users and roles and need to provide a matching authorization scheme in Reporting Services.
Sorry I don't any better ideas...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trigger javascript function when facebook comment left
Possible Duplicate:
Facebook like callback, and post it to target to like
I'm trying to find a way to run a javascript function when someone leaves a comment on something in my facebook app via the comment pluggin. Is there any way I detect the event. Would also like to a the same when some clicks the "Like" button.
Any Ideas?
A: Here is how :
http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
A: You can use the FB.Event.subscribe function.
http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
FB.Event.subscribe('comments.add', function (response) {
// do something with response
});
I haven't tried this out myself, but I've read you should add the notify="true" attribute to the fb:comments tag for it to work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem with Chrome and Google web fonts. Showing different output from Firefox I am using google web fonts for a page of mine, but I get a different result in Chrome from Firefox. Firefox's result is the correct and I don't have a clue why Chrome does this problem.
The code is simple
intro { font-family: 'Open Sans Condensed', sans-serif; font-size:33px; line-height:38px; color: #404040;}
logo { font-family: 'Open Sans', sans-serif; }
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300italic&subset=greek' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:600&subset=greek,latin' rel='stylesheet' type='text/css'>
<logo>Logo goes here</logo>
<br><br>
<intro>Text goes right here</intro>
or as you can see in http://jsfiddle.net/KSVTA/ or http://fiddle.jshell.net/KSVTA/show/ Chrome does not make use of Open Sans Condensed.
Why is that and how can I fix it?
A: Open Sans Condensed is defined with font-style: italic, so you'd need to apply that style to your second text as well: http://jsfiddle.net/KSVTA/1/.
The CSS file of that font is as follows:
@media screen {
@font-face {
font-family: 'Open Sans Condensed';
font-style: italic;
font-weight: 300;
src: local('Open Sans Cond Light Italic'), local('OpenSans-CondensedLightItalic'), url('http://themes.googleusercontent.com/static/fonts/opensanscondensed/v3/jIXlqT1WKafUSwj6s9AzV1qvxng10Zx7YyzmqNB25XX3rGVtsTkPsbDajuO5ueQw.woff') format('woff');
}
}
You can see the italic definition.
A: If you give your "intro" the CSS property
font-style: italic;
then it works fine in Chrome.
Also, you may want to read this older question about non-standard HTML tags.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get source/line number for IL instruction using Mono.Cecil I'm using Mono.Cecil to write a simple utility that looks for type/method usage within .NET assemblies (ex. calling ToString on enums).
I am able to get find the method, but it would be cool to display the source/line information to the user. Is this possible with Mono.Cecil?
A: It is possible. First you should read the guide from the Mono.Cecil wiki about debugging symbols.
Make sure you have Mono.Cecil.Pdb.dll near Mono.Cecil.dll, set the ReaderParameters to read the symbols as indicated in the guide, and then, instructions who have a sequence point in the pdb file will have their SequencePoint property non null, with line information available. The Document property of the SequencePoint holds the name of the source file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Using NowJS for Node.js with jQuery UI Draggable I started with the code found at this post: http://www.bennadel.com/blog/2171-Realtime-Messaging-And-Synchronization-With-NowJS-And-Node-js.htm.
I tried refactoring the html so that the example would use jQuery UI Draggable. The code is pasted below; server side is unchanged. It works fine, but there is an issue with flickering when dragging. I assume this is a jQuery question, although I was thinking there might be a problem with the filtering on the server side?
Also, I was wondering about how I might create an "initialPosition" function so that opening a new page would put the draggable div in the proper position. I assume this is something that needs to be done on the server side, and ideally it would come from a database value that gets written after a drag ends.
Also, beyond that I was wondering what the code would look like if I had multiple draggable items on a page.
HTML
<!DOCTYPE html>
<html>
<head>
<title>NowJS Draggable using jQuery UI</title>
<style type="text/css">
html, body { height: 100%; width: 100%; overflow: hidden; }
#draggable { width: 150px; height: 150px; border: 1px solid black; }
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"/></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"/></script>
<script type="text/javascript" src="/nowjs/now.js"></script>
<script>
$(function() {
$( "#draggable" ).draggable();
$( "#draggable" ).bind( "drag", function( event ) {
var newPosition = {
left: ( event.pageX ),
top: ( event.pageY ),
};
now.syncPosition( newPosition );
});
now.updatePosition = function( newPosition ){
$( "#draggable" ).css( newPosition );
};
});
</script>
</head>
<body>
<div id="draggable"></div>
</body>
</html>
NODE.JS (comments stripped out)
var sys = require( "sys" );
var http = require( "http" );
var url = require( "url" );
var path = require( "path" );
var fileSystem = require( "fs" );
var server = http.createServer(
function( request, response ){
fileSystem.readFile(
__dirname+'/index.html',
"binary",
function( error, fileBinary ){
if (error){
response.writeHead( 404 );
response.end();
return;
}
response.writeHead( 200 );
response.write( fileBinary, "binary" );
response.end();
}
);
}
);
server.listen( 8080 );
(function(){
var nowjs = require( "now" );
var everyone = nowjs.initialize( server );
var primaryKey = 0;
everyone.connected(
function(){
this.now.uuid = ++primaryKey;
}
);
everyone.now.syncPosition = function( position ){
everyone.now.filterUpdateBroadcast( this.now.uuid, position );
};
everyone.now.filterUpdateBroadcast = function( masterUUID, position ){
if (this.now.uuid == masterUUID){
return;
}
everyone.now.updatePosition( position );
};
})();
sys.puts( "Server is running on 8080" );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem with quoting and sed I'm trying to find and replacing some text using sed. Specifically, I'm trying to add quotes around a variable which could contain whitespaces.
sed -i 's/$VAR some.file/"$VAR" some.file/g' path/to/file
Unfortunately, the result is not expected. I've also tried to backslash the quotes, with no luck. What am I missing here?
The sed command is executed under Windows/cygwin.
A: You're missing the fact that single quotes prevent variable substitution:
sed -i "s/$VAR some.file/\"$VAR\" some.file/g" path/to/file
or even
sed -i $(printf 's/%s some.file/"%s" some.file/g' "$VAR" "$VAR") path/to/file
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Create RTF files from PHP (any better way?) Currently I am generating RTF documents using PHPRtfLite. It works perfectly. The only issue is that I have more than 1000 documents with one or more pages in each. To output them via PHPRtfLite, I have to copy paste the data + write formatting details (such as bold, italics or table) into my php file using PHPRtfLite methods. That means a lot of copy and paste. The resulting PHP file is big and messy.
Is there any better / easier way?
Currently I create one PHP file per RTF file.
Thank you for any suggestions.
Best regards,
Tony.
A: Look at the PHPRtfLite code, you'll see how to format text to rtf.
Then, put in a loop in your php, and open each file, read the file and output it.
Then close both files and move on to next file
EDIT
@TonyGeorge in that case, load the rtf file
$h=fopen("myfile.rtf", "r");
$text=fread($h);
fclose($h);
//Now put the code that handles the rtf conversion, the contents of the rtf will be in $text
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Listing record specific nested data from a single store I have a store, model, scriptTagProxy and custom Reader that consumes some json(p). The json describes a collection of objects. Each parent object hasMany child objects.
Is it possible to use an Ext.List to list all the children for a parent? - In my research it seems that you have to point a list at a store.
I would like alternatives to a nestedList.
A: Use store.filter('parentID', specificParentId); on the store that is binded to the list.
To change the items on the list to another parent clear the current filter first with store.clearFilter(false);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Fetching information from SVN Background:
SVN server installed in linux server. Using subclipse to check in files from Windows XP. I don't have admin access for SVN.
Every time I check in a file SVN will generate the revision number.
Question:
How to get the files checked between one revision number and another?
For example, I'd like to fetch all files from build 1 (I know the revision number) to the last checked in version from Windows XP.
A: Try this one, it should give you the difference between two revisions, put in your own params as needed.
svn diff -r ${startingSvnRevision}:${endingSvnRevision} --summarize ${RepoURL}
A: It is hard to know what the question is, so there could be a lot of ways to answer it.
In the SVN Repository Browsing view, right-click on the path and choose Compare. Then enter the two Revisions you want and you will see a summarized list of the changes. You can then double-click on any file to see a graphical compare of the differences.
The Show History option will show all the changes on a selected path, which might also be what you want.
Finally, you might also want something like Team > Synchronize with Repository which will show all the incoming changes from the repository to your working copy and let you see differences etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calling array objects in object-c iphone app I'm attempting to create an array from parsed JSON. I know that the JSON is parsing correctly because I tested it by outputting the values into the console. I then changed the code to:
// Start parsing the json
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSError *jsonError;
parsedJson = [[parser objectWithString:myRawJson error:&jsonError] copy];
[parser release];
NSDictionary *price = [parsedJson objectForKey:@"prices"];
NSEnumerator *enumerator = [price objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
NSArray *price_chunk = [[NSArray alloc] arrayWithObjects:[item objectForKey:@"id"],[item objectForKey:@"table"],[item objectForKey:@"table_id"],[item objectForKey:@"value"],nil];
NSLog(@"Prices ID: %@", [price_chunk objectAtIndex:0]);
NSLog(@"Prices Table: %@", [price_chunk objectAtIndex:1]);
NSLog(@"Prices Table ID: %@", [price_chunk objectAtIndex:2]);
NSLog(@"Prices Value: %@", [price_chunk objectAtIndex:3]);
}
So I'm trying to make the array, and then test the array by outputting the data into the console. The app crashes, and I receive:
2011-09-21 11:36:56.397 vegas_hipster[23496:207]
-[__NSPlaceholderArray arrayWithObjects:]: unrecognized selector sent
to instance 0x631b820
2011-09-21 11:36:56.399 vegas_hipster[23496:207] * Terminating app
due to uncaught exception 'NSInvalidArgumentException', reason:
'-[__NSPlaceholderArray arrayWithObjects:]: unrecognized selector sent
to instance 0x631b820'
* Call stack at first throw:
(
0 CoreFoundation 0x01624be9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x017795c2 objc_exception_throw + 47
2 CoreFoundation 0x016266fb -[NSObject(NSObject) doesNotRecognizeSelector:] + 187
3 CoreFoundation 0x01596366 ___forwarding___ + 966
4 CoreFoundation 0x01595f22 _CF_forwarding_prep_0 + 50
5 vegas_hipster 0x0006ec88 -[UpdateViewController update:] + 1433
6 UIKit 0x003bfa6e -[UIApplication sendAction:to:from:forEvent:] + 119
7 UIKit 0x0044e1b5 -[UIControl sendAction:to:forEvent:] + 67
8 UIKit 0x00450647 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
9 UIKit 0x0044f438 -[UIControl touchesBegan:withEvent:] + 277
10 UIKit 0x003e4025 -[UIWindow _sendTouchesForEvent:] + 395
11 UIKit 0x003c537a -[UIApplication sendEvent:] + 447
12 UIKit 0x003ca732 _UIApplicationHandleEvent + 7576
13 GraphicsServices 0x01dd2a36 PurpleEventCallback + 1550
14 CoreFoundation 0x01606064 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
15 CoreFoundation 0x015666f7 __CFRunLoopDoSource1 + 215
16 CoreFoundation 0x01563983 __CFRunLoopRun + 979
17 CoreFoundation 0x01563240 CFRunLoopRunSpecific + 208
18 CoreFoundation 0x01563161 CFRunLoopRunInMode + 97
19 GraphicsServices 0x01dd1268 GSEventRunModal + 217
20 GraphicsServices 0x01dd132d GSEventRun + 115
21 UIKit 0x003ce42e UIApplicationMain + 1160
22 vegas_hipster 0x00002330 main + 102
23 vegas_hipster 0x000022c1 start + 53
24 ??? 0x00000001 0x0 + 1
)
terminate called after throwing an instance of 'NSException'
Program received signal: “SIGABRT”.
A: You need to use initWithObjects: method, not arrayWithObjects.
A: [[NSArray alloc] arrayWithObjects:...
isn't valid. Try:
[NSArray arrayWithObjects:...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Handle NSURLRequest Response I am working on an app that queries a web service. I want to know how can I handle errors like "404" (NOT FOUND). The delegate method connection:(NSURLConnection *)conn didFailWithError:(NSError *)error only handles errors caused by connection. I have been told that dealing with those errors should be in connection:(NSURLConnection *)conn didReceiveData:(NSData *)data method, how can I do that? I've been looking over the documentation, there is no such property of NSURLRequest like "ResponseCode" or something. Any help is appreciated.
A: Implement the following delegate method
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse
*)response
Then check the response object for a statusCode property. You may have to cast it to NSHTTPURLResponse to see it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: .htaccess query string removal - can't figure out how re,
I can't figure out how to remove a query string from URL, redirect to another URL and pass that query string to a PHP script:
RewriteRule ^shopping/paypal/([0-9A-Za-z]*)?$ https://myserver.com/shopping/? [R=301,L]
RewriteRule ^shopping/$ php/shopping.php [QSA,L]
Basically, when I get the following request:
https://myserver.com/shopping/paypal/?token=EC-3L827812DL640424T
I want it to redirect to:
https://myserver.com/shopping/
and since /shopping/ is a "virtual" directory, I want it to pass the token key and map to:
php/shopping.php?token=EC-3L827812DL640424T
Please advise. Thanks!
A: I'd suggest you use an intermediate PHP script like this:
RewriteRule ^shopping/paypal/([0-9A-Za-z]*)?$ php/savetoken.php [QSA,L]
RewriteRule ^shopping/$ php/shopping.php [L]
where in savetoken.php:
<?php
session_start();
$_SESSION['token'] = $_GET['token'];
header("HTTP/1.1 301 Moved Permanently"); //without this PHP issues a 302
header('Location: shopping/');
exit;
Then in shopping.php you start the session and read the token value from it (and maybe delete it from the session, to prevent it from popping up in the future)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to integrate Custom report to Hudson email and in Hudson UI? I am generating custom report(HTML) for soapUi and I am using TestNG and Maven.
How do i generate Report?
->I manually create a Reports Folder and create HTML Report file after every run.(I am NOT
using surefire report) i.e, I have added this action in setup and teardown method.
Mentioned below is my project overview.
Main Proj(Maven)
| - src/main/java/tests/classes
| - test-output(TestNG)
| - Reports
| - SampleReport.html
Now How to integrate with Hudson? I mean This report should be displayed in Hudson and sent as email report.
A: There is a TestNG plugin for Jenkins that you can use to parse TestNG reults, ie.
TestNG XML report pattern: **/testng-results.xml
We are using it and this presents results in a very nice way in Jenkins.
Then, to email your html report, you can use Email-ext plugin. It will let you change email contents to HTML and attach your result, ie.
${FILE, path="target/surefire-reports/emailable-report.html"}
Hope this helps somewhat
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: IValidatableObject not triggered I'm trying to make use of the IValidatableObject as described here http://davidhayden.com/blog/dave/archive/2010/12/31/ASPNETMVC3ValidationIValidatableObject.aspx.
But it just wont fire when I'm trying to validate, the ModelState.IsValid is always true.
Here is my model code:
[MetadataType(typeof(RegistrationMetaData))]
public partial class Registration : DefaultModel
{
[Editable(false)]
[Display(Name = "Property one")]
public int PropertyOne { get; set; }
}
public class RegistrationMetaData :IValidatableObject
{
[Required(ErrorMessage = "Customer no. is required.")]
[Display(Name = "Customer no.")]
public string CustomerNo { get; set; }
[Display(Name = "Comments")]
public string Comments { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (new AccountModel().GetProfile(CustomerNo) == null)
yield return new ValidationResult("Customer no. is not valid.", new[] { "CustomerNo" });
}
}
I extend a LINQ to SQL table called Registration, my first guess was that this is not possible to do on a Meta class, but I'm not sure?
I do not get any errors, and it builds just fine, but the Validate method will not fire. What have I missed?
A: That's because it is the Registration model that should implement IValidatableObject and not RegistrationMetaData:
[MetadataType(typeof(RegistrationMetaData))]
public partial class Registration : IValidatableObject
{
[Editable(false)]
[Display(Name = "Property one")]
public int PropertyOne { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (new AccountModel().GetProfile(CustomerNo) == null)
yield return new ValidationResult("Customer no. is not valid.", new[] { "CustomerNo" });
}
}
public class RegistrationMetaData
{
[Required(ErrorMessage = "Customer no. is required.")]
[Display(Name = "Customer no.")]
public string CustomerNo { get; set; }
[Display(Name = "Comments")]
public string Comments { get; set; }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: searching from database with zend search lucene I am developing a social network kind of web application. I want to enable my users to search for people. As I am using Zend framework, Zend search lucene looks like a nice choice to create search functionality but there is no tutorial on web that can suit my needs. Is zend search written for searching from web pages only? Should I use Zend search or I should use simple like query and create the entire functionality my self?
A: Zend_Lucene is meant for every possible data . When you got raw data (like from database without in a special format .html or .doc) then you need to build your own document yourself . Which is good thing since it gives you lot more options
consider you got User table
<<User>>
*user_id
*email
*first_name
*last_name
*password
$userTb = new Default_Model_DbTable_User();
$index = Zend_Search_Lucene::create('/data/my-index');
$users = $userTb->fetchAll();
foreach($users as $user)
{
$doc = new Zend_Search_Lucene_Document();
$doc->addField(Zend_Search_Lucene_Field::Text('email', $user->email)); //here field = ur database column
$doc->addField(Zend_Search_Lucene_Field::Text('first_name',$user->first_name));
$index->addDocument($doc);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to format a date in shell script How can i format the date "01-SEP-2011" on "2011-09-01" format in shell script?
A: Try this:
$ date --date='01-SEP-2011' +%Y-%m-%d
A: If you have Ruby installed on the target system you could do this:
#/bin/bash
read DATE # 01-SEP-2011
set DATE=$(ruby -rdate -e "puts Date.parse('$DATE').to_s")
echo $DATE # 2011-09-01
A: kent$ date +%F -d "01-SEP-2011"
2011-09-01
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cannot change indicatorView.backgroundColor in a tableView I changed the backgroundColor of my UITableView (with a pattern image) and I want my cells entirely white, I assigned a backgroundColor to cell.contentView. I cannot change the backgroundColor of accessoryType. How can I do that ?
Here is an illustration of what I have for the moment:
- (void)viewDidLoad
{
[super viewDidLoad];
UIImage *bgImg = [UIImage imageNamed:@"backgroundPattern.png"];
self.tableView.backgroundColor = [UIColor colorWithPatternImage:bgImg];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// Put an arrow
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// In order to have my cell with a white background. I assign a whiteColor
// to my contentView because assign color to the cell.backgroundColor property doesn't
// to work..
cell.contentView.backgroundColor = [UIColor whiteColor];
// HERE is my problem, I would assign a backgroundColor of my accessoryType.
// Because for the moment, just behind the accessoryType this is a the color of the
// tableView.backgroundColor
cell.accessoryView.backgroundColor = [UIColor whiteColor];
}
// Configure the cell...
return cell;
}
A: Set the table view cell's background color, not the content view's.
cell.backgroundColor = [UIColor whiteColor];
The content view is only for the content your table view cell manages. Any additional views (like the accessor view or the reordering views when the table is in edit mode) are handled internally by the table view and table view cell class. They resize the content view as necessary, so you can't rely on the content view to set the background color.
EDIT: Sorry, this is incorrect. The correct place to set state-based properties on the table view cell is in the -tableView:willDisplayCell:forRowAtIndexPath: method of UITableViewDelegate. Set the cell's background color here.
A: I don't think you can change the background color of a standard accessory view. Instead of using UITableViewCellAccessoryDisclosureIndicator, set cell.accessoryView to an UIImageView, using your custom image.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java Apache FileUtils readFileToString and writeStringToFile problems I need to parse a java file (actually a .pdf) to an String and go back to a file. Between those process I'll apply some patches to the given string, but this is not important in this case.
I've developed the following JUnit test case:
String f1String=FileUtils.readFileToString(f1);
File temp=File.createTempFile("deleteme", "deleteme");
FileUtils.writeStringToFile(temp, f1String);
assertTrue(FileUtils.contentEquals(f1, temp));
This test converts a file to a string and writtes it back. However the test is failing.
I think it may be because of the encodings, but in FileUtils there is no much detailed info about this.
Anyone can help?
Thanks!
Added for further undestanding:
Why I need this?
I have very large pdfs in one machine, that are replicated in another one. The first one is in charge of creating those pdfs. Due to the low connectivity of the second machine and the big size of pdfs, I don't want to synch the whole pdfs, but only the changes done.
To create patches/apply them, I'm using the google library DiffMatchPatch. This library creates patches between two string. So I need to load a pdf to an string, apply a generated patch, and put it back to a file.
A: A PDF is not a text file. Decoding (into Java characters) and re-encoding of binary files that are not encoded text is asymmetrical. For example, if the input bytestream is invalid for the current encoding, you can be assured that it won't re-encode correctly. In short - don't do that. Use readFileToByteArray and writeByteArrayToFile instead.
A: Just a few thoughts:
*
*There might actually some BOM (byte order mark) bytes in one of the files that either gets stripped when reading or added during writing. Is there a difference in the file size (if it is the BOM the difference should be 2 or 3 bytes)?
*The line breaks might not match, depending which system the files are created on, i.e. one might have CR LF while the other only has LF or CR. (1 byte difference per line break)
*According to the JavaDoc both methods should use the default encoding of the JVM, which should be the same for both operations. However, try and test with an explicitly set encoding (JVM's default encoding would be queried using System.getProperty("file.encoding")).
A: Ed Staub awnser points why my solution is not working and he suggested using bytes instead of Strings. In my case I need an String, so the final working solution I've found is the following:
@Test
public void testFileRWAsArray() throws IOException{
String f1String="";
byte[] bytes=FileUtils.readFileToByteArray(f1);
for(byte b:bytes){
f1String=f1String+((char)b);
}
File temp=File.createTempFile("deleteme", "deleteme");
byte[] newBytes=new byte[f1String.length()];
for(int i=0; i<f1String.length(); ++i){
char c=f1String.charAt(i);
newBytes[i]= (byte)c;
}
FileUtils.writeByteArrayToFile(temp, newBytes);
assertTrue(FileUtils.contentEquals(f1, temp));
}
By using a cast between byte-char, I have the symmetry on conversion.
Thank you all!
A: Try this code...
public static String fetchBase64binaryEncodedString(String path) {
File inboundDoc = new File(path);
byte[] pdfData;
try {
pdfData = FileUtils.readFileToByteArray(inboundDoc);
} catch (IOException e) {
throw new RuntimeException(e);
}
byte[] encodedPdfData = Base64.encodeBase64(pdfData);
String attachment = new String(encodedPdfData);
return attachment;
}
//How to decode it
public void testConversionPDFtoBase64() throws IOException
{
String path = "C:/Documents and Settings/kantab/Desktop/GTR_SDR/MSDOC.pdf";
File origFile = new File(path);
String encodedString = CreditOneMLParserUtil.fetchBase64binaryEncodedString(path);
//now decode it
byte[] decodeData = Base64.decodeBase64(encodedString.getBytes());
String decodedString = new String(decodeData);
//or actually give the path to pdf file.
File decodedfile = File.createTempFile("DECODED", ".pdf");
FileUtils.writeByteArrayToFile(decodedfile,decodeData);
Assert.assertTrue(FileUtils.contentEquals(origFile, decodedfile));
// Frame frame = new Frame("PDF Viewer");
// frame.setLayout(new BorderLayout());
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can I display only certain characters from a mysql_fetch_array I am trying to create a list of upcoming events by pulling data from an event table in mysql. Currently the output looks like this:
Upcoming Events
2011-09-21 School Walkathon
2011-10-06 Open House
2011-10-17 PTA Meeting
2011-11-14 PTA Meeting
2011-09-30 Staff Development Day
However, I would like the date to display only the month and day. Here is my code:
<?php
//---Connect To Database
$hostname="localhost";
$username="root";
$password="urbana116";
$dbname="vcalendar3";
mysql_connect($hostname,$username, $password) OR DIE ("<html><script language='JavaScript'<alert('Unable to connect to database! Please try again later.'),history.go(-1)</script></html>");
mysql_select_db($dbname);
//---Query the database into dataset ($result) stop after the fifth item
$query = 'SELECT event_id, event_title, event_date FROM events WHERE event_date >= CURDATE() ORDER BY category_id != 9, category_id != 7, event_date ASC limit 5';
$result = mysql_query($query);
//---Populate $array from the dataset then display the results (or not)
if ($result) {
while ($array= mysql_fetch_assoc($result)) {
echo "<TR><td>".$array[event_date]."</TD><td><a href='/vcalendar/event_view.php?event_id=".$array[event_id]."'>".$array[event_title]."</a></td></tr>";
}
}else{
echo "No results";
}
?>
I've tried to select just certain characters from the event_date array like this:
echo "<TR><td>".$array[event_date][5]."</TD><td><a href='/vcalendar/event_view.php?event_id=".$array[event_id]."'>".$array[event_title]."</a></td></tr>";
but that only displays the 5th character, not characters 5-9...
A: You can achieve this with the substr() PHP function: http://pt.php.net/manual/en/function.substr.php
Example:
substr($array[event_date],5);
A: echo date("m-d",srtotime($array[event_date]);
//09-05
A: How about:
echo "<TR><td>".substr($array[event_date], 5)."</TD><td><a href='/vcalendar/event_view.php?event_id=".$array[event_id]."'>".$array[event_title]."</a></td></tr>";
A: You should format the date.
use date('m-d',strtotime($array[event_date]))
This way, you have the flexibility to display it any way you like (say September 21 instead of 09-21)
A: For more freedom, you can use this:
echo "<tr><td>".date("m-d",strtotime($array['event_date']))."</td> ...
Change the m-d around to whatever format you want. For example, F dS would give something like September 21st.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I write the following callback continuations in c# lambda syntax? I'm writing an asynch unit test and I would like to string it together using lambdas (or anonymous methods?) so I don't have to define named functions for the continuations.
I have read several posts on lambdas, but most of these deal with for each style constructs which I am not interested in.
I would like to do something like the following (taken from here):
using Microsoft.Silverlight.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;
{
[TestClass]
public class Test2 : SilverlightTest
{
[TestMethod]
[Asynchronous]
public void TestAsync1()
{
var eventRaised = false;
var result = false;
var timer = new System.Windows.Threading.DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(2);
timer.Tick += (object sender, EventArgs e) =>
{
timer.Stop();
// Simulate an expected result
result = true;
// Mark the event has being raised
eventRaised = true;
};
// Start timer
EnqueueCallback(() => timer.Start());
// Wait until event is raised
EnqueueConditional(() => eventRaised);
EnqueueCallback(() =>
{
// Additional tasks can be added here
Assert.IsTrue(result);
});
EnqueueTestComplete();
}
}
}
But I guess I don't need the EnqueueCallback() stuff.
The following is my code without lambdas:
[TestClass]
public class IdentityEditDatabaseTest : WorkItemTest
{
[TestMethod, Asynchronous] public void testNullInsert()
{
wipeTestData(testNullInsertContinue1);
}
private void testNullInsertContinue1(String errorString)
{
IdentityProperties properties = new IdentityProperties(getContext());
properties.setUserName(DATABASE_TEST);
postUserEdit(properties, testNullInsertContinue2);
}
private void testNullInsertContinue2(String errorString)
{
Assert.assertTrue(errorString == null);
wipeTestData(testNullInsertContinue3);
}
private void testNullInsertContinue3(String errorString)
{
TestComplete();
}
}
...
Again, the question is:
How can I string the above together using lambdas (or anonymous methods?) so I don't have to define named functions for the continuations?
Please explain the new syntax as much as possible, as I'm still trying to wrap my head around the concept.
Many thanks!
A: If we have the following method:
private void DoSomething(object argument)
{
// Do something with the argument here
}
you're probably aware that it can be assigned to a delegate variable like this:
Action<object> asDelegate = DoSomething;
to make this same assignment using an anonymous method, we can use a lambda expression:
Action<object> asDelegate = (object argument) =>
{
// Do something with the argument here
}
So in your example, the method testNullInsert could be written like this:
[TestMethod, Asynchronous]
public void testNullInsert()
{
wipeTestData((string errorString) =>
{
IdentityProperties properties = new IdentityProperties(getContext());
properties.setUserName(DATABASE_TEST);
postUserEdit(properties, testNullInsertContinue2);
});
}
All I've done there is replaced the name testNullInsertContinue1 with a lambda expression containing the same functionality. You could do the same thing with testNullInsertContinue2 as well if you want.
Once you get more familiar with using lambda expressions, you can drop things like the brackets around the argument (if there's only one argument) and the types of the arguments as the compiler can often infer them, but I've written it like this to try to give you as good an idea of what's going on as possible. Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: In Delphi is it possible to bind an interface to an object that doesn't implement it I know Delphi XE2 has the new TVirtualInterface for creating implementations of an interface at runtime. Unfortunately I am not using XE2 and I'm wondering what kind of hackery is involved in doing this sort of thing in older versions of Delphi.
Lets say I have the following interface:
IMyInterface = interface
['{8A827997-0058-4756-B02D-8DCDD32B7607}']
procedure Go;
end;
Is it possible to bind to this interface at runtime without the help of the compiler?
TMyClass = class(TObject, IInterface)
public
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
procedure Go; //I want to dynamically bind IMyInterface.Go here
end;
I've tried a simple hard cast:
var MyInterface: IMyInterface;
begin
MyInterface := IMyInterface(TMyClass.Create);
end;
but the compiler prevents this.
Then I tried an as cast and it at least compiled:
MyInterface := TMyClass.Create as IMyInterface;
So I imagine the key is to get QueryInterface to return a valid pointer to an Implementation of the interface being queried. How would I go about constructing one at runtime?
I've dug through System.pas so I'm at least vaguely familiar with how GetInterface, GetInterfaceEntry and InvokeImplGetter work. (thankfully Embacadero chose to leave the pascal source along with the optimized assembly). I may not be reading it right but it appears that there can be interface entries with an offset of zero in which case there is an alternative means of assigning the interface using InvokeImplGetter.
My ultimate goal is to simulate some of the abilities of dynamic proxies and mocks that are available in languages with reflection support. If I can successfully bind to an object that has the same method names and signatures as the interface it would be a big first step. Is this even possible or am I barking up the wrong tree?
A: Adding support for an interface to an existing class at runtime can theoretically be done, but it would be really tricky, and it would require D2010 or later for RTTI support.
Each class has a VMT, and the VMT has an interface table pointer. (See the implementation of TObject.GetInterfaceTable.) The interface table contains interface entries, which contain some metadata, including the GUID, and a pointer to the interface vtable itself. If you really wanted to, you could create a copy of the interface table, (DO NOT do this the original one; you're likely to end up corrupting memory!) add a new entry to it containing a new interface vtable with the pointers pointing to the correct methods, (which you could match by looking them up with RTTI,) and then change the class's interface table pointer to point to the new table.
Be very careful. This sort of work is really not for the faint of heart, and it seems to me it's of kind of limited utility. But yes, it's possible.
A: I'm not sure, what you want to accomplish and why you want to dynamically bind that interface, but here is a way to do it (don't know if it fits your need):
type
IMyInterface = interface
['{8A827997-0058-4756-B02D-8DCDD32B7607}']
procedure Go;
end;
TMyClass = class(TInterfacedObject, IInterface)
private
FEnabled: Boolean;
protected
property Enabled: Boolean read FEnabled;
public
constructor Create(AEnabled: Boolean);
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
procedure Go; //I want to dynamically bind IMyInterface.Go here
end;
TMyInterfaceWrapper = class(TAggregatedObject, IMyInterface)
private
FMyClass: TMyClass;
protected
property MyClass: TMyClass read FMyClass implements IMyInterface;
public
constructor Create(AMyClass: TMyClass);
end;
constructor TMyInterfaceWrapper.Create(AMyClass: TMyClass);
begin
inherited Create(AMyClass);
FMyClass := AMyClass;
end;
constructor TMyClass.Create(AEnabled: Boolean);
begin
inherited Create;
FEnabled := AEnabled;
end;
procedure TMyClass.Go;
begin
ShowMessage('Go');
end;
function TMyClass.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if Enabled and (IID = IMyInterface) then begin
IMyInterface(obj) := TMyInterfaceWrapper.Create(Self);
result := 0;
end
else begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
end;
And this is the corresponding test code:
var
intf: IInterface;
my: IMyInterface;
begin
intf := TMyClass.Create(false);
if Supports(intf, IMyInterface, my) then
ShowMessage('wrong');
intf := TMyClass.Create(true);
if Supports(intf, IMyInterface, my) then
my.Go;
end;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: ASP.NET - Check if a WebControl contains server blocks? Is there a way in code to determine if a Web control contains server blocks (other than, for example, parsing out the file, grabbing the contents of the tag, and scanning for <% ... %>)?
My reason for wanting this is because I have a lot of old Web forms that were designed without any regard whatsoever to HTML conformance. The header control (which is included on every page but is inside the body tag) contains the link tag referencing the site's main stylesheet. As long as the page's head tag does not contain server blocks, I can programmatically insert the link tag into Page.Controls.OfType(Of HtmlHead).First(), then set the visibility of the "bad" link tag to false.
Again, this is all legacy stuff (it's in 3.5 now, but most was written in the .NET 1.1 days), so changing everything over to use a master page is something for which I simply do not have the time and budget. Regardless, it would be nice to see the pages come up with the stylesheet pre-loaded, rather than having the browser begin rendering with no styling, then applying the stylesheet once it reaches the reference to it in the body.
A: Seems like a silly work around but could you change the name of your CSS file so that when the legacy code goes to load, it can't find it?
A: Although Mufasa entered his response as a comment, this question has been sitting unresolved too long. Therefore, I will surmise that the only solution is his -- to wrap it in a try/catch black.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Firmata over Bluetooth on Arduino? I have Firmata working fine on an Arduino Uno, communicating over cable USB to Processing.
I want to get rid of the cable, and run the connection over Bluetooth transport (with a BlueSMIRF module). I am unclear on what I need to do to Firmata to tell it to use the BT module rather than the (unconnected) USB cable interface. In particular, do I need to hack Firmata itself to add initialization code which is
*
*specific to the BT module I'm using, or
*more generally, needed to tell Firmata to use a port other than the cabled USB?
Thanks
D
A: I am NOT very good in Firmata, but as i know, Firmata (on arduino) uses 'Serial' (pin 0 and 1, also aka as TX,RX) to communication with the Host. So, if u want to use a BT module to replace your USB cable on the arduino, hack the Firmata to use other pins, other connect the BT to pin 0 and 1.
A: You have to upload standard firmata with baud rate changed to 9600 inside the ino file (or test with other speed rate) and then connect BTooth TX>Rx(uno RX) and the bt RX>Tx(uno TX) as said in the previous post ,testing it with arduinoCommander worked like a charm!Arduino uno rx tx are pin0 and pin 1.also have it powered not from usb pc but external source cause having the BT ontop while on usb could mess up thing (in general disconnect the ground from BT module while uploading sketches).
A: All you have to do is make sure the USB is connected only when you are uploading your sketches to the arduino and then have the BlueSMIRF connected when you are ready to actually run the Arduino code. This way they will both use the default hardware serial port and you should not have to modify any code.
You could try and use SoftwareSerial.h in the Arduino to emulate another serial port but I have found that to be problematic.
A: Just connect Bluetooth to the Rx Tx pin and upload same standard firmata. Then pass command over bluetooth which you were passing over usb cable....it wil work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to configure Shiro + Spring MVC when @Controller REDIRECTS to a login page I have a typical Spring MVC + GWT architecture with Apache Shiro as a security layer.
Problem:
No matter what protocol is used for a request to the App server, pages should be returned in the protocol specified in the request's "X-Forwarded-Proto" header (so, app server can receive a HTTP request, but if the header says HTTPS, it should respond using HTTPS). Obviously, the configuration specified in the Shiro-Spring tutorial won't work as it has nothing to do with the protocols (login.jsp will be returned using the protocol used in request):
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login.jsp"/>
<property name="filterChainDefinitions">
<value>
/** = authc
</value>
</property>
</bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm"/>
</bean>
<bean id="myRealm" class="com.myapp.security.DBRealm">
<property name="credentialsMatcher" ref="sha256Matcher"/>
</bean>
Possible solution:
Use @Controller to REDIRECT to the login view with the specified protocol:
@RequestMapping(value="/login", method=RequestMethod.GET)
public RedirectView doLogin(HttpServletRequest req) throws MalformedURLException {
URL originalURL = new URL(req.getRequestURL().toString());
return new RedirectView(new URL(req.getHeader("X-Forwarded-Proto"), originalURL.getHost(), "/login.jsp").toString());
}
and change the loginUrl in shiro configuration to point to /login, so that @controller catches it:
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login"/>
... leave everything else the same
</bean>
But with this configuration, although I get the same login page, the myRealm (com.myapp.security.DBRealm) is not triggered at all (meaning, the credentials are not checked), and login always fails. Seems like the redirected page loses the "hook" to the realm.
Any ideas on what I am doing wrong?
A: The reason this is failing is because the Shiro authc Filter (a FormAuthenticationFilter) expects the loginUrl to be the one where the login attempt occurs.
That is, when authc filters a request that matches the loginUrl, it will automatically support form-based authentication. Because you are redirecting the end-user to a URL that does not match the loginUrl (i.e. loginUrl=/login, but you redirect them to /login.jsp), the authc filter won't perform a login.
Your best option IMO:
Subclass FormAuthenticationFilter and override the redirectToLogin method to use your X-Forwarded-Proto logic. Then redefine 'authc' to be your custom subclass. For example, using shiro .ini:
[main]
...
authc = com.foo.my.FormAuthenticationFilterSubclass
Also, if you want this behavior in Shiro directly (so Shiro looks for that header when performing a redirect by default) so you can remove your subclass, please open a feature request in Apache Shiro's Jira.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Selecting/deleting certain rows depending on value I wrote this script to delete rows which contain a value in column C that is different than "201103". When I use this to bold it, it works, but when I use it with .Delete it behaves strange and does not work properly.
I was trying to get selected rows and than use UNION to merge it and use .SELECT (multiple) so I could delete it manually but not sure how to make it.
Sub test()
Dim Cell As Range
For Each Cell In Range("C2:C2308").Cells
If (Cell.Value <> "201103" And Cell.Value <> "") Then
Cell.EntireRow.Font.Bold = True
'Cell.EntireRow.Delete
End If
Next Cell
End Sub
Does anyone know how to fix it so it works fine?
A: Try this:
Sub test()
'
With ActiveSheet
.AutoFilterMode = False
With Range("C2", Range("C" & Rows.Count).End(xlUp))
.AutoFilter 1, "<>201103"
On Error Resume Next
.Offset(1).SpecialCells(12).EntireRow.Delete
End With
.AutoFilterMode = False
End With
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unix ls command file name sort (differently than default) Chris-Muenchs-Mac-Book-Pro:database cmuench$ ls -1
database.sql
database_10.0-10.1.sql
database_10.1-10.2.sql
database_10.3-10.4.sql
database_10.4-10.5.sql
database_10.5-10.6.sql
database_10.9-11.0.sql
database_11.0-11.1.sql
database_11.1-11.2.sql
database_11.2-11.3.sql
database_11.6-12.0.sql
database_12.1-12.2.sql
database_12.11-12.12.sql
database_12.12-12.13.sql
database_12.13-12.14.sql
database_12.3-12.4.sql
database_12.4-12.5.sql
database_12.5-12.6.sql
database_12.9-12.10.sql
Is there a way to sort like this?
database.sql
database_10.0-10.1.sql
database_10.1-10.2.sql
database_10.3-10.4.sql
database_10.4-10.5.sql
database_10.5-10.6.sql
database_10.9-11.0.sql
database_11.0-11.1.sql
database_11.1-11.2.sql
database_11.2-11.3.sql
database_11.6-12.0.sql
database_12.1-12.2.sql
database_12.3-12.4.sql
database_12.4-12.5.sql
database_12.5-12.6.sql
database_12.9-12.10.sql
database_12.11-12.12.sql
database_12.12-12.13.sql
database_12.13-12.14.sql
I am on Mac OS X and don't have the sort -V option
A: You can probably sort by time using ls -lrt or some combination like that
r for reverse,
t for time
A: Try using the sort utility:
ls | sort -n
A: Not sure about Mac OS, but give this a try:
LC_COLLATE=C ls -1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: cv maillist script
I've been trying to send many cv at once. But my script doesn't work.
The getrow program works well -> parse a cv file
Any idea?
EDIT5 :
I was stupid. I forgot that my variable was not i
Here is my revised code (that still doesn't work).
Do you know how to increment $var0?
#!/bin/bash
path=~/tests/project_mall
vc=$path/scurricula.pdf
tiv=$path/smotiv.pdf
index=0
LIMIT=$(getrow $1)
while [ "$index" -lt "$LIMIT" ]
do
(mail1_s $(getrow $1 $index 1) $(getrow $1 $index 2) ; uuencode $vc $vc ; uuencode $tiv $tiv) | mailx -s "candidature spontanèe" $(getrow $1 $index 0)
echo -n "mail number $index has been sent" ; echo
sleep 7
let "index+=1"
done
exit 0
EDIT6 : solved, i deleted the output because it contained my mail.
The script above has been edited and works. See ya.
A: To me this looks like a problem $var0++, try var0 = $var0 + 1 to update the value.
A:
So the answer is simple. To increment the while loop, you use let index+=1 with index the variable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.