text
stringlengths
8
267k
meta
dict
Q: how to register a dll using MSBuild I'm trying to register a DLL on a machine using MS build to avoid having to manually register it every time. Can anyone point me in the right direction please? Thanks, A: using the MSBuild Community Tasks you can use the InstallAssembly task Example: <InstallAssembly AssemblyFiles="Engine.dll;Presenter.dll" /> Or: <MSBuild Projects="Project1.csproj;Project2.csproj"> <Output TaskParameter="TargetOutputs" ItemName="ProjectBinaries" /> </MSBuild> <InstallAssembly AssemblyFiles="@(ProjectBinaries)" /> A: Another approach is using the Exec task and call gacutil.exe which is shipped with .NET FX SDK. So you don't need any additional software.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Temporarily disable auto_now / auto_now_add I have a model like this: class FooBar(models.Model): createtime = models.DateTimeField(auto_now_add=True) lastupdatetime = models.DateTimeField(auto_now=True) I want to overwrite the two date fields for some model instances (used when migrating data). The current solution looks like this: for field in new_entry._meta.local_fields: if field.name == "lastupdatetime": field.auto_now = False elif field.name == "createtime": field.auto_now_add = False new_entry.createtime = date new_entry.lastupdatetime = date new_entry.save() for field in new_entry._meta.local_fields: if field.name == "lastupdatetime": field.auto_now = True elif field.name == "createtime": field.auto_now_add = True Is there a better solution? A: You can't really disable auto_now/auto_now_add in another way than you already do. If you need the flexibility to change those values, auto_now/auto_now_add is not best choice. It is often more flexible to use default and/or override the save() method to do manipulation right before the object is saved. Using default and an overridden save() method, one way to solve your problem would be to define your model like this: class FooBar(models.Model): createtime = models.DateTimeField(default=datetime.datetime.now) lastupdatetime = models.DateTimeField() def save(self, *args, **kwargs): if not kwargs.pop('skip_lastupdatetime', False): self.lastupdatetime = datetime.datetime.now() super(FooBar, self).save(*args, **kwargs) In your code, where you want to skip the automatic lastupdatetime change, just use new_entry.save(skip_lastupdatetime=True) If your object is saved in the admin interface or other places, save() will be called without the skip_lastupdatetime argument, and it will behave just as it did before with auto_now. A: You can also use the update_fields parameter of save() and pass your auto_now fields. Here's an example: # Date you want to force new_created_date = date(year=2019, month=1, day=1) # The `created` field is `auto_now` in your model instance.created = new_created_date instance.save(update_fields=['created']) Here's the explanation from Django's documentation: https://docs.djangoproject.com/en/stable/ref/models/instances/#specifying-which-fields-to-save A: You can override auto_now_add without special code. I came across this question when I tried to create an object with particular date: Post.objects.create(publication_date=date, ...) where publication_date = models.DateField(auto_now_add=True). So this is what I've done: post = Post.objects.create(...) post.publication_date = date post.save() This has successfully overridden auto_now_add. As a more long-term solution, overriding save method is the way to go: https://code.djangoproject.com/ticket/16583 A: I used the suggestion made by the asker, and created some functions. Here is the use case: turn_off_auto_now(FooBar, "lastupdatetime") turn_off_auto_now_add(FooBar, "createtime") new_entry.createtime = date new_entry.lastupdatetime = date new_entry.save() Here's the implementation: def turn_off_auto_now(ModelClass, field_name): def auto_now_off(field): field.auto_now = False do_to_model(ModelClass, field_name, auto_now_off) def turn_off_auto_now_add(ModelClass, field_name): def auto_now_add_off(field): field.auto_now_add = False do_to_model(ModelClass, field_name, auto_now_add_off) def do_to_model(ModelClass, field_name, func): field = ModelClass._meta.get_field_by_name(field_name)[0] func(field) Similar functions can be created to turn them back on. A: From django docs DateField.auto_now_add Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True: For DateField: default=date.today - from datetime.date.today() For DateTimeField: default=timezone.now - from django.utils.timezone.now() A: I went the context manager way for reusability. @contextlib.contextmanager def suppress_autotime(model, fields): _original_values = {} for field in model._meta.local_fields: if field.name in fields: _original_values[field.name] = { 'auto_now': field.auto_now, 'auto_now_add': field.auto_now_add, } field.auto_now = False field.auto_now_add = False try: yield finally: for field in model._meta.local_fields: if field.name in fields: field.auto_now = _original_values[field.name]['auto_now'] field.auto_now_add = _original_values[field.name]['auto_now_add'] Use like so: with suppress_autotime(my_object, ['updated']): my_object.some_field = some_value my_object.save() Boom. A: I needed to disable auto_now for a DateTime field during a migration and was able to do this. events = Events.objects.all() for event in events: for field in event._meta.fields: if field.name == 'created_date': field.auto_now = False event.save() A: I'm late to the party, but similar to several of the other answers, this is a solution I used during a database migration. The difference from the other answers is that this disables all auto_now fields for the model under the assumption that there's really no reason to have more than one such field. def disable_auto_now_fields(*models): """Turns off the auto_now and auto_now_add attributes on a Model's fields, so that an instance of the Model can be saved with a custom value. """ for model in models: for field in model._meta.local_fields: if hasattr(field, 'auto_now'): field.auto_now = False if hasattr(field, 'auto_now_add'): field.auto_now_add = False Then to use it, you can simply do: disable_auto_now_fields(Document, Event, ...) And it will go through and nuke all of your auto_now and auto_now_add fields for all of the model classes you pass in. A: A bit more clean version of context manager from https://stackoverflow.com/a/35943149/1731460 NOTE: Do NOT use this context manager in your views/forms or anywhere in your Django app. This context manager alter internal state of field (by temporarily setting auto_now and auto_now_add to False). That will cause Django to not populate these fields with timezone.now() during execution of context manager's body for concurrent requests (ie. same process, different thread). Although this can be used for standalone scripts (ex. management commands, data migration) which are not run in the same process with Django app. from contextlib import contextmanager @contextmanager def suppress_auto_now(model, field_names=None): """ Temp disable auto_now and auto_now_add for django fields @model - model class or instance @field_names - list of field names to suppress or all model's fields that support auto_now_add, auto_now""" def get_auto_now_fields(user_selected_fields): for field in model._meta.get_fields(): field_name = field.name if user_selected_fields and field_name not in user_selected_fields: continue if hasattr(field, 'auto_now') or hasattr(field, 'auto_now_add'): yield field fields_state = {} for field in get_auto_now_fields(user_selected_fields=field_names): fields_state[field] = { 'auto_now': field.auto_now, 'auto_now_add': field.auto_now_add } for field in fields_state: field.auto_now = False field.auto_now_add = False try: yield finally: for field, state in fields_state.items(): field.auto_now = state['auto_now'] field.auto_now_add = state['auto_now_add'] You can use it even with Factories (factory-boy) with suppress_auto_now(Click, ['created']): ClickFactory.bulk_create(post=obj.post, link=obj.link, created__iter=created) A: I've recently faced this situation while testing my application. I needed to "force" an expired timestamp. In my case, I did the trick by using a queryset update. Like this: # my model class FooBar(models.Model): title = models.CharField(max_length=255) updated_at = models.DateTimeField(auto_now=True, auto_now_add=True) # my tests foo = FooBar.objects.get(pk=1) # force a timestamp lastweek = datetime.datetime.now() - datetime.timedelta(days=7) FooBar.objects.filter(pk=foo.pk).update(updated_at=lastweek) # do the testing. A: For those looking at this when they are writing tests, there is a python library called freezegun which allows you to fake the time - so when the auto_now_add code runs, it gets the time you actually want. So: from datetime import datetime, timedelta from freezegun import freeze_time with freeze_time('2016-10-10'): new_entry = FooBar.objects.create(...) with freeze_time('2016-10-17'): # use new_entry as you wish, as though it was created 7 days ago It can also be used as a decorator - see the link above for basic docs. A: copy of Django - Models.DateTimeField - Changing dynamically auto_now_add value Well , I spent this afternoon find out and the first problem is how fetch model object and where in code . I'm in restframework in serializer.py , for example in __init__ of serializer it could not have the Model yet . Now in to_internal_value you can get the model class , after get the Field and after modify the field properties like in this example : class ProblemSerializer(serializers.ModelSerializer): def to_internal_value(self, data): ModelClass = self.Meta.model dfil = ModelClass._meta.get_field('date_update') dfil.auto_now = False dfil.editable = True A: I needed solution that will work with update_or_create, I've came to this solution based on @andreaspelme code. Only change is that You can set skipping by setting modified field to skip not only by actually passing kwarg skip_modified_update to save() method. Just yourmodelobject.modified='skip' and update will be skipped! from django.db import models from django.utils import timezone class TimeTrackableAbstractModel(models.Model): created = models.DateTimeField(default=timezone.now, db_index=True) modified = models.DateTimeField(default=timezone.now, db_index=True) class Meta: abstract = True def save(self, *args, **kwargs): skip_modified_update = kwargs.pop('skip_modified_update', False) if skip_modified_update or self.modified == 'skip': self.modified = models.F('modified') else: self.modified = timezone.now() super(TimeTrackableAbstractModel, self).save(*args, **kwargs) A: Here's another variation and simplification of the useful answer from @soulseekah https://stackoverflow.com/a/35943149/202168 This one can suppress fields on multiple models simultaneously - useful in conjunction with factory_boy such as when you have a SubFactory that also has fields that need suppressing It looks like: @contextmanager def suppress_autonow(*fields: DeferredAttribute): _original_values = {} for deferred_attr in fields: field = deferred_attr.field _original_values[field] = { 'auto_now': field.auto_now, 'auto_now_add': field.auto_now_add, } field.auto_now = False field.auto_now_add = False try: yield finally: for field, values in _original_values.items(): field.auto_now = values['auto_now'] field.auto_now_add = values['auto_now_add'] And is used like (with factory_boy): with suppress_autonow(Comment.created_at, Post.created_at): PostFactory.create_batch(10) # if e.g. PostFactory also creates Comments or just Django: with suppress_autonow(FooBar.createtime, FooBar.lastupdatetime): foobar = FooBar( createtime=datetime(2013, 4, 6), lastupdatetime=datetime(2016, 7, 9), ) foobar.save() i.e. you pass in the actual fields you want to suppress. Note that you must pass them as class fields (i.e. Comment.created_at) and not instance fields (not my_comment.created_at) NOTE: This will break if you pass non-Date/DateTime/Time field to the fields args. if it bothers you, add in an extra isinstance check after field = deferred_attr.field A: While not exactly an answer (the question mentions data migration), here is an approach for testing with pytest. Basically, it is possible to define a fixture to monkeypatch certain field instance attributes. Example may be adapted to loop through fields, etc. @pytest.fixture def disable_model_auto_dates(monkeypatch): """Disables auto dates on SomeModel.""" # might be local, might be on top from project.models import SomeModel field = SomeModel._meta.get_field('created_at') monkeypatch.setattr(field, 'auto_now', False) monkeypatch.setattr(field, 'auto_now_add', False)
{ "language": "en", "url": "https://stackoverflow.com/questions/7499767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "136" }
Q: Applying style resource programmatically I didn't find a way to do that programmatically so I am posting this question here (also i didn't find any question related to this one). I have a resource style, defined in the res/values/styles.xml. What I am trying to do is apply this style inside my activity using java to a View object that i am manipulating. Is it possible to achieve this in Android or the style can only be applied to an object using the android:style attribute? A: Shared this answer here, but since this has it's own conversational thread, I feel like its relevant here as well. There is no one line solution to this problem, but this worked for my use case. The problem is, the 'View(context, attrs, defStyle)' constructor does not refer to an actual style, it wants an attribute. So, we will: * *Define an attribute *Create a style that you want to use *Apply a style for that attribute on our theme *Create new instances of our view with that attribute In 'res/values/attrs.xml', define a new attribute: <?xml version="1.0" encoding="utf-8"?> <resources> <attr name="customTextViewStyle" format="reference"/> ... </resources> In res/values/styles.xml' I'm going to create the style I want to use on my custom TextView <style name="CustomTextView"> <item name="android:textSize">18sp</item> <item name="android:textColor">@color/white</item> <item name="android:paddingLeft">14dp</item> </style> In 'res/values/themes.xml' or 'res/values/styles.xml', modify the theme for your application / activity and add the following style: <resources> <style name="AppBaseTheme" parent="android:Theme.Light"> <item name="@attr/customTextViewStyle">@style/CustomTextView</item> </style> ... </resources> Finally, in your custom TextView, you can now use the constructor with the attribute and it will receive your style public class CustomTextView extends TextView { public CustomTextView(Context context) { super(context, null, R.attr.customTextView); } } It's worth noting that I repeatedly used customTextView in different variants and different places, but it is in no way required that the name of the view match the style or the attribute or anything. Also, this technique should work with any custom view, not just TextViews. A: No, it isn't possible to generically apply a style resources to an existing View instance. Style resources can only be applied to Views during construction time. To understand why, study the View(Context context, AttributeSet attrs, int defStyle) constructor. This is the only place where central View attributes (like android:background) are read, so there is no way to apply a style after the View has been constructed. The same pattern is used for sub classes of View, like TextView. You will need to apply the style attributes manually using setters. Note that if you progamatically instantiate the View, you can use any style resource through the defStyle constructor parameter. A: No this is not possible. The Resources class you normally use to access anything from the /res/ directory has no support for getting styles. http://developer.android.com/reference/android/content/res/Resources.html -- UPDATE -- What I said here wasn't completely right. You can give a style in the constructor of View objects like this: View(Context context, AttributeSet attrs, int defStyle) and also like crnv says for some View implementations A: At least for a TextView this is possible using the setTextAppearance(context, resid) method. The resId of the style can be found under R.style..
{ "language": "en", "url": "https://stackoverflow.com/questions/7499770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Joda Period Formatter System.out.println( PeriodFormat.getDefault().print(Period.hours(1).plusMinutes(30).plusSeconds(60))); The output from the above Joda PeriodFormatter is "1 hour, 30 minutes and 60 seconds". I know that this is a fringe case, but is there a way to output this as "1 hour and 31 minutes"? Thanks! A: You could normalize it first with normalizedStandard: Period period = Period.hours(1).plusMinutes(30).plusSeconds(60); PeriodFormat.getDefault().print(period.normalizedStandard()); Or possibly: Period period = Period.hours(1).plusMinutes(30).plusSeconds(60); PeriodFormat.getDefault() .print(period.normalizedStandard(period.getPeriodType())); A: Try adding toStandardDuration(): System.out.println( PeriodFormat.getDefault().print(Period.hours(1).plusMinutes(30).plusSeconds(60).toStandardDuration()));
{ "language": "en", "url": "https://stackoverflow.com/questions/7499774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pointers in objective-c I have some NSDictionarys full of data and I have a method which utilizes the data. Which NSDictionary is used depends on some input from the user, so I was wondering how I could create a pointer to the NSDictionary with the data. For example The user chooses "option foo", so the method will need to use the "foo dictionary". Instead of copying the "foo dictionary" into a temporary dictionary, how can I reference it so that "tempdictionary" has the contents of "foo dictionary" for example. That probably made no sense, but thanks in advance. A: Copying doesn't happen by default. Just grab the NSDictionary you want and assign it to a new pointer: NSDictionary *fooDictionary = [dataDictionary valueForKey:@"foo"]; That will give you a pointer to the dictionary stored within dataDictionary. It doesn't make a copy unless you ask it to. A: The copy isn't made unless you explicitly tell the code to do so. E.g.: NSDictionary *fooDict = ...; // initialize fooDict and probably other dicts if ([self useFoo]) { [self stuffWithFooDict:fooDict]; // will pass pointer of fooDict } if ([self useFooCopy]) { [self stuffWithFooCopy:[fooDict copy]]; // will use a copy of fooDict }
{ "language": "en", "url": "https://stackoverflow.com/questions/7499775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with jstree can expand nodes with no children I'm working with jstree with ajax and I see that all my nodes have the arrow to expand it, even those which have no children. On the demo page of jstree http://www.jstree.com/demo this is not the case. I don't see on the demo code something different from mine, so does it come from the server ? Have I a parameter to put in response of "getChildren" method to say at jstree "this one, have no children, don't enable to expand it"? Anyone know from where it come from? And what can I do to fix that ? Because it seems to be a problem when I used the copy / paste function of the contextmenu plugin. When I paste on a node (the new parent) with no children and not yet open (so children haven't been loaded), nothing happen except the request to get children (like if I click to open the node) that return nothing obviously. And it doesn't execute the move_node function. EDIT : I have the same problem with "add" from the contextmenu Someone can help me ? Thanks A: From the jsTree documentation: http://www.jstree.com/documentation/html_data one of the three classes will be applied depending on node structure : <li class="[ jstree-open | jstree-closed | jstree-leaf ]"> Jonathan Stowell is right, but setting attr.class to "jstree-leaf" won't work (at least not on the latest version). But "open" and "closed" reminded me of node.state, so I tried, and it turned out that when you set node.state to "leaf" in your JSON serialzation class, it will be non-expandable. A: I added the jstree-leaf class to the attr property for my nodes that do not have children. attr: { "class" : "jstree-leaf" } This then sets the CSS class you need to not have the expand feature. A: I had the same problem with "create" method and nodes without children. Solved it specifying such nodes' state as "open" instead of the default "closed". Hopes this helps. A: if you send json data, give "jstree-leaf" as li_attr's class li_attr: {class = "jstree-leaf" } A: When you return the JSON object, if the node does not have children, set the children property to false and set the state property to false.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why are the OFS and the FS different in awk? In awk, at least in gawk, the field separator FS is whitespace (tab or space), which is reasonable. The output field separator OFS however is set to space by default. I would expect it to be tab, since tab is more standard as a separator of columns in UNIX text files than space (in my experience). What is the rationale behind making it a space? A: Text with TAB may look different in different text editors. Because many of them have the option 'how to interpret TAB' e.g. 4 spaces, 8 spaces etc. But text with space looks everywhere the same. Also some indent sensitive programming languages recommend to use spaces instead of tab, e.g. here. from your point of view, this recommendation may not reasonable either. If you prefer to have space as OFS default, you may create an alias say, myawk=awk -v OFS='\t' A: The awk programming language is probably older than your intuition of any present-day de facto Unix standard. Having said that, the default makes perfect sense, for roughly the same reasons you often see cited when people argue against using tabs for indentation in source files. A: Building on @Kent scripts, here are my aliases to handle csv and tsv, in input (F-parmeter) and output (OFS-parameter): # alias to use awk on csv-files alias awkt='awk -F"\t" -v OFS="\t"' # alias to use awk on tsv-files alias awkc='awk -F"," -v OFS=","' A: Actually, the default value of FS is " " so it makes sense for OFS to have the same value. The implementation of awk is such that when FS is " ", awk skips any leading or trailing spaces and treats all contiguous spaces as separating the fields but nevertheless the default values of both FS and OFS are identical, " ".
{ "language": "en", "url": "https://stackoverflow.com/questions/7499791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is IE9/Firefox showing a different font size in relation to other browsers? I'm programming the CSS of a site, and realized that the Internet Explorer 9 is showing different font size in relation to other browsers (Firefox, Chrome, Safari, IE7 and IE8). I've tried using some RESETS, and I am specifying the font in px, but IE9 still shows the difference in font size. I've tried using font-size in pt, in, percentage, but had no success. I changed the font before (Georgia, Times New Roman, Verdana). Some of them are shown larger, others are smaller in IE9. I checked the zoom settings and text size in IE. They are 100% and medium respectively. To illustrate, I created a simple HTML and CSS as you can see the code below. How to solve this problem? Thanks! The problem: Code: HTML <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="style.css" /> <title>Untitled Document</title> </head> <body> <p> AAAAA BBBBB CCCCC DDDDD EEEEE FFFFF GGGGG HHHHH IIIII JJJJJ KKKKK LLLLL MMMMM NNNNNN OOOOO PPPPP QQQQQ </p> </body> </html> CSS /* RESET */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; } /* END OF RESET */ body { background-image:url(GreenLine.png); background-repeat:no-repeat; font-family:"Courier New", Courier, monospace; font-size:12px; } A: IE9 uses DirectWrite to render text, and other browsers do not (except for Firefox 4+). That is the reason for the slightly different size of the text between the two browsers. There is no way to make the text the same size. Read this: http://www.basschouten.com/blog1.php/font-rendering-gdi-versus-directwrite And this, particularly the "Hinting and spacing differences" section: https://web.archive.org/web/20120603023828/https://blog.mozilla.org/nattokirai/2011/08/11/directwrite-text-rendering-in-firefox-6/ A: Two possible things, both untested: * *try changing the doctype to something other than xhtml transitional. See if the HTML5 doctype renders it better. <!DOCTYPE html> *try using only font-family: monospace; to see if it is a font issue. EDIT If those do not work and you cannot find a solution, you might want to serve IE9 a different font-size using conditional comments. A: Try to set the body{font-size:medium; line-height:1em;} where the font-size will be of 16px now and use percent on p tag to increase or decrease the font-size. To be sure of limit the width of the p tag. P{max-width:40%; font-size:86%; line-height:1.2em;}
{ "language": "en", "url": "https://stackoverflow.com/questions/7499794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Error on cvApproxPoly function I have the following fragment of code: int count = (int)sizes.size(); CvPoint2D32f p; CvSeq* seq = cvCreateSeq(CV_SEQ_KIND_GENERIC|CV_32FC2, sizeof(CvSeq), sizeof(CvPoint2D32f), memStorage1); CvSeq* result; for (int i=0;i<count;i++) { p.x = sizes[i]; p.y = depths[i]; cvSeqPush(seq, &p); } result = cvApproxPoly(seq, sizeof(CvPoint2D32f), memStorage2, CV_POLY_APPROX_DP, 3, 0); but this code throws exception: Error: Bad argument (Unsupported sequence type) in cvApproxPoly what's wrong in my code? on documentation it says that cvApproxPoly takes first argument as CvSeq * A: According to this post, cvApproxPoly gives an error when the CV_SEQ_POLYLINE flag isn't set for the sequence you pass in. Try adding that flag to your cvCreateSeq line.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GetDIBits help I'm trying to get the bits of a 1bpp bitmap using getDIBits using this code: HDC dcmem=NULL; PBYTE buf=NULL; LPBITMAPINFO bmpInfo; HBITMAP bmpfile = NULL; int dibLineCount; //load bitmap bmpfile = (HBITMAP)LoadImageA(NULL, FILENAME, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); if(!bmpfile) { //Load Image failed return 0; } //select bitmap to dc dcmem = CreateCompatibleDC ( NULL ); if (NULL==SelectObject(dcmem,bmpfile)) { //select object failed DeleteDC(dcmem); return 0; } bmpInfo = (LPBITMAPINFO)calloc(1,sizeof(BITMAPINFO)); bmpInfo->bmiHeader.biSize=sizeof(BITMAPINFOHEADER); //getDIBits to fill bmpInfo dibLineCount = GetDIBits(dcmem,bmpfile,0,0,NULL,bmpInfo,DIB_RGB_COLORS); if(dibLineCount == 0) { //getdibits 1 failed DeleteDC(dcmem); free(bmpInfo); return 0; } if(bmpInfo->bmiHeader.biSizeImage <= 0) bmpInfo->bmiHeader.biSizeImage=bmpInfo->bmiHeader.biWidth*abs(bmpInfo->bmiHeader.biHeight)*(bmpInfo->bmiHeader.biBitCount+7)/8; if((buf = (PBYTE)malloc(bmpInfo->bmiHeader.biSizeImage)) == NULL) return 0; bmpInfo->bmiHeader.biCompression =BI_RGB; //get bits dibLineCount = GetDIBits(dcmem,bmpfile,0,bmpInfo->bmiHeader.biHeight,buf,bmpInfo,DIB_RGB_COLORS); if(dibLineCount == 0) { //getdibits 2 failed DeleteDC(0,dcmem); free(buf); free(bmpInfo); return 0; } Then I send the bits using winsock to another PC. But everytime I send the packet with the bits I see the bits only contain periods "..." or FF in hex which is very weird. I see that the second call to getDIBits returns the correct amount of lines scanned though. Can anyone help me why the bits are like this? Any help would be appreciated. A: You're getting the pixel format of the compatible DC instead of the original pixel format, when you first call GetDIBits. Selecting the bitmap into the DC doesn't set up the DC to use the pixel format of the bitmap, it converts the bitmap to the format of the screen. (I suspect the way you're loading the image also converts the bitmap to the pixel format of the screen.) When you load the bitmap, you probably want to load it as a DIBSECTION by adding LR_CREATEDIBSECTION to the options in LoadImage. This will keep the bits in their original pixel format. If you want the bits out in a particular pixel format, you should manually initialize the bmpInfo structure to the format you want and then call GetDIBits. If you want the bits in the pixel format of the original file, you probably don't even need GetDIBits. If you use LR_CREATEDIBSECTION on the LoadImage, you can then use GetObject to get the DIBSECTION, which has the format in it (and probably a pointer to the bits).
{ "language": "en", "url": "https://stackoverflow.com/questions/7499801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Confused about number in SQL SELECT statement I was reading a SQL "cookbook" type reference, and I came across a statement that I has never come across before: INSERT INTO table (col1, col2) SELECT t.col1, 8 FROM table AS t WHERE t.col2 = 5 UNION ALL SELECT 8, 8 Now what confuses me is a number (in this example, 8) immediately following the SELECT statement. In my limited SQL experience, I have only come across SELECT queries that are followed by column names. Could somebody help me understand what this does? Thanks! A: The SELECT 8, 8 does exactly what it appears to do; it returns a result set with 2 un-named columns each containing 8 - if you run just that statement yourself you'll see exactly that. You are free to select literal values & expressions just as you are columns, function results etc; SELECT 'cake', 123 + 456 The UNION ALL merges (non-duplicate) rows from the 1st table select with the result of the 2nd select so your inserting a single additional (8,8) row into the table. A: You can add a literal value to the select statement. In this case it will just add an additional column to the result with the value 8 for all rows. You can also use functions that don't reference columns similarly. e.g. SELECT t.col1, NOW() AS t The AS t defines a column alias for the extra column. This is not important in your example as it is just used as the source for an insert anyway. I won't bother addressing the UNION ALL as that isn't the point of confusion to you. A: It selects the literals 8 and 8. The statement will insert into table the values of col1 and 8 from table where col2 of table = 5 AND one more row with values 8 and 8 A: INSERT INTO table1 (col1, col2) Insert into a table named table1 a row with values for col and col2. Set all other columns to their default value (or null if there is none). SELECT t.col1, 8 FROM table AS t WHERE t.col2 = 5 Insert the output of this select statement. Note that select 8 will substitute a literal 8 in every row of the output. UNION ALL SELECT 8, 8 Put an extra row with just col1=8, col2=8 in the result. Links: http://dev.mysql.com/doc/refman/5.0/en/insert-select.html http://dev.mysql.com/doc/refman/5.0/en/select.html From the last link: SELECT can also be used to retrieve rows computed without reference to any table. For example: mysql> SELECT 1 + 1; -> 2 A: You can SELECT anything you want, starting from table fields, ending at custom expressions that can be evaluated by SQL engine (for example table.field * 2). In this query you'll have 8 as fields of every returned record. A: It is the relational operation known as 'extend' (interestingly, Codd initially omitted extend from his relational algebra, probably because he envisaged calculations being done in the 'front end'). Although typically used for calculation, extension involving a literal is allowed and, while not terribly useful, from a language design point of view there is no reason to disallow it. A: You can put a value directly in a SELECT statement. t.col1 is actually a variable which will have different values in different returned registers. 8 is a literal value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is fastest, @Entity or @Embedded? Im new (today) to the NoSql MongoDb and trying to understand the Morphia. I want to have one @Entity like this: If i have 3 Tables (Collections) named Stat Friendlist Userdata I save UserData.Class in Userdata right and Statistic.Class in Stat and so on... My thought was if i give each user a unique ObjectId UUID nr and then every Statistic and FriendList having this UUID nr as there ObjectId. Because if the program need to run statistic only, it will load/work against Statistic only. @Entity public class UserData { @Id private ObjectId id = "UUID 123456789; public String userName = ""; public String password = ""; @Embedded private Statistic statistic; @Embedded private FriendList friendList; } If there are like 18000/hour request to get the UserData would it not be faster to declare them like this: ( i use the same ObjectId and they ares stored in separate Collections (tables) @Entity public class UserData { @Id private ObjectId id = "UUID 123456789; public String userName = ""; public String password = ""; } @Entity public class Statistic { @Id private ObjectId id = "UUID 123456789; public int loginTimes; public String gps; } @Entity public class FriendList { @Id private ObjectId id = "UUID 123456789; public ArrayList<String> fiends; } A: I think that the correct is use DBRef or Embedded. If you want some object of the list in other object too, use DBRef, if not, use embedded. For example, in a blog post, the comments will never be used in another post, so, its embedded. So, use somehting like: @Entity public class UserData { @Id private ObjectId id = "UUID 123456789; public String userName = ""; public String password = ""; @Embedded private Statistic statistic; @Embedded private List<Friends> friendList; } hope it helps. A: Embedded is always faster because Reference stored in different physical location.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: URL exists gives "Does not Exists" To check if url exists not regular file Tried 1. file_exists - just a test, should not be for a url 2. empty 3. fopen All the above gave a "Does not exists if(fopen("http://www.google.com",r)){ echo "exists"; } else { echo "doesnot exist"; } I have ran out of ideas as to why its happening. the file has been given 777. Code is being tested from 127.0.0.1. This is the only code on the page. I do not wish to use curl, and keep it simple and normal coding. Checked on Google and other Q's on stackoverflow All I want to check is if the URL is real. A: You need to enable allow_url_fopen in your php.ini config file. A: Check your php.ini file and ensure you have access to the fopen function. Also, the the first two parameters in fopen are strings. So the correct syntax of your command is: if( fopen( "http://www.google.com", "r" ) !== false ) A: Maybe the php setting allow_url_fopen is set to false so this won't work. Did you try using CURL and checking the response headers? A: I ran this at my local machine if (fopen("http://www.google.nl", 'r')) { echo 'exists'; } else { echo 'no exists'; } While you do have an error (r doesnt exist, but is interperted as 'r', unless you defined it elsewhere this shoudn't be a problem. Check your local php configuration and or system configuration. (possible the ini setting allow_url_fopen)
{ "language": "en", "url": "https://stackoverflow.com/questions/7499804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: show loading image until the content is fully loaded I'm using image slide show in my site, but when i loading my site it take more time and initially page not look better one by one image. So, i want to load first loading image on the image slide and when div content is fully loaded then hide the loading image and display image slide show. so, hows this possible please help me. i'm not loading content from ajax. it's simple loading. A: $('#loading-image').show(); // show loading image before request $('#content').load('my-content-source.php', function() { // load content $('#loading-image').hide(); // hide image after content was loaded }); where loading-image is id of your loading indicatior, and content is id of your content container. A: It depends what you want to display, a simple loading background image could be done like this: before starting with loading your content you could set a class on your Div element. $('#myDiv').addClass('loading'); in CSS you could have #myDiv { width: 100px; height; 100px; } #myDiv.loading { background: url(loading.gif) no-repeat center center; } after loading you can remove the class $('#myDiv').load("http://www.mypage.com/contentToLoad.php", function(){ $('#myDiv').removeClass('loading'); }); if you want to display more markup (html, a div with text and an image ...) you will need to do the same but instead of using addClass() and removeClass, you would need to Show() and Hide() the other element. A: You can use the onload event of an image and then hide your loading animation. <img onload="hideLoadingDiv();"> A: This kind of depends on how you exactly are doing everything right now.. But this is about as simple as it gets: http://jsfiddle.net/JTCpB/1/ Edit: Updated that loading image to something that.. makes sense. <div id="load"> <img src="http://lorempixum.com/g/400/200/" alt="" /> </div> #load { width: 400px; height: 200px; background: url("loading.gif") no-repeat center center; } A: $(window).on("load", function (e) { $(".loader").fadeOut("slow"); }) .loader{position:fixed;left:0;top:0;width:100%;height:100%;z-index:9999;background:url(https://texas-ppo-plans.com/p/img2/loading.gif) 50% 50% no-repeat #fff;opacity:.80; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> Here is the working snippet example. <!--add this loader in your just start of the body tag--> <div class="loader"> </div><br><br> <!--this is the content area--> <a href="#">Home</a> | <a href="#">About</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/7499805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to add Textviews next to each other and move them to the next line if they dont fit I have 5 textviews, each textview has its own background and they are one next to the other, their sizes change depending on the amount of text that I put in them. I want to know if at any point they stop fitting because they reach the border of the parent. But not only that if they dont fit I want to be able to add something like "click here to see more". So how do I detect how much space have they taken so far as I go adding the text to them? thanks A: You can use TextUtils.ellipsize. Maintain the actual text in a member. Call ellipsize with the text as parameter and set the returned text to the textview. You can set a callback TextUtils.EllipsizeCallback which will be called when the text gets ellipsized. TextUtils.EllipsizeCallback ellipsizeCallback = new TextUtils.EllipsizeCallback(){ void ellipsized(int start, int end) { // enable the `click here to see more` button. } } ... CharSequence elipsizedText = ellipsize (mtext, mtxtpaint, avail, TextUtils.TruncateAt.END , preserveLength, ellipsizeCallback); tv.setText(mtext);
{ "language": "en", "url": "https://stackoverflow.com/questions/7499807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: html5 audio 'mediaplayable' event? my app lets user drag songs to add them. I was wondering how can i make sure that the files user dragged are actually music files and are playable? i can use loadedmetadata event but how would i know when a file does not get loaded so that i can discard it? i remember readng about an event that would tell if the file is playable. I googled a lot but couldn't find it, maybe my mind is making things up.. so how can i know weather a file is playable? checking file extension is an option but i would like to make it platform independent and different platform plays different files. A: I believe you ar looking for canplay event: http://www.w3.org/TR/html5/the-iframe-element.html#mediaevents A: What i ended up with was the progress event. canplay waits for data to be loaded so that some of it can be played, but progress shows that the media is available and it is now progressing to download its meta.. If given an invalid file, it throws an error event instead of progress hence facilitates the knowledge of weather the file is a valid and playable media file or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Troubles with keyboardEvent.shiftKey in Chrome I'd met a very strange problem. Take a look at the following code: Lib.current.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed); ... private static function onKeyPressed(e: KeyboardEvent) { trace(e.shiftKey); } if you press any key (except SHIFT) false is outputed. Press SHIFT+ALT (first press SHIFT and then ALT). Then after pressing of any key true is outputed. Note that if I press SHIFT, press of any key will output false again. you may download swf containing code listed above from here. IMPORTANT: I have this issue only on Chrome, e.g. on Firefox everything is ok. Note: If that's important, I'm working with Haxe languge, not with AS3. Any thoughts will be appreciated. Thank you in advance!! A: Go into chrome://plugins/ in a new tab. Check and see if under the flash section you have more than 1 flash plugins installed for Chrome. If so, disable the older version(s) and then try your test again. A: That's a known bug. It should work fine in tomorrow's canary build (16.0.890.0) and will be fixed on stable in a week or two. Absolutely do not disable the built-in Flash. It will leave you with an outdated and unsandboxed version of Flash.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I get a Silverlight 4 client to connect to a windows service I have an existing window service. It does not use WCF and nor do I want it to. The windows service listens on a port and once a socket connects it starts publishing application status information every second. I want to build a SilverLight application that can consume all the published information and update a display. I have come across plenty of articles that describe this for a web service or for a WCF service. I have stock standard executable running as a window service. Am I trying to do the impossible here. A: Silverlight has some support for using sockets directly. See Working With Sockets on MSDN. Pay special attention to the part about security restrictions policy. If Silverlight runs in the sandbox (not OOB) you cannot connect to any random host on the network.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How create Context menu in AIR application plus how add sub menu against any parent item in Flex? How create Context menu in AIR application plus how add sub menu against any parent item in Flex? A: couldn't be simpler, as for flex I am not sure, but I think its even easier. import flash.ui.ContextMenu; import flash.ui.ContextMenuItem; import flash.events.ContextMenuEvent; //create a new context menu to replace the default var myContextMenu:ContextMenu = new ContextMenu(); //hide the default items myContextMenu.hideBuiltInItems(); //create custom items: var myMenuItem1:ContextMenuItem = new ContextMenuItem("Item 1"); var myMenuItem2:ContextMenuItem = new ContextMenuItem("Item 2"); var myMenuItem3:ContextMenuItem = new ContextMenuItem("Item 3"); //listen to the events of those items myMenuItem1.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,handleMenuItems); myMenuItem2.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,handleMenuItems); myMenuItem3.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT,handleMenuItems); //put those items inside an array var myItems:Array = [myMenuItem1,myMenuItem2,myMenuItem3]; //put the array containing the items inside the contextMenut myContextMenu.customItems = myItems; //now you can apply the context menu on any display object or the root mc this.contextMenu = myContextMenu; //now handle clicks function handleMenuItems(event:ContextMenuEvent):void { switch (event.currentTarget) { case myMenuItem1: trace("you clicked the first menu Item"); break; case myMenuItem2: trace("you clicked the second menu Item"); break; case myMenuItem3: trace("you clicked the third menu Item"); break; } } A: Have you tried........ google? http://www.adobe.com/devnet/air/flex/quickstart/articles/adding_menus.html http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/ui/ContextMenu.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7499823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java Framework for automation based on Pixel Pattern recoginition I have to develop some kind of bot for a testing background with Java. We used Selenium for all the web stuff, and outside the browser: Pixel recognition; that is, taking a screenshot, then compare it with a image I have already, and get the coordinates of where that pattern is on the screenshot. Any Framework or free Java libraries that could make this job easier? Thanks in advance! A: You could read this simple example. A: You could probably get the following to work: * *Use java.awt.Robot to take a screen capture as a BufferedImage *Convert the BufferedImage to a byte array *Do a standard string matching search to locate the pattern in the byte array. Even a naive string search (i.e. checking for the pattern at every possible location) could well be fast enough. *Convert the position in the byte array back to image co-ordinates
{ "language": "en", "url": "https://stackoverflow.com/questions/7499825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JPA relation Persistence I am using JPA 2 with following jars on class path [INFO] +- org.aspectj:aspectjrt:jar:1.6.9:compile [INFO] +- org.aspectj:aspectjweaver:jar:1.6.9:compile [INFO] +- org.springframework:spring-aspects:jar:3.1.0.M2:compile [INFO] | +- org.springframework:spring-beans:jar:3.1.0.M2:compile [INFO] | | \- org.springframework:spring-core:jar:3.1.0.M2:compile [INFO] | \- org.springframework:spring-context-support:jar:3.1.0.M2:compile [INFO] +- com.googlecode.commonspringaspects:common-spring-aspects:jar:1.0.9:compile [INFO] | +- net.sf.ehcache:ehcache-core:jar:1.7.2:compile [INFO] | \- com.jamonapi:jamon:jar:2.4:compile [INFO] +- com.jamon:jamonapi:jar:2.73:compile [INFO] +- javax.validation:validation-api:jar:1.0.0.GA:compile [INFO] +- org.springframework:spring-context:jar:3.1.0.M2:test (scope not updated to compile) [INFO] | +- org.springframework:spring-aop:jar:3.1.0.M2:test [INFO] | | \- aopalliance:aopalliance:jar:1.0:test [INFO] | +- org.springframework:spring-expression:jar:3.1.0.M2:test [INFO] | \- org.springframework:spring-asm:jar:3.1.0.M2:test [INFO] +- org.springframework:spring-orm:jar:3.1.0.M2:test [INFO] | +- org.springframework:spring-jdbc:jar:3.1.0.M2:test [INFO] | \- org.springframework:spring-tx:jar:3.1.0.M2:test [INFO] +- org.mockito:mockito-all:jar:1.9.0-rc1:test [INFO] +- dirty-mockito:dirty-mockito:jar:0.4:test [INFO] +- org.hibernate:hibernate-validator:jar:4.2.0.Final:test [INFO] +- org.hsqldb:hsqldb:jar:2.2.4:compile [INFO] +- org.hibernate:hibernate-entitymanager:jar:3.6.2.Final:compile [INFO] | +- org.hibernate:hibernate-core:jar:3.6.2.Final:compile [INFO] | | +- antlr:antlr:jar:2.7.6:compile [INFO] | | +- commons-collections:commons-collections:jar:3.1:compile [INFO] | | +- dom4j:dom4j:jar:1.6.1:compile [INFO] | | +- org.hibernate:hibernate-commons- annotations:jar:3.2.0.Final:compile [INFO] | | \- javax.transaction:jta:jar:1.1:compile [INFO] | +- cglib:cglib:jar:2.2:compile [INFO] | | \- asm:asm:jar:3.1:compile [INFO] | +- javassist:javassist:jar:3.12.0.GA:compile [INFO] | \- org.hibernate.javax.persistence:hibernate-jpa-2.0- api:jar:1.0.0.Final:compile [INFO] +- javax.inject:javax.inject:jar:1:compile [INFO] +- junit:junit:jar:4.8.1:test [INFO] +- org.springframework:spring-test:jar:3.1.0.M2:test [INFO] +- commons-logging:commons-logging:jar:1.1.1:compile [INFO] +- org.slf4j:slf4j-api:jar:1.5.10:compile [INFO] +- org.slf4j:jcl-over-slf4j:jar:1.5.10:compile [INFO] +- org.slf4j:slf4j-log4j12:jar:1.5.10:compile [INFO] \- log4j:log4j:jar:1.2.15:compile and my model is as follows <access>FIELD</access> <mapped-superclass class="com.compnay.qube.foundation.core.model.BaseModel"> <attributes> <id name="uid"> <column name="UID" nullable="false" /> <generated-value strategy="AUTO" /> </id> <basic name="creationDate"> <column name="CREATIONDATE" updatable="false" nullable="false" /> <temporal>TIMESTAMP</temporal> </basic> <basic name="modificationDate"> <column name="MODIFICATIONDATE" updatable="true" nullable="true" column-definition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP" /> <temporal>TIMESTAMP</temporal> </basic> <one-to-many name="changeLog"> <cascade> <cascade-persist /> <cascade-merge /> <cascade-refresh /> </cascade> </one-to-many> <!-- <element-collection name="changeLog" fetch="LAZY"> </element-collection> --> </attributes> </mapped-superclass> <entity class="com.compnay.qube.services.core.user.model.User" name="User"> <table name="USER" /> <inheritance strategy="JOINED" /> <named-query name="findUserByUserName"> <query><![CDATA[select user from User user where user.userName = :userName]]></query> </named-query> <attributes> <basic name="userName"> <column name="USERNAME" length="100" updatable="false" unique="false" /> </basic> <basic name="passsword"> <column name="PASSWORD" length="100" updatable="false" unique="false" /> </basic> <basic name="email"> <column name="EMAIL" length="100" updatable="false" unique="false" /> </basic> <basic name="optIn"> <column name="OPTIN" updatable="true" unique="false" /> </basic> <one-to-many name="userRoles"> <join-table name="USER_ROLES"> <join-column name="USER_ID" /> <inverse-join-column name="ROLE_ID" /> </join-table> <cascade> <cascade-persist /> <cascade-merge /> <cascade-refresh /> </cascade> </one-to-many> </attributes> </entity> <entity class="com.compnay.qube.services.core.user.model.Role" name="ROLE"> <table name="ROLE" /> <inheritance strategy="JOINED" /> <named-query name="findByUniqueName"> <query><![CDATA[select role from ROLE role where role.roleName = :roleName]]></query> </named-query> <attributes> <basic name="roleName"> <column name="ROLE" length="100" updatable="true" unique="true" /> </basic> <!--<transient name="user" /> --> <many-to-one name="user"> <cascade> <cascade-all /> </cascade> </many-to-one> </attributes> </entity> Base DAO has method public void create(M model) throws DAOException { try { entityManager.persist(model); } catch (RollbackException rollBackExp) { ErrorCode errorCode = new ErrorCode(); // SQLException sqle = (SQLException) pExp.getCause().getCause(); // errorCode = errorHandler.getErrorCode(sqle); // errorCode.setCode(sqle.getErrorCode() + ""); throw new DAOException(errorCode, rollBackExp); } catch (PersistenceException pExp) { ErrorCode errorCode = new ErrorCode(); // SQLException sqle = (SQLException) pExp.getCause().getCause(); // errorCode = errorHandler.getErrorCode(sqle); // errorCode.setCode(sqle.getErrorCode() + ""); throw new DAOException(errorCode, pExp); }finally{ entityManager.flush(); } } and services just delegates it to dao for now wrapped in transaction by spring. when i run my test to persist User only it works fine but when i add userRoles to the user if(roles.size() == 0){ Role arole = initRole(RoleType.ADMIN.name(), CREATION_DATE_YESTERDAY, MODIFICATION_DATE_TODAY); Role srole = initRole(RoleType.SUPER_USER.name(), CREATION_DATE_YESTERDAY, MODIFICATION_DATE_TODAY); Role urole = initRole(RoleType.USER.name(), CREATION_DATE_YESTERDAY, MODIFICATION_DATE_TODAY); roles.put(arole.getRoleName(), arole); roles.put(srole.getRoleName(), srole); roles.put(urole.getRoleName(), urole); } User user_one = initUser("user" + (i+1) , "user" + (i+1), "user" + (i+1) + "@user.com", CREATION_DATE_YESTERDAY, MODIFICATION_DATE_TODAY); user_one.setUserRoles(new HashSet<Role>(roles.values())); Enumeration<String> roleKeys = roles.keys(); while(roleKeys.hasMoreElements()){ String key = roleKeys.nextElement(); Role role = roles.get(key); role.setUser(user_one); } try { userService.create(user_one); Set<Role> urole = user_one.getUserRoles(); for (Role role : urole) { roles.put(role.getRoleName(), role); } //logger.debug(user_one); } catch (ServiceException e) { e.printStackTrace(); } It thorws an exception in second iteration java.sql.BatchUpdateException: Duplicate entry '3' for key 'ROLE_ID' ERROR: org.hibernate.util.JDBCExceptionReporter - Duplicate entry '3' for key 'ROLE_ID' org.hibernate.util.JDBCExceptionReporter - SQL Error: 1062, SQLState: 23000 Can someone suggest what is wrong with this bit of code. Can't use annotations as this is mapping legacy code being used in various applications
{ "language": "en", "url": "https://stackoverflow.com/questions/7499827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I load all Entity Framework 4.1 entity configuration entities via reflection? In my OnModelCreating method for my data context I currently am manually mapping all my entity configuration mapping classes manually, like: protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new UserMap()); // 20 or so mapping configuration below } I want to streamline this by using reflection, so I have the following code: protected override void OnModelCreating(DbModelBuilder modelBuilder) { // Find all EntityTypeConfiguration classes in the assembly foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) foreach (Type t in asm.GetTypes()) if (t.IsDerivedFromOpenGenericType(typeof(EntityTypeConfiguration<>))) modelBuilder.Configurations.Add(Activator.CreateInstance(t)); } the IsDerivedFromOpenGenericType is from this question and works properly. The problem is this doesn't compile because Activator.CreateInstance(t) returns an object, but the model builder is expecting a System.Data.Entity.ModelConfiguration.ComplexTypeConfiguration<TComplexType>. Normally when using the Activator class I would just cast the object as whatever I expect type t to be (or what I expect the class to take), but since this is using a generics I don't know of a way to do that. Does anyone have any ideas? A: I'm not sure why this information is so hard to find (at least it was for me), but there is a much simpler way to do it detailed here. public class MyDbContext : DbContext { protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.AddFromAssembly(Assembly.GetAssembly(GetType())); //Current Assembly base.OnModelCreating(modelBuilder); } } A: I got this from Rowan Miller at Microsoft: protected override void OnModelCreating(DbModelBuilder modelBuilder) { var addMethod = typeof (ConfigurationRegistrar) .GetMethods() .Single(m => m.Name == "Add" && m.GetGenericArguments().Any(a => a.Name == "TEntityType")); var assemblies = AppDomain.CurrentDomain .GetAssemblies() .Where(a => a.GetName().Name != "EntityFramework"); foreach (var assembly in assemblies) { var configTypes = assembly .GetTypes() .Where(t => t.BaseType != null && t.BaseType.IsGenericType && t.BaseType.GetGenericTypeDefinition() == typeof (EntityTypeConfiguration<>)); foreach (var type in configTypes) { var entityType = type.BaseType.GetGenericArguments().Single(); var entityConfig = assembly.CreateInstance(type.FullName); addMethod.MakeGenericMethod(entityType) .Invoke(modelBuilder.Configurations, new[] {entityConfig}); } } base.OnModelCreating(modelBuilder); } A: I found a much better way of doing this using composition with MEF: public class Album { public int AlbumId { get; set; } public int GenreId { get; set; } public int ArtistId { get; set; } public string Title { get; set; } public decimal Price { get; set; } public string AlbumArtUrl { get; set; } public Genre Genre { get; set; } public Artist Artist { get; set; } } using System.Data.Entity.ModelConfiguration.Configuration; namespace MvcMusicStore.Models { public interface IEntityConfiguration { void AddConfiguration(ConfigurationRegistrar registrar); } } using System.ComponentModel.Composition; using System.Data.Entity.ModelConfiguration; using System.Data.Entity.ModelConfiguration.Configuration; namespace MvcMusicStore.Models.TypeConfig { [Export(typeof(IEntityConfiguration))] public class AlbumTypeConfiguration : EntityTypeConfiguration<Album>, IEntityConfiguration { public AlbumTypeConfiguration() { ToTable("Album"); } public void AddConfiguration(ConfigurationRegistrar registrar) { registrar.Add(this); } } } using System.Collections.Generic; using System.ComponentModel.Composition; namespace MvcMusicStore.Models { public class ContextConfiguration { [ImportMany(typeof(IEntityConfiguration))] public IEnumerable<IEntityConfiguration> Configurations { get; set; } } } using System; using System.ComponentModel.Composition.Hosting; using System.Data.Entity; using System.Data.Entity.ModelConfiguration; using System.Data.Entity.ModelConfiguration.Configuration; using System.Linq; using System.Reflection; namespace MvcMusicStore.Models { public class MusicStoreEntities : DbContext { public DbSet<Album> Albums { get; set; } public DbSet<Genre> Genres { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(catalog); var exports = container.GetExportedValues<IEntityConfiguration>(); foreach (var entityConfiguration in exports) { entityConfiguration.AddConfiguration(modelBuilder.Configurations); } base.OnModelCreating(modelBuilder); } } } credit: OdeToCode.com Composing Entity Framework Fluent Configurations A: You have to use reflection here as well. Get the Method with Type.GetMethod() and then create the generic version you need with MethodInfo.MakeGenericMethod(): Type tCmpxTypeConfig = typeof (EntityTypeConfiguration<>); tCmpxTypeConfig = tCmpxTypeConfig.MakeGenericType(t); modelBuilder.Configurations.GetType() .GetMethod("Add", new Type[] { tCmpxTypeConfig }) .MakeGenericMethod(t) .Invoke(modelBuilder.Configurations, new object[] { Activator.CreateInstance(t) });
{ "language": "en", "url": "https://stackoverflow.com/questions/7499829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Need T-SQL code for the following pseudo code Table A: | BillToName | Current| Total | ----------------------------- | Company29 | N | 100 | ----------------------------- | Company02 | Y | 80 | ----------------------------- I need T-SQL for the following pseudo code: SELECT BillToName, SUM(Total *regardless if the status is "Y" or "N") WHERE Current = 'Y' Feel free to ask questions. Thanks! A: I think you mean something like: SELECT BillToName, SUM(Total) FROM Table WHERE BillToName IN (SELECT BillToName FROM Table WHERE Current = 'Y') GROUP BY BillToName A: SELECT a.BillToName, b.Total FROM TableA a CROSS APPLY (SELECT SUM(Total) Total FROM TableA) b WHERE Current = 'Y' A: select billtoname,(select sum(total) from table) where current='Y'
{ "language": "en", "url": "https://stackoverflow.com/questions/7499832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: boost shared_ptr get owner count I'm using boost::shared_ptr to store a pointer to texture. I'm loading new textures as i need and share them among the program using shared_ptr. If my app is using too much memory i want to remove unused textures to clear memory. Is there a way I can determine how many objects are having access to the texture via shared_ptr ? A: If it's unused then the shared_ptr will free it automatically. That's the point of shared_ptr. If you are holding a shared_ptr to a texture without actually using it, then you're violating the contract of shared_ptr and should not be using it. A: You can use shared_ptr::use_count(), but read the documentation before doing so! A: There is use_count(), however note that as the documentation says, it's not necessarily too efficient. A: The shared_ptr class has member functions use_count() and unique() to give you access to its usage count. It's a different question how that information will be useful to you, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: convert getch() response to ascii character I am using ncurses on linux. I use getch() to get the next key pressed from the input stream but it returns a number not a letter. After doing research on google I have found that getch() is not standard so I am at a loss of what to do. I need the keys 0-9, tab, ctrl, p,v,m,l,a,b,c,d,e,f, and the arrow keys as well as 0xff, 0x4F00, 0x4700, 0x4800, 0x5000, 0x4D00:, 0x4B00, 0x4900, 0x5100. These are what are uses in if statments against the returned valus of getch(). this is the code in the windows version of the program am trying to recreate. unsigned long nr; if( GetNumberOfConsoleInputEvents(ConH,&nr) ) { if( nr > 0 ) { INPUT_RECORD ipr; ReadConsoleInput(ConH,&ipr,1,&nr); if( ipr.EventType == KEY_EVENT && ipr.Event.KeyEvent.bKeyDown ) { int key = ipr.Event.KeyEvent.uChar.AsciiChar; if( key == 0 ) key = ipr.Event.KeyEvent.wVirtualScanCode<<8; return key; } } } return 0; Is there a function i can use on the result of getch() so i can get the actual key pressed, something like the .AsciiChar seen above ? A: MAJOR EDIT Get rid of previous examples, try this large one. The return value from getch() is either an ASCII character, or the curses name for some special key. Here is a program that might make the point clear: #include <ncurses.h> #include <cctype> int main(int ac, char **av) { WINDOW* mainWin(initscr()); cbreak(); noecho(); // Invoke keypad(x, true) to ensure that arrow keys produce KEY_UP, et al, // and not multiple keystrokes. keypad(mainWin, true); mvprintw(0, 0, "press a key: "); int ch; // Note that getch() returns, among other things, the ASCII code of any key // that is pressed. Notice that comparing the return from getch with 'q' // works, since getch() returns the ASCII code 'q' if the users presses that key. while( (ch = getch()) != 'q' ) { erase(); move(0,0); if(isascii(ch)) { if(isprint(ch)) { // Notice how the return code (if it is ascii) can be printed either // as a character or as a numeric value. printw("You pressed a printable ascii key: %c with value %d\n", ch, ch); } else { printw("You pressed an unprintable ascii key: %d\n", ch); } } // Again, getch result compared against an ASCII value: '\t', a.k.a. 9 if(ch == '\t') { printw("You pressed tab.\n"); } // For non-ASCII values, use the #define-s from <curses.h> switch(ch) { case KEY_UP: printw("You pressed KEY_UP\n"); break; case KEY_DOWN: printw("You pressed KEY_DOWN\n"); break; case KEY_LEFT: printw("You pressed KEY_LEFT\n"); break; case KEY_RIGHT: printw("You pressed KEY_RIGHT\n"); break; } printw("Press another key, or 'q' to quit\n"); refresh(); } endwin(); } References: * *http://linux.die.net/man/3/getch *http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/ *http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/keys.html *http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/keys.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7499846", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook FQL page_user Right i have a problem which i have done so much research for that i still cant be able to solve the problem. What i am trying to achieve is when a facebook user LIKES my page not an app, i want to be able to retrieve all the users that have liked the facebook page. I am using FQL but having no luck at all, if i do an FQL based on the admins of the page it brings the data up. SELECT first_name, last_name FROM user WHERE uid IN (SELECT uid FROM page_fan WHERE page_id = [your page id]) the above FQL should work. But nothing is being displayed, is this a facebook bug that has not been flagged or fixed? using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MVCFacebookTestApp.Models; using Facebook; using Facebook.Web; namespace MVCFacebookTestApp.Controllers { public class HomeController : Controller { public FacebookSession FacebookSession { get { return (FacebookWebContext.Current.Session); } } public ActionResult Index() { string request = Request.Form["signed_request"]; string accessToken = ""; if (Request.Form["access_token"] != null) { accessToken = Request.Form["access_token"]; } FacebookApplication app = new FacebookApplication(); FacebookSignedRequest result = FacebookSignedRequest.Parse(app.InnerCurrent, request); if (String.IsNullOrWhiteSpace(accessToken)) { accessToken = result.AccessToken; } dynamic data = result.Data; bool liked = data.page.liked; //bool liked = true; if (!liked) { Home h = Home.NotLiked(); return View(h); } else { Home h = Home.Liked(); FacebookWebClient fb = null; if (String.IsNullOrWhiteSpace(accessToken)) { var fbRequest = FacebookWebContext.Current; if (fbRequest.IsAuthorized()) fb = new FacebookWebClient(fbRequest); } else { fb = new FacebookWebClient(accessToken); } if (fb != null) { dynamic r = fb.Get("/me"); h.TestString2 += " Ha! We captured this data about you!"; h.TestString2 += " Name: " + r.name; h.TestString2 += " Location: " + r.location; h.TestString2 += " Birthday: " + r.birthday; h.TestString2 += " About Me: " + r.aboutme; h.ImgUrl = "http://graph.facebook.com/" + r.id + "/picture?type=large"; string fqlResult = ""; var fbApp = new FacebookClient(accessToken); //basic fql query execution dynamic friends = fbApp.Query("SELECT uid FROM page_admin WHERE page_id='160828267335555'"); //SELECT uid FROM page_fan WHERE page_id = 160828267335555 //"SELECT uid FROM page_fan WHERE uid=me() AND page_id=<your page id>"; //loop through all friends and get their name and create response containing friends' name and profile picture foreach (dynamic friend in friends) { fqlResult += friend.uid + "<br />"; //fqlResult += friend.name + "<img src='" + friend.pic_square + "' alt='" + friend.name + "' /><br />"; } ViewBag.Likes = fqlResult; } else { //Display a message saying not authed.... } return View(h); } } } } is there a solution out there that actually works? Please do get back to me ASAP your help would be much appreciated, will save me from losing all my hair with the stress LOL Thanks in advance. A: You can make a GET request to /USER_ID/likes/PAGE_ID (replacing the caps part with the relevant IDs) to check if a particular user is a fan of your page. This is the replacement for the old 'pages.isFan' API method. There's no way to retrieve a list of users that like your page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: phpMyAdmin + CentOS 6.0 - Forbidden I always get this message when I would like access my phpMyAdmin. w3m localhost/phpmyadmin Forbidden You don't have permission to access /phpmyadmin/ on this server. Apache/2.2.15 (CentOS) Server at localhost Port 80 Install steps: rpm --import http://dag.wieers.com/rpm/packages/RPM-GPG-KEY.dag.txt yum install http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2- 2.el6.rf.x86_64.rpm yum install phpmyadmin Add Aliases vi /etc/httpd/conf.d/phpmyadmin.conf Alias /phpmyadmin /usr/share/phpmyadmin Alias /phpMyAdmin /usr/share/phpmyadmin Alias /mysqladmin /usr/share/phpmyadmin Change from cookie to http vi /usr/share/phpmyadmin/config.inc.php [...] /* Authentication type */ $cfg['Servers'][$i]['auth_type'] = 'http'; [...] Restart /etc/init.d/httpd restart SELinux - /etc/httpd drwxr-xr-x. root root system_u:object_r:httpd_config_t:s0 . drwxr-xr-x. root root system_u:object_r:etc_t:s0 .. drwxr-xr-x. root root system_u:object_r:httpd_config_t:s0 conf drwxr-xr-x. root root system_u:object_r:httpd_config_t:s0 conf.d lrwxrwxrwx. root root system_u:object_r:httpd_log_t:s0 logs -> ../../var/log/httpd lrwxrwxrwx. root root system_u:object_r:httpd_modules_t:s0 modules -> ../../usr/lib64/httpd/modules lrwxrwxrwx. root root system_u:object_r:httpd_config_t:s0 run -> ../../var/run/httpd SELinux - /usr/share/phpmyadmin drwxr-xr-x. root root system_u:object_r:usr_t:s0 . drwxr-xr-x. root root system_u:object_r:usr_t:s0 .. -rw-r--r--. root root system_u:object_r:usr_t:s0 browse_foreigners.php -rw-r--r--. root root system_u:object_r:usr_t:s0 calendar.php -rw-r--r--. root root system_u:object_r:usr_t:s0 changelog.php -rw-r--r--. root root system_u:object_r:usr_t:s0 chk_rel.phph . . . -rw-r--r--. root root system_u:object_r:usr_t:s0 view_create.php OS centos-release-6-0.el6.centos.5.x86_64 A: I tried all answers provided here: editing phpMyAdmin.conf, changing selinux context for phpmyadmin folder, disabling selinux... but I still got a 'Forbidden' from the web server. I finally found what I was missing in Edouard Thiel post here : $ yum install php then restart httpd : $ service httpd restart => for centos 6 hots $ systemctl restart httpd => for centos 7 hosts What has me amazed is why php is not installed as dependency for phpmyadmin in the first place. Regards, Fred A: Edit your httpd.conf file as follows: # nano /etc/httpd/conf/httpd.conf Add the following lines here: <Directory "/usr/share/phpmyadmin"> Order allow,deny Allow from all </Directory> Issue the following command: # service httpd restart If your problem is not solved then disable your SELinux. A: None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that's what worked for me: Edit file phpMyAdmin.conf sudo nano /etc/httpd/conf.d/phpMyAdmin.conf And replace this at the top: <Directory /usr/share/phpMyAdmin/> AddDefaultCharset UTF-8 <IfModule mod_authz_core.c> # Apache 2.4 <RequireAny> #Require ip 127.0.0.1 #Require ip ::1 Require all granted </RequireAny> </IfModule> <IfModule !mod_authz_core.c> # Apache 2.2 Order Deny,Allow Deny from All Allow from 127.0.0.1 Allow from ::1 </IfModule> </Directory> A: I had the same issue for two days now. Disabled SELinux and everything but nothing helped. And I realize it just may not be smart to disable security for a small fix. Then I came upon this article - http://wiki.centos.org/HowTos/SELinux/ that explains how SELinux operates. So this is what I did and it fixed my problem. * *Enable access to your main phpmyadmin directory by going to parent directory of phpmyadmin (mine was html) and typing: chcon -v --type=httpd_sys_content_t phpmyadmin *Now do the same for the index.php by typing: chcon -v --type=httpd_sys_content_t phpmyadmin/index.php Now go back and check if you are getting a blank page. If you are, then you are on the right track. If not, go back and check your httpd.config directory settings. Once you do get the blank page with no warnings, proceed. *Now recurse through all the files in your phpmyadmin directory by running: chron -Rv --type=httpd_sys_content_t phpmyadmin/* Go back to your phpmyadmin page and see if you are seeing what you need. If you are running a web server that's accessible from outside your network, make sure that you reset your SELinux to the proper security level. Hope this helps! A: Non of the above mentioned solutions worked for me. Below is what finally worked: #yum update #yum install phpmyadmin Be advised, phpmyadmin was working a few hours earlier. I don't know what happened. After this, going to the browser, I got an error that said ./config.inic.php can't be accessed #cd /usr/share/phpmyadmin/ #stat -c %a config.inic.php #640 #chmod 644 config.inic.php This shows that the file permissions were 640, then I changed them to 644. Finially, it worked. Remember to restart httpd. #service httpd restart A: I have faced the same problem when I tape the URL https://www.nameDomain.com/phpmyadmin the forbidden message shows up, because of the rules on /use/share/phpMyAdmin directory I fix it by adding in this file /etc/httpd/conf.d/phpMyAdmin.conf in this section <Directory /usr/share/phpMyAdmin/> .... </Directory> these line of rules <Directory /usr/share/phpMyAdmin/> Order Deny,Allow Deny from All Allow from 127.0.0.1 Allow from ::1 Allow from All ... </Directory> you save the file, then you restart the apache service whatever method you choose service httpd graceful or service httpd restart it depends on your policy for security reasons you can specify one connection by setting one IP address if your IP does not change, else if your IP changes every time you have to change it also. <Directory /usr/share/phpMyAdmin/> Order Deny,Allow Deny from All Allow from 127.0.0.1 Allow from ::1 Allow from 105.105.105.254 ## set here your IP address ... </Directory> A: I had the same issue. Only after I changed in php.ini variable display_errors = Off to display_errors = On Phpadmin started working.. crazy....
{ "language": "en", "url": "https://stackoverflow.com/questions/7499849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: SQL Replication, CE device I have a Windows CE device that I'd like to replicate data to a SQL Server 2008 R2 database. I understand the basics of replication and I need to use MSDN's "Two-Server Topology". Where there is an IIS box and a separate SQL Server box. I have replication and a publication set up on the SQL database. Also, on the IIS box I created a virtual directory and via UNC have the physical folder on the database box. So the virtual dir path on the IIS box looks something like "\databasebox\c$\Replications". I set up a user on both boxes and am able to test the connection successfully. I'm able to browse to the virtual directory from the device via a path such as: "https://www.mydomain.com/Replications" and with directory browsing turned on I can see the sqlcesa35.dll. The issue is adding the subscription. Using the Web Synchronization Wizard, I cannot complete the process. I get to the point where I'm configuring the existing virtual directory. Choose it and get an error "ConnWiz - The local path is not in the correct format". If I use the wizard to create a new virtual dir and get tot he point of adding the remote directory UNC it does not allow it. I've tried mapped drives, not allowed. This has to be possible, its part of Microsoft's "Two-Server Topology". How do I create a replication subscription on IIS box-1 where the virtual directory points to a folder on box-2? A: The problem you are facing is related to IIS 7&8 support of Web Synchronization wizard. According to this MSDN article "The Configure Web Synchronization Wizard is not supported on IIS 7.0.". What you need is to do manual configuration of IIS for Web Synchronization. You can find the steps to do that here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to geocode an address into lat/long with Google maps I want to be able to plot several companies on a google map and understand I need to geocode these. I also have the code below that plot's multiple markers on a map. How can I Geocode several company addresses (using the following address as the first example) and incorporate it into the current code I have? I really need someone's help as I can't make sense of the Google documentation as well as incorporating it with what I already have. A: you could use google's geocoding to obtain coordinates of your post codes EDIT: I don't really like you changing the sense of the question like that but ok. Please try sth like that (its not tested): // Creating an array that will contain the coordinates // for New York, San Francisco, and Seattle var places = []; // Adding a LatLng object for each city //places.push(new google.maps.LatLng(40.756, -73.986)); //places.push(new google.maps.LatLng(37.775, -122.419)); //places.push(new google.maps.LatLng(47.620, -122.347)); //places.push(new google.maps.LatLng(-22.933, -43.184)); var result; var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", "http://maps.googleapis.com/maps/api/geocode/json?address=your+code&sensor=false",true); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4) { result = eval('(' + xmlhttp.responseText + ')'); if (result.status == "OK") { var location = new google.maps.LatLng(result.results[0].geometry.location.lat, result.results[0].geometry.location.lng); places.push(location); this should probably work, despite possible minor errors. EDIT2: I have just now found simpler solution: // Creating an array that will contain the coordinates // for New York, San Francisco, and Seattle var places = []; // Adding a LatLng object for each city //places.push(new google.maps.LatLng(40.756, -73.986)); //places.push(new google.maps.LatLng(37.775, -122.419)); //places.push(new google.maps.LatLng(47.620, -122.347)); //places.push(new google.maps.LatLng(-22.933, -43.184)); var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': "your+code"}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); //var marker = new google.maps.Marker({ //map: map, //position: results[0].geometry.location //}); places.push(results[0].geometry.location); } else { alert("Geocode was not successful for the following reason: " + status); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7499862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Returning reference to a local variable Why can this code run successfully in Code::block. The IDB just reports warning: "reference to local variable ‘tmp’ returned", but ouput the result "hello world" successfully. #include <iostream> #include<string> using namespace std; const string &getString(const string &s) { string tmp = s; return tmp; } int main() { string a; cout<<getString("hello world")<<endl; return 0; } A: Upon leaving a function, all local variables are destroyed. By returning a reference to tmp, you are returning a reference to an object that soon ceases to exist (that is, technically, the address of a memory region whose contents are no longer meaningful). Accessing such a dangling reference invokes what is called 'undefined behaviour' - and sadly, 'work as usual' is one kind of 'undefined behaviour'. What might happen here is that std::string keeps a small static buffer for small strings (as opposed to large strings, for which it grabs memory from the heap), and upon leaving getString the stack space occupied by this string is not zeroed so it still seems to work. If you try a debug build, or invoke another function in between (which will effectively overwrite the stack space), it won't work anymore. A: You are causing an undefined behaviour. The standard doesn't tell what happens in that case, however your compiler detected it. A: tmp disappears the moment you return from getString. Using the returned reference is undefined behaviour, so anything can happen. To fix your code, return the string by value: string getString(const string &s) { ... A: Are you sure? It should segfault (it will with gcc on most platforms). That code does contain an error, and if you get 'lucky' and it works, then you're brushing a nasty bug under the carpet. Your string is returned by reference, that is, rather than making a new string which is valid in the context you are returning into, a pointer to a stale, destructed, object is being returned, which is bad. const string getString... will do as the declaration for the function's return type. A: The temporary object is deallocated, however its contents are still there on the stack, until something rewrites it. Try to call a few functions between calling your function and printing out the returned object: const string& garbage = getString("Hello World!"); callSomeFunctionThatUsesALotOfStackMemory(); cout<< garbage << endl; A: As you can see the below example code is just slightly modified by calling goodByeString(). Like the other answers already pointed out the variable in getString called tmp is local. the variable gets out of scope as soon as the function returns. since it is stack allocated the memory is still valid when the function returns, but as soon as the stack grows again this portion of memory where tmp resided gets rewritten with something else. Then the reference to a contains garbage. However if you decide to output b since it isn't returned by reference the contents is still valid. #include <iostream> #include<string> using namespace std; const string &getString(const string &s) { string tmp = s; return tmp; } string goodByeString(const string &s) { string tmp = "lala"; tmp += s; return tmp; } int main() { const string &a = getString("Hello World!\n"); string b = goodByeString("ciao\n"); cout << a << endl; return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7499864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ASP.NET button options.clientSubmit is set to false I have a ASP.NET button which sometimes does not post back. I checked this in IE developer and found that when the button does not work options.clientSubmit is set to false in the function WebForm_DoPostBackWithOptions() My button code <asp:Button runat="server" ID="btnSubmit" CssClass="button" OnClick="btnSubmit_Click" meta:resourcekey="btnSubmitResource1" /> Inside WebForm_DoPostBackWithOptions(options) if (options.clientSubmit) { __doPostBack(options.eventTarget, options.eventArgument); } Can anyone tell me why the button sometimes works and sometimes does not? what should I do to make it work always? A: This may be a possibility: Check if you have any Validators on the page which have not been grouped to any ValidationGroup and may be visible false(may be due container is visible false). This validator may be validating the control which is of no relevance under this circumstance and causing the postback to cancel saying it invalid. If you find any, to group all the related controls, assign a ValidationGroup to all the corresponding Validators and then assign that group to your submit control(whichever causes postback). This is most common mistake I have seen.. A: Try adding CausesValidation = "False" and see what happens. I suspect you have some validation that isn't passing. A: You're not using anything to prevent repeated submission of the form? I had exactly the same issue, the .Net validation method indicated that the form was valid, but options.clientSubmit was always false :S The culprit turned out to be: <script type="text/javascript"> $(document).ready(function() { $('.prevDblSubmit').preventDoubleSubmit(); }) </script> A: This seems that should be working, instead of using meta:resourcekey="btnSubmitResource1", try explicit localization. See question: ASP.NET: explicit vs implicit localization?
{ "language": "en", "url": "https://stackoverflow.com/questions/7499870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to safely store credentials entered in Application Preferences? My iPhone App connects to a web service using a username and a password. I prefer to save the credentials in the Application Preferences (settings bundle) like the Mail App. Is this secure enough? Is it possible to save those values to the keychain (via Application Preferences)? Edit: I want my users to enter their credentials in the Application Preferences of my App. Normally, I can retrieve this data in my app with NSUserDefaults. But Application Preferences saves the data as plain text and it's neither encrypted nor hashed. Is there a safe way? Eg. I know the keychain on the iPhone and I find it great! Can I use the keychain to hold the credentials entered in Application Preferences? Food for thought: How does Apple do it? I mean, when I want to use the Mail App, I provide my username and password in the Application Preferences. Are those values stored as plaintext? A: Did you check the keychain documentation? On the security, see this white paper by the Fraunhofer SIT institute. A: Keychain Services will be required for secure storage. Using NSUserDefaults will not secure your data. A: You can save it securely using Security.framework. It is very nice sample from Apple where many aspects of using that framework are discussed. I advice you to look through it. Here is the link to that sample: GenericKeychain This sample shows how to add, query for, remove, and update a keychain item of generic class type. Also demonstrates the use of shared keychain items. All classes exhibit very similar behavior so the included examples will scale to the other classes of Keychain Item: Internet Password, Certificate, Key, and Identity. A: It seems that many people do not seem to understand your question. Unfortunately I can not find the answer myself. The question is how do you use the keychain AND NSUserDefaults at the same time. I too would like to use the NSUserDefaults interface. Hopefully we can figure this out... One option would be to store just the username. Then when the app starts if there is no password in the keychain or if there is a wrong password in the keychain--ask for a new password. A: You can remove items from NSUserDefaults when your app runs after the user uses Settings to enter them into the app's Application Preferences. Then put them into the keychain. But these items may be in plain text in storage in the interim(depending on which iPhone model, some may encrypt the flash storage and the backups), before you can remove them from NSUserDefaults. A: Apple owns the entire OS and of course the Mail app. They are using features outside of the public SDK, because they can. How do you think the Mail app can run in the background and keep checking for your mails? Normal app can't achieve this :( Back to your main question, using keychain is the right way to go. But you probably have to disallow users to enter username & password in Application Preferences. There is no way to secure that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Find rows without relations in sqlite3? I have two tables. One called "members" and another called "homes" (should be household, but I suck in english). Those have a many-one relation (i.e. several members belong to one household). Those are linked together by members.homefk and homes.Id Now, how can I find homes that don't belong to any members? I want this for house cleaning purposes. A: SELECT homes.* FROM homes LEFT JOIN members ON (members.home_id = home.id) WHERE members.home_id IS NULL A: Use a subquery to return all the homefk values, then select from homes where id not in the subquery, In Oracle would look something like SELECT h.id FROM homes h WHERE h.id NOT IN( SELECT DISTINCT(m.homefk) FROM members m)
{ "language": "en", "url": "https://stackoverflow.com/questions/7499876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Determining the values of beta in a logistic regression equation I read about logistic regression on Wikipedia and it talks of the equation where z, the output depends on the values of beta1, beta2, beta3, and so on which are termed as regression coefficients along with beta0, which is the intercept. How do you determine the values of these coefficients and intercept given a sample set where we know the output probability and the values of the input dependent factors? A: Use R. Here's a video: www.youtube.com/watch?v=Yv05RjKpEKY
{ "language": "en", "url": "https://stackoverflow.com/questions/7499892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Does Spring's PlatformTransactionManager require transactions to be committed in a specific order? I am looking to retrofit our existing transaction API to use Spring’s PlatformTransactionManager, such that Spring will manage our transactions. I chained my DataSources as follows: DataSourceTransactionManager - > LazyConnectionDataSourceProxy - > dbcp.PoolingDataSource - > OracleDataSource In experimenting with the DataSourceTransactionManager , I have found that where PROPAGATION_REQUIRES_NEW is used, it seems that Spring’s transaction management requires that the transactions be committed/rolled back in LIFO fashion, i.e. you must commit/rollback the most recently created transactions first. Example: @Test public void testSpringTxns() { // start a new txn TransactionStatus txnAStatus = dataSourceTxnManager.getTransaction(propagationRequiresNewDefinition); // specifies PROPAGATION_REQUIRES_NEW Connection connectionA = DataSourceUtils.getConnection(dataSourceTxnManager.getDataSource()); // start another new txn TransactionStatus txnBStatus = dataSourceTxnManager.getTransaction(propagationRequiresNewDefinition); Connection connectionB = DataSourceUtils.getConnection(dataSourceTxnManager.getDataSource()); assertNotSame(connectionA, connectionB); try { //... do stuff using connectionA //... do other stuff using connectionB } finally { dataSourceTxnManager.commit(txnAStatus); dataSourceTxnManager.commit(txnBStatus); // results in java.lang.IllegalStateException: Cannot deactivate transaction synchronization - not active } } Sadly, this doesn’t fit at all well with our current transaction API which allows you to create transactions, represented by Java objects, and commit them in any order. My question: Am I right in thinking that this LIFO behaviour is fundamental to Spring’s transaction management (even for completely separate transactions)? Or is there a way to tweak its behaviour such that the above test will pass? I know the proper way would be to use annotations, AOP, etc. but at present our code is not Spring-managed, so it is not really an option for us. Thanks! A: yes,I have met the same problems below when using spring: java.lang.IllegalStateException: Cannot deactivate transaction synchronization - not active. According above,Spring’s transaction management requires that the transactions be committed/rolled back in LIFO fashion(stack behavior).The problem disappear. thanks. A: Yes, I found this same behavior in my own application. Only one transaction is "active" at a time, and when you commit/rollback the current transaction, the next active transaction is the next most recently started transaction (LIFO/stack behavior). I wasn't able to find any way to control this, it seems to be built into the Spring Framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to serialize nested types in WCF response? Scenario: I'm in the process of creating a WCF service that exposes user data. An instance of User has a property called Role. If I omit this property, the service works; if don't omit the property, the service fails. Below is a (very) simplified representation of the code. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1, EmitConformanceClaims = true)] [ServiceContract(Name = "IService", Namespace = "http://local/version1/")] public interface IService : IDisposable { [WebMethod] [SoapDocumentMethod(ParameterStyle = SoapParameterStyle.Bare)] [OperationContract(Action = "http://local/version1/GetUser")] GetUserResponse GetUser(GetUserRequest request); } [MessageContract(IsWrapped = true, WrapperName = "GetUserResponse")] [XmlRoot("GetUserResponse")] public class GetUserResponse { [XmlElement(ElementName = "User")] [MessageBodyMember(Order = 0)] public User User { get; set; } } public class User { public int UserId { get; set; } public string UserName { get; set; } public Role Role { get; set; } } public class Role { public string Name { get; set; } } The root of the problem is that the Role is nested/embedded (how do you call it...) in the User class. It seems that it can't be serialzed this way. If searched on possible solutions, but can't seem to find the right solution. I've tried something with KnownTypeAttribute on the contract as well as the User class, but that didn't work. Questions: * *What is the proper way to include the Role property on the User class? *Which attributes should be added where to make it work? *Possible interfaces to be implemented to make it serializable? Thanks in advance for any replies! Update #1 After suggestions of @CPX, I created additional test code on the server side: using (StringWriter stringWriter = new StringWriter()) { XmlSerializer serializer = new XmlSerializer(typeof(GetUserResponse)); serializer.Serialize(stringWriter, response); string result = stringWriter.ToString(); } This results in an InvalidOperationException with message 'There was an error generating the XML Document'. This exception has an InvalidOperationException (again) as InnerException, with message 'The type System.Data.Entity.DynamicProxies.User_FAC9CE2C5C9966932C0C37E6677D35437C14CDD08‌​884AD33C546805E62B7101E was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.'. Forgot to mention in the post, that the User and Role classes are used within Entity Framework 4.1. Didn't guess should be a problem, but apparently it does. A: You will need to make User and Role DataContracts like this: [DataContract] public class User { [DataMember] public int UserId { get; set; } [DataMember] public string UserName { get; set; } [DataMember] public Role Role { get; set; } } [DataContract] public class Role { [DataMember] public string Name { get; set; } } This lets WCF know how and what to serialize. There is an example of mixing MessageContract and DataContract, as you are doing in your case, on MSDN here: http://msdn.microsoft.com/en-us/library/ff648210.aspx A: Probably has something to do with proxy creation. Try setting the following: context.ContextOptions.ProxyCreationEnabled = false; A: [DataContract] public class User { [DataMember] public int UserId { get; set; } [DataMember] public string UserName { get; set; } [DataMember] public Role role { get; set; } } [DataContract] public class Role { [DataMember] public string Name { get; set; } } A: Add datacontract attributes to the classes and datamember attributes to each property you want to serialize
{ "language": "en", "url": "https://stackoverflow.com/questions/7499896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating SQLite Table from Android HTML Assets I tried to use a HTML in android to create a table in sqlite but it is not working Sample HTML is here <!DOCTYPE html> <html> <head> <title>Contact Example</title> <script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for PhoneGap to load // //document.addEventListener("deviceready", onDeviceReady, false); // PhoneGap is ready // function onDeviceReady() { var db = openDatabase("Database", "1.0", "PhoneGap Demo", 200000); db.transaction(populateDB, errorCB, successCB); } // Populate the database // function populateDB(tx) { tx.executeSql('DROP TABLE IF EXISTS DEMO'); tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)'); tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")'); tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")'); } // Transaction error callback // function errorCB(tx, err) { alert("Error processing SQL: "+err); } // Transaction success callback // function successCB() { alert("success!"); } </script> </head> <body onload="onDeviceReady()"> <h1>Example</h1> <p>Database</p> </body> </html> Android 2.2 I am not able to see any database create in android. Please some suggestion A: I think your database created in android's cache directory, that's why to are unable to see it. so use WebView's setting method and make cache enable also give WebView's SQLite database path to your cache directory then use your database. If I am wrong then please let me know it. EDIT: look at this, Step 1: Create a WebView, Step 2. Get the webSettings, and set the Database Path. The path should be the path to your databases, which will be /path/path/your_package_name/. appView.setWebChromeClient(new WebClient(this)); WebSettings settings = appView.getSettings(); settings.setJavaScriptEnabled(true); settings.setJavaScriptCanOpenWindowsAutomatically(true); settings.setDatabaseEnabled(true); settings.setDatabasePath("/data/data/<database path>/app_database"); Step 3: Create a WebChromeClient, and override the onExceededDatabaseQuota method. This is called when you first open the application because there’s initially no database setup. This will allow you to set the quota in Java. Since this was test code, I just threw an arbitrary value in here. final class WebClient extends WebChromeClient { Context mCtx; WebClient(Context ctx) { mCtx = ctx; } public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota,WebStorage.QuotaUpdater quotaUpdater) { Log.d(LOG_TAG, "We exceeded the quota"); quotaUpdater.updateQuota(100000); } } EDIT: for more details look at here. Thanks. A: On rooted device go to : * *DDMS *File Explorer *data ->data *package name *app_databases Here "app_databases" contains "Databases.db" file that contains other databases files . A: WebView has the ability to invoke java code through javascript code. How about trying this solution?
{ "language": "en", "url": "https://stackoverflow.com/questions/7499899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: c++ inserting elements at the end of a vector I am experiencing a problem with the vector container. I am trying to improve the performance of inserting a lot of elements into one vector. Basically I am using vector::reserve to expand my vector _children if needed: if (_children.capacity() == _children.size()) { _children.reserve(_children.size() * 2); } and using vector::at() to insert a new element at the end of _children instead of vector::push_back(): _children.at(_children.size()) = child; _children has already one element in it, so the first element should be inserted at position 1, and the capacity at this time is 2. Despite this, an out_of_range error is thrown. Can someone explain to me, what I misunderstood here? Is it not possible to just insert an extra element even though the chosen position is less than the vector capacity? I can post some more code if needed. Thanks in advance. /mads A: Increasing the capacity doesn't increase the number of elements in the vector. It simply ensures that the vector has capacity to grow up to the required size without having to reallocate memory. I.e., you still need to call push_back(). Mind you, calling reserve() to increase capacity geometrically is a waste of effort. std::vector already does this. A: This causes accesses out of bounds. Reserving memory does not affect the size of the vector. Basically, you are doing manually what push_back does internally. Why do you think it would be any more efficient? A: Neither at nor reserve increase the size of the vector (the latter increases the capacity but not the size). Also, your attempted optimization is almost certainly redundant; you should simply push_back the elements into the array and rely on std::vector to expand its capacity in an intelligent manner. A: That's not what at() is for. at() is a checked version of [], i.e. accessing an element. But reserve() does not change the number of elements. You should just use reserve() followed by push_back or emplace_back or insert (at the end); all those will be efficient, since they will not cause reallocations if you stay under the capacity limit. Note that the vector already behaves exactly like you do manually: When it reaches capacity, it resizes the allocated memory to a multiple of the current size. This is mandated by the requirement that adding elements have amortized constant time complexity. A: You have to differentiate between the capacity and the size. You can only assign within size, and reserve only affects the capacity. A: vector::reserve is only internally reserving space but is not constructing objects and is not changing the external size of the vector. If you use reserve you need to use push_back. Additionally vector::at does range checking, which makes it a lot slower compared to vector::operator[]. What you are doing is trying to mimic part of the behaviour vector already implements internally. It is going to expand by its size by a certain factor (usually around 1.5 or 2) every time it runs out of space. If you know that you are pushing back many objects and only want one reallocation use: vec.reserve(vec.size() + nbElementsToAdd); If you are not adding enough elements this is potentially worse than the default behaviour of vector. A: The capacity of a vector is not the number of elements it has, but the number of elements it can hold without allocating more memory. The capacity is equal to or larger than the number of elements in the vector. In your example, _children.size() is 1, but there is no element at position 1. You can only use assignment to replace existing elements, not for adding new ones. Per definition, the last element is at _children.at(_children.size()-1). The correct way is just to use push_back(), which is highly optimized, and faster than inserting at an index. If you know beforehand how many elements you want to add, you can of course use reserve() as an optimization. It's not necessary to call reserve manually, as the vector will automatically resize the internal storage if neccessary. Actually I believe what you do in your example is similar what the vector does internally anyway - when it reaches the capacity, reserve twice the current size. See also http://www.cplusplus.com/reference/stl/vector/capacity/
{ "language": "en", "url": "https://stackoverflow.com/questions/7499902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IPv6 samples Wireshark Samples Possible Duplicate: Sample data for IPv6? Apart from what wireshark has at its website, is there a good resource where I can download various samples of IPv6 pcaps? A: Take a look at PacketLife or pcapr (you have to register).
{ "language": "en", "url": "https://stackoverflow.com/questions/7499903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to remove single quotes that is automatically inserted in codeigniter? How to prevent in codeigniter to not insert single quotes around in our query? When we write query in codeigniter it inserts automatically single quotes, like this: $this->db->select('id, ifnull(name,\'\') as name'); $this->db->from('table'); which creates database error. A: $this->db->select('id, ifnull("name",\'\') as name', false); $this->db->from('table'); Is what you're after. The quotes are escaping to stop sql injection, be sure not to mix unsanitized input from the user. I guess I should also note that using this false parameter will stop double quote encapsulation, if you're using postgres you'll probably need to encapsulate any kew words used as column names yourself. (see difference between name and "name") Active Record - Selecting Data
{ "language": "en", "url": "https://stackoverflow.com/questions/7499911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Outlook Flagging and make E-mail Important Using C# I am currently automating emails being sent out I have everything working ok I just want to be able to flag the email and set it to important. I looked on outlook help page and they tell you most of this stuff and explain well, but I can't find flag email or set to important. Any help is greatly appreciated. Thanks using Outlook = Microsoft.Office.Interop.Outlook; private void button13_Click(object sender, EventArgs e) //Send Email of Drawing { // Create the Outlook application by using inline initialization. Outlook.Application oApp = new Outlook.Application(); //Create the new message by using the simplest approach. Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem); //Add a recipient Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add("email address here"); oRecip.Resolve(); //Set the basic properties. oMsg.Subject = "Job # " + textBox9.Text + " Release (" + textBox1.Text + ")"; oMsg.HTMLBody = "<html><body>"; oMsg.HTMLBody += "Hello" //Send Message oMsg.Send //Explicitly release objects oRecip = null; oMsg = null; oApp = null; } A: Set the MailItem.Importance property; http://msdn.microsoft.com/en-us/library/ff866759.aspx A: MailItem.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh should do the trick A: Choose one of: oMsg.Importance = Outlook.OlImportance.olImportanceHigh; oMsg.Importance = Outlook.OlImportance.olImportanceNormal; oMsg.Importance = Outlook.OlImportance.olImportanceLow;
{ "language": "en", "url": "https://stackoverflow.com/questions/7499914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Defining a Mongoose Schema on the fly I have a model file that gathers together all my Mongoose models. One of the models I would like to initialize with a variable number of fields. Currently I'm defining more fields than I think I am going to require: TallySchema = new mongoose.Schema 0: Number 1: Number ... 20: Number Obviously this is not ideal. I see Mongoose will let you specify options outside the Schema definition but can't see how to add new fields (or paths, I guess, in Mongoose). A: Based on the mongoose plugin documentation it looks like you can just do: schema.add({ field: Number }) A: This would need to be verified, but looking at the source it should be possible: In the Schema constructor, it simply passes the definition object to this.add() (source). The actual paths then get created within Schema.prototype.add (source). So, seems like all you would need to do is something like: // not sure what this looks like in CoffeeScript TallySchema.add({ /* new property definition here */ }); A: I found this in the Mongoose documentation page: var ToySchema = new Schema; ToySchema.add({ name: 'string', color: 'string', price: 'number' }); A: You can use the 'mixed' type to encapsulate your values. It wouldn't be possible to have them be at the top level though but it works great otherwise. new mongoose.Schema({ average: Number, countPerRating: mongoose.Schema.Types.Mixed, }); This is an excerpt from a mapreduce schema. I use the mixed type to store the number of times someone gives a certain rating, so we can say things like "10 1 star ratings, 45 4 star ratings", etc. mixed type worked great for that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Data Persistence in ViewData verses tempData I was wondering how long Data can persist in the ViewData dictionary. I know data can't persist that long in TempData (less than an hour). So how long can it last in ViewData? Is there another Data dictionary That will persist Data for a long time. I know it is starting to sound like I want a session variable and that is very un-MVC, but is there any other way I can get data from a control to a view without passing it directly as a parameter. A: I was wondering how long Data can persist in the ViewData dictionary It lasts from the moment you put it there to the moment the request ends, i.e. the page is rendered and sent to the client. I know data can't persist that long in TempData (less than an hour) TempData is like Session but persists only until the next request. So it could be like seconds, minutes, hours, days, ... I know it is starting to sound like I want a session variable and that is very un-MVC I wouldn't say un-MVCish, I would say un-RESTfulish. Is there another Data dictionary That will persist Data for a long time Yes, the Session, your underlying data storage (like a database or something), cookies, application scope, cache, ... it will all depend on your specific requirements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Tkinter: one or more mainloops? I have an already large Tkinter program, so that I have an init file, where the root = Tk() window is defined (containing basically a Text widget and a few other things), some more code, and last the call to mainloop() function. Everything works, until I needed to call a procedure before the mainloop, and I wanted to raise a wait window at the begin, to be destroyed at procedure's end. I wrote something like: msg = Message(root, text='wait a few seconds...') msg.pack() But it doesn't and cannot work, since mainloop() has not been called yet! If I instead do: msg = Message(root, text='wait a few seconds...') msg.pack() mainloop() The program stops at this first mainloop, doesn't finish the procedure call. mainloop() should be used as your last program line, after which the Tkinter program works by a logic driven by user clicks and interactions, etc. Here, I need a sequence of raise window > do stuff > destroy window > mainloop A: You are correct that mainloop needs to be called once, after your program has initialized. This is necessary to start the event loop, which is necessary for windows to draw themselves, respond to events, and so on. What you can do is break your initialization into two parts. The first -- creating the wait window -- happens prior to starting the event loop. The second -- doing the rest of the initialization -- happens once the event loop has started. You can do this by scheduling the second phase via the after method. Here's a simple example: import Tkinter as tk import time class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): # initialize Tkinter tk.Tk.__init__(self, *args, **kwargs) # hide main window self.wm_withdraw() # show "please wait..." window self.wait = tk.Toplevel(self) label = tk.Label(self.wait, text="Please wait...") label.pack() # schedule the rest of the initialization to happen # after the event loop has started self.after(100, self.init_phase_2) def init_phase_2(self): # simulate doing something... time.sleep(10) # we're done. Close the wait window, show the main window self.wait.destroy() self.wm_deiconify() app = SampleApp() app.mainloop() A: You should use Tkinter's method to run asyncore's loop function, but you should use asyncore.poll(0) instead of asyncore.loop(). If you call function asyncore.poll(0) every x ms, it has no longer an effect on Tkinter's main loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Split text using Python Possible Duplicate: Python split string on regex How do I split some text using Python's re module into two parts: the text before a special word cut and the rest of the text following it. A: You can do it with re: >>> import re >>> re.split('cut', s, 1) # Split only once. But in this case you can just use str.split: >>> s.split('cut', 1) # Split only once. A: Check this, might help you >>> re.compile('[0-9]+').split("hel2l3o") ['hel', 'l', 'o'] >>> >>> re.compile('cut').split("hellocutworldcutpython") ['hello', 'world', 'python'] split about first cut >>> l=re.compile('cut').split("hellocutworldcutpython") >>> print l[0], string.join([l[i] for i in range(1, len(l))], "") hello worldpython
{ "language": "en", "url": "https://stackoverflow.com/questions/7499929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Twitter style validation in homepage to sign up I've got a Rails app right now that has a form on the homepage for sign up. It's a nested model form that creates both user and profile. When sign up is clicked, the newly created user is taken to Profiles#edit to fill in their profile. This annoys me because I wanted to use Profiles#edit in my User's settings. So I'd like to do what Twitter does to try and bypass this. Specifically, what I'd like to do is add a similar validation process that occurs between twitter.com and twitter.com/signup. On twitter.com, the User enters their information, then clicks sign up. You're taken to twitter.com/signup with in-line validation showing whether the Full name, email, and password are valid. (I imagine this is using some form of jQuery/JavaScript because it doesn't create the user.) The user then fills out the rest of the form, agrees to terms, and joins. This creates the user and User profile. Can anyone suggest how this might be done? Particularly with a nested model form like mine. I'm new to programming but would appreciate any help in helping me re-create this. A: This is how I would approach the problem from a structuring standpoint. On the front page, with the sign up...you just need a standard form that you can submit to your server. Your server should then do the name/email/password validation and the response should redirect the browser to the signup page, with the information from the validation (which fields pass/fail). Now that you are on the sign up page, when the user tries to sign up, you would send an AJAX request to your server for the name/email/username/password verification. If it checks out, then register the user, log them in, and then send the redirect response to the user's home page or profile page, or whatever they should see when logging in. If this validation fails, then you would return the error information and then display it on the page. Hope this helps you get started.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Git show files that were changed in the last 2 days How can I have a list with all the files that were changed in the last 2 days? I know about git log --name-status --since="2 days ago" but this will show me ids, dates and commit messages. All I need is the list of the file names which were changed. Is that possible with git? A: git diff --stat @{2.days.ago} # Deprecated!, see below Short and effective Edit TLDR: use git diff $(git log -1 --before=@{2.days.ago} --format=%H) --stat Long explanation: The original solution was good, but it had a little glitch, it was limited to the reflog, in other words, only shows the local history, because reflog is never pushed to remote. This is the reason why you get the warning: Log for 'master' only goes back to... in repos recently cloned. I have configured this alias in my machine: alias glasthour='git diff $(git log -1 --before=@{last.hour} --format=%H) --stat' alias glastblock='git diff $(git log -1 --before=@{4.hours.ago} --format=%H) --stat' alias glastday='git diff $(git log -1 --before=@{last.day} --format=%H) --stat' alias glastweek='git diff $(git log -1 --before=@{last.week} --format=%H) --shortstat | uniq' alias glastmonth='git diff $(git log -1 --before=@{last.month} --format=%H) --shortstat | uniq' credits: answer below by @adam-dymitruk A: git log --pretty="format:" --since="2 days ago" --name-only A: Use the --raw option to git log: $ git log --raw --since=2.days See the --diff-filter part of the git log help page for the explanation of the flags shown in the --raw format. They explain what happen to the files in each commit: --diff-filter=[(A|C|D|M|R|T|U|X|B)...[*]] Select only files that are Added (A), Copied (C), Deleted (D), Modified (M), Renamed (R), have their type (i.e. regular file, symlink, submodule, ...) changed (T), are Unmerged (U), are Unknown (X), or have had their pairing Broken (B). Any combination of the filter characters (including none) can be used. When * (All-or-none) is added to the combination, all paths are selected if there is any file that matches other criteria in the comparison; if there is no file that matches other criteria, nothing is selected. A: You can do a diff of a version that's closest to 2 days ago with: git diff $(git log -1 --before="2 days ago" --format=%H).. --stat --stat gives you a summary of changes. Add --name-only to exclude any meta information and have only a file name listing. Hope this helps. A: git log --pretty=format: --name-only --since="2 days ago" if some files duplicate in multiple commits, you can use pipe to filter it git log --pretty=format: --name-only --since="2 days ago" | sort | uniq
{ "language": "en", "url": "https://stackoverflow.com/questions/7499938", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "77" }
Q: Django Comment Framework - Setting Email With Session Variable How can I set the email address in Django's comment form with a value stored in a session variable? A: I think you need to create an app for comments customisation: https://docs.djangoproject.com/en/dev/ref/contrib/comments/custom/ As the article explains you will need to read your session value inside your form's get_comment_create_data method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Low-level keyboard hooks to inspect source device ID I know there are good articles and questions on installing keyboard hooks already, but I'm interested to know if and how it's possible to inspect the source device ID? The idea would be to ignore any keyboard presses from the main keyboard, but hook any that come from a barcode scanner (which, if you didn't know, pretends to be a keyboard as far as the OS is concerned). A: Check this article. It looks like it's not possible through keyboard hooks. He used the Raw Input API. A: Raw Input (C# Example) can do this. I had a play with that code with my own basic keyboard-wedge barcode scanner & found that in order to register events I needed to remove the if (rid.dwType == RIM_TYPEKEYBOARD || rid.dwType == RIM_TYPEHID) filter so something needs tweaking. If I did remove the restrictions it was successfully registering keyboard+scanner input and reporting different device details for each.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Offset position of "close button" in Three20 TTLauncherView I'm using the Three20 library to create a TTLauncherView in an iPhone app that I'm working on. When the user touches and holds on one of the items in the launcher view it causes all the items to start wiggling and an "x" button to appear in the top left corner of the of each item image. This button is used to remove items from the launcher view. I would like to move this "x" button a little down and to the right relative to the item image. I have looked at TTDeafaultStyleSheet andfound the following code: /////////////////////////////////////////////////////////////////////////////////////////////////// - (TTStyle*)launcherCloseButtonImage:(UIControlState)state { return [TTBoxStyle styleWithMargin:UIEdgeInsetsMake(-2, 0, 0, 0) next: [TTImageStyle styleWithImageURL:nil defaultImage:nil contentMode:UIViewContentModeCenter size:CGSizeMake(10,10) next:nil]]; } /////////////////////////////////////////////////////////////////////////////////////////////////// - (TTStyle*)launcherCloseButton:(UIControlState)state { return [TTShapeStyle styleWithShape:[TTRoundedRectangleShape shapeWithRadius:TT_ROUNDED] next: [TTInsetStyle styleWithInset:UIEdgeInsetsMake(1, 1, 1, 1) next: [TTShadowStyle styleWithColor:RGBACOLOR(0,0,0,0.5) blur:2 offset:CGSizeMake(0, 3) next: [TTSolidFillStyle styleWithColor:[UIColor blackColor] next: [TTInsetStyle styleWithInset:UIEdgeInsetsMake(-1, -1, -1, -1) next: [TTSolidBorderStyle styleWithColor:[UIColor whiteColor] width:2 next: [TTPartStyle styleWithName:@"image" style:TTSTYLE(launcherCloseButtonImage:) next: nil]]]]]]]; } This code touches the "x" button, but I haven't been able to figure out how to change its position. Does anyone have any suggestions? A: I was unable to figure our how to move the close button in the way that I wanted using the code in my question, but I did find where to adjust the position of the button by editing the Three20 file TTLauncherButton.m. In the -(void)layoutSubviews method I adjusted the origin of the _closeButton property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java: Transferable Objects & Serialization I need to serialize a Transferable object to I can send it over an object data stream but during runtime I get the error java.io.NotSerializableException & I have no idea whats wrong. How do I fix this? Here's the part of the code that is causing the error Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable contents = clipboard.getContents(null); System.out.println(contents); //Initialiaze ObjectStreams FileOutputStream fos = new FileOutputStream("t.tmp"); ObjectOutputStream oos = new ObjectOutputStream(fos); //write objects oos.writeObject(contents); oos.close(); A: It seems that your object have to implements both Transferable and Serializable. Hope this code helps you Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); //Initialiaze ObjectStreams FileOutputStream fos = new FileOutputStream("t.tmp"); ObjectOutputStream oos = new ObjectOutputStream(fos); clipboard.setContents(new Plop(), null); final Transferable contents = clipboard.getContents(null); final Plop transferData = (Plop) contents.getTransferData(new DataFlavor(Plop.class, null)); oos.writeObject(transferData); oos.close(); with a plop like: static class Plop implements Transferable, Serializable{ @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[0]; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isDataFlavorSupported(final DataFlavor flavor) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException { return this; } } A: The vest way around this is to parse each data flavor into a serializable object of it's kind i.e. put string clipboard content into a string object A: Your concrete class must implement the Serializable interface to be able to do so. A: * Thrown when an instance is required to have a Serializable interface. * The serialization runtime or the class of the instance can throw * this exception. The argument should be the name of the class. Hmm. Have you added to your object implements Serializable ? UPD. Also check that all fields are also serializable. If not - mark them as transient.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I load a jquery colorbox from a remote page? I have a page that generates a google map on page load that I would like to call from another page via a link. Here is how I'm creating the google map inside a colorbox: // show_map.php jQuery(document).ready(function(){ $.colorbox({width:"643px", height: "653px", inline:true, href:"#map_container"}, function() { $.getJSON('map.php', function(data){ initialize(); setMarkers(map, data); }); }); }); Here is my attempt but something tells me I've headed down the wrong path. Should I use the modal window for something like this or is there a better way? $(document).ready(function() { $('.show_map').click(function() { $.get("show_map.php", function(data) { // alert(data); }) }); A: If I've understood correctly, colorbox is already designed to do what you want to do. You don't need to use extra ajax calls (it's already built in). Just set the href option to your page instead of your inline html (then of course remove the inline:true option). The full code (in the page with the link to your map): $(document).ready(function() { $('.show_map').click(function() { $.colorbox({ href: "show_map.php", width:"643px", height:"653px" }); }) }); You can also load any external page if you add the iframe: true option to that code. A: Either you use jQuery's .getScript() if the page only contains JavaScript or you can use .load() to insert the page content into the DOM. $(document).ready(function() { $('.show_map').click(function() { $('.some-element').load("show_map.php"); }) }); EDIT: a better approach have the colorbox inline instead. Saves a round trip to the server. $(document).ready(function() { $('.show_map').colorbox({width:"643px", height: "653px", inline:true, href:"#map_container"}, function() { $.getJSON('map.php', function(data){ initialize(); setMarkers(map, data); }); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7499958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Indoor Positioning System based on Gyroscope and Accelerometer I am developing an Android App to track indoor position. My phone is an Google Nexus S using two sensors, the first being an Accelerometer and the second being a Gyroscope. My idea is that from a starting reference point (a known GPS position), using the 2 sensors (accelerometer for motion and Gyro for directions) track the phone when moving. And display on a map when the user is going. But the problem is that i have no idea how to combine both of these sensors to give me an actual position? I have read some article on internet that talk about "kalman filter" and after some more research i found out that that filter is very very complex /too much for me) especially to code it in java for Android (cpu killer) Does someone has some experience that he can share with me about indoor positioning system using Gyro and accelerometer? A: I think this is a great post answering your question. This kalman filter combine data from accelerometers and gyros. Hope it helps. A: Gyros and accelerometers are not enough. You get position by integrating the linear acceleration twice but the error is horrible. It is useless in practice. Here is an explanation by (Google Tech Talk) at 23:20. I highly recommend this video. As for indoor positioning, I have found these useful: * *RSSI-Based Indoor Localization and Tracking Using Sigma-Point Kalman Smoothers *Pedestrian Tracking with Shoe-Mounted Inertial Sensors *Enhancing the Performance of Pedometers Using a Single Accelerometer I have no idea how these methods would perform in real-life applications or how to turn them into a nice Android app. A similar question is Calculating distance within a building. A: For some other interesting reading on emerging indoor positioning technologies, check out this blog post from Qubulus. There are several startups and research projects trying to find a good replacement for GPS indoors. Attempts range from Dead Reckoning, to QR Codes, to light pulses, to radio fingerprinting. It looks like any viable solution will combine multiple technologies (similar to how most smartphones rely on A-GPS, where the satellite signal is assisted by cell tower multilateration). Best of luck with your application! A: I think it is too late for answer this question, but now, there is a good solution called iBeacon technology. You can scan iBeacon devices by your smartphone, and you can get the rssi from iBeacon. So, you can calculate your position by those rssi. A: To track indoor position starting from some reference point, only gyro and accelerometer is not enough. With accelerometer you can calculate speed, with gyro you can get direction of the mobile device, but to calculate indoor position you also need to have direction of movement, so for this case you need to use magnetic sensor. Such approach is called Dead Reckoning method and it's quite complex to combine all 3 sensors to get appropriate indoor position. Kalman filters allow you to smooth your measurement and filter some noise, but it's not the method to calculate indoor position. If you want to get indoor position you can try iBeacon approach and Trilateration method, there are some libraries (like this one) that already has this functionality, so you can try to investigate this method from such libs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "76" }
Q: Can two Android devices, running different applications, use the same SQLite Database? I read this question and wondered if the same would apply to my situation. I want to write accelerometer values (x, y and z) from an Android phone to a database and retrieve it with another app on a tablet to display a graph of the values changing over time. This does not have to happen in real time. So basically my questions are: 1) can two different applications on two different Android devices use the same SQLite database? and 2) how do I specify an IP so that the one app on the phone writes to a specified database and the other app on the tablet reads from that same specified database? I can already read the Accelerometer values and I know how to create a graph, but I'm having trouble with the database component of my project since everything I come across seems to be storing the values on the device's SD card or in a database that is only accessible to the device itself and no other applications or devices. I've read about specifying a static IP by first obtaining a ContentResolver: ContentResolver cr = getContentResolver(); then adapting the settings: Settings.System.putString(cr, Settings.System.WIFI_USE_STATIC_IP, "1"); Settings.System.putString(cr, Settings.System.WIFI_STATIC_IP, "6.6.6.6"); and then enabling the permissions: WRITE_SETTINGS and WRITE_SECURE_SETTINGS. but I'm not sure where exactly to write this or how to use it correctly. Please direct me to where I can find some more information regarding setting up SQLite databases and how it can be used by two different applications on two different Android devices? Thank you in advance. P.S. I'll update this question with some of my code soon. A: can two different applications on two different Android devices use the same SQLite database? No more than two Web servers running on two different continents can use the same MySQL database. Only processes running on a device with filesystem access to a file can read and write to that file. how do I specify an IP so that the one app on the phone writes to a specified database and the other app on the tablet reads from that same specified database? You don't. Android is not a server platform. At best, you might be able to pull this off if both devices are on the same WiFi LAN, and you write a Web service that exposes a database from one device. This, of course, exposes you to the same security issues that you would have with a Web server, without the benefit of firewalls and the like. I want to write accelerometer values (x, y and z) from an Android phone to a database and retrieve it with another app on a tablet to display a graph of the values changing over time. This does not have to happen in real time. Hence, you do not need two devices to access the same database. You need them to work with the same data. So, you could have the phone send the data to some server via a Web service, and have the tablet retrieve the data from that server via the Web service. Or, have the phone send data to the tablet via Bluetooth. Or, if you feel the security is adequate, have the tablet expose a Web service via WiFi that the phone uses (though this really scares me, particularly if the tablet might join some other network, such as by being moved). In neither case does the phone nor the tablet necessarily even have a database, let alone try to directly share it. A: A SQlite database is private to the application which creates it. If you want to share data with other applications you can use a Content Provider. A: Although not SQLite, I believe this can be achieved using PouchDB, where you would host one shared remote database which would then sync to two seperate databases for each application. https://pouchdb.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/7499961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Internal error not handled System.InvalidOperationException at System.Data.OracleClient.OracleConnection.CheckError I have a web application and I am getting an error related to oracle. System.InvalidOperationException Internal error not handled (-2) at System.Data.OracleClient.OracleConnection.CheckError() This is the scenario. sql1 select * from table1@otheroracledb sql2 select * from table2 I am getting this error when I run the sql1 and then sql2. What could be the problem?
{ "language": "en", "url": "https://stackoverflow.com/questions/7499962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android float button over scroll view I have to put a button at a fix position(top-right) so that when I scroll the screen/view, the button is always visible. It's like a button floating over the view. The button is visible over the scroll view all the time. A: I made a dummy app and it works here is the layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <RelativeLayout android:layout_width="match_parent" android:id="@+id/relativeLayout1" android:layout_height="wrap_content"> <ScrollView android:id="@+id/scrollView1" android:layout_height="fill_parent" android:layout_width="fill_parent"> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <RatingBar android:id="@+id/ratingBar1" android:layout_width="wrap_content" android:layout_weight="1" android:layout_height="wrap_content"></RatingBar> <Spinner android:layout_width="wrap_content" android:id="@+id/spinner1" android:layout_weight="1" android:layout_height="wrap_content"></Spinner> <Spinner android:layout_width="wrap_content" android:id="@+id/spinner2" android:layout_height="wrap_content" android:layout_weight="1"></Spinner> <SeekBar android:id="@+id/seekBar1" android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="match_parent"></SeekBar> <QuickContactBadge android:layout_width="wrap_content" android:id="@+id/quickContactBadge1" android:layout_weight="1" android:layout_height="wrap_content"></QuickContactBadge> <RatingBar android:id="@+id/ratingBar2" android:layout_width="wrap_content" android:layout_weight="1" android:layout_height="wrap_content"></RatingBar> <RadioGroup android:layout_width="wrap_content" android:id="@+id/radioGroup1" android:layout_weight="1" android:layout_height="wrap_content"> <RadioButton android:text="RadioButton" android:layout_width="wrap_content" android:id="@+id/radio0" android:layout_height="wrap_content" android:checked="true"></RadioButton> <RadioButton android:text="RadioButton" android:layout_width="wrap_content" android:id="@+id/radio1" android:layout_height="wrap_content"></RadioButton> <RadioButton android:text="RadioButton" android:layout_width="wrap_content" android:id="@+id/radio2" android:layout_height="wrap_content"></RadioButton> </RadioGroup> <Spinner android:layout_width="match_parent" android:id="@+id/spinner3" android:layout_height="wrap_content" android:layout_weight="1"></Spinner> <TextView android:layout_width="wrap_content" android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_weight="1" android:text="TextView" android:textAppearance="?android:attr/textAppearanceMedium"></TextView> <Button android:layout_width="wrap_content" android:text="Button" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/button2"></Button> <ProgressBar android:layout_width="wrap_content" android:layout_weight="1" android:id="@+id/progressBar1" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal"></ProgressBar> <RatingBar android:id="@+id/ratingBar3" android:layout_width="wrap_content" android:layout_weight="1" android:layout_height="wrap_content"></RatingBar> <QuickContactBadge android:layout_width="wrap_content" android:id="@+id/quickContactBadge2" android:layout_weight="1" android:layout_height="wrap_content"></QuickContactBadge> <Button android:layout_width="wrap_content" android:text="Button" android:layout_height="wrap_content" android:layout_weight="1" android:id="@+id/button3"></Button> <CheckBox android:layout_width="wrap_content" android:text="CheckBox" android:id="@+id/checkBox1" android:layout_height="wrap_content" android:layout_weight="1"></CheckBox> </LinearLayout> </ScrollView> <Button android:layout_height="wrap_content" android:text="Button" android:layout_width="wrap_content" android:id="@+id/button1"></Button> </RelativeLayout> </LinearLayout> A: You should have a relative layout. Inside the layout you will have a scrollview to fill the parent both in height and with and the button will be also inside the layout but it will have align with parent top to true... this is the answer, if you have any questions ask again A: I guess you are using xml files to define your layout. Then you need to define the button outside the ScrollView definition, for example: <ScrollView ...> ... </ScrollView> <Button ...> </Button> A: Guys I know this is a old post just FYI, Google has come up with a library to support the a lot of cool stuff like float button, etc. Worth a look. Google Design Support Lib
{ "language": "en", "url": "https://stackoverflow.com/questions/7499968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL Server - Conditional Join to whatever table is not null Badly phrased title my apologies. I am trying to join a table to one of two other tables MasterTable SubTable SubTableArchive So, MasterTable contains an ID field. SubTable and SubTableArchive contain a MasterTableId field for the join. But, data will only ever exist in one of these SubTables. So I just want to join to whichever table has the data in it. But the only way I know of doing it is by joining to both and using isnull's on all the fields im selecting, and its quickly becoming complicated to read (and write). Especially because some of the fields are already wrapped in ISNULL's SELECT M.Id, ISNULL(S.Field1, SA.field1), ISNULL(S.field2, SA.Field2), SUM(CASE WHEN (ISNULL(S.Finished,SA.Finished)=1 AND ISNULL( ISNULL(S.ItemCode,SA.ItemCode),'')='') THEN 1 WHEN (ISNULL(S.Finished,SA.Finished)=0 AND ISNULL( ISNULL(S.AltItemCode,SA.AltItemCode),'')='') THEN 1 ELSE 0 END) AS SummaryField FROM MAsterTable M LEFT OUTER JOIN SubTable S ON S.MasterTableId = M.Id LEFT OUTER JOIN SubTableArchive SA ON S.MasterTableId = M.Id GROUP BY M.Id, ISNULL(S.Field1, SA.field1), ISNULL(S.field2, SA.Field2) So that is working, but its not pretty. Thats a sample, but the real queries are longer and more convoluted. I was hoping SQL might have had some sort of conditional joining functionality built in. Something to do what I am trying to do and leave the query itslef a little friendlier. A: Another option is to use a UNION and then use INNER JOINs SELECT M.x, S.x FROM MAsterTable M INNER JOIN SubTable S ON S.MasterTableId = M.Id UNION SELECT M.x, STA.x FROM MAsterTable M INNER JOIN SubTableArchive STA ON STA.MasterTableId = M.Id From a maintenance point of view, if you make the above union a view, you can then apply where filters and sorts to the view, which should simplify matters. A: Use sub-select or better WITH statement (code not tested): WITH SubTable_WithArchive AS (SELECT Field1, Field2, Finished, ItemCode, AltItemCode, MasterTableID FROM SubTable UNION ALL SELECT Field1, Field2, Finished, ItemCode, AltItemCode, MasterTableID FROM SubTableArchive ) SELECT M.Id, S.Field1, S.Field2, SUM(CASE WHEN s.Finished = 1 AND ISNULL(s.ItemCode, '') == '' THEN 1 WHEN s.Finished = 0 AND ISNULL(s.AltItemCode, '') == '' THEN 1 ELSE 0 END) AS SummaryField FROM MasterTable M LEFT OUTER JOIN SubTable_WithArchive S ON S.MasterTableId = M.Id GROUP BY M.Id, S.Field1, s.field2 A: No, unfortunately, there isn't. A: Try this SELECT M.Id, S.Field1,S.field2, SUM(CASE WHEN S.Finished=1 AND ISNULL( S.ItemCode,'')='') THEN 1 WHEN S.Finished=0 AND ISNULL( S.AltItemCode,'')='') THEN 1 ELSE 0 END) AS SummaryField FROM MAsterTable M JOIN ( SELECT id,field1,field2,ItemCode,AltItemCode,finished FROM subTable UNION SELECT id,field1,field2,ItemCode,AltItemCode,finished FROM subTableArchive ) S ON S.id = M.Id GROUP BY M.Id, S.Field1,S.field2 A: Because a ID value from MasterTable will exist in only one table (SubTable or SubTableArchive) you can use this query: SELECT MasterTableId Id, Field1, Field2, SUM(CASE WHEN Finished=1 AND ItemCode IS NULL THEN 1 --OR ISNULL(ItemCode,'') = '' WHEN Finished=0 AND AltItemCode IS NULL THEN 1 --OR ISNULL(AltItemCode,'') = '' ELSE 0 END) AS SummaryField FROM SubTable GROUP BY 1, 2, 3 UNION ALL SELECT MasterTableId Id, Field1, Field2, SUM(CASE WHEN Finished=1 AND ItemCode IS NULL THEN 1 --OR ISNULL(ItemCode,'') = '' WHEN Finished=0 AND AltItemCode IS NULL THEN 1 --OR ISNULL(AltItemCode,'') = '' ELSE 0 END) AS SummaryField FROM SubTableArchive GROUP BY 1, 2, 3
{ "language": "en", "url": "https://stackoverflow.com/questions/7499971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to set local notification on Mac OS X? I'm writing an app for mac os x, and I have to display a notification every day, to remind users about something. The notification should appear even if the app isn't running, and I can't use push notification. I guess the best solution would be local notification, just like on iOS. Also I know UILocalNotification is available on iOS only. But I think there should be an alternative solution. Can anybody please point me in the right direction? Is it even possible? If yes, what is the best practice to do this? A: Local notifications support, very similar to iOS local notifications, has been added in MacOS 10.8 (Mountain Lion). See MacOSX10.8/Frameworks/Foundation.Framework/NSUserNotification.h for more information. Quick usage example could be found here. A: The notification should appear even if the app isn't running Well, something will still have to be running to send the actual notification. Mostly helper programs are used for this (separate executable binaries that are added as launch agents or launch daemons). So I'm suggesting you create a daemon-like helper program that would be added as launch daemon on a per-user basis. You can also look at shared file list api to see how can it be added to user's login items.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: overwrite file content/bytes I have a (PDF) file that exists on the file system, at a known location. I wish to overwrite the content of that file (with a fresh byte[]). Best (and most efficient) possible way to do so (using Java APIs)? A: public void oneShotAPI(File file, byte[] bytes) throws IOException { FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(bytes); fos.flush(); } finally { if (fos != null) try { fos.close(); } catch (IOException e) { // Sad, but true } } } Call it with: oneShotAPI(new File("myPDF.png"), byteArray); A: There's nothing built into the Java APIs that does this, but if you're looking for a library: * *Apache Commons IO has FileUtils.writeByteArrayToFile(File, byte[]) *Google Guava has Files.write(byte[], File) I don't see why any of the short methods posted here wouldn't work, though. There's no actual need for a library IMHO.
{ "language": "en", "url": "https://stackoverflow.com/questions/7499977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Tags within StoreKit receipt I'm developing a web service where I need to verify a purchase on the server and return some info if validation is successful. I want to make sure someone can't spoof the service by requesting validation with a receipt from another application. Is there a way to get the product id or some other meaningful information that will let my server verify it's my app requesting validation? Ken A: as far as i remember, the receipt contain productId as well as bundleId so just use those. The receipt validation (at apple side) ensures that the receipt has been not tampered with. further reading: Veryfiyng Store Receipts
{ "language": "en", "url": "https://stackoverflow.com/questions/7499984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: detect if application running on virtual box I went thrrough some links in stackoverflow. But code given here doesnt work for virtual box. I have also tried redpill but thats not working too. my application will run on both linux and windows(preferably). Please let me know if anyone has any solution. Edit: Preet Sangha's link not working as well A: VBox 1.0 uses a different method. Check http://spth.virii.lu/eof2/articles/WarGame/vboxdetect.html A: from http://www.gedzac.com/rrlf.dr.eof.eZine/articles/WarGame/vboxdetect.html Check if the pseudo-device \\.\VBoxMiniRdrDN exists in the system (you need CreateFile()) #include <windows.h> int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { if(CreateFile("\\\\.\\VBoxMiniRdrDN",GENERIC_READ,FILE_SHARE_READ, NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL) != INVALID_HANDLE_VALUE) { MessageBox(NULL,"VBox detected!","Warning",MB_OK|MB_ICONWARNING); } else { MessageBox(NULL,"Not inside VBox","Info",MB_OK|MB_ICONINFORMATION); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7499985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to get the Key and Value from a Collection VB.Net How do you get the key value from a vb.net collection when iterating through it? Dim sta As New Collection sta.Add("New York", "NY") sta.Add("Michigan", "MI") sta.Add("New Jersey", "NJ") sta.Add("Massachusetts", "MA") For i As Integer = 1 To sta.Count Debug.Print(sta(i)) 'Get value Debug.Print(sta(i).key) 'Get key ? Next A: Pretty sure you can't from a straight Microsoft.VisualBasic.Collection. For your example code above, consider using a System.Collections.Specialized.StringDictionary. If you do, be aware that the Add method has the parameters reversed from the VB collection - key first, then value. Dim sta As New System.Collections.Specialized.StringDictionary sta.Add("NY", "New York") '... For Each itemKey in sta.Keys Debug.Print(sta.Item(itemKey)) 'value Debug.Print(itemKey) 'key Next A: I don't recommend using the Collection class, as that is in the VB compatibility library to make migrating VB6 programs easier. Replace it with one of the many classes in the System.Collections or System.Collections.Generic namespace. A: It is possible to get a key with using Reflection. Private Function GetKey(Col As Collection, Index As Integer) Dim flg As BindingFlags = BindingFlags.Instance Or BindingFlags.NonPublic Dim InternalList As Object = Col.GetType.GetMethod("InternalItemsList", flg).Invoke(Col, Nothing) Dim Item As Object = InternalList.GetType.GetProperty("Item", flg).GetValue(InternalList, {Index - 1}) Dim Key As String = Item.GetType.GetField("m_Key", flg).GetValue(Item) Return Key End Function Not using VB.Collection is recommended but sometimes we are dealing with code when it was used in past. Be aware that using undocumented private methods is not safe but where is no other solution it is justifiable. More deailed information can be found in SO: How to use reflection to get keys from Microsoft.VisualBasic.Collection A: Yes, it may well, but I want recomend that you use another Collection. How to do you do with Reflection, the type Microsoft.VisualBasic.Collection contains some private fields, the field one should use in this case is "m_KeyedNodesHash" the field, and the field type is System.Collections.Generic.Dictionary(Of String, Microsoft.VisualBasic.Collection.Node), and it contains a property called "Keys", where the return type is System.Collections.Generic.Dictionary(Of String, Microsoft.VisualBasic.Collection.Node).KeyCollection, and the only way to get a certain key is to convert it to type IEnumerable(Of String), and the call ElementAt the function. Private Function GetKey(ByVal col As Collection, ByVal index As Integer) Dim listfield As FieldInfo = GetType(Collection).GetField("m_KeyedNodesHash", BindingFlags.NonPublic Or BindingFlags.Instance) Dim list As Object = listfield.GetValue(col) Dim keylist As IEnumerable(Of String) = list.Keys Dim key As String = keylist.ElementAt(index) Return key End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/7499989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what is the best way to split a string I have file name which look like Directory\name-secondName-blabla.txt If I using string .split my code need to know the separator I am using, But if in some day I will replace the separator my code will break Is the any build in way to split to get the following result? Directory name secondNmae blabla txt Thanks Edit My question is more general than just split file name, is splitting string in general A: The best way to split a filename is to use System.IO.Path You're not clear about what to do with directory1\directory2\ , but in general you should use this static class to find the path, name and suffix parts. After that you will need String.Split() to handle the - separators, you'll just have to make the separator(s) a config setting. A: You can make an array with seperators: string value = "Directory\name-secondName-blabla.txt"; char[] delimiters = new char[] { '\\', '-', '.' }; string[] parts = value.Split(delimiters, StringSplitOptions.RemoveEmptyEntries); A: var filepath = @"Directory\name-secondName-blabla.txt"; var tokens = filepath.Split(new[]{'\\', '-'}); A: If you're worried about your separator token changing in the future, set it as a constant in a settings file so you only have to change it in one place. Or, if you think it is going to change regularly, put it in a config file so you don't have to release new builds every time. A: As Henk suggested above, use System.IO.Path and its static methods like GetFileNameWithoutExtenstion, GetDirectoryName, etc. Have a look at this link: http://msdn.microsoft.com/en-us/library/system.io.path.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7499994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to call an Oracle Form(6i) with user parameters from command line Is there any way to call an Oracle Form(6i) from command line with User Parameters ? Typing ifrun60.exe userid=<uid/pwd> module=<form name> in the command line will launch the form, but my form is having some User Parameters to which i need to pass values while launching. Any clues ? A: Typing: ifrun60.exe help=Y Tells me what you need is: ifrun60.exe userid=<uid/pwd> module=<form name> [parameters]
{ "language": "en", "url": "https://stackoverflow.com/questions/7500002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to determing if a file has finished downloading in python I have a folder called raw_files. Very large files (~100GB files) from several sources will be uploaded to this folder. I need to get file information from videos that have finished uploading to the folder. What is the best way to determine if a file is currently being downloaded to the folder (pass) or if the video has finished download (run script)? Thank you. A: The most reliable way is to modify the uploading software if you can. A typical scheme would be to first upload each file into a temporary directory on the same filesystem, and move to the final location when the upload is finished. Such a "move" operation is cheap and atomic. A variation on this theme is to upload each file under a temporary name (e.g. file.dat.incomplete instead of file.dat) and then rename. You script will simply need to skip files called *.incomplete. A: If you check those files, store the size of the files somewhere. When you are in the next round and the filesize is still the same, you can pretty much consider them as finished (depending on how much time is between first and second check). The time interval could e.g. be set to the timeout-interval of your uploading service(FTP, whatever). There is no special sign or content showing that a file is complete.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Database design - Multiple objecttypes shown hierarcial? I have been struggling and searching for a solution about this for a couple of days but i cannot find any "best practices" or good explanations of how to achive what i want. Lets say that I have a database consisting of the following tables (just an example); Customers (Fields: Id, CustomerName, Location) Products (Fields: Id, ProductName, ProductCode) Groups (Fields: Id, GroupName) I then need to link these together to be shown in a Treeview. For example; Customer1 | |-Group1 | |-Product1 | |-Product2 | |-Group2 |-Product2 |-Product3 |-Group3 | |-Product1 |-Product4 As i said, this is just an example. The real solution consists of other types. Since the products can occur in several places i need to create a "link table" to display the hierarchial data. So i created another table looking like this; Id (int) ParentId (int) ObjectType (int) GroupId (int) ProductId (int) CustomerId (int) The reason for the ObjectType field is to know in what database i need to check for the items name etc. to display in the treeview. My question now: Is there any other way to design this database? I am developing in C# using LINQ etc. A: from your example, each level of the tree should be a new link table. you do not show if group 1 is repeated for more than one customer, should the contents of group1 also be repeated.? but i assume group1 contents are the same no matter which customers are associated. if you can truly link anything to anything, then the objectType is the way to go... but you would have something like: parentId ParentObjectType childId childObjectType
{ "language": "en", "url": "https://stackoverflow.com/questions/7500007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a thread wait and execute another??? I have two Threads classes "AddThread" and "ReadThread". The execution of these threads should be like this "AddThread should add 1 record and wait until ReadThread displays the record after that ReadThread should display that added record again AddThread should add another record" this process should continue untill all the records are added(REcords are accessed from LinkedList). Here is the code class AddThread extends Thread { private Xml_Parse xParse; LinkedList commonlist; AddThread(LinkedList commonEmpList) { commonlist = commonEmpList; } public void run() { System.out.println("RUN"); xParse=new Xml_Parse(); LinkedList newList=xParse.xmlParse(); try { synchronized (this) { if(newList.size()>0) { for(int i=0;i<newList.size();i++) { System.out.println("FOR"); commonlist.add(newList.get(i)); System.out.println("Added" +(i+1)+ "Record"); } System.out.println(commonlist.size()); } } } catch(Exception e) { } } } class ReadThread extends Thread { LinkedList commonlist; ReadThread(LinkedList commonEmpList) { commonlist = commonEmpList; } public void run() { try { synchronized (this) { System.out.println(); System.out.println("ReadThread RUN"); sleep(1000); //System.out.println("After waiting ReadThread RUN"); System.out.println(commonlist.size()); if(commonlist.size()>0) { for(int j=0;j<commonlist.size();j++) { System.out.println("Read For"); System.out.println("EmpNo: "+((EmployeeList)commonlist.get(j)).getEmpno()); System.out.println("EmpName: "+((EmployeeList)commonlist.get(j)).getEname()); System.out.println("EmpSal: "+((EmployeeList)commonlist.get(j)).getEmpsal()); } } } } catch(Exception e) { } } } public class MainThread { public static LinkedList commonlist=new LinkedList(); public static void main(String args[]) { AddThread addThread=new AddThread(commonlist); ReadThread readThread=new ReadThread(commonlist); addThread.start(); readThread.start(); } } A: You'll need to learn how to effectively use wait() and notify(). See also: * *Guarded Blocks A: What about using a BlockingQueue with a capacity of 1? Use offer instead of add so that producer thread is blocked. You might also consider using a Semaphore with one permit, making it a mutex. A: You use join() and yield() to control flux. If you want the current thread to stop and wait until the new thread finishes the work, t1.run() t.join() when t1 finishes t continues.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Message Format thread safety HI could anyone please tell me the answers to following. --Is java.text.MessageFormat class thread safe??(y/n) --is it true that out of many format methods in java.text.MessageFormat only 1 is thread safe since it creates a local instance of MessageFormat every time.??(y/n) can anyone provide an explannation also to above two questions? can anyone provide a code which shows java.text.MessageFormat is not threadsafe? A: From the javadoc: Synchronization Message formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500015", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to programmatically send a POST request and parse the HTML result? I have developed an application in Java. * *A database with a table student with columns userid, password, name, address. *A login.html page asking for username and password and having submit button. There is a <form action="display.jsp" method="post">. *On display.jsp I am printing name and address. This is working fine in browser. But now I want to make a simple Java application in which I will pass the URL of my login.html running on localhost. And that Java application should fill in the form, click that button and print value of name and address on console. It will print name and address of all 20 students when I will use while loop from 1 to 20. How can I achieve this? A: This seems like a undesirable way to achieve this but if you must, you can just use something like Apache Http Client... http://hc.apache.org/httpcomponents-client-ga/index.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7500020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Preventation from starting a thread twice Imagine you have a little calculation method, which is startet by a thread: boost::mutex mMutex; void MyClass::DoSomething { boost::unique_lock<boost::mutex> tLock(mMutex); if(tLock.owns_lock() { // do some stuff... } } And you want to start this in a thread, raised from different member functions. They can be called simultanous, but you can't know when: void MyClass::Process { boost::thread t1(&MyClass::DoSomething, this); // go on ... } void MyClass::Foo { boost::thread t2(&MyClass::DoSomething, this); // and something more ... } How to prevent t2 from beeing executed at all, if t1 is running? My unique_lock seems to fail. A: Based on Naszta's idea, here's a possible approach using atomic bools and atomic swaps: std::atomic<bool> thread_in_use(False); void DoSomething() { if (thread_in_use.exchange(true)) return; // ... thread_in_use = false; } A: Make a variable and before you start the t1 thread, increase that variable in atomic way. When it finished, decrease that variable to null in atomic way. In Foo you should just check if this variable is null, or not. Check this example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how do I define a member of the linked list? LinkedList<T> Class: I want each member to be a struct containing an IPAddress object and an integer. A: struct Foo { IPAddress a; int dummy; }; int main() { LinkedList<Foo> list; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7500024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: (C) Virtual network adapter Is there any way in linux to programatically create a virtual network adapter that can be listened to, so that whenever an attempt is made to send data through the adapter, a method is called? I am trying to forward all packets to a single ip address, then include their original location in the packet. something like this: void sendPacket(char to[], char data[]) So like if I ping google.com through the virtual network adapter, the method will be called like this sendPacket("GooglesIp","Whatever data a ping sends") A: I think what you are looking for is a TUN/TAP device in Linux, which allows a program to act as a network interface. http://en.wikipedia.org/wiki/TUN/TAP You could then write a program to listen to that TUN/TAP interface for incoming data, and process it accordingly. Basically you would route the pings to the new TUN/TAP interface, then have a program read the packets off the interface, and route them from there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Spring/Hibernate Exception: createCriteria is not valid without active transaction I spent few days on an spring-hibernate-transaction issue. I create a simple webservice with jaxws + spring + hibernate, it works fine but when I call a web methode which use a transactional bean spring threw the following error: 21 sept. 2011 14:29:29 com.sun.xml.ws.server.sei.EndpointMethodHandler invoke GRAVE: org.hibernate.HibernateException: createCriteria is not valid without active transaction I seems the transaction has been started ... but something wrong happened. [jmedia] 21 sept. 2011 14:29:29 [http-8080-1] DEBUG org.springframework.orm.hibernate3.HibernateTransactionManager - Creating new transaction with name [com.cellfish.mediadb.ws.encoder.MediaDBFeeds.testTransaction]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; '' [jmedia] 21 sept. 2011 14:29:29 [http-8080-1] DEBUG org.springframework.orm.hibernate3.HibernateTransactionManager - Opened new Session [org.hibernate.impl.SessionImpl@26b20a31] for Hibernate transaction [jmedia] 21 sept. 2011 14:29:29 [http-8080-1] DEBUG org.springframework.orm.hibernate3.HibernateTransactionManager - Preparing JDBC Connection of Hibernate Session [org.hibernate.impl.SessionImpl@26b20a31] [jmedia] 21 sept. 2011 14:29:29 [http-8080-1] DEBUG org.springframework.orm.hibernate3.HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [jdbc:mysql://xxxxxxxx, MySQL-AB JDBC Driver] [jmedia] 21 sept. 2011 14:29:29 [http-8080-1] DEBUG org.springframework.orm.hibernate3.HibernateTransactionManager - Found thread-bound Session [org.hibernate.impl.SessionImpl@26b20a31] for Hibernate transaction [jmedia] 21 sept. 2011 14:29:29 [http-8080-1] DEBUG org.springframework.orm.hibernate3.HibernateTransactionManager - Participating in existing transaction [jmedia] 21 sept. 2011 14:29:29 [http-8080-1] DEBUG org.springframework.orm.hibernate3.HibernateTransactionManager - Participating transaction failed - marking existing transaction as rollback-only [jmedia] 21 sept. 2011 14:29:29 [http-8080-1] DEBUG org.springframework.orm.hibernate3.HibernateTransactionManager - Setting Hibernate transaction on Session [org.hibernate.impl.SessionImpl@26b20a31] rollback-only [jmedia] 21 sept. 2011 14:29:29 [http-8080-1] DEBUG org.springframework.orm.hibernate3.HibernateTransactionManager - Initiating transaction rollback [jmedia] 21 sept. 2011 14:29:29 [http-8080-1] DEBUG org.springframework.orm.hibernate3.HibernateTransactionManager - Rolling back Hibernate transaction on Session [org.hibernate.impl.SessionImpl@26b20a31] [jmedia] 21 sept. 2011 14:29:29 [http-8080-1] DEBUG org.springframework.orm.hibernate3.HibernateTransactionManager - Closing Hibernate Session [org.hibernate.impl.SessionImpl@26b20a31] after transaction 21 sept. 2011 14:29:29 com.sun.xml.ws.server.sei.EndpointMethodHandler invoke Here my applicationContext : <context:annotation-config/> <!-- List of packages managed by Spring --> <context:component-scan base-package="..." /> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://xxxx"/> <property name="username" value="xxx"/> <property name="password" value="xxx"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="packagesToScan" value="xxxx"/> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:hibernate.cfg.xml" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> And the hibernate.cfg.xml : <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <!-- a SessionFactory instance listed as /jndi/name --> <session-factory> <property name="dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> <property name="show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.connection.pool_size">1</property> <property name="hibernate.jdbc.batch_size">20</property> <!-- Bind the getCurrentSession() method to the thread. --> <property name="current_session_context_class">thread</property> <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</property> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.use_query_cache">true</property> <!-- Lucene Search --> <property name="hibernate.search.default.directory_provider">org.hibernate.search.store.RAMDirectoryProvider</property> </session-factory> I deployed this webapp on tomcat6. I hope can you help me to resolve that issue. Cheers A: Ok I found the problem ! I removed this line from the hibernate configuration. Spring manages the transaction, and it doesn't need of that the session is holding in a hibernate thread. <!-- Bind the getCurrentSession() method to the thread. --> <property name="current_session_context_class">thread</property>
{ "language": "en", "url": "https://stackoverflow.com/questions/7500030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: c++ native code using an abstract class into a wrapper I need to implement a c# GUI for my unmanaged code. So i have designed a wrapper to deal with my native code, but this does not work porperly. I have a method which requires to make an instance to an abstract class and i'm not sure how to deal with it. First for my C++ classes i used an abstract class: class Interface abstract { public: Interface (void); public: ~Interface (void); public: virtual double Get() = 0; }; And i used a ClassSpecific1 and a ClassSpecific2 depending on my current application, and i inherited the functions from the abstract class for each one. class ClassSpecific1 : public Interface { public: ClassSpecific1 (void); public: ~ClassSpecific1 (void); private: double Get();//based on the abstract class }; class ClassSpecific2 : public Interface { public: ClassSpecific2 (void); public: ~ClassSpecific2 (void); private: double Get();//based on the abstract class }; Later i used another class, it works as a general class and uses the ClassSpecific1 or the ClassSpecific2 with an instance of the abstract class. class ClassAPI { public: ClassLaserAPI(void); public: ~ClassLaserAPI(void); public: double Get(Interface *objToInterface);//This Get() calls the Get() in ClassSpecific1 or ClassSpecific2 }; Until here everything seems all right. I have tested everything and works as expected. My big problem is that i don't know how to make my method Get(Interface *objToInterface) from ClassAPI into my wrapper. Do i need to make a wrapper for my abstract class first in order to be able to create the instance**(Interface *objToInterface)** on the wrapper? This is what i have so far, i hope someone can give me some help, i'm getting lost in how to proceed. namespace API { public __gc class APIManaged { public: APIManaged(void); public: ~APIManaged(void); /** Unmanaged pointer to ClassAPI * */ private: ClassAPI __nogc* cAPI; public: double Get(Interface __nogc* objInterface); }; A: I'm also having the same problem and got it resolved using this topic: C++/CLI Inheriting from a native C++ class with abstract methods and exposing it to C# I too am using an unmanaged abstract class and got things working by following the tips outlined in the link. I ended up with a few errors to fix and fixed them by changing my linker options in my unmanaged projects to not compile with /clr and only the wrapper project compiles using /clr. Posting your output errors may help clarify some of the troubles you are having...
{ "language": "en", "url": "https://stackoverflow.com/questions/7500036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use the Email template in Magento I develop my store in magento community edition 1.5.0.1. I need a Email template that content will be editable by admin. I create a email template through admin "Transactional Emails". Now I need to access and use that email from my custom module. How do I get it?, you have any idea let me know. A: This should do it. public function sendTransactionalEmail() { // Transactional Email Template's ID $templateId = 1; // Set sender information $senderName = Mage::getStoreConfig('trans_email/ident_support/name'); $senderEmail = Mage::getStoreConfig('trans_email/ident_support/email'); $sender = array('name' => $senderName, 'email' => $senderEmail); // Set recepient information $recepientEmail = 'john@example.com'; $recepientName = 'John Doe'; // Get Store ID $storeId = Mage::app()->getStore()->getId(); // Set variables that can be used in email template $vars = array('customerName' => 'customer@example.com', 'customerEmail' => 'Mr. Nil Cust'); $translate = Mage::getSingleton('core/translate'); // Send Transactional Email Mage::getModel('core/email_template') ->sendTransactional($templateId, $sender, $recepientEmail, $recepientName, $vars, $storeId); $translate->setTranslateInline(true); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7500038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: JQuery - upload and show preview image (based on ZURB) I'm newbie in scripting and try to follow Zurb articles on Image Uploads with 100% Less Suck. Guaranteed. But still can not make it right. On requirement said that I need JQuery and AjaxUpload plugin. So I do make links to files needed: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript" src="http://www.zurb.com/javascripts/plugins/ajaxupload.js"></script> (Sorry Zurb and others that I use the links, I use the file for educational purpose only. I don't mean anything bad) This is the script that I follow from Zurb JQUERY $(document).ready(function(){ var thumb = $('img#thumb'); new AjaxUpload('imageUpload', { action: $('form#testForm').attr('action'), name: 'image', onSubmit: function(file, extension) { $('div.preview').addClass('loading'); }, onComplete: function(file, response) { thumb.load(function(){ $('div.preview').removeClass('loading'); thumb.unbind(); }); thumb.attr('src', response); } }); }); CSS span.wrap { padding: 10px; } span.wrap.new { margin-left: 30px; } span.wrap button { display: block; margin-top: 10px; } span.wrap label { margin-bottom: 5px; } div.preview { float: left; width: 100px; height: 100px; border: 2px dotted #CCCCCC; } div.preview.loading { background: url(http://www.woningcorporatie-processen.nl/static/modules/sensus/images/loading.gif) no-repeat 39px 40px; } div.preview.loading img {display: none; } input#imageUpload { width: 400px; } span.wrap form { margin: 0; } HTML <div class="wrap"> <div class="preview"> <img id="thumb" width="100px" height="100px" src="https://greenhouse.lotus.com/plugins/plugincatalog.nsf/blankLogo.gif" /> </div> <span class="wrap new"> <form id="testForm" action="ajax_upload"> <label>Upload a Picture of Yourself</label> <input type="file" id="imageUpload" size="20" /> <button type="submit" class="button">Save</button> </form> </span> </div> Already try in JsFiddle but not working good. Can you guys help what I supposed to do so I can preview the uploaded image with this Jquery? Thanks a lot!
{ "language": "en", "url": "https://stackoverflow.com/questions/7500039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get the closest tr value in JavaScript function I am having table which contain some data. This table is generating using a component. All td's has the same class name. Each row begins with a check-box with a specific value to that row. When click on a td on that row I want to get check-box value. When I click on a label JavaScript function is triggered. Cannot use jQuery click function. A: sample: http://jsfiddle.net/gCGVJ/ $('td').click(function() { alert($(this).closest('tr').find('input[type=checkbox]').val()); }); A: $('td').click(function(){ var val = $(this).closest('tr').find('#checkbox').val(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7500046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Boost.asio & UNIX signal handling Preface I have a multi-threaded application running via Boost.Asio. There is only one boost::asio::io_service for the whole application and all the things are done inside it by a group of threads. Sometimes it is needed to spawn child processes using fork and exec. When child terminates I need to make waitpid on it to check exit code an to collect zombie. I used recently added boost::asio::signal_set but encountered a problem under ancient systems with linux-2.4.* kernels (that are unfortunately still used by some customers). Under older linux kernels threads are actually a special cases of processes and therefore if a child was spawned by one thread, another thread is unable to wait for it using waitpid family of system calls. Asio's signal_set posts signal handler to io_service and any thread running this service can run this handler, which is inappropriate for my case. So I decided to handle signals in old good signal/sigaction way - all threads have the same handler that calls waitpid. So there is another problem: The problem When signal is caught by handler and process is successfully sigwaited, how can I "post" this to my io_service from the handler? As it seems to me, obvious io_service::post() method is impossible because it can deadlock on io_service internal mutexes if signal comes at wrong time. The only thing that came to my mind is to use some pipe or socketpair to write notifications there and async_wait on another end as it is done sometimes to handle signals in poll() event loops. Are there any better solutions? A: I've not dealt with boost::asio but I have solved a similar problem. I believe my solution works for both LinuxThreads and the newer NPTL threads. I'm assuming that the reason you want to "post" signals to your *io_service* is to interrupt an system call so the thread/program will exit cleanly. Is this correct? If not maybe you can better describe your end goal. I tried a lot of different solutions including some which required detecting which type of threads were being used. The thing that finally helped me solve this was the section titled Interruption of System Calls and Library Functions by Signal Handlers of man signal(7). The key is to use sigaction() in your signal handling thread with out SA_RESTART, to create handlers for all the signals you want to catch, unmask these signals using pthread_sigmask(SIG_UNBLOCK, sig_set, 0) in the signal handling thread and mask the same signal set in all other threads. The handler does not have to do anything. Just having a handler changes the behavior and not setting SA_RESTART allows interruptible systems calls (like write()) to interrupt. Whereas if you use sigwait() system calls in other threads are not interrupted. In order to easily mask signals in all other threads. I start the signal handling thread. Then mask all the signals in want to handle in the main thread before starting any other threads. Then when other threads are started they copy the main thread's signal mask. The point is if you do this then you may not need to post signals to your *io_service* because you can just check your system calls for interrupt return codes. I don't know how this works with boost::asio though. So the end result of all this is that I can catch the signals I want like SIGINT, SIGTERM, SIGHUO and SIGQUIT in order to perform a clean shutdown but my other threads still get their system calls interrupted and can also exit cleanly with out any communication between the signal thread and the rest of the system, with out doing anything dangerous in the signal handler and a single implementation works on both LinuxThreads and NPTL. Maybe that wasn't the answer you were looking for but I hope it helps. NOTE: If you want to figure out if the system is running LinuxThreads you can do this by spawning a thread and then comparing it's PID to the main thread's PID. If they differ it's LinuxThreads. You can then choose the best solution for the thread type. A: If you are already polling your IO, another possible solution that is very simple is to just use a boolean to signal the other threads. A boolean is always either zero or not so there is no possibility of a partial update and a race condition. You can then just set this boolean flag without any mutexes that the other threads read. Tools like valgrind wont like it but in practice it works. If you want to be even more correct you can use gcc's atomics but this is compiler specific.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Making JARs from Java Classes and Implementing via GWT I created the following generic class (and a number of custom widgets) and want to do two things: 1) externalize to a JAR for portability 2) import and use that JAR in my GWT project How might I go about doing so? Do other items (i.e. dependencies) need to be included when I right-click->export on the class(es) in Eclipse? import java.io.Serializable; import com.google.gwt.user.client.ui.HasValue; public class MinMaxAvg<T> extends HasValueConcrete<MinMax<T>> implements HasValue<MinMax<T>>, Serializable { private static final long serialVersionUID = -54806010801403294L; private T min; private T max; private T avg; public MinMaxAvg() { super(); } public MinMaxAvg(T min, T max, T avg) { super(); this.min = min; this.max = max; this.avg = avg; } public MinMaxAvg(MinMaxAvg<T> rhs) { super(); if (rhs != null) { this.min = rhs.min; this.max = rhs.max; this.avg = rhs.avg; } } public T getMin() { return min; } public void setMin(T min) { this.min = min; } public T getMax() { return max; } public void setMax(T max) { this.max = max; } public T getAvg() { return avg; } public void setAvg(T avg) { this.avg = avg; } public boolean hasMin() { return min != null; } public boolean hasMax() { return max != null; } public boolean hasAvg() { return avg != null; } @Override public MinMax<T> getValue() { return new MinMax<T>(min, max); } @Override public void setValue(MinMax<T> value) { min = value.getMin(); max = value.getMax(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((avg == null) ? 0 : avg.hashCode()); result = prime * result + ((max == null) ? 0 : max.hashCode()); result = prime * result + ((min == null) ? 0 : min.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; @SuppressWarnings("unchecked") MinMaxAvg<T> other = (MinMaxAvg<T>) obj; if (avg == null) { if (other.avg != null) return false; } else if (!avg.equals(other.avg)) return false; if (max == null) { if (other.max != null) return false; } else if (!max.equals(other.max)) return false; if (min == null) { if (other.min != null) return false; } else if (!min.equals(other.min)) return false; return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("MinMaxAvg [min="); builder.append(min); builder.append(", max="); builder.append(max); builder.append(", avg="); builder.append(avg); builder.append("]"); return builder.toString(); } } A: Importing and using jars in GWT is done by means of modules. Since GWT Compiler needs to see the source of your classes to produce javascript, if you intend to use your classes not only on server side but in a browser as well, you need to include the source files(.java) along with your .class files in the same package in your jar. You need also to have a moduleName.gwt.xml file at the root of your module. An example package would look like this : org.test.mymodule --> MyModule.gwt.xml org.test.mymodule.client --> MinMaxAvg.class --> MinMaxAvg.java Moreover to include this module in a GWT project you need to include the jar you created and you need to add <inherits name="org.test.mymodule.MyModule" /> to module descriptor of your parent project. There is also a link I find useful about Creating Reusable Modules here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker I have following datepicker script: <script> $(function(){ $("#to").datepicker(); $("#from").datepicker().bind("change",function(){ var minValue = $(this).val(); minValue = $.datepicker.parseDate("mm/dd/yy", minValue); minValue.setDate(minValue.getDate()+1); $("#to").datepicker( "option", "minDate", minValue ); }) }); </script> Now dateformat is MM/DD/YY .how to change the date format to YYYY-MM-DD? A: $( ".selector" ).datepicker( "option", "dateFormat", 'yy-mm-dd' ); See: http://jqueryui.com/demos/datepicker/ and http://docs.jquery.com/UI/Datepicker/formatDate#utility-formatDate A: Use the dateFormat option $(function(){ $("#to").datepicker({ dateFormat: 'yy-mm-dd' }); $("#from").datepicker({ dateFormat: 'yy-mm-dd' }).bind("change",function(){ var minValue = $(this).val(); minValue = $.datepicker.parseDate("yy-mm-dd", minValue); minValue.setDate(minValue.getDate()+1); $("#to").datepicker( "option", "minDate", minValue ); }) }); Demo at http://jsfiddle.net/gaby/WArtA/ A: If in jquery the dateformat option is not working then we can handle this situation in html page in input field of your date: <input type="text" data-date-format='yyyy-mm-dd' id="selectdateadmin" class="form-control" required> And in javascript below this page add your date picker code: $('#selectdateadmin').focusin( function() { $("#selectdateadmin").datepicker(); }); A: Try the following: $('#to').datepicker({ dateFormat: 'yy-mm-dd' }); You'd think it would be yyyy-mm-dd but oh well :P A: I had the same issue and I have tried many answers but nothing worked. I tried the following and it worked successfully : <input type=text data-date-format='yy-mm-dd' > A: You need something like this during the initialization of your datepicker: $("#your_elements_id").datepicker({ dateFormat: 'yyyy-mm-dd' }); A: this also worked for me. Go to the bootstrap-datepicker.js. replace this code : var defaults = $.fn.datepicker.defaults = { autoclose: false, beforeShowDay: $.noop, calendarWeeks: false, clearBtn: false, daysOfWeekDisabled: [], endDate: Infinity, forceParse: true, format: 'mm/dd/yyyy', keyboardNavigation: true, language: 'en', minViewMode: 0, multidate: false, multidateSeparator: ',', orientation: "auto", rtl: false, startDate: -Infinity, startView: 0, todayBtn: false, todayHighlight: false, weekStart: 0 }; with : var defaults = $.fn.datepicker.defaults = { autoclose: false, beforeShowDay: $.noop, calendarWeeks: false, clearBtn: false, daysOfWeekDisabled: [], endDate: Infinity, forceParse: true, format: 'yyyy-mm-dd', keyboardNavigation: true, language: 'en', minViewMode: 0, multidate: false, multidateSeparator: ',', orientation: "auto", rtl: false, startDate: -Infinity, startView: 0, todayBtn: false, todayHighlight: false, weekStart: 0 }; A: I used this approach to perform the same operation in my app. var varDate = $("#dateStart").val(); var DateinISO = $.datepicker.parseDate('mm/dd/yy', varDate); var DateNewFormat = $.datepicker.formatDate( "yy-mm-dd", new Date( DateinISO ) ); $("#dateStartNewFormat").val(DateNewFormat); A: Try this: $.datepicker.parseDate("yy-mm-dd", minValue); A: Use .formatDate( format, date, settings ) http://docs.jquery.com/UI/Datepicker/formatDate A: just add dateFormat:'yy-mm-dd' to your .datepicker({}) settings, your .datepicker({}) can look something like this $( "#datepicker" ).datepicker({ showButtonPanel: true, changeMonth: true, dateFormat: 'yy-mm-dd' }); }); </script> A: Just need to define yy-mm-dd here. dateFormat Default is mm-dd-yy Change mm-dd-yy to yy-mm-dd. Look example below $(function() { $( "#datepicker" ).datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true }); } ); Date: <input type="text" id="datepicker"> A: Thanks for all. I got my expected output <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script> <script> $(function(){ $("#to").datepicker({ dateFormat: 'yy-mm-dd' }); $("#from").datepicker({ dateFormat: 'yy-mm-dd' }).bind("change",function(){ var minValue = $(this).val(); minValue = $.datepicker.parseDate("yy-mm-dd", minValue); minValue.setDate(minValue.getDate()+1); $("#to").datepicker( "option", "minDate", minValue ); }) }); </script> <div class=""> <p>From Date: <input type="text" id="from"></p> <p>To Date: <input type="text" id="to"></p> </div> A: this worked for me. $('#thedate').datepicker({ dateFormat: 'dd-mm-yy', altField: '#thealtdate', altFormat: 'yy-mm-dd' }); A: This work for me: $('#data_compra').daterangepicker({ singleDatePicker: true, locale: { format: 'DD/MM/YYYY' }, calender_style: "picker_4", }, function(start, end, label) { console.log(start.toISOString(), end.toISOString(), label); }); A: This is what worked for me in every datePicker version, firstly converting date into internal datePicker date format, and then converting it back to desired one var date = "2017-11-07"; date = $.datepicker.formatDate("dd.mm.yy", $.datepicker.parseDate('yy-mm-dd', date)); // 07.11.2017 A: For me in datetimepicker jquery plugin format:'d/m/Y' option is worked $("#dobDate").datetimepicker({ lang:'en', timepicker:false, autoclose: true, format:'d/m/Y', onChangeDateTime:function( ct ){ $(".xdsoft_datetimepicker").hide(); } }); A: $('#selectdateadmin').focusin( function() { $("#selectdateadmin").datepicker(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7500058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "53" }
Q: Making file transfer more efficient Java I have two wireless computers connected to an N wireless router. Each of these PCs are connected at between 108-150Mbps. Theoretically, I should be able to transfer at 13.5MB/s to 18.75MB/s, under the absolute best of conditions. The first computer (that is sending), uses a very fast SSD, which is around 100MB/s if I remember correctly. CPU usage also stays below 20%. It sent 1960273535 bytes (1.8GB) in 656367ms. That's 2.8MB/s (22 out of 108 Megabits). When I open up task manager, I see that only 25-27% of the network connection is being used. I am looking for any ideas, suggestions, or improvements that can make the transfer faster (over a network). I was thinking of buffering the file from the disk on a thread and sending the buffered data from another thread but I'm not sure if it's a good idea. Here is the SSCCE: Host: import java.io.*; import java.net.*; public class Host { public static void main(String[] args) throws IOException { ServerSocket servsock = new ServerSocket(15064); Socket sock = servsock.accept(); long time = System.currentTimeMillis(); OutputStream out = sock.getOutputStream(); FileInputStream fileInputStream = new FileInputStream("C:\\complete.rar"); byte [] buffer = new byte[64*1024]; int bytesRead = 0; long totalSent = 0; while ( (bytesRead = fileInputStream.read(buffer)) != -1) { if (bytesRead > 0) { out.write(buffer, 0, bytesRead); totalSent += bytesRead; System.out.println("sent " + totalSent); } } sock.close(); System.out.println("Sent " + totalSent + " bytes in " + (System.currentTimeMillis() - time) + "ms."); } } Client: import java.io.*; import java.net.*; public class Client { public static void main(String[] args) throws Exception { Socket sock = new Socket("127.0.0.1", 15064); InputStream in = sock.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream("output.rar"); byte [] buffer = new byte[64*1024]; int bytesRead = 0; while ( (bytesRead = in.read(buffer)) != -1) fileOutputStream.write(buffer, 0, bytesRead); sock.close(); fileOutputStream.close(); } } Edit: I tried mapping a network drive and sending the file over that, and windows did even worse - 2.35MB/s. According to this article http://tinyurl.com/634qaqg mapping a network drive is faster than FTP, and I also don't have the time to stay playing around and setting up the FTP server. Edit2: After changing the timer, turns out it was transferring at 3MB/s over WiFi. I hate the "theoretical" throughput. When I buy something, I want to know it's REAL performance. It turns out the code is indeed limited by WiFi speeds. I am still open to suggestions though. Edit 3: After running the program on 100Mbps LAN, it managed to transfer the file at 11.8MB/s. That's pretty good considering that the maximum transfer rate is 12.5MB/s. A: At 2.8MB/s, it is unlikely that the slowness has anything to do with your code. It is almost certainly due to the wireless network not being able to achieve the theoretical throughput (possibly due to environmental conditions). It's easy to test whether this is the case: simply time a large ftp or scp file transfer between the same two computers and see what kind of throughput you're seeing. A: I suggest you try the following code which prints Wed Oct 26 14:21:03 BST 2011: Accepted a connection Wed Oct 26 14:21:13 BST 2011: Transfer rate was 3212.5 MB/s on the server and on the client prints Wed Oct 26 14:21:03 BST 2011 Sending for 10.0 seconds. Wed Oct 26 14:21:13 BST 2011 ... sent. Wed Oct 26 14:21:13 BST 2011 ... received 33691287552 Send and received 3212.8 MB/s Note: the total amount transferred is double this as everything sent client to server is sent server to client. import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Date; public class EchoServerMain { public static void main(String... args) throws IOException { int port = args.length < 1 ? 55555 : Integer.parseInt(args[0]); ServerSocketChannel ss = ServerSocketChannel.open(); ss.socket().bind(new InetSocketAddress(port)); while (!ss.socket().isClosed()) { SocketChannel s = ss.accept(); System.out.println(new Date() + ": Accepted a connection"); long start = System.nanoTime(); ByteBuffer bytes = ByteBuffer.allocateDirect(32*1024); int len; long total = 0; // Thank you @EJP, for a more elegant single loop. while ((len = s.read(bytes)) >= 0 || bytes.position() > 0) { bytes.flip(); s.write(bytes); bytes.compact(); total += len; } long time = System.nanoTime() - start; System.out.printf(new Date() + ": Transfer rate was %.1f MB/s%n", total * 1e9 / 1024 / 1024 / time); } ss.close(); } } and import java.io.EOFException; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.Date; public class EchoClientMain { public static void main(String ... args) throws IOException { String hostname = args.length < 1 ? "localhost" : args[0]; int port = args.length < 2 ? 55555 : Integer.parseInt(args[1]); double seconds = args.length < 3 ? 10 : Double.parseDouble(args[2]); SocketChannel s = SocketChannel.open(new InetSocketAddress(hostname, port)); s.configureBlocking(false); ByteBuffer bytes = ByteBuffer.allocateDirect(32*1024); System.out.printf(new Date()+ " Sending for %.1f seconds.%n", seconds); long start = System.nanoTime(); long dataSent = 0, dataReceived = 0; // run for 10 seconds. while(start + seconds*1e9 > System.nanoTime()) { bytes.clear(); int wlen = s.write(bytes); if (wlen < 0) throw new IOException(); dataSent += wlen; bytes.clear(); int rlen = s.read(bytes); if (rlen < 0) throw new EOFException(); dataReceived += rlen; } System.out.println(new Date()+ " ... sent."); while(dataReceived < dataSent) { bytes.clear(); int rlen = s.read(bytes); if (rlen < 0) throw new EOFException(); dataReceived += rlen; } s.close(); long time = System.nanoTime() - start; System.out.println(new Date()+ " ... received "+dataReceived); System.out.printf("Send and received %.1f MB/s%n", dataReceived * 1e9/1024/1024/time); } } A: Your timer is wrong ! you should start it after you accept the connection not when you start the host Did you try increasing your buffer size ? A: Test the same program using a wired, Fast Ethernet (100Mbit/s) link between the computers (and then possibly using a 1Gbit link). That way, you'll see whether the transfer rate is actually limited by your program or by the link. A: Just set a very large socket send buffer, and if possible set a very large socket receive buffer at the receiver. Code 'optimizations' contribute basically nothing to these scenarios.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Database encryption and connecting to such a database We have a project where the client would like their SQLServer2008 database to be encrypted. I understand that it is possible with SQL server 2008 to easily encrypt the database, but I don't really know how. Can anybody help me with this ? Also, once this database is encrypted, how can we connect to it ? I can't seem to find any way in the connection strings found in ConnectionStrings.com to enter any information about the encryption key. If we can't connect to the database once it's encrypted, there is no incentive to encrypt it... Thanks A: Full documentation on encrypting a SQL Server 2008 database is here: http://msdn.microsoft.com/en-us/library/cc278098(v=sql.100).aspx#_Toc189384672 In a nutshell, the encryption can be transparently achieved either through an internal "TDE" mechanism or through encryption of the underlying database files using either Windows EFS or Bitlocker. The article neatly discusses the pros and cons of each approach. It also points out that you'll want to consider encrypting the communication between the client and the database server with HTTPS. On the client side, you'd encrypt the connection string. Details on doing this in a configuration file for a .NET application are here: http://msdn.microsoft.com/en-us/library/ff647398.aspx. A: Do you know what it is that you want encrypted? You can encrypt stored procedures so that they can't be (accidentally) opened or modified by anyone looking at the database with SSMS. In that case, the procedures are still executable but you can't see the logic without decrypting them. Looks like you can also encrypt data in SQL Server 2008, although I've not tried it myself. There is a ton of reading on Technet and MSDN around the subject which seems like it should be good background!
{ "language": "en", "url": "https://stackoverflow.com/questions/7500062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting website displayed correctly in Google I have a website that is now listed in Google's search directory, but it will only display 'Home' as title and will not display a descriptive text as it would for other results found. This is the search I've done to retrieve my website: here. It's the 8th result (for me, might be different for you guys), but it's the only one that has no description attached to itself and no title (only Home). I assume the title has got to do with the tags in my html, though if you have a look at the website's source code, the title is not Home. So I'm not quite sure what to do here. Also, I'm using wordpress for this website so maybe there's something I should be doing on the server-side to fix this? I always assumed google would extract directly from the page, so I have no idea what to do here. A: I'm guessing the page title used to be 'home' and Google just hasn't caught up with the change yet. Google doesn't check every time it returns your page as a result (think about how that would work). You could also update the meta description tag in your homepage so Google can present a proper description of your site to searchers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UITabbarcontroller with nested pages - cannot get tab bar control to show root I have used UITabbar control to navigate to the top level pages of my app. Each top level page navigates to 5 other pages using command buttons to drill deeper. When the user selects the next tabbar item, instead of navigating to the root, they end up on the page they were last reading in the hierarchy. I am using XCode 4 and Tab Bars have been created using IB. How can I change this behavior so that the tab bar button always navigates to the top level page? Your help would be very much appreciated since I have spent many days trying to resolve this issue. A: I believe this will work if your tabs have UINavigationController at their root //somewhere in the initialization process tabBarController.delegate = self - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{ UINavigationController *navController = (UINavigationController *)viewController; if([navController.viewControllers count]>0) [navController popToRootViewControllerAnimated:NO]; } A: I have implemented UITabBar with each button loading a separate view controller and each of those view controllers having a navigation controller as a drill-down interface. When each button on the tab bar is clicked, the UIViewController is loaded and it is responsible for handling the drill down. This sounds like what you want to do. Since I'm not sure what you mean by "page", I don't know how you are implementing the change that happens when a button is tapped on the tab bar. It sounds like you have one UIViewController and that's not quite how the UITabBar was designed to function. I could be wrong, so I think a little more explanation is needed. If you are implementing with multiple UIViewControllers, You may want to think about whether a user is going to want to remain buried in the drill down even on changing tabs. Not sure what you App does, but this may be desired behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CommonDomain/EventStore Interface Fetching I'd like to access my aggregate root by an interface it implements: repository.GetById[[IMyInterface]](id); What do I need to tell CommonDomain or EventStore to accomplish this? I believe my IConstructAggregates receives the Implementation Type of the aggregate that stored the events. Do i need to just keep my own map of ids. For example, say I have these agg roots : class AggRoot1 : IInterface1, IInterface2 {} class AggRoot2 : IInterface1, IInterface2 {} I already saved an aggregate1 instance having 'idFromAggRoot1'. Now I want to fetch like so: repository.GetById<IInterface1>(idFromAggRoot1); How can I know what I should create later since there are two implementors of IInterface1? AggRoot1? AggRoot2? IInterface1? Activator would bomb here so I know I need to implement IConstructAggregates but wonder if there is some other descriptor to tell me what the original commit agg root type was. A: The IConstructAggregates.Build() method can be implemented to return whatever type you need. In Common.AggregateFactory the default implementation creates an instance of the Aggregate via Activator.CreateInstance(type) as IAggregate. An own implementation might look like this: public class MyAggregateFactory : IConstructAggregates { public IAggregate Build(Type type, Guid id, IMemento snapshot) { if (type == typeof(IMyInterface)) return new MyAggregate(); else return Activator.CreateInstance(type) as IAggregate; } } Edit: The aggregate type is being stored in the event message's header as EventMessage.Header[EventStoreRepository.AggregateTypeHeader]
{ "language": "en", "url": "https://stackoverflow.com/questions/7500068", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make a JPanel border with title like in Firefox I would like to make an option dialog in my application. In this dialog I want to make kind of Areas surrounded with a border and with a title. An example of what I want is in Firefox: How can I do something like that in Java? A: Here you can find all informations you need. Basically you can use border factory to create a Border using types available in Swing: Border lineBorder = BorderFactory.createLineBorder(Color.black); JPanel panel = new JPanel(); panel.setBorder(lineBorder); You can also define your custom borders implementing Border interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Improving the readability of a FParsec parser I have a hand-written CSS parser done in C# which is getting unmanageable and was trying to do it i FParsec to make it more mantainable. Here's a snippet that parses a css selector element made with regexes: var tagRegex = @"(?<Tag>(?:[a-zA-Z][_\-0-9a-zA-Z]*|\*))"; var idRegex = @"(?:#(?<Id>[a-zA-Z][_\-0-9a-zA-Z]*))"; var classesRegex = @"(?<Classes>(?:\.[a-zA-Z][_\-0-9a-zA-Z]*)+)"; var pseudoClassRegex = @"(?::(?<PseudoClass>link|visited|hover|active|before|after|first-line|first-letter))"; var selectorRegex = new Regex("(?:(?:" + tagRegex + "?" + idRegex + ")|" + "(?:" + tagRegex + "?" + classesRegex + ")|" + tagRegex + ")" + pseudoClassRegex + "?"); var m = selectorRegex.Match(str); if (m.Length != str.Length) { cssParserTraceSwitch.WriteLine("Unrecognized selector: " + str); return null; } string tagName = m.Groups["Tag"].Value; string pseudoClassString = m.Groups["PseudoClass"].Value; CssPseudoClass pseudoClass; if (pseudoClassString.IsEmpty()) { pseudoClass = CssPseudoClass.None; } else { switch (pseudoClassString.ToLower()) { case "link": pseudoClass = CssPseudoClass.Link; break; case "visited": pseudoClass = CssPseudoClass.Visited; break; case "hover": pseudoClass = CssPseudoClass.Hover; break; case "active": pseudoClass = CssPseudoClass.Active; break; case "before": pseudoClass = CssPseudoClass.Before; break; case "after": pseudoClass = CssPseudoClass.After; break; case "first-line": pseudoClass = CssPseudoClass.FirstLine; break; case "first-letter": pseudoClass = CssPseudoClass.FirstLetter; break; default: cssParserTraceSwitch.WriteLine("Unrecognized selector: " + str); return null; } } string cssClassesString = m.Groups["Classes"].Value; string[] cssClasses = cssClassesString.IsEmpty() ? EmptyArray<string>.Instance : cssClassesString.Substring(1).Split('.'); allCssClasses.AddRange(cssClasses); return new CssSelectorElement( tagName.ToLower(), cssClasses, m.Groups["Id"].Value, pseudoClass); My first attempt yielded this: type CssPseudoClass = | None = 0 | Link = 1 | Visited = 2 | Hover = 3 | Active = 4 | Before = 5 | After = 6 | FirstLine = 7 | FirstLetter = 8 type CssSelectorElement = { Tag : string Id : string Classes : string list PseudoClass : CssPseudoClass } with static member Default = { Tag = ""; Id = ""; Classes = []; PseudoClass = CssPseudoClass.None; } open FParsec let ws = spaces let str = skipString let strWithResult str result = skipString str >>. preturn result let identifier = let isIdentifierFirstChar c = isLetter c || c = '-' let isIdentifierChar c = isLetter c || isDigit c || c = '_' || c = '-' optional (str "-") >>. many1Satisfy2L isIdentifierFirstChar isIdentifierChar "identifier" let stringFromOptional strOption = match strOption with | Some(str) -> str | None -> "" let pseudoClassFromOptional pseudoClassOption = match pseudoClassOption with | Some(pseudoClassOption) -> pseudoClassOption | None -> CssPseudoClass.None let parseCssSelectorElement = let tag = identifier <?> "tagName" let id = str "#" >>. identifier <?> "#id" let classes = many1 (str "." >>. identifier) <?> ".className" let parseCssPseudoClass = choiceL [ strWithResult "link" CssPseudoClass.Link; strWithResult "visited" CssPseudoClass.Visited; strWithResult "hover" CssPseudoClass.Hover; strWithResult "active" CssPseudoClass.Active; strWithResult "before" CssPseudoClass.Before; strWithResult "after" CssPseudoClass.After; strWithResult "first-line" CssPseudoClass.FirstLine; strWithResult "first-letter" CssPseudoClass.FirstLetter] "pseudo-class" // (tag?id|tag?classes|tag)pseudoClass? pipe2 ((pipe2 (opt tag) id (fun tag id -> { CssSelectorElement.Default with Tag = stringFromOptional tag; Id = id })) |> attempt <|> (pipe2 (opt tag) classes (fun tag classes -> { CssSelectorElement.Default with Tag = stringFromOptional tag; Classes = classes })) |> attempt <|> (tag |>> (fun tag -> { CssSelectorElement.Default with Tag = tag }))) (opt (str ":" >>. parseCssPseudoClass) |> attempt) (fun selectorElem pseudoClass -> { selectorElem with PseudoClass = pseudoClassFromOptional pseudoClass }) But I'm not really liking how it's shaping up. I was expecting to come up with something easier to understand, but the part parsing (tag?id|tag?classes|tag)pseudoClass? with a few pipe2's and attempt's is really bad. Came someone with more experience in FParsec educate me on better ways to accomplish this? I'm thinking on trying FSLex/Yacc or Boost.Spirit instead of FParsec is see if I can come up with nicer code with them A: You could extract some parts of that complex parser to variables, e.g.: let tagid = pipe2 (opt tag) id (fun tag id -> { CssSelectorElement.Default with Tag = stringFromOptional tag Id = id }) You could also try using an applicative interface, personally I find it easier to use and think than pipe2: let tagid = (fun tag id -> { CssSelectorElement.Default with Tag = stringFromOptional tag Id = id }) <!> opt tag <*> id A: As Mauricio said, if you find yourself repeating code in an FParsec parser, you can always factor out the common parts into a variable or custom combinator. This is one of the great advantages of combinator libraries. However, in this case you could also simplify and optimize the parser by reorganizing the grammer a bit. You could, for example, replace the lower half of the parseCssSelectorElement parser with let defSel = CssSelectorElement.Default let pIdSelector = id |>> (fun str -> {defSel with Id = str}) let pClassesSelector = classes |>> (fun strs -> {defSel with Classes = strs}) let pSelectorMain = choice [pIdSelector pClassesSelector pipe2 tag (pIdSelector <|> pClassesSelector <|>% defSel) (fun tagStr sel -> {sel with Tag = tagStr})] pipe2 pSelectorMain (opt (str ":" >>. parseCssPseudoClass)) (fun sel optPseudo -> match optPseudo with | None -> sel | Some pseudo -> {sel with PseudoClass = pseudo}) By the way, if you want to parse a large number of string constants, it's more efficient to use a dictionary based parsers, like let pCssPseudoClass : Parser<CssPseudoClass,unit> = let pseudoDict = dict ["link", CssPseudoClass.Link "visited", CssPseudoClass.Visited "hover", CssPseudoClass.Hover "active", CssPseudoClass.Active "before", CssPseudoClass.Before "after", CssPseudoClass.After "first-line", CssPseudoClass.FirstLine "first-letter", CssPseudoClass.FirstLetter] fun stream -> let reply = identifier stream if reply.Status <> Ok then Reply(reply.Status, reply.Error) else let mutable pseudo = CssPseudoClass.None if pseudoDict.TryGetValue(reply.Result, &pseudo) then Reply(pseudo) else // skip to beginning of invalid pseudo class stream.Skip(-reply.Result.Length) Reply(Error, messageError "unknown pseudo class")
{ "language": "en", "url": "https://stackoverflow.com/questions/7500075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Scala: what is the best way to append an element to an Array? Say I have an Array[Int] like val array = Array( 1, 2, 3 ) Now I would like to append an element to the array, say the value 4, as in the following example: val array2 = array + 4 // will not compile I can of course use System.arraycopy() and do this on my own, but there must be a Scala library function for this, which I simply could not find. Thanks for any pointers! Notes: * *I am aware that I can append another Array of elements, like in the following line, but that seems too round-about: val array2b = array ++ Array( 4 ) // this works *I am aware of the advantages and drawbacks of List vs Array and here I am for various reasons specifically interested in extending an Array. Edit 1 Thanks for the answers pointing to the :+ operator method. This is what I was looking for. Unfortunately, it is rather slower than a custom append() method implementation using arraycopy -- about two to three times slower. Looking at the implementation in SeqLike[], a builder is created, then the array is added to it, then the append is done via the builder, then the builder is rendered. Not a good implementation for arrays. I did a quick benchmark comparing the two methods, looking at the fastest time out of ten cycles. Doing 10 million repetitions of a single-item append to an 8-element array instance of some class Foo takes 3.1 sec with :+ and 1.7 sec with a simple append() method that uses System.arraycopy(); doing 10 million single-item append repetitions on 8-element arrays of Long takes 2.1 sec with :+ and 0.78 sec with the simple append() method. Wonder if this couldn't be fixed in the library with a custom implementation for Array? Edit 2 For what it's worth, I filed a ticket: https://issues.scala-lang.org/browse/SI-5017 A: The easiest might be: Array(1, 2, 3) :+ 4 Actually, Array can be implcitly transformed in a WrappedArray A: val array2 = array :+ 4 //Array(1, 2, 3, 4) Works also "reversed": val array2 = 4 +: array Array(4, 1, 2, 3) There is also an "in-place" version: var array = Array( 1, 2, 3 ) array +:= 4 //Array(4, 1, 2, 3) array :+= 0 //Array(4, 1, 2, 3, 0) A: You can use :+ to append element to array and +: to prepend it: 0 +: array :+ 4 should produce: res3: Array[Int] = Array(0, 1, 2, 3, 4) It's the same as with any other implementation of Seq.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500081", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "125" }
Q: Print same values once in a while loop $query = mysql_query("SELECT * FROM tblname"); while($fetch =mysql_fetch_array($query)) { $name = $fetch['name']; echo "$name"; } In my example, after echoing out $name in a while, the values are: Carrots Lemon Carrots Lemon Is there a way to not repeat printing the same value that will look like this: Carrots Lemon Thank you very much. A: $query = mysql_query("SELECT DISTINCT name FROM tblname"); while($fetch =mysql_fetch_array($query)) { echo $fetch['name']; } A: SQL Solution: SELECT DISTINCT `name` FROM tblname; or SELECT `name` FROM tblname GROUP BY `name`; PHP Solution: $my_array = array(); $query = mysql_query("SELECT * FROM tblname"); while($fetch =mysql_fetch_array($query)) { $my_array[] = $fetch['name']; } $my_array = array_unique($my_array); echo implode('<br />', $my_array); A: $names = array(); $query = mysql_query("SELECT * FROM tblname"); while($fetch =mysql_fetch_array($query)) { $name = $fetch['name']; if (!in_array($name,$names)){ echo "$name"; $names[] = $name; } } Will work. A: $sql = mysql_query("SELECT DISTINCT table1.id, table2.id, table2.name FROM table1, table2 WHERE id=id GROUP BY name"); This Will Work 100% sure. SET GROUP BY name and DISTINCT. If not it is not working. A: Simply append them into an array like: $items[] = $item; After that do: $items = array_unique($items); After that, simply print the items. A: You can fetch them all into an array and then run array_unique() $query = mysql_query("SELECT * FROM tblname"); $arr = array(); while($fetch =mysql_fetch_array($query)) { $arr[] = $fetch; } $output = array_unique($arr); foreach ($output as $uniqe_val) { echo $unique_val; } A: I find the question ambiguous. I think you're asking for what appears in How to make a list of unique items from a column w/ repeats in PHP SQL
{ "language": "en", "url": "https://stackoverflow.com/questions/7500082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Bundling Sql scripts to execute them in a secure way I am generating CSV files using an Oracle SQL scripts in a Unix environment. The code is visible to other users. How can I can encrypt or bundle the code and the generated CSV files? A: unix has file system privileges. you should set those to protect the directory where you are working.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iirf {REQUEST_FILENAME} issue I have the following iirf rules for my web application RewriteFilterPriority HIGH RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{QUERY_STRING} ^$ RewriteRule ^/(.*)$ /index.cfm?path=$1 [L] RewriteRule ^/(.*)\?(.*)$ /index.cfm?path=$1&$2 [L] Everything works, except when there is a file that exists but has a parameter. eg. http://www.domain.com/file.cfm works http://www.domain.com/file.cfm?var=foo doesn't work? it skips and redirects to index.cfm how do i fix this? thanks A: I don't see that problem. What version of IIRF are you using? The RewriteFilterPriority directive is no longer supported in the iirf.ini file. Which makes me think you are using an old v1.x version of IIRF. If so, you should upgrade to v2.x.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: identifying which jpa mapping between customer and currentPaymentMethod I have written a Customer class which has two fields.A Set<Payment> payments and a selectedPayment .A customer can have many credit cards and can select one of them for current purchase.The various credit cards are modelled by the payments field. @Entity class Customer{ ... @OneToMany( cascade=CascadeType.ALL,orphanRemoval=true) Set<Payment> payments; @OneToOne( cascade=CascadeType.ALL) Payment selectedPayment; } @Entity class Payment{ String creditCardNumber; String creditCardType; ... } Are these the correct mappings? In the db table ,a customer can only be associated with a single Payment record through selectedPayment field.That is why I made it one-to-one. Are there any pitfalls I haven't anticipated? Please advise.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Retrieve In-app Products from Android Market I read a couple posts saying that Google does not offer any way to retrieve a list of the In-app products available for your app. I need my application to be able to offer new In-app products dynamically, did anyone come up with an idea other than storing all your products in a database and map product ids ? A: At this time, there is no way to query the market for your products. I used an xml dashboard that contains my productIds that match the app market product ids so my products are loaded dynamically in the application and I can enable/disable products without putting up a new build.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: R Modifying a region of a matrix/data frame depending on another matrix/data frame I have a question about modifying a matrix. I have managed to change values in a matrix depending on the value of another matrix when they are of the same dimension. But now I need to apply this procedure to matrixes with different dimensions. In other words, I want to apply some changes to a "region" of the bigger matrix depending on the values of the smaller one, bearing in mind that I know the positions of the smaller matrix associated to the bigger one. Suppose this are matrix A 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 and B 0 0 0 0 0 0 0 1 1 1 1 0 0 0 1 1 1 0 0 0 1 1 0 0 0 0 0 0 0 0 I know that B[1,1] is the value I have to check to modify A[2,1], B[2,1] for A[3,1] and so on... The final result I am looking for is 1 2 3 4 5 6 7 8 1 2 0 0 0 0 7 8 1 2 3 0 0 0 7 8 1 2 3 0 0 6 7 8 1 2 3 4 5 6 7 8 For the A values replacement I use a for loop in my original script for (i in 1:10) A[B == i] = 0 that works when A and B have same dimension. How should I make the replacement in matrix A? apply? a for loop? Any help would be appreciated and of course you can point me to some basic reading I haven't still read. A: Just select the submatrix and do what you want, i.e.: A[1:5,2:8][B == 1] = 0 Or, in general, if [row, col] is the starting position of matrix B in matrix A: A[row:nrow(A),col:ncol(A)][B == 1] = 0 Here is the test code so that you can check it works: A = matrix(rep(1:8, each = 5), nrow = 5) B = matrix(c(rep(0, 7), 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, rep(0, 8)), nrow = 5, byrow = TRUE) A[1:5,2:8][B == 1] = 0 Thanks to Andrie ho for hinting me the ncol function instead of ugly dim(A)[2]...
{ "language": "en", "url": "https://stackoverflow.com/questions/7500122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use % operator for float values in c When I use % operator on float values I get error stating that "invalid operands to binary % (have ‘float’ and ‘double’)".I want to enter the integers value only but the numbers are very large(not in the range of int type)so to avoid the inconvenience I use float.Is there any way to use % operator on such large integer values???? A: You're probably better off using long long, which has greater precision than double in most systems. Note: If your numbers are bigger than a long long can hold, then fmod probably won't behave the way you want it to. In that case, your best bet is a bigint library, such as this one. A: The % operator is only defined for integer type operands; you'll need to use the fmod* library functions for floating-point types: #include <math.h> double fmod(double x, double y); float fmodf(float x, float y); long double fmodl(long double x, long double y); A: You can use the fmod function from the standard math library. Its prototype is in the standard header <math.h>. A: When I haven't had easy access to fmod or other libraries (for example, doing a quick Arduino sketch), I find that the following works well enough: float someValue = 0.0; // later... // Since someValue = (someValue + 1) % 256 won't work for floats... someValue += 1.0; // (or whatever increment you want to use) while (someValue >= 256.0){ someValue -= 256.0; } A: consider : int 32 bit and long long int of 64 bits Yes, %(modulo) operator isn't work with floats and double.. if you want to do the modulo operation on large number you can check long long int(64bits) might this help you. still the range grater than 64 bits then in that case you need to store the data in .. string and do the modulo operation algorithmically. or either you can go to any scripting language like python A: If you want to use an int use long long, don't use a format that is non-ideal for your problem if a better format exists.
{ "language": "en", "url": "https://stackoverflow.com/questions/7500128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: PullToRefresh TableView inside UIViewController I've got a UIViewController which is also the UITableViewDelegate, amongst other things, for a UITableView, created in FirstView.xib @interface FirstViewController : UIViewController < UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource > { UITableView *searchResults; // this is the property for the table view ... } I want this table view to make use of PullToRefresh: https://github.com/leah/PullToRefresh, but the documentation there only explains how to make use of the class as a sub class of the view controller #import "PullRefreshTableViewController.h" @interface DemoTableViewController : PullRefreshTableViewController { NSMutableArray *items; } My app uses a Tab bar as the root view controller, can anyone explain to me how I can make the UITableView into a PullRefreshTableView? When I don't have a UITableViewController to edit? A: The secret is in the scroll view delegate methods which you can already respond to since you are acting as the tables delegate. This article provides a good start to create your own pull to refresh. * *- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView This will let you know when the user starts dragging the scrollview so you can begin checking whether to refresh or not. *- (void)scrollViewDidScroll:(UIScrollView *)scrollView This allows you to make necessary transitions while scrolling (mainly swapping text and flipping the arrow) *- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate This is where you decide if the user has dragged far enough down to start the refresh. A: Use this API It works fine with UIViewController
{ "language": "en", "url": "https://stackoverflow.com/questions/7500130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Only n records for every x field Given this data set: ID Name City Birthyear 1 Egon Spengler New York 1957 2 Mac Taylor New York 1955 3 Sarah Connor New York 1959 4 Jean-Luc Picard La Barre 2305 5 Ellen Ripley Nostromo 2092 6 James T. Kirk Nostromo 2233 7 Henry Jones La Barre 1899 How can I get only 2 records from every city? A: Try this: SELECT i1.* FROM your_table i1 LEFT JOIN your_table i2 ON (i1.City = i2.City AND i1.ID > i2.ID) GROUP BY i1.ID HAVING COUNT(*) < 2 ORDER BY city, ID;
{ "language": "en", "url": "https://stackoverflow.com/questions/7500134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Transform XML to display results. What to use XSLT or a POJO? The application I am working on receives a very complex XML as a response form an external system. The XML needs to be parsed to display results to the user. I am trying to figure out the best approach to transform the XML to 'Display Ready' form. I have 2 options * *Use XPATH to populate POJOs from XML which could be sent to the view layer for display. *Use XSLT transformation and display the results received in XML. Which one would be faster? I understand that XSLT would get verbose and difficult to maintain. Thanks in advance. Shardul. A: If it's for displaying only, I would prefer a XLST file. But when you have to proces files in some sort way POJO will to the job
{ "language": "en", "url": "https://stackoverflow.com/questions/7500140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery+Simple Toggle Script + Use more than once on one site I have modified this script a little bit to my needs, but now i have come across a problem, which I cant find a solution for. HTML: <div class="toggle"> <p>Grumpy wizards make toxic brew for the evil Queen and Jack.</p> </div><!-- end .toggle --> <div class="readMoreDiv"> </div><!-- end .readMoreDiv --> <div class="toggle"> <p>Grumpy wizards make toxic brew for the evil Queen and Jack.</p> </div><!-- end .toggle --> <div class="readMoreDiv"> </div><!-- end .readMoreDiv --> Script: $(document).ready(function() { // Andy Langton's show/hide/mini-accordion - updated 23/11/2009 // Latest version @ http://andylangton.co.uk/jquery-show-hide var showText='down'; var hideText='up'; // initialise the visibility check var is_visible = false; // insert Show/hide links in the readMoreDiv $('.toggle').next('.readMoreDiv').html('<a href="#" class="toggleLink">'+showText+'</a>'); // hide all of the elements with a class of 'toggle' $('.toggle').hide(); // capture clicks on the toggle links $('a.toggleLink').click(function() { // switch visibility is_visible = !is_visible; // change the link depending on whether the element is shown or hidden $(this).html( (!is_visible) ? showText : hideText); // toggle the display $(this).parent().prev('.toggle').slideToggle(); return false; }); }); See it in action here: http://jsfiddle.net/CeBEh/ As you can see on Fiddle, the script works good when you are opening and closing just one div. But as soon you start opening and closing the second div, WHILE the first one is still open, the problems begin.... I would just like to have it work at all times, no matter if no or all divs are currently open. Thanks! A: Get rid of the is_visible flag and change the code in the click function to this: var toggleDiv = $(this).parent().prev('.toggle'); // change the link depending on whether the element is shown or hidden $(this).html(toggleDiv.is(":visible") ? showText : hideText); // toggle the display toggleDiv.slideToggle(); http://jsfiddle.net/CeBEh/3/ A: The problem is your is_visible variable which you use in both your callbacks. Any a.toggleLink will change that value. Try using an extra class to identify if the div is visible or not, or something else. A: http://jsfiddle.net/CeBEh/1/ Remove is_visible and check the actual text of the clicked link. A: What if you do it this way instead: Html: <div> <p class='toggleMe'> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <a class="toggle"> Hide box </a> </div> <div> <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <a class="toggle"> Hide box </a> </div> javascript: $(document).ready(function(){ $('.toggle').click(function(){ $(this).parent().find('p').toggle(); $(this).text($(this).text() == 'Show box' ? 'Hide box' : 'Show box'); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7500144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP set magic method with array as names I am creating a class which I will use to store and load some settings. Inside the class all settings are stored in an array. The settings can be nested, so the settings array is a multidimensional array. I want to store and load the settings using the magic methods __get and __set, so the settings can act as class members. However, since I'm using nested methods, I can't get the __set method to work when I try to access a nested setting. The class is like this: class settings { private $_settings = array(); //some functions to fill the array public function __set($name, $value) { echo 'inside the __set method'; //do some stuff } } And the code to use this class: $foo = new settings(); //do some stuff with the class, so the internal settings array is as followed: //array( // somename => somevalue // bar => array ( // baz = someothervalue // qux = 42 // ) // ) $foo->somename = something; //this works, __set method is called correctly $foo->bar['baz'] = somethingelse; //Doesn't work, __set method isn't called at all How can I get this last line to work? A: When accessing an array using this method, it actually goes through __get instead. In order to set a parameter on that array that was returned it needs to be returned as a reference: &__get($name) Unless, what you mean is that you want each item that is returned as an array to act the same way as the parent object, in which case you should take a look at Zend Framework's Zend_Config object source for a good way to do that. (It returns a new instance of itself with the sub-array as the parameter). A: This would work: $settings = new Settings(); $settings->foo = 'foo'; $settings->bar = array('bar'); But, there is no point in using magic methods or the internal array at all. When you are allowing getting and setting of random members anyway, then you can just as well make them all public. Edit after comments (not answer to question above) Like I already said in the comments I think your design is flawed. Let's tackle this step by step and see if we can improve it. Here is what you said about the Settings class requirements: * *settings can be saved to a file or a database *settings might need to update other parts of the application *settings need to be validated before they are changed *should use $setting->foo[subsetting] over $setting->data[foo[subsetting]] *settings class needs to give access to the settings data for other classes *first time an instance is made, the settings need to be loaded from a file Now, that is quite a lot of things to do for a single class. Judging by the requirements you are trying to build a self-persisting Singleton Registry, which on a scale of 1 (bad) to 10 (apocalyptic) is a level 11 idea in my book. According to the Single Responsibility Principle (the S in SOLID) a class should have one and only reason to change. If you look at your requirements you will notice that there is definitely more than one reason to change it. And if you look at GRASP you will notice that your class takes on more roles than it should. In detail: settings can be saved to a file or a database That is at least two responsibilites: db access and file access. Some people might want to further distinguish between reading from file and saving to file. Let's ignore the DB part for now and just focus on file access and the simplest thing that could possibly work for now. You already said that your settings array is just a dumb key/value store, which is pretty much what arrays in PHP are. Also, in PHP you can include arrays from a file when they are written like this: <?php // settings.php return array( 'foo' => 'bar' ); So, technically you dont need to do anything but $settings = include 'settings.php'; echo $settings['foo']; // prints 'bar'; to load and use your Settings array from a file. This is so simple that it's barely worth writing an object for it, especially since you will only load those settings once in your bootstrap and distribute them to the classes that need them from there. Saving an array as an includable file isnt difficult either thanks to var_export and file_put_contents. We can easily create a Service class for that, for example class ArrayToFileService { public function export($filePath, array $data) { file_put_contents($filePath, $this->getIncludableArrayString($data)); } protected function getIncludableArrayString($data) { return sprintf('<?php return %s;', var_export($data, true)); } } Note that I deliberatly did not make the methods static despite the class having no members of it's own to operate on. Usign the class statically will add coupling between the class and any consumer of that class and that is undesirable and unneccessary. All you have to do now to save your settings is $arrayToFileService = new ArrayToFileService; $arrayToFileService->export('settings.php', $settings); In fact, this is completely generic, so you can reuse it for any arrays you want to persist this way. settings might need to update other parts of the application I am not sure why you would need this. Given that our settings array can hold arbitrary data you cannot know in advance which parts of the application might need updating. Also, knowing how to update other parts of the application isnt the responsiblity of a data container. What we need is a mechanism that tells the various parts of the application when the array got updated. Of course, we cannot do that with a plain old array because its not an object. Fortunately, PHP allows us to access an object like an array by implementing ArrayAccess: class HashMap implements ArrayAccess { protected $data; public function __construct(array $initialData = array()) { $this->data = $initialData; } public function offsetExists($offset) { return isset($this->data[$offset]); } public function offsetGet($offset) { return $this->data[$offset]; } public function offsetSet($offset, $value) { $this->data[$offset] = $value; } public function offsetUnset($offset) { unset($this->data[$offset]); } public function getArrayCopy() { return $this->data; } } The methods starting with offset* are required by the interface. The method getArrayCopy is there so we can use it with our ArrayToFileService. We could also add the IteratorAggregate interface to have the object behave even more like an array but since that isnt a requirement right now, we dont need it. Now to allow for arbitrary updating, we add a Subject/Observer pattern by implementing SplSubject: class ObservableHashMap implements ArrayAccess, SplSubject … protected $observers; public function __construct(array $initialData = array()) { $this->data = $initialData; $this->observers = new SplObjectStorage; } public function attach(SplObserver $observer) { $this->observers->attach($observer); } public function detach(SplObserver $observer) { $this->observers->detach($observer); } public function notify() { foreach ($this->observers as $observers) { $observers->update($this); } } } This allows us to register arbitrary objects implementing the SplObserver interface with the ObservableHashMap (renamed from HashMap) class and notify them about changes. It would be somewhat prettier to have the Observable part as a standalone class to be able to reuse it for other classes as well. For this, we could make the Observable part into a Decorator or a Trait. We could also decouple Subject and Observers further by adding an EventDispatcher to mediate between the two, but for now this should suffice. Now to notify an observer, we have to modify all methods of the class that should trigger a notification, for instance public function offsetSet($offset, $value) { $this->data[$offset] = $value; $this->notify(); } Whenever you call offsetSet() or use [] to modify a value in the HashMap, any registered observers will be notified and passed the entire HashMap instance. They can then inspect that instance to see whether something important changed and react as needed, e.g. let's assume SomeComponent class SomeComponent implements SplObserver { public function update(SplSubject $subject) { echo 'something changed'; } } And then you just do $data = include 'settings.php'; $settings = new ObservableHashMap($data); $settings->attach(new SomeComponent); $settings['foo'] = 'foobarbaz'; // will print 'something changed' This way, your settings class needs no knowledge about what needs to happen when a value changes. You can keep it all where it belongs: in the observers. settings need to be validated before they are changed That one is easy. You dont do it inside the hashmap/settings object at all. Given that the HashMap is just a dumb container holding arbitrary data that is supposed to be used by other classes, you put the validation into those classes that use the data. Problem solved. should use $setting->foo[subsetting] over $setting->data[foo[subsetting]] Well, yeah. As you probably have guessed already, the above implementation doesnt use this notation. It uses $settings['foo'] = 'bar' and you cannot use $settings['foo']['bar'] with ArrayAccess (at least to my knowledge). So that is somewhat of a limitation. settings class needs to give access to the settings data for other classes This and the next requirement smell like Singleton to me. If so, think again. All you ever need is to instantiate the settings class once in your bootstrap. You are creating all the other classes that are required to fulfill the request there, so you can inject all the settings values right there. There is no need for the Settings class to be globally accessible. Create, inject, discard. first time an instance is made, the settings need to be loaded from a file See above. A: The part $foo->bar is actually calling __get, this function should (in your case) return an array. returning the right array in the __get would then be your solution. A: As has been stated, this is because it is the array stored in $foo->bar that is being modified rather than the class member. The only way to invoke __set behaviour on an 'array' would be to create a class implementing the ArrayAccess interface and the offsetSet method, however this would defeat the purpose of keeping the settings in the same object. A reasonably neat and common work around is to use dot delimited paths: class Settings { protected $__settings = array(); // Saves a lot of code duplication in get/set methods. protected function get_or_set($key, $value = null) { $ref =& $this->__settings; $parts = explode('.', $key); // Find the last array section while(count($parts) > 1) { $part = array_shift($parts); if(!isset($ref[$part])) $ref[$part] = array(); $ref =& $ref[$part]; } // Perform the appropriate action. $part = array_shift($parts); if($value) $ref[$part] = $value; return $ref[$part]; } public function get($key) { return $this->get_or_set($key); } public function set($key, $value) { return $this->get_or_set($key, $value); } public function dump() { print_r($this->__settings); } } $foo = new Settings(); $foo->set('somename', 'something'); $foo->set('bar.baz', 'somethingelse'); $foo->dump(); /*Array ( [somename] => something [bar] => Array ( [baz] => somethingelse ) )*/ This also makes it clearer you are not manipulating instance variables, as well as allowing arbitrary keys without fear of conflicts with instance variables. Further processing for specific keys can be achieved by simply adding key comparisons to get/set e.g. public function set(/* ... */) { /* ... */ if(strpos($key, 'display.theme') == 0) /* update the theme */ /* ... */ }
{ "language": "en", "url": "https://stackoverflow.com/questions/7500148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }