"lock" a portion of HTML in wysiHTML5

Question: I'm using https://github.com/xing/wysihtml5 for an editor in my code base and I'd like to "lock" portions of the code to not be editable, like so:
<form>
<textarea id="wysihtml5-textarea" placeholder="Enter your text ..." autofocus>

Some Editable Text here :)

YOU CAN'T EDIT ME!!!

Some More editable code here

</textarea>
</form>

Does anyone know if this is possible?  I've tried several ways so far with no success.  I've also not seen anything in the documentation.  If this isn't possible, do you know a similar editor where it is possible?
Answer: You have to make block "locked" after you have inserted. There are several issues to handle:
1. On insertion of locked element
I assume, it will be via insertHTML command.
editor.composer.commands.exec('insertHTML', lockedhtml);
$(editor.composer.iframe).contents().find('.lockedForEditing').attr('contenteditable', 'false');

2. On initialization of wysihtml
i.e. locked element is in the contents of text area. First you need to add your "lockedForEditing" class to whitelist in wysihtml rules. then after composer initialized you need to lock elements.
editor.on('load', function(){
   $(editor.composer.iframe).contents().find('.lockedForEditing').attr('contenteditable', 'false');
});

3. Prevent contenteditable commands affect contents of locked element
If user selects all text inside composer and styles it, your locked element's content will also be affected even contenteditable attribute is false. So you need to use CSS to make text inside locked element not-selectable
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;

An humble advise, instead of using div tag for your locked element, you may prefer section tag, which you reserve for lock.

"lock" a portion of HTML in wysiHTML5


MYSQL:Where condition in Case statement

Question: I have table room_category_charges with fields like
id room_category(id) category_charges payment_type(id)
1       1                   300              1
2       1                   600              2
3       2                   400              1
4       2                   800              2

and there is another table patient_detail(patient_admission) where tpa(third_party_name) is selected. Whether or not tpa name is selected the rates of payment type varies.
Accordingly I am trying to use the following mysql query using case.
I want to return the charges

as 600 where room_category is 1 and tpa_name is not null.
as 400 where room_category is 2 and tpa_name is null

SQL:
  select rn.room_name,
    CASE WHEN p.tpa_name is NULL
    THEN rcc.category_charges where rcc.payment_type=1
    ELSE rcc.category_charges where rcc.payment_type=2
    END AS 'charges'
  from estimate e,patient_detail p,room_name n

the where clause in then and else statement is generating the error, how I can incorporate the where clause in the case statement.
Thanks.
Comment: please simplify your question by removing the irrelevant tables, and provide an example output
Answer: Ok I found one solution, which seems to be working fine. Any better solution is welcome.
SELECT rn.room_name, rcc.category_charges
FROM estimate e,room_category rc, room_name rn, room_category_charges rcc, patient_detail p
WHERE rn.room_category = rc.id and rcc.room_category=rc.id
AND e.alloted_bed = p.bed_type
AND rcc.payment_type =2 and e.alloted_bed=rn.id and p.tpa_name is not null

union

SELECT rn.room_name, rcc.category_charges
FROM estimate e,room_category rc, room_name rn, room_category_charges rcc, patient_detail p
WHERE rn.room_category = rc.id and rcc.room_category=rc.id
AND e.alloted_bed = p.bed_type
AND rcc.payment_type =1 and e.alloted_bed=rn.id and p.tpa_name is null

Answer: where is a clause of the select statement and you cannot use it in a case operator.
The syntax of case can be as follows:

CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN result ...] [ELSE result] END
CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END

As I understand the question, you might want a query like this
select rn.room_name,
rcc.category_charges
from estimate e
join room_name rn on e.alloted_bed=rn.id
join patient_detail p on e.ipd_patient_id=p.ipd_patient_id
join room_category_charges rcc on rn.room_category=rcc.id and ((rcc.payment_type=1 and p.tpa_name is null) or (rcc.payment_type=2 and p.tpa_name is not null))

Comment: Not exactly - the room charges can vary depending on on the category. The category can be 1,2,3,4 and room_charges will change accordingly.
Comment: well, then the question does not really seem to be clear on that: only room category 1 and 2 are mentioned. do you have another table for room_charges? you could simply join then. or you can extend the case with two more when clauses for room category 3 and 4.
Comment: I have around 10 room category. is that the proper way to do that?
Comment: then it would be probably better to have another table for them instead of operating with case
Comment: or maybe, you can have another column in room_category_charges. one column for charges with tpa_name, and another one for charges without that.
Comment: Ok I will consider that
Comment: ok, probably I understand now what you mean. so payment_type is 1 when tpa_name is not null and it is 2 tpa_name is null, right? then you can use that for the join condition. I updated the query.
Comment: Exactly but that is where I am getting the error `MySQL server version for the right syntax to use near 'where rcc.payment_type=1 `
Comment: sure, you don't need the case then, check out the updated version.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/69927/discussion-between-pawan-and-lp).

MYSQL:Where condition in Case statement


Product archive description in WooCommerce with a read more tag

Question: is it possible to add a read more tag to a WooCommerce archive description? I found some solution for it, but they are all for the single product page, like for example this solution. Couldn't find a way to get this also done on the archive page. I would like to get the read more tag on mobile devices, cause otherwise the content would be to long and the products would't be visible at the beginning.
That's the code that i have at the moment, placed in the category.php

<?php woocommerce_page_title(); ?>

                   <?php
                        /**
                         * woocommerce_archive_description hook
                         *
                         * @hooked woocommerce_taxonomy_archive_description - 10
                         * @hooked woocommerce_product_archive_description - 10
                         */
                        do_action( 'woocommerce_archive_description' );
                    ?>

Comment: Please share your code. I'd like to help.
Comment: you are referring to product's description at the archive page right?
Comment: yeah, exactly. I updated my question with the code that i have now to display the description
Answer: I found a solution, wich works for me pretty good.
I fixed it with a lil bit of JQuery.  The Text where the read more link should appear, is triggered with a data-js="content" attribute. For example

 This is the Text where it should appear>

With the JQuery below, i'm firing the trigger. So it's only showing on mobile devices and only at the point where the paragraph, has the data-js="content" attribute.
if(window.outerWidth < 991) {
// Select all text areas
var textArea = document.querySelectorAll('[data-js=content]'),
    maxText = 100;

// For each one...
[].forEach.call( textArea, function( el ) {

  var textAreaLength = el.innerHTML.length,
    teaserText = el.innerHTML.substr(0, 100),
    fullText = el.innerHTML,
    showTeaser = false;

  // Check to see if this text length is more
  // than the max
  if (textAreaLength >= maxText) {
    // Set flag
    showTeaser = true;

    // Set teaser text
    el.innerHTML = teaserText;
    el.innerHTML += '...';

    // Create button
    var button = document.createElement('button');
    button.innerHTML = 'Mehr anzeigen';
    button.classList.add('button');
    el.appendChild(button);

    // Button click event
    button.onclick = function () {
      if (showTeaser === true) {
        // Update flag
        showTeaser = false;

        // Update button text
        this.innerHTML = 'Weniger anzeigen';

        // Show full text
        el.innerHTML = fullText;

        // Re-append the button
        el.appendChild(this);
      } else {
        // Update flag
        showTeaser = true;

        // Update button text
        this.innerHTML = 'Mehr anzeigen';

        // Show teaser text
        el.innerHTML = teaserText;
        el.innerHTML += '...';

        // Re-append the button
        el.appendChild(this);
      }
      return false;
    };
  } else {
    // Show full text
    el.innerHTML = fullText;
  }

});
}

Answer: if your code is inside the products loop, try removing the do_action( 'woocommerce_archive_description' ); and add this below your title.
<a href="<?php echo get_the_permalink(); ?>"><?php _e('read more', 'woocommerce');?>

This will display a read more link that will redirect to your product.


NSAttributedString has no member replacingOccurrences error

Question: This is my code
class AmDocViewController: UIViewController,UITextViewDelegate {
    var text1:String!
    let replaceYName: String = "text1"

    var textA:String!
    let replaceFName: String = "textA"

    var textB:String!
    let replaceyGFName: String = "textB"

    @IBOutlet weak var myTextView: UITextView!
override func viewDidLoad() {
        super.viewDidLoad()
        myTextView.delegate = self;
        self.view.endEditing(true)

 let notes37 = NSAttributedString(string:"""
(SOME SAMPLE TEXT......)
""", attributes:[NSAttributedStringKey.foregroundColor: UIColor.gray])

 let newMutableString77 = notes37.mutableCopy() as! NSMutableAttributedString
        newMutableString77.append(notes37)

myTextView.attributedText = newMutableString77 as NSAttributedString

        let originalString = myTextView.text

        let updatedString = originalString?.replacingOccurrences(of: replaceYName, with: text1)
        let updatedString1 = updatedString?.replacingOccurrences(of: replaceFName, with: textA)

        if textB == "" {
            let updatedString2 = updatedString1?.replacingOccurrences(of: str25, with: "N/A")
        }
        if textB != ""{
            let updatedString2 = updatedString1?.replacingOccurrences(of: replaceyGFName, with: textB)
        }

        myTextView.text = updatedString2

        myTextView.textAlignment = NSTextAlignment.center
    }

Getting below error message in the if statement lines
Argument type 'NSAttributedString' does not conform to expected type 'StringProtocol'

Please advice how to use the String value received from other ViewController TextField(text1) and replace a attributed String in a TextView ?
Comment: You need to give more infos: What line is creating this error? What the class of the objects? Because I don't see NSAttributedString in your question, I guess that `replaceyGFName` is a NSAttributedString and not a String? It's clearly unclear.
Comment: Find the occurence ranges (with regex or loop), then use `replaceCharacters(in range: NSRange, with str: String)` on each of the ranges. `NSMutableAttributedString` doesn't have a `replacingOccurrences()` equivalent. (Edit, I removed my previous downvote because now, even if you code is messy in my personal opinion, it gives more infos and important one concerning your issue).
Comment: Thanks and may be messy and learning thro mistakes
Answer: First:
A StringProtocol defined by apple documentation:

A type that can represent a string as a collection of characters.

Im assuming that the variable  str25 is an NSAttributedString This is the cause of your error. Ensure that the variable you pass into replacingOccurrences(of:with:) is of Type String
Another route you could take is to convert your String into an NSMutableAttributedString, this object has a var mutableString: NSMutableString { get } property that

returns The mutable string object

Then you can use this in your replacingOccurrences(of:with:) method
Comment: If I change into String, I will loose the attributes Correct? I want to retain
Comment: Yes, use the other method if you want to keep your attributes , change to `NSMutableAttributedString `
Comment: Will it be possible to correct or advice my above code? Searched/tried and not successful so dar
Comment: used this code`let attrString = NSMutableAttributedString(string: "Hello friend")

attrString.mutableString.replaceOccurrencesOfString("", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: NSRange(location: 0, length: attrString.length))` from [https://stackoverflow.com/questions/29635950/replace-character-in-nsmutableattributedstring] no issues now. Thanks


SQLite Database Copy

Question:
Is it is necessary to copy my local Database.sqlite to Documents directory in ios environment?
   If Yes .,then please explain or refer link..
Comment: `ios environment?` You should add `.sqlite` to your project, and make code to `copy` that into your `NSDocumentDirectory`. [Here's a good example of it.](http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/)
Comment: Is it you or someone else asking this question? If it's you, then why did you put the entire text in a quote?
Answer: You need to copy it because if you put it on your app main bundle, it will be readOnly, and that's not what you want. So you must copy your .sqlite in Documents directory, or whatever directory where you have write permission.

SQLite Database Copy


How to manage categories within a rotating image display?

Question: Here is the specifics: I am designing a website where the client wants to feature different services they offer in rotating images on the front page. There will be categories on the side of the image display so the user can jump to ahead if they see what they are looking for before the images rotate. The complication is that some of the services are part of a main package but another service is a smaller special service. I want to know if there is a good way to differeniate between the special service and the main services within the context of the rotating image display.
Hopefully that makes sense. I'm here to clarify if necessary.
Comment: Yeah, please clarify by giving an example (wireframe, screenshot, website URL) so we can check it out.
Comment: It might also be helpful if you think up a fictional business to stand in for your real client so you can describe it in more concrete terms (e.g. ACME Gardening has lawn care package and also a pest control service)
Answer: I don't think you need to differentiate between main packages and special services for two reasons:

If the client thinks the service is important enough to be featured in this (I'm assuming) highly-visible display, then it can probably stand on its own without needing to be branded as a "main package" or "special service"
When users visit the site and are looking at this image display, they won't care weather a service is part of a main package or a special service. Likely they'll see the picture for the service, say, "hey, that's exactly what I'm looking for!" and click on it. At that point the user can be taken to additional information about the service, including whether the service is a main package or a special service.

In other words, don't clutter the display with information about whether it's a main package or special service; it's better to focus on the service itself (what it does, why users would want it) and save the "main vs. special" differentiation for the service's detail page.
Answer: I'm with mickeyf.
I too may be misunderstanding the intention of the brief you're trying to work to, but this would appear to be one of those classic client situations where asking "Why?" a few more times would do all concerned the world of good. I'm going to assume that the services offered lend themselves to visual representation (perhaps a hotel showing facilities or something along those lines?). That's all well and good if the only intention is to convey a generalised sense of the service - an air of luxury or style or comfort perhaps - but you really should be resisting the notion that more complex characteristics about the services can sensibly conveyed in this way.
You can use the fact that there are thematic differences between the different services as a good basis for having the discussion that starts with "Why do you want to use an image carousel to tell people about different levels of service?"
In your shoes, I would try to illustrate a representative use case to show that a user who wants to look at pictures of services will be using the intended website differently to a user who wants to inform themselves about specific differences between offered services.
Answer: I hope I misunderstood your problem, but really - a "Rotating Image Display" that is supposed to convey content? If I found my way to a site like that I'd run screaming down the hall (figuratively) to a competitor. I'd explain to the client why this is a Bad Idea, and start over. Again, perhaps I misunderstood...?
Comment: Maybe I'm using incorrect terminology. I'm referring to something such as Dell's website uses: dell.com


How to remove application shortcut from home screen on uninstall automatically?

Question: I'm developing an application that should add its shortcut to home screen after installation and remove it after the application is being uninstalled. The application will be preinstalled on the end user device, but still should have an option for uninstall). The task looks very simple but I've faced lots of troubles implementing it.
What I have done:

Add shortcut to the home screen using
com.android.launcher.action.INSTALL_SHORTCUT
on app first launch or on newt device
reboot.
MANUALLY remove shortcut using
com.android.launcher.action.UNINSTALL_SHORTCUT.

What I can't (and almost giving up):

Automatically remove the shortcut when
the application is being uninstalled.

There's not way to use Intent.ACTION_PACKAGE_REMOVED because the application being uninstalled does not receive this intent.
I performed some tests and found out that the only shortcut type that is being removed with the application is the shortcut that is created from menu 'Add to home screen => Shortcuts => Applications => Application activity'. The shortcuts that are being created programatically or that are declared in AndroidManifest remain on home screen after the app is uninstalled.
There's almost none docs and posts on forums about this topic and I'm confused a little bit why such a simple operation that doesn't contradict with the Android security policy could not be implemented in a straight way.
Is there any way to ask OS to remove the corresponding shortcut on application uninstall?
Can I catch the event that the application is being uninstalled before it is removed?
Answer: I don't believe you can do this.
Firstly because you cannot uninstall applications that are pre-installed on the device firmware — they exist on the /system partition which is a read-only filesystem.
Secondly, as you note, your application receives no notification that it is being uninstalled.
If users may not want to use your application, won't they just ignore the application icon, much like I do for a couple of pre-installed apps on my phone?

Edit:
If you are going to pre-install apps (but not on the firmware as commonsware.com notes), you could pre-install two APKs.  One of which has no launcher and consists only of a broadcast receiver which handles the ACTION_PACKAGE_REMOVED event and calls UNINSTALL_SHORTCUT.
I don't believe there is any explicit permission checks that require a shortcut to be removed by the same app that added it, but you could get around that anyway by using a sharedUserId for both APKs.
Comment: Note that "pre-installed" does not necessarily imply "firmware". It is possible to have an application installed as if it were a normal application, but just so happens to ship on the device in advance. The ARCHOS 5 Android tablet did that with a dozen or so apps, for example.
Comment: Indeed. I'm working with devices that *will* have apps installed on the firmware, so I made sure to mention the firmware part. But I think the problem will still stand anyway due to the lack of PACKAGE_REMOVED broadcast.
Comment: Though your comment prompted me to add a potential solution for non-firmware pre-installs. :)
Comment: Christopher, thanks for the idea with two applications, I'll check if it's suitable for my application.
Answer: Seems that you don't use install_shortcut intent in right way. Probably you create an intent without any parameters. You should to create intent with an action Intent.ACTION_MAIN param.
Intent shortcutIntent = new Intent(Intent.ACTION_MAIN);
shortcutIntent.setClassName(this, this.getClass().getName());

Intent intent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
Parcelable iconResource = Intent.ShortcutIconResource.fromContext(
            this,  R.drawable.launcher_icon);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
sendBroadcast(intent);

Answer: What you are describing is a limitation of the Home screen. The next version of Launcher2 addresses this issue and automatically removes widgets and shortcuts associated with an app. Some shortcuts might be left though if no association can be found (if your app creates a shortcut to the music player for instance.)
Comment: Sounds great. What version will include the new Launcher?


Can you substitute one 3/8" rebar by three 1/4" rebars?

Question: [This question is about constructing techniques in Brazil, so if anything is not clear or not properly worded, please let me know and/or suggest phrasing improvements]
I am building the foundations for the railings which will separate my plot of land from my neighbour. The foundations will be built with concrete blocks and reinforced with metal bars. The standard rebar size to be used is 3/8". However, I have some leftover 1/4" bars from my house which I would like to use.
So here's my thought process: up to some constant, the cross section area covered by a 3/8" bar is 9/64 (~0.14) square inches, whereas for a 1/4" bar it is 1/16=4/64 square inches. Two 1/4" bars would cover 8/64, and three bars would cover 12/64 square inches, which is more than the one 3/8" bar would.
Is my thought process correct? Similarly, could I use one 1/4 and one 5/16" bars (covering ~0.16 square inches) instead of the one 3/8" bar?
Comment: For what you want, basically a fence instead of something like a building, it should not matter.  Besides the diameter/sq. in difference, a 3/8 rebar is stronger than a 1/4 rebar(or three 1/4 inch rebar).
Comment: Seems that this would be determined by your local building codes. What does your local building department/building inspector have to say about it?
Comment: @crip659 what's your reasoning for one 3/8" being stronger than three 1/4"?
Answer: Your reasoning is sound. Spread them out evenly, though. Don't bundle them together in a blob. The rebar's bending strength is assumed to be zero for reinforced concrete design, so the bar diameters don't matter. Steel areas are used in design (Av for shear reinforcement, As for flexural tension reinforcement, etc.). In the US, below ground rebar gets covered with a minimum of 3" of concrete between the rebar and soil.
Not in your subgrade case, but for a beam that's supported in the air, too much reinforcement can be a liability. The extra area from the 3 #2 bars could be a problem in such a case. Loading a concrete beam up to failure, you want the lower rebar to yield and stretch before the beam's upper concrete explodes. If you add a bunch of additional reinforcement to a beam designed for this stretching, the concrete may explode before the rebar stretches at all. The stretching rebar gives people an opportunity to move to safety, whereas the case without stretching is considered brittle and gets penalized in the design code.


How to automatically indent the JavaScript code in Aptana Studio?

Question: Previously I used Eclipse for PHP and Java development, and I liked the command Ctrl + i to automatically indent the code.
Now am I using Aptana Studio that is based on Eclipse, for JavaScript development. I would like to automatically indent my JavaScript code, but Ctrl + i deletes all my code. Is there any other command that automatically indent JavaScript code in Aptana Studio?
Answer: The Studio does not have this feature yet. You can add a feature request here: https://aptana.lighthouseapp.com/projects/35272-studio/tickets/new
Ctrl+Shift+F will format your entire file, as Tim suggested.
You can control some of the formatter settings through the preferences at 'Window -> Preferences -> Aptana Studio -> Formatter'
Comment: `Ctrl+Shift+F` seem to work good for PHP, but it doesn't seem to work for JavaScript.
Comment: It should also work for JS. If you got an error in the log, you can open ticket with some code sample that trigger it and we'll fix it :)
Comment: @Jonas solution works for me in Aptana 3.4.2 for JS. Question is pretty old so I figure it was added meanwhile.
Answer: Maybe you mean format feature CTRL+SHIFT+F?
Comment: Oh, no, I tried this command for PHP now, and it changed everything. Before I had my lines at maximum 80 chars, but now they may be super long. Thanks anyway.
Comment: This worked for me to indent javascript code. thanks. at someplaces like if and else statement... the indentation is packing. but its alright for me.
Answer: I've just updated to Aptana Studio 3.0.9 and it now seems to be able to format specific (selected) lines of JavaScript, HTML and CSS, in some circumstances.  The default key binding for me was something odd so I changed the key binding to CTRL+I in Preferences > General > Keys.
If no code is selected then Source > Format seems to always reliably format the entire file.  The behaviour of Source > Format on selections differs depending on the type of code you're editing:
JavaScript

Editing a .js file: Source > Format appears to work as you'd expect: if you select a few lines of code then Source > Format will correctly indent just the selected lines of code.
Editing JavaScript within HTML: Formatting JavaScript within an HTML file appears to work most of the time but sometimes fails; I have not been able to discover the rules.

HTML

If you select a chunk of HTML, AND IF the top line of that selection is correctly indented ALREADY, AND IF the selection does not include any unclosed elements then Source > Format will do the right thing.
Otherwise Source > Format seems to act unpredictably with HTML.

CSS

Editing a .css file:

works fine if I select an entire rule (i.e. including all of selector { declaration block; }) (in which case Aptana formats just that rule).
But if my selection does not include the entire rule then I get an error.

Editing css within HTML:

If part of the CSS is selected within a


Is a Champion a good tank?

Question: I often run into trouble looking for groups in LOTRO, so often I use whatever I get. Often, a Champion is willing to join, but considering the way Champions burn down health in exchange for damage, I'm not sure if this is a good idea...
I know what the tanking classes are (Guardian and Warden) but I actually meant, would it work?
Comment: The answers here may no longer be relevant, as they were answered before the game overhauled the class system.
Comment: Thanks for the answers, but would things improve if I had two healers? I often do.
Comment: In GA it should work out with a Champion as main tank and a second healer because there are no damage race encounters (so you won't miss a additional damage dealer that much). Personally i would choose a Captain as support healer/buffer and/or a Burgler or Lore-master as debuffer (prefering the Burglar because he can increase the threat generated by the Champion)

A good setup would be like: Champion (main tank), Bard (healer), Captain (support heal/buffer), Burglar (debuffer), two damage dealer (Hunter, Rune-keeper or Champion)
Comment: Bard? You mean Mini? I generally like RK's to heal.
Comment: Argh, sorry playing on a german client and yes i mean the Minstrel. A Rune-keeper is also ok as healer.
Comment: If you ask me, RK's make a way better healer than Minstrels (Rune of Restoration, for instance).
Comment: Well you can't say that. That highly depends on the instance, encounter, group and group size. The Minstrel is a direct healer while Rune-keeper is a HoT-healer. The Minstrel is a overall good group healer and the Rune-keeper is a excellent single target healer.
Answer: The Guardian class is the most effective tank in LOTR: Online. They don't typically burn through as much health in exchange for damage. A primary function of this class is crowd control which is necessary for tanking in a fellowship.
Champions are considered more of an off-tank and are generally thought to be the best soloing class if you plan on adventuring alone. They have some tank-like attributes but not as many as the Guardian class. Additionally, the Champion class does not have any adequate crowd control skills.
There is a lot more information about classes on the LOTR Wiki. Here are the links to both the Guardian and Champion wiki pages:
Guardian Class Information
Champion Class Information
Comment: Thanks for the answer, but this isn't what I was looking for.
Answer: The Champion class is NOT a good main tank. If you compare a Champion with a Guardian or a Warden you'll find one or more deficits. The average Champion will have lesser block-, parry- and evade ratings, lesser critical hit protection, lesser damage reduction, lesser incoming heal, lesser skills for survivability and poor skills to get and gain aggro.
But a Champion can get used as main tank. But that highly depends on the skill, experience and equiptment of the Champion, the instance and the other members of the group. I did quite some main tanks runs with my Champion and i have also a Warden. If a rate the difficulty of instances/encounters with my Champion as main tank:

Sammath Gûl: not easy but ok
Halls of Crafting: quite difficult
Great Barrows (Thadur/Sambrog): hard
The Blind One in Dar Narbugud: very hard
Durchest in Barad Guldur: is nearly impossible

and compare if the with the difficulty rating for my Warden:

Sammath Gûl: easy
Halls of Crafting: easy
Great Barrows (Thadur/Sambrog): not easy but ok
The Blind One in Dar Narbugud: difficulr
Durchest in Barad Guldur: hard

It obvious that tanking with a tank class is just much easier.
Comment: I'm lvl 34 and do GA instances/quests.
Comment: For outdoor quest a Champion is suffient as main tanl. For the instances it can work out with a Champion as main tank but you have to get a good Champion player. Especially the first boss encounter in Garth Aragwen is very hard to tank as Champion.
Answer: After the Helms Deep expansion (and complete redesign of the class system), Champions are now intended to be legitimate main tanks, if built that way.

Is a Champion a good tank?


How to stop Google Drive from automatically saving csv's imported into a Google Sheets document

Question: I often make spreadsheets in Google Sheets by importing a collection of csv files. But whenever I import a csv file into a Google Sheets document, the csv file is uploaded to my Google Drive as well.
As a result, I have a huge number of csv files in my Google Drive that I don't want.
Can I stop this from happening? I want to import the csv into the Google Sheets document but I don't also need the csv file in my Google Drive.
A follow-up question is: if I can't prevent the csv from being uploaded to my drive, can I delete the csv from my drive without affecting the Google Sheets document?
This question is related to this one How to stop Google Sheets automatically saving downloaded CSV files to Google Drive, but they asked the question incorrectly, and never followed up with a corrected question.
Comment: About `But whenever I import a csv file into a Google Sheets document, the csv file is uploaded to my Google Drive as well.`, can I ask you about the detailed flow for correctly replicating this situation?
Comment: @Tanaike Open a new Google Sheets document, click File -> Import, go to the 'Upload' tab, and select a csv file from my local directory.
Comment: Thank you for replying. In that case, how about directly putting the CSV data to the Spreadsheet retrieved from the CSV data using a custom dialog and sidebar on Spreadsheet? When the custom dialog and sidebar created by Javascript and Google Apps Script are used, the CSV data can be put into the Spreadsheet without saving the CSV file to Google Drive. Is that your expected result?
Answer: The CSV files being uploaded to the Google Drive is necessary. It is due to the fact that Google Sheets will only look for the source files to be imported either from your personal Google Drive or from other people's Google Drive that are shared with you.
Suggestion
As for your issue on multiple csv files, you can create a script to automatically delete csv files from your Google Drive. However, the only available feature in Google Apps Script is to move the said files to a folder using the File.moveTo(destination) function since the removeFile(child) function was already deprecated. Afterwards, you may use the setTrashed(trashed) function to send the files to the trash folder.
References:
You may view the following links for further details on how to apply the suggestion.

removeFile(child)
moveTo(destination)
setTrashed(trashed)
Google Apps Script Deleting Google Drive Files in Folder Example


Make element wider, then narrower when certain point is reached

Question: To the point: Right now every button click makes content-div 100px wider. The starting point is 300 pixels, and in 600 pixels, when user clicks the button the width should go back to 300 pixels.
For clearance: I don't want the width to go straight to 600px and then back to 300px with the next click, the pattern should be like click 1. +100px, click 2. +100px, click 3. +100px, click 4. -300px .. Then start all over.
I have tried to apply the else if -statement but for some reason div-element gets wider with every click but when it gets wider than 600 pixels, the else if -statement won't apply.

var content = document.getElementById("content");
var btn = document.getElementById("btn");
content.style.width = "300px";
btn.addEventListener("click", function() {
if (content.style.width >= "300px") {
content.style.width = content.offsetWidth + 100 + "px"; }
else if (content.style.width >= "600px") {
content.style.width = content.offsetWidth - 300 + "px"; }
});
#content {
width: 300px;
height: 100px;
background: lightblue;
display: flex;
align-items: center; justify-content: center;
transition: all 1s ease-in-out;
}
#btn {
width: 100px; height: 50px;
background: grey;
display: flex;
align-items: center; justify-content: center;
color: white;
text-decoration: none;
}
a {
color: white;
text-decoration: none;
}

Click

Comment: `content.style.width` is a string. You're best move is get the width of the element using `offsetWidth` and then comparing it to a number.
Answer: This should do it:
  if (content.offsetWidth < 600) {
    content.style.width = content.offsetWidth + 100 + "px";
  }
  else {
    content.style.width = content.offsetWidth - 300 + "px";
  }

var content = document.getElementById("content");
var btn = document.getElementById("btn");
content.style.width = "300px";
btn.addEventListener("click", function() {
  if (content.offsetWidth < 600) {
    content.style.width = content.offsetWidth + 100 + "px";
  }
  else {
    content.style.width = content.offsetWidth - 300 + "px";
  }
});
#content {
width: 300px;
height: 100px;
background: lightblue;
display: flex;
align-items: center; justify-content: center;
transition: all 1s ease-in-out;
}
#btn {
width: 100px; height: 50px;
background: grey;
display: flex;
align-items: center; justify-content: center;
color: white;
text-decoration: none;
}
a {
color: white;
text-decoration: none;
}

Click

Comment: Amazing! Thank you.
Answer:

var content = document.getElementById("content");
var btn = document.getElementById("btn");
content.style.width = "300px";
btn.addEventListener("click", function() {
if (content.style.width >= "600px") {
  content.style.width = content.offsetWidth - 300 + "px";
  return;
}
content.style.width = content.offsetWidth + 100 + "px";
});
#content {
width: 300px;
height: 100px;
background: lightblue;
display: flex;
align-items: center; justify-content: center;
transition: all 1s ease-in-out;
}
#btn {
width: 100px; height: 50px;
background: grey;
display: flex;
align-items: center; justify-content: center;
color: white;
text-decoration: none;
}
a {
color: white;
text-decoration: none;
}

Click


Boost Gil is able to rasterize a font?

Question: I would like to ask if with Boost Gil alone I can render text into an image using a custom ttf/otf font, my impression is that there is no such thing in Boost Gil, and so I should adopt something like freetype, but since I don't like to add yet another dependency if I can possibly avoid it.
Answer: There's a Freetype GIL extension by Tom Brinkman here:

boost/gil/extension/toolbox/ (imported from code.google.com archive)

(I think it's probably in toolbox/freegil.h). I found anouncements on the boost mailing list around here.
Comment: @user2485710 I have just updated the broken links in the the answer.
Comment: I'm not familiar with `svn` but if I checkout this I can't see the same file that I can see through the web interface, I need to checkout some sub-module or sub-project like with `git` ? I see `freegil.hpp` online but I can't locate it inside my copy of the repository .

Boost Gil is able to rasterize a font?


xml alternative for javascript app used on IE?

Question: What would be the best alternative to xml for a javascript app. The app parse the data then uses Highcharts framework to show some charts.
I can't use xml because it has problems running locally on Internet Explorer (access denied error and other problems ....see my other question here).
Also this new thing that should replace xml in this situation should be exported from excel.
I was thinking about csv... but csv can be a little bit messy an not as easy to use as xml.
Thanks!
Comment: The problem you mention in your other question is caused by the "HTTPRequest" part, not the "XML" part. XML is a suitable choice for the data format.
Comment: I understand but maybe other technology works without HTTPRequest? Or maybe there is any way to getit work without that error in IE...the problem is that I'll use this stuff at work and there everybody uses IE and if some error will appear they won't know what to do...also it has to work out of the box because they aren't allowed to change IE's security options
Answer: The best data format that you can use with JavaScript is JSON (JavaScript Object Notation) - it was designed for it.
Comment: JSON and JSONP are the way to go if you want a light weight data format and no cross domain issues. The explanation on wikipedia is pretty straightforward: http://en.wikipedia.org/wiki/JSONP
Comment: thanks... does it work without http request? I started to read right now about JSON...
Comment: Well it does "work without httprequest" (e.g `var a = {"test" : "yeah"};`) but I'm not entirely sure what you mean by that


Please help with my twodimensional array source code

Question: Here is what i have done but i have some questions:
class masivins {
    public static void main (String args[]) {

        int mas[][] = {{0, 2, 7, 0, 8, 5, 3},
                       {0, 4, 0, 6, 0, 0, 0},
                       {0, 0, 0, 0, 3, 0, 0},
                       {7, 0, 0, 9, 1, 0, 7},
                       {5, 0, 4, 0, 0, 2, 0}};

        int nulmas[] =  new int [7];
        int nul=0;

        for(int j=0; j<7; j++) {
            nul=0;
            for(int i=0; i<5; i++) {
                if(mas[i][j]==0) {
                    nul++;
                }
            }
            nulmas[j]=nul;
        }
        for(int i=0; i<5; i++) {
            for(int j=0; j<7; j++) {
                System.out.println(mas[i][j]);
            }
            System.out.println();
        }
        System.out.println();

        for(int i=0; i<5; i++) {

            System.out.println("Zeros in each array column: " + nulmas[i]);
        }
        System.out.println();
    }
}

so my questions are:

Why after running project there are only 5 "Zeros in each array column....." shown?
What and where i need to change in this code to get out the number of column in which zeros are least?
Comment: i wish i could be back in school some days
Comment: So what's the question here ? What precisely are you having difficulty with ?
Comment: +1 OP has made an attempt to do the homework.
Comment: i need to get out index of column in which zeros are least < this is my problem, i cant do this :(
Comment: Previous similar question from OP: http://stackoverflow.com/questions/2484752/please-help-with-my-twodimensional-array-source-code
Comment: @Baiba: Please change the title of your question. it's almost useless: this site is about programming, you tagged the question as Java, it says nothing about your question. (missing 103 rep to edit it myself...)
Comment: @Lirik looks like the OP took the previous stuff from the previous question and now is confused again. With the rest of the code already gathered from stackoverflow, the addition of searching for the lowest zero is stupidly easy. I'd tag this 'do-my-homework-for-me' but 'homework' suffices.
Comment: @Chris I wish I could go out and cross out all the statements you've corrected me on :).
Comment: @Lirik lol, I only just noticed you were the one I corrected on the == true thing. You haven't made that many mistakes, plus the code worked anyway :) I used to do that *all* the time. I just noticed on his posting history that he was giving the community stuff to do in piecemeal fashion to mask his activity ;)
Answer: Question 1 - look at your code:
for(int i=0; i<5; i++) {
    System.out.println("Zeros in each array column: " + nulmas[i]);
}

In particular, look at the loop. How many lines do you expect it to print out?
Question 2: You could keep a "least number of 0s in an array column so far" and "column in which the least number of 0s appeared" - then update those variables at the end of the inner loop where you set nulmas[j].
Comment: @Baiba: I've already explained to you how to do it. Presumably this is a homework question - I've given you all the hints you should need; I'm not just going to write out the code for you.
Comment: Ok, but when i change the code to for(int i=0; i<7; i++)
             for(int j=0; j<5; j++);
after project running it says me "Exception in thread "main"                      java.lang.ArrayIndexOutOfBoundsException: 5
    at masivins.main(masivins.java:19)
Comment: then update those variables at the end of the inner loop where you set nulmas[j] < how can i do that??
Comment: @Baiba: First point: why would you want two loops? And what's the body of your loop? Second point: you test whether you need to update them (whether `nul` is less than your current "least number of 0s") and if so, you update the "least number of 0s" variable to `nul` and the new "column with least number of 0s" to `i`.
Comment: actually, i don't know why there are two loops, i made this program from examples and i don't understand why it is like that!!!
Comment: @Baiba check the code example in my answer, hope it helps :-)
Comment: ok i have another version of this code, please tell me what i need to do when i need to get out of program The INDEX NUMBER OF COLUMN IN WHICH ARE LEAST ZEROS?
Answer: 1) because you loop from 0 to 4:
for(int i=0; i<5; i++) {

If you looped until 7, all values would be printed out:
for(int i=0; i<7; i++) {
    System.out.println("Zeros in each array column: " + nulmas[i]);
}

2) you could keep an index and a minimum counter. The min counter stores the minimum number of zeros, the index the column where this is found:
int nulmas[] =  new int [7];
int nul=0;
int minNuls=5;
int minIndex=0;

for(int j=0; j<7; j++) {
    nul=0;
    for(int i=0; i<5; i++) {
        if(mas[i][j]==0) {
            nul++;
        }
    }
    nulmas[j]=nul;
    if (nul < minNul) {
        minNul = nul;
        minIndex = j;
    }
}

Comment: for(int i=0; i<5; i++) {

            System.out.println("Zeros in each array column: " + nulmas[i]);
what i need to change in this place?
Answer: You seem to be very close to answering the question. It looks to me like you've set up the nul_mas array to contain the number of zeros in each column, so the question becomes "which index of nul_mas has the smallest value?". You can do this with two variables - one for the smallest value seen so far, one for the index where it was seen - and a loop through that array to look at each element in turn. (Then, when you've got it working, consider what happens if there is a tie.)
Answer: Try:
 int leastZeroIndex = 0;

 for(int i=0;i<5;i++) {
   if (nul_mas[i] < nul_mas[leastZeroIndex])
     leastZeroIndex = i;
 }

 System.out.print(leastZeroIndex);

Though there is no check if there are multiple rows with the lowest amount of zeros.
Answer: It looks to me as if you need to create some new arrays, so create an array for each column, and then put the numbers for the column in there. After that, just iterate over that array of arrays which represent the columns and count the numbers (you could use a method for doing this, i.e., int count(int num, int[] arr). I think this'll give the least amount of code.
int[][] mas  = ...; // (you have this already), it's [NO_OF_ARRS][NO_OF_COLS] with the data
int[][] colsarrs = new int[NO_OF_COLS][NO_OF_ARRS];

for (int i = 0; i < NO_OF_ARRS; i++) {
    for (int j = 0; j < NO_OF_COLS; i++) {
        colsarrs[j][i] = mas[i][j];
    }
}

int[] resultarr = new int[NO_OF_COLS];
for (int i = 0; i < NO_OF_COLS; i++) {
    resultarr[i] = count(0, colsarrs[i]);
}

int count(int num, int[] arr) {
    int count;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == num) ++count;
    }
    return count;
}

Store the amount of zeros in an additional array (resultarr) gathered from this function for each column. After this, go over the array and find the lowest number, and grab the index of it. That's your column with the lowest amount of zeroes.
int lowestcurr = 0;
for (int i = 0; i < NO_OF_COLS; i++) {
    if (resultarr[i] < resultarr[lowestcurr]) {
        lowestcurr = i;
    }
}

Comment: can you please write how it looks when it is in source code because i dont understand
Answer:
    for(int i=0; i<5; i++) {

        System.out.println("Zeros in each array column: " + nulmas[i]);
    }
    System.out.println(); place there it

change it on :
int minElement = 0;
    for(int i=0; i<7; i++) {
        if (nulmas[i] < nulmas[minElement]) minElement = i;
        System.out.println("Zeros in each array column: " + nulmas[i]);
    }
    System.out.println(nulmas[minElement]);

better use "\n" to skip one line in console


Can you use SLF4J with log4j-audit?

Question: Can you use SLF4J with log4j-audit?
Documentations says Log4j-audit requires Java 8 and Log4j 2.10.0 or greater, but can you used it with SLF4J with Log4j 2 underneat?
If not, can you use log4j-audit alongside SLF4J? I mean call SLF4J logger for debug loggers and Log4j 2 loggers for audit logging?
Answer: Yes, you can use SLF4J alongside Log4j-audit. Log4j-audit has its own API that uses the Log4j 2 API. It relies heavily on Log4j's Message support so trying to use it with Logback would probably not work well.

Can you use SLF4J with log4j-audit?


XCode 4 for Embedded Linux Kernel Development?

Question: I'm trying to use XCode 4 (with external build utility) for embedded Linux on ARM kernel development. Please note that I have all the cross-compilers and tools working from the command line on the Mac, but would like to use XCode for comfort.
The standard make phase (make ARCH=arm CROSS_COMPILE=arm-none-eabi- uImage) seems to work just fine, but can't figure out how to:
(a) Create a target that needs interactive input in the shell (make ARCH=arm menuconfig). This always complains about "Error opening terminal: unknown", and as of XCode 4 it runs in the background. Any ideas how I can open an interactive shell in the foreground?
(b) Use arm-none-eabi-gdb as my debugger. This is optional but would be really neat.
Thanks!
Comment: have you done this successfully?
Answer: a) Can you figure out how to launch the equivalent of an xterm containing the command?  Or some IDE's have a checkbox option to run a command in an interactive window.  Finally consider just doing any menuconfig-involved makes from the command line
b) Depends on if xcode can talk gdb's protocol in general.  If it can, then its a matter of figuring out the whole gdbserver target launch procedure.  If it can't you'll have to do text mode debugging or use a gdb-compatible front end.


Storing Scraped data in csv

Question: I am learning web scraping using scrapy. Having Pretty Fun with it. The only problem is I can't save the scraped data in the way I want to.
The below code scrapes reviews from Amazon. How to make the storing of data better?
# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request
import csv

class Oneplus6Spider(scrapy.Spider):
    name = 'oneplus6'
    allowed_domains = ['amazon.in']
    start_urls = ['https://www.amazon.in/OnePlus-Silk-White-128GB-
    Storage/product-reviews/B078BNQ2ZS/ref=cm_cr_arp_d_viewopt_sr?
    ie=UTF8&reviewerType=all_reviews&filterByStar=positive&pageNumber=1']

    def parse(self, response):

        writer = csv.writer(open('jack.csv','w+'))

        opinions = response.xpath('//*[@class="a-size-base a-link-normal
        review-title a-color-base a-text-bold"]/text()').extract()

        for opinion in opinions:
            yield({'Opinion':opinion})

        reviewers = response.xpath('//*[@class="a-size-base a-link-normal
        author"]/text()').extract()

        for reviewer in reviewers:
            yield({'Reviewer':reviewer})

         verified = response.xpath('//*[@class="a-size-mini a-color-state a-
         text-bold"]/text()').extract()

         for verified_buyer in verified:
             yield({'Verified_buyer':verified_buyer})

          ratings = response.xpath('//span[@class="a-icon-
          alt"]/text()').extract()

          for rating in ratings:
              yield({'Rating':rating[0]})

           model_bought = response.xpath('//a[@class="a-size-mini a-link-
           normal a-color-secondary"]/text()').extract()

          for model in model_bought:
              yield({'Model':model})

I tried using scrapy's default way -o method and also tried using csv.
The data gets stored in single row.I am very new to pandas and csv modules and I can't figure out how to store the scraped data in a proper format?
It is storing all the values in one single row.
I want the different values in different rows
Eg: Reviews|Rating|Model|
but I just can't figure out how to do it
How can I do it ?
Comment: It is difficult to say which way is the best. In general I would use .json files and the json module in Python to store data. You can also read these files with pandas.
Comment: Give us a basic view or an example to show how the data is stored.
Answer: It's observed in your code that you're trying to extract records with different types: they're all dict objects with a single key, where the key might have different values ("Opinion", "Reviewer", etc.).
In Scrapy, exporting data to CSV is handled by CsvItemExporter where the _write_headers_and_set_fields_to_export method is what matters with your current problem, as the exporter needs to know the list of fields (column names) before writing the first item.
Specifically:

It'll first check the fields_to_export attribute (configured by the FEED_EXPORT_FIELDS setting via feed exporter (related code here))
If unset:

2.a. If the first item is a dict, it'll use all its keys as the column name.
2.b. If the first item is a scrapy.Item, it'll use the keys from the item definition.

Thus there're several ways to resolve the problem:

You may define a scrapy.Item class with all possible keys you need, and yield items of this type in your code (just fill in the one field you need, and leave others empty, for any specific record).
Or, properly configure the FEED_EXPORT_FIELDS setting and leave other part of your existing code unchanged.

I suppose the hints above are sufficient. Please let me know if you need further examples.
Answer: To set csv data format one of the easiest way is to clean data using excel power queries, follow these steps:

Open csv file in excel.
Select all values using ctrl+A.
Then click on table from insert and create table.
After create table click on Data from top menu and select
From Table.
Know they open new excel window power queries.
Select any column and click on split column.
From split column select by delimiter.
Know select delimiter like comma, space etc.
Final step: Select advanced option in which there are two
options split in rows or column.

You can do all type of data cleaning using these power queries, this is the easiest way to setup data format according to your need.

Storing Scraped data in csv


Riemann tensor with all indices lowered on a 2D manifold

Question: I found the following in a textbook:
On a 2-dimensional manifold the Riemann tensor with all indices lowered takes the form:
$R_{abcd} = R{g_{a}[_{c}g_{d}]_{b}}$
However I cannot see why this is true! I am sure it is correct but no amount of fiddling on my part gives the desired above result. Help would be much appreciated
Comment: is $g$ the metric tensor?
Comment: Yes, I believe so.
Answer: Since the Riemann tensor is anti-symmetric under exchange of the first two components, as well as under exchange of the last two components, we must have $a \neq b$ and $c \neq d$. Since $a,b,c,d$ can only take the values $1,2$ in two dimensions, this tells us that the only non-zero components of the Riemann tensor are $R_{1212}$ and permutations thereof.
If we work in Riemann normal coordinates at a given point, we obtain $$R_{abcd} = 2 R_{1212} g_{a[c} g_{d]b}$$
(just check all possible values of $a,b,c,d$ and use $g_{ab} = \delta_{ab}$ in normal coordinates). Taking the trace of both sides to compute the scalar curvature $R$ we obtain
$$ R = R_{abcd} g^{ac} g^{bd} = 2 R_{1212} g_{a[c} g_{d]b} g^{ac} g^{bd} = 2R_{1212}$$
Combining this with the result above we have
$$ R_{abcd} = R g_{a[c} g_{d]b} $$
and since this last equation is tensorial, it holds independent of the chosen coordinate system.
Disclaimer: the calculation may be off by some overall factors, which I did not bother to check.


Setup Failed: Visual Studio 2010 Pro installation

Question: Trying to install VS2010Pro on Windows 7 (64bit) and i also checked all system requirements for the same.
ERROR:

VIEW ERROR LOG:
[05/15/12,10:48:22] Microsoft Visual Studio 2010 64bit Prerequisites (x64): [2] Error: Installation failed for component Microsoft Visual Studio 2010 64bit Prerequisites (x64). MSI returned error code 1603
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 64bit Prerequisites (x64) is not installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft Visual F# 2.0 Runtime was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates TFS Object Model (x64) was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates .NET Framework 4 Multi-Targeting Pack was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 Professional - ENU was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft Web Deployment Tool (x64) was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft ASP.NET MVC 2 - Visual Studio 2010 Tools was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft ASP.NET MVC 2 was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft Silverlight 3 SDK was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 Tools for Office Runtime (x64) was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft Office Developer Tools (x64) was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Dotfuscator Software Services - Community Edition was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Crystal Reports templates for Visual Studio 2010 was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft SQL Server Compact 3.5 SP2 (x64) ENU was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Visual Studio 2010 Tools for SQL Server Compact 3.5 SP2 ENU was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft Sync Framework Runtime v1.0 (x64) ENU was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft Sync Services for ADO.NET v2.0 (x64) ENU was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft Sync Framework Services v1.0 (x64) ENU was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft Sync Framework SDK v1.0 (x64) ENU was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates VC 10.0 Designtime (x64) was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft SQL Publishing Wizard 1.4 was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft SQL Server System CLR Types was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Management Objects was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Management Objects (x64) was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 Express Service Pack 1 (x64) was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Data-Tier Application Framework was not attempted to be installed.
[05/15/12,10:48:22] VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Data-Tier Application Project was not attempted to be installed.

REF LINKS
1. MSDN
2. BLOG (tried)
have also asked question in MSDN forum.
Do i have any better solutions to trouble shoot this problem other than re installing the OS ?
Comment: Please rate my answer if it has helped.
Answer: After 2days of work around, Solution is finally here.....Phew!!!!!
Here we go,
As error indicated VS2010 was getting stuck while installing Microsoft Visual Studio 2010 64bit Prerequisites (x64)
Error: Installation failed for component Microsoft Visual Studio 2010 64bit Prerequisites (x64). MSI returned error code 1603

So i searched for the corresponding directory and ran .exe manually
VS2010Pro\adminpoint\WCU\64bitPrereq\x64

ran VS_Prerequisites_x64_enu & got one more ERROR
error 25541 failed to open xml file C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG\machine.config, system error -2147024786

Looked for machine.config in indicated path, but I couldn't find machine.config in
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG

So i copied machine.config.default on to desktop and renamed it to machine.config and added it to  C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG then ran VS_Prerequisites_x64_enu & then VS2010 installer.
VS_Prerequisites_x64_enu ---> (finally) VS2010 installer

Note: by doing this i tricked installer & installation went smooth.
More details HERE
Answer: Error code 1603: solution can be found at this msdn link http://social.msdn.microsoft.com/Forums/eu/vssetup/thread/3f07772c-4187-4be7-a390-d775f8eb5a50
If its not solved please try to post it here in VisualStudio Setup & Installation forum. Hope it helps
Answer: Had the same issue today and fixed it by reinstalling the .NET frameworks 4.5 and 4.0
http://www.microsoft.com/en-us/download/details.aspx?id=30653
http://www.microsoft.com/en-us/download/details.aspx?id=17851
Answer: the problem is with the software you downloaded , its not downloaded completely, thats why that error ,
i also experienced the same , but i resolved it by redownloading the software,
after downloading check that the size of downloaded and the mentioned size in the website are same , if not its not downloaded completely, again download it and install
Answer: You might have missing machine.config file.
Location: C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG
Answer: I had a similar problem installing visual studio 2010 professional on a Windows 8.1 machine.
I tried to install Visual Studio from a local directory, but this failed.
Although all the files from the DVD looked exact the same as on the local directory I recopied all the files again and this time I had success with installing.
I also followed these steps found here to install without typing in the Product Key and your custom settings. And adding SP1 with the installation as well.
It didn't solved the problem, but I installed the software with unattended setup.
Answer: I had a corrupted image that I downloaded and got the same result. My advice is to run the installer of a component individually; corrupted setups should fail immediately.


How do I estimate the time taken? (Growth Rates)

Question: Suppose you have a program that solves an AI problem. When the problem size is $N = 1,000$ your program takes 10 seconds to find a solution. Estimate the time it will take to solve a problem of size $N = 1,000,000$ if the time complexity of your algorithm is:

$\mathcal{O}(\log N)$
$\mathcal{O}(N)$
$\mathcal{O}(N\log N)$
$\mathcal{O}(N^2)$
$\mathcal{O}(N^3)$

You may use the approximations $\log(1,000) = 10$ and $\log(1,000,000) = 20$
(I'm not great at maths so I really do appreciate any help given)
Comment: Presumably, these logs are base 2.
Answer: Let's start with (4). The use of the $O$ notation here is very sloppy, but what is meant here by saying that the time complexity of the algorithm is $O(N^2)$ is that the time required is roughly proportional to $N^2$. That is, there is some constant $k$ such that the time required to process an input of size $N$ is approximately $kN^2$. In this problem you're told that when $N=1000$, the time is $10$ seconds, so $k(1000)^2=10$. You could solve this for $k$, if you really wanted to, but it's unnecessary: you want $kN^2$ when $N=1,000,000$, and $1,000,000=1000^2$, so you want $$k(1,000,000)^2= k(1000)^2(1000)^2=10(1000)^2=10,000,000\;,$$ since $k(1000)^2=10$. In other words, in (4) your algorithm will take about ten million seconds, which is a little less than a third of a year.
In (2) you're told that the algorithm takes about $kN$ seconds to handle a problem of size $N$, and you know that $1000k=10$. I'll let you try to solve this one and (5) using my solution to (4) as a model; you should get a little over two and three-quarters hours for (2) and over three centuries for (5).
Now let's look at (1): it says that the approximate running time on an input of size $N$ is $k\log N$ for some constant $k$, and we're told that $k\log 1000=10$. You're allowed the approximation $\log 1000\approx 10$, so we have $10k=10$, or $k=1$. Thus, the approximate running time for $N=1,000,000$ is $$k\log 1,000,000=\log 1,000,000\approx 20$$ seconds.
(3) looks the messiest, but it's no harder than the others: the approximate running time on an input of size $N$ is $kN\log N$, and you're given that $k(1000)\log 1000=10$. Once again you can either solve for $k$ and plug in $N=1,000,000$ or use the given data point in a more direct way, as I did with (4); you should get a running time of a bit over five and a half hours.


Repairing water-damaged paint (possibly drywall)?

Question: I have a first-floor wall that has some water damage in one of the corners. The cause was apparently a clogged gutter, which was spraying rain water directly onto the exterior of the wall. The clogged gutter is fixed but now I would like to repair the damaged interior paint.
My first idea was to simply remove the damaged paint, prime, and repaint with a color-matched paint color. However, I'm worried about whether more extensive work might be necessary, since I came upon some other threads that mentioned also replacing the drywall. (I'm a complete DIY novice, BTW.) Is this a case where I'd be fine with just repainting, or is there more to it than that?
Here's a picture of the damage. The house was built in 1994 but I believe the paint is relatively new...not entirely sure though. Any advice would be greatly appreciated.
Answer: If it was indeed just recent & not an ongoing for years situation. Then, let it dry for a week or 2 & see how solid it is then. As long as it feels as solid as before & the rest of the walls, then definitely scrape off what bubbled, split & wrinkled paint you can so there are no lifting or flapping edges.
You'll want to fill those new low spots with Joint Compound or Spackle for a nothing ever happened end result. Lay that on in very-very thin coats just as thick as the paint you have surrounding the scraped areas. Dry-Sand with sandpaper to perfection & a lot of dust or Wet-Sand with a wet sponge for no dust. Let dry & do another Compound or Spackle coat, if needed & sand again.
Then, roller-on a Stain Blocking Primer & let that cure for 2-days, you shouldn't need a 2nd coat but do that if it's needed. And finally, roller-on your paint, 2-coats over the primer-ed areas & even do the rest of both walls to get everything uniform & to use up your paint...of course do this with the Primer too, prior to the paint, in order to use that up as well.


Can't Log Into Ubuntu 12.04

Question: Yesterday, after turning on Ubuntu, I logged into a Gnome session. A few minutes later, I tried switching to Unity for a change. Unfortunately,  the background and my desktop icons loaded, but the system bar and launcher failed to load even after several minutes. Unity had always worked fine for me.
I then tried the guest account, and it worked fine on both Unity and Gnome. However, the problem with my account got worse; I couldn't log into any desktop at all anymore. I would type in my password and press enter and it would just sit there doing nothing. The computer no longer responded in any way, so I had to hold the power button and reboot. The same problem happened repeatedly.
Earlier today, I tried to get on again. I found that I hadthe same problem, when I tried to log in, the computer no longer locked up, but instead flashed a black screen with theconsole output and what seemed to be an error message before returning to the log in screen. It was to quick for me to read, about 1/4-1/2 second.
I'd really appreciate some help as I have some important files that are not backed up yet. I can't transfer the files to a new account, or even make a new account because I tried taking the password off my account so now I can't authenticate from the guest to perform root functions.
I'd really appreciate some help as I have some important files that are not backed up yet. Thanks.
Comment: Try creating a new user account and log into Gnome and Unity to see if both work ok. If so, the problem is with your user.
Comment: I can't create a new user because my account, the admin, has no password.
Answer: I ran into the same issue.  The problem was in the user .XAuthority file permission was owned by the root user.  I changed the file permission and was able to log back in.
Answer: You can get in your account from the terminal without GUI and back up the files or fix some issues from there.
Hit Ctrl+Alt+F1, and you'll see a login prompt. Log in and do your stuff, from the command line.
You can create a new user from the command line like this:
<code>sudo adduser <newusername>
</code>
If you want to get back to GUI desktop, hit Ctrl+Alt+F7.
Comment: I found out I have the files I need in Ubuntu One. So I'm reinstalling. This did help me make some progress and I think would have worked though, so thank you!

Can't Log Into Ubuntu 12.04


What is the etymology of 'sinc function'?

Question: The title says it all.  I'm curious what the origin/etymology of the name 'sinc function' (pronounced 'sink') comes from. Presumably its a modification of 'sin'.
$\textrm{sinc}(x) \equiv \frac{ sin(x) }{x} $
Comment: This is quite curious... I just came across the sinc function myself, and was wondering the same exact question!
Comment: This superannuated mathematician never heard of it --- looks like a neologism, maybe even a nonce word, or a hapax legomenon.
Answer: Wikipedia says

The term "sinc"  is a contraction of the function's full Latin name, the sinus cardinalis (cardinal sine) It was introduced by Phillip M. Woodward in his 1952 paper "Information theory and inverse probability in telecommunication" in which he said the function "occurs so often in Fourier analysis and its applications that it does seem to merit some notation of its own" and his 1953 book Probability and Information Theory, with Applications to Radar.

See also this answer of mine.
Comment: Interesting, and why 'cardinal' ?
Comment: Very late reply, but it seems that cardinal here means 'of the greatest importance; fundamental,' as in 'cardinal sins'


Create df column concatenated value over each row

Question: How can I create a new column in my DataFrame which is a json string equivalent to concatenated column values over each row in the below format?
Code so far:
import pandas as pd
data = {'Name':['Tom', 'Nat', 'Harry', 'Jack'],'Age':[20, 21, 22, 23]}
df = pd.DataFrame(data)

Input df:
  Name  Age
0    Tom   20
1   Nat   21
2  Harry   22
3   Jack   23

Output df:
  Name  Age Combined
0    Tom   20   [{"Name":"Tom","Age":20}]
1   Nat   21    [{"Name":"Nat","Age":21}]
2  Harry   22   [{"Name":"Harry","Age":22}]
3   Jack   23   [{"Name":"Jack","Age":23}]

Comment: Basically I want the output of `df.to_json(orient='records')` for each row
Comment: Done. I tried to use `df = df.join(pd.Series(df.to_json(orient='records'),index=df.index,name='combined'))` but that concatenates the entire df for each row. Thoughts?
Answer: Here is one way
import pandas as pd
data = {'Name':['Tom', 'Nat', 'Harry', 'Jack'],'Age':[20, 21, 22, 23]}
df = pd.DataFrame(data)

df['Combined'] = '[{"'+str(df.columns[0])+'": "'+df['Name']+'", "'+str(df.columns[1])+'": '+df['Age'].apply(str)+'}]'

it works but there may be better ways to do this
    Name    Age Combined
0   Tom     20  [{"Name": "Tom", "Age": 20}]
1   Nat     21  [{"Name": "Nat", "Age": 21}]
2   Harry   22  [{"Name": "Harry", "Age": 22}]
3   Jack    23  [{"Name": "Jack", "Age": 23}]

Answer: If you want your output as a serialized string: This solution works independent of the columns but is not vectorized and slow. @PaulBrennan's answer should be faster for larger dataframes if you can construct the string manually.
df['Combined'] = df.apply(lambda x: f'[{x.to_json()}]', axis=1)
df

Out:
    Name  Age                     Combined
0    Tom   20    [{"Name":"Tom","Age":20}]
1    Nat   21    [{"Name":"Nat","Age":21}]
2  Harry   22  [{"Name":"Harry","Age":22}]
3   Jack   23   [{"Name":"Jack","Age":23}]


How to hurry a wonder as China with a builder

Question: I'm playing as China and I'm supposed to be able to hurry up a wonder with a builder. I've positioned my brand new builder in the city as well as the tile where the wonder is being build and I can't seem to find out in game or goggling how to hurry it.
Answer: The builder needs to be in the tile where the wonder is being built.  They will then have an option to help build the wonder, similarly to building other tile improvements.  Note that it only works on Ancient and Classical wonders, so if it isn't working, you might be working on a more modern wonder that isn't eligible.
Comment: Thanks, I missed the fact that it only works on really wonders.
Comment: What are "really winders"? Did you mean "really old ..."?
Comment: Sorry, missed that comment. Yeah, auto correct ate my "early" :)


How to write lambda methods in Objective-C?

Question: How to write lambda methods in Objective-C ?
Comment: Late to the party but if anyone is still looking for official documentation on this, it can be found here: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html
Answer: The concept of a lambda in Objective-C is now encapsulated with the idea of Blocks which are the equivalent of pass-by-reference functions. Of course, arguably one had that already in C with the idea of function pointers; blocks are just a way of also capturing local state (i.e. can be closures). In fact, blocks can also be used in other C languages as well (on Mac) - there's a proposal to make them part of the standard C syntax.
Here's an example of defining a lambda to multiply two numbers together:
int (^mult)(int, int) = ^(int a, int b) { return a*b; };

The first part declares a variable, of type ^int(int,int) and then assigns it to the lambda expression (aka block) which returns the multiple of its two arguments. You can then pass that fn around, define it in other places etc; you can even use it in other functions.
Here's an example of defining a function, which when invoked, returns another function:
multiplyBy = ^(int a) { return ^(int b) { return b*a; }; };
triple = multiplyBy(3);

Note that you can intermix blocks with object types (usually using id as the object type) and many of the new Objective-C object data structures have some kind of block-level operation. GCD also uses blocks in order to pass in arbitrary events; however, note that GCD can also be used with function pointers as well.
Comment: ObjC blocks are similar to Smalltalk blocks, but it's unclear in Objective C how or whether it's even possible to define, implement, pass, accept, and call blocks of arbitrary types.
Comment: Note that Blocks can be used in iOS 4, without the Plausible Blocks project.
Comment: Note also that block support has been ported to 10.5 and the iPhone OS with the Plausible Blocks project. http://code.google.com/p/plblocks/
Comment: +1 Excellent example with 'multiplyBy' AIBlue, thanks for demonstrating the flexibility of blocks so concisely.
Comment: where do you declare the type of multiplyBy?
Comment: +1, but please don't use the word equivalent as you mention that you can close over the environment. Similar maybe. There is a huge gap between reference function. Runtime has to make work for that to happen and there is no chance you can use only reference function to make closure work.
Answer: OS X 10.6 introduced blocks. See AlBlue's answer for examples.
If you're not using Snow Leopard, you can get something close to function composition using various other features.
Example using C function pointers:
void sayHello() {
    NSLog(@"Hello!");
}

void doSomethingTwice(void (*something)(void)) {
    something();
    something();
}

int main(void) {
    doSomethingTwice(sayHello);
    return 0;
}

Example using the command pattern:
@protocol Command <NSObject>
- (void) doSomething;
@end

@interface SayHello : NSObject <Command> {
}
@end

@implementation SayHello
- (void) doSomething {
    NSLog(@"Hello!");
}
@end

void doSomethingTwice(id<Command> command) {
    [command doSomething];
    [command doSomething];
}

int main(void) {
    SayHello* sayHello = [[SayHello alloc] init];
    doSomethingTwice(sayHello);
    [sayHello release];
    return 0;
}

Example using a selector:
@interface SaySomething : NSObject {
}
- (void) sayHello;
@end

@implementation SaySomething
- (void) sayHello {
    NSLog(@"Hello!");
}
@end

void doSomethingTwice(id<NSObject> obj, SEL selector) {
    [obj performSelector:selector];
    [obj performSelector:selector];
}

int main(void) {
    SaySomething* saySomething = [[SaySomething alloc] init];
    doSomethingTwice(saySomething, @selector(sayHello));
    [saySomething release];
    return 0;
}

Comment: This may have been true earlier, but the language now does have Blocks, which allow you to define real lambda expressions. Having said that, being able to pass around @selector()s as described above is a really useful mechanism in the Objective-C toolkit.
Comment: -1 for missing info about blocks, a central new feature, available in C, ObjC and C++, when using Apple's GCC in the new 10.6 version of OS X.
Comment: +1 for providing design patterns that may be preferable over blocks in some situations.
Answer: I heard André Pang at NSConference talking about how blocks were going to be introduced with the next version of Objective-C.
This should allow functional programming.
Edit: Since Snow Leopard has been released, this is indeed the case. Objective-C now has Blocks.
Answer: Well, I think you can write your anonymous function like this:
myBlock = ^( int number )
{
    return [ NSString stringWithFormat: @"Passed number: %i", number ];
};

For this, you need to add the following syntax:
NSString * ( ^ myBlock )( int );

In general, this link has written something for obj-c and obj-c++, I hope it will help you.
https://xs-labs.com/en/archives/articles/objc-blocks/
Comment: Please don't post duplicate answers. This doesn't add anything that the other answers don't already cover.
Comment: please read website


Xamarin Forms Display Alert Disappear

Question: i'm developing an app in Xamarin Forms, but i've noticed a strange behavior, when i display an alert, in Android (version major than 4.2.2), if i press outside the alert modal, the alert disappear immediately. There is any way to prevent this? I want that the alert disappear only on user selection.
Many thanks
Answer: When a dialog is shown in Android, clicking just outside of it to cancel is pretty standard. To change this behavior you will need to create an interface in your PCL:
public interface ICustomAlert
{
  void ShowAlert(string message);
}

In your Android project create the implementation (something like this):
  [assembly: Xamarin.Forms.Dependency (typeof (AndroidCustomAlert))]
  public class AndroidCustomAlert : ICustomAlert
    {
      void ShowAlert(string message)
      {
        var builder = new AlertDialog.Builder(Xamarin.Forms.Forms.Context);
        builder.SetMessage(message);
        builder.SetPositiveButton("OK", (sender, args) => { });
        builder.SetCancelable(false);
        builder.Show();
      }
    }

Notice the SetCancelable(false). That's what makes it so the user can't click outside of the alert and make it disappear.
To use it, get ICustomAlert from the dependency service and call ShowAlert:
DependencyService.Get<ICustomAlert>().ShowAlert("Hello!");

Comment: Hi Adam, thanks for your answer. I tried your solution but my app crash: "Android.Views.WindowManagerBadTokenException: Unable to add window -- token null is not for an application". Can you help me to solve this problem?
Comment: I wasn't in my IDE when typing that out. The issue was in AndroidCustomAlert's AlertDialog.Builder. It needs the context. Get it from Xamarin.Forms.Forms.Context instead of Application.Context.

What's important is that you understand the DependencyService and the SetCancelable(false).
Comment: @AndreaMarinoni I believe this answers your question. Did the updated answer work for you?
Answer: Implement your own DisplayAlert with a PopupLayout.
OR
Make use of ACR User Dialogs Plugin for Xamarin by Allan Ritchie

Xamarin Forms Display Alert Disappear


Python user input file path

Question: I am working on an easy project which requires user input a path for program and goes to this path
Here, I Worte on OSX:
from pathlib import Path

def main():
    user_input_path = Path(input())

And debug like this
>>> /Users/akrios/Desktop/123
SyntaxError: invalid syntax

Comment: You are entering a path in to the Python interpreter. Have you actually *called* `main()` anywhere?
Comment: If you add a prompt, you'll know when to type. Perhaps `user_input_path = Path(input("Input path: "))`.
Comment: I am new to Python. I though when I am debugging it, the only thing I need to do is F5 and function would have be called. Like when you finish a *.exe It is program and can be executed without calling your functions.
Comment: Yes, that's true if you're using an IDE like Eclipse
Comment: If you are using python 2 - you need to use raw_input for this.
Answer: The input() function reads in the input, and then tries to parse it as if it's something in Python notation. Instead, use the raw_input() function, it does not parse anything and returns the input as a string.

Python user input file path


In Go, why isn't the stringer interface used when casting to string?

Question: package main

type foo struct {
    bar string
    baz string
}

func (f foo) String() string {
    return f.bar + " " + f.baz
}

func main() {
    f := foo{"hello", "world"}
    v := string(f)
}

This outputs main.go:14: cannot convert f (type foo) to type string.
So it would seem that casting something to a string does not look at the stinger interface. My guess is that this is because casting is implemented on a lower level than the stringer interface and it's impossible/hard to mix the two, but I'm not sure. Can anyone shed any light on this?
Also, since this is not possible, what would be idiomatic way to convert my struct to a string in this case? Do I just call .String() myself, or fmt.Sprintf("%s", f), or something else?
Answer: There is no casting in Go, there is type Conversion and Type assertion.
What you're doing (T(Expression)) is a conversion and it has strict rules when it can be used and what the result will be.
There are specific rules applied to Conversions to and from a string type. So what you want cannot be achieved with type conversion.
The simplest and preferred way would be to call the method yourself:
v := f.String()

fmt.Sprintf() would be just an unnecessary overhead and complication if your struct already implements Stringer. But if you don't have guarantee for this, then yes, fmt.Sprintf() would be the general way.
You could ask why?
In the specification level the type conversion expression is not defined as the result of a custom/user made function or method. The Stringer interface (type Stringer interface{String() string}) is not even a built-in type in contrast to the error interface.
But despite the fact that Stringer is not a built-in type, it is still present in some packages (for example in fmt.Stringer) and is checked by various methods or functions (e.g. fmt.Printf() and relatives).
Comment: `error` is the *only* builtin interface. `Stringer` is the more-normal case.


Qt Q_PROPERTY with template accessors

Question: I'm aiming for a little bit more code reuse, while maintaining verbosity.
Consider the following sample code:
// qdot@defixio /tmp/test4 $ cat test.h
#include <QObject>

class Foo : public QObject {
  Q_OBJECT
  // Q_PROPERTY(int bar1 READ bar<1>)
  // Q_PROPERTY(int bar2 READ bar<2>)

  public:
  template <int i> int bar() const;
};

// qdot@defixio /tmp/test4 $ cat test.cpp
#include "test.h"
#include <QDebug>

template <int i>
int Foo::bar() const { qDebug() << "Template parameter" <<  i; }

int main() {
  Foo foo;
  foo.bar<1>();
  foo.bar<2>();
  return 0;
}

This one compiles and runs as expected.
In case you're wondering why I would like that - imagine a set of properties, DESIGNABLE, etc, but falling under the same "class" - in that case, I would like to have separate properties, using enum-templatetyped accessors.
Uncommenting the property definitions, results in the following moc error:
/usr/bin/moc -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I. -I/usr/include/qt4/QtCore -I/usr/include/qt4/QtGui -I/usr/include/qt4 -I. test.h -o moc_test.cpp
test.h:5: Parse error at "bar"

Any idea on how to properly mix templating and moc?

To answer cmannet85's comment, and add more insight - yes, that moc invocation generates moc_test.cpp from moc.h.
To test and demonstrate it further, I added another property
Q_PROPERTY(int baz1 READ baz1)

and the diff between moc_test.cpp before and after is this:
--- moc_test.cpp        2012-10-02 13:23:39.442333849 +0200
+++ moc_test_baz1.cpp   2012-10-02 13:23:29.822328462 +0200
@@ -1,7 +1,7 @@
 /****************************************************************************
 ** Meta object code from reading C++ file 'test.h'
 **
-** Created: Tue Oct 2 13:23:39 2012
+** Created: Tue Oct 2 13:22:27 2012
 **      by: The Qt Meta Object Compiler version 63 (Qt 4.8.3)
 **
 ** WARNING! All changes made in this file will be lost!
@@ -24,17 +24,20 @@
        0,       // classname
        0,    0, // classinfo
        0,    0, // methods
-       0,    0, // properties
+       1,   14, // properties
        0,    0, // enums/sets
        0,    0, // constructors
        0,       // flags
        0,       // signalCount

+ // properties: name, type, flags
+       8,    4, 0x02095001,
+
        0        // eod
 };

 static const char qt_meta_stringdata_Foo[] = {
-    "Foo\0"
+    "Foo\0int\0baz1\0"
 };

 void Foo::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
@@ -76,6 +79,30 @@
     _id = QObject::qt_metacall(_c, _id, _a);
     if (_id < 0)
         return _id;
+
+#ifndef QT_NO_PROPERTIES
+     if (_c == QMetaObject::ReadProperty) {
+        void *_v = _a[0];
+        switch (_id) {
+        case 0: *reinterpret_cast< int*>(_v) = baz1(); break;
+        }
+        _id -= 1;
+    } else if (_c == QMetaObject::WriteProperty) {
+        _id -= 1;
+    } else if (_c == QMetaObject::ResetProperty) {
+        _id -= 1;
+    } else if (_c == QMetaObject::QueryPropertyDesignable) {
+        _id -= 1;
+    } else if (_c == QMetaObject::QueryPropertyScriptable) {
+        _id -= 1;
+    } else if (_c == QMetaObject::QueryPropertyStored) {
+        _id -= 1;
+    } else if (_c == QMetaObject::QueryPropertyEditable) {
+        _id -= 1;
+    } else if (_c == QMetaObject::QueryPropertyUser) {
+        _id -= 1;
+    }
+#endif // QT_NO_PROPERTIES
     return _id;
 }
 QT_END_MOC_NAMESPACE

There is absolutely nothing to prevent moc from just copying over the entire bar<1> statements into the QMetaObject::ReadProperty switch statements - but it somehow barfs on the <> template tags.
Comment: The main problem is `moc` using its own parser which recognizes only a subset of C++.
Comment: AFAIK the `moc` is ran before the C++ preprocessor (to replace all the Qt keywords with 'real' C++), so template code is not expanded - and the `moc` can't do that itself.  That's what the parse error is referring to.
Comment: yeah, but I wonder how to get it to do the same to the template code - I don't think it needs any expanding at this step - if you substitute 'baz1' with 'bar<1>' in the moc_test.cpp, it works just fine.
Answer: moc does not like template braces inside Q_PROPERTY declarations. You can do the following:
class Foo : public QObject {
  Q_OBJECT
  Q_PROPERTY(int bar1 READ bar_1)
  Q_PROPERTY(int bar2 READ bar_2)

  private:
  inline int bar_1() const { return bar<1>(); }
  inline int bar_2() const { return bar<2>(); }

  public:
  template <int i> int bar() const;
};

The code generated by moc should be able to access private methods of your class, and this indirection should not induce any runtime cost since the compiler can inline the calls to bar_N.
You probably want to hide the declaration of bar_N in a macro.
Comment: how would I hide that declaration?
Comment: I would have done something like `#define BAR(N) inline int bar_##N() const { return bar(); }`, but your solution of macroizing only `bar` is cleaner.
Comment: Well, I would say that yours is cleaner - mine pollutes the global namespace, since there is absolutely no DEFINE that distinguishes compilation of moc-generated code from compilation of 'real' code.
Answer: OK. I think I almost figured this one out. It's just evil.due to namespace pollution - and there seem to be no DEFINE in moc_test.cpp prior to including my header file.
merely defining
#define ___BAR1 bar<1>
Q_PROPERTY(int bar1 READ ___BAR1)

did the job - I would however prefer if ___BAR1 was only defined during MOC run (easy) and during moc_test.cpp compilation.
Bracketing
#ifdef Q_MOC_RUN
#define ___BAR1 bar<1>
#endif Q_MOC_RUN

hides the define from anything but moc, but it's irrlelevant - it's also hidden from gcc when it compiles moc_test.cpp
Answer: Just put () around the reader function:
Q_PROPERTY(int bar1 READ (bar<1>))

Qt Q_PROPERTY with template accessors


I use the SELECT query to download contacts from Salesforce.com. As it is given below and i am getting "MALFORMED_QUERY" exception

Question: I use this select query and i am not getting what's the wrong with this.
Select Id,Contact.FirstName,Contact.LastName,Contact.Title,Contact.Department,Contact.Birthdate,
   Contact.Phone,Contact.HomePhone,Contact.MobilePhone,Contact.OtherPhone,Contact.Fax,Contact.Email,Contact.MailingStreet,
       Contact.MailingCity,Contact.MailingState,Contact.MailingCountry,Contact.MailingPostalCode,Contact.OtherStreet,
   Contact.OtherCity,Contact.OtherState,Contact.OtherCountry,Contact.OtherPostalCode,Contact.Description,Contact.Account.Name From Contact where strcmp('%@',Id) = -1",lastcontactId
Comment: this doesn't seem to be an iPhone Question and i think you need to reformat it. Please Retag it!
Comment: Retagged, this is not a direct iOS question
Answer: You need to generate a query that uses =, e.g.
select name from contact where id='005123123123123123'

so, you can use this to generate the query.
NSString *query = [NSString stringWithFormat:@"select name,etc from contact where id='%@'", lastContactId];

Here's the SOQL docs which has more examples.
And if you're trying to do paging, you should just run the entire query and use query/queryMore to page through the results.


how to loop through menu and remove class and then add class to current menu item

Question: I have this menu structure that is used to navigate through content slider panels.

Bliss Fine Foods

Menus

Wines

News

Contact Us

I would like to loop through these elements and remove the highlight class and then add the highlight class to the current / last clicked menu item.
Any ideas? Any help would be greatly appreciated.
Thanks
Jonathan
Answer: May be so?
$('#menu li a').click(function(){
  $('#menu li a').removeClass('highlight');
  $(this).addClass('highlight');
});

Comment: Thanks that worked in combination with Jacob's help in where to add the code
Answer: ...your  and opening  tags...

Bliss Fine Foods

Menus

Wines

News

Contact Us

Comment: Thanks Jacob -how do I call this from the menu?
Comment: @Jonathan, just add this to your jQuery.ready code and you're all set.
Comment: @jacob - sorry please excuse my ignorance but can you tell me how I add this to my header in terms of syntax
Comment: Or rather you can just stick this at the end of your `` tag.
Comment: Hi Jacob - perfect(ish) that works apart from it doesn't remove the class so every item is highlighted if I click on it
Comment: @Jonathan, Updated, try it now
Comment: Hi jacob figured it out - your help in where to add the code along with edtsech's code worked like magic - thanks so much for your help!


slidetoggle jquery won't display

Question: I just wanted to ask why is it when im using jsfiddle to construct a ul li structured archives with slidetoggle, year>month>title it WORKS, but when I am to apply it to my archives section, only the year and month works, the titles won't display, do css have a problem with this?
   <?php
include("connection/connect.php");

$sql2 = mysqli_query($con, "SELECT DISTINCT YEAR(post_date) FROM posts ORDER BY YEAR(post_date) DESC");
                echo "

";

                while($row2 = mysqli_fetch_assoc($sql2)){
                    foreach ($row2 as $year) {
                    echo "
$year
"; //year
                        $sql3 = mysqli_query($con, "SELECT DISTINCT MONTH(post_date) FROM posts WHERE YEAR(post_date)='$year' ORDER by MONTH(post_date) DESC");

                        while($row3 = mysqli_fetch_assoc($sql3)){
                            foreach ($row3 as $month) {

                                echo "
".date('F', mktime(0, 0, 0, $month, 1, 2000))."
"; //month

                                $sql4 = mysqli_query($con, "SELECT * FROM posts WHERE MONTH(post_date)='$month' AND YEAR(post_date)='$year' ORDER by post_date DESC");
                                while($row4 = mysqli_fetch_assoc($sql4)){
                                    $title2 = $row4['post_title'];
                                    echo "

".$title2."

";//title
                                }
                            }
                            echo "

"; //end month
                        }
                    echo "

"; //end year
                    }
                }
                echo "

";

    }
    ?>

in jsfiddle this is how it looks like
2014
 January
 February
 March <<(clicked and the titles displayed)
  title 1
  title 2
in my archives section this is how it looks like
2014
 January
 February
 March <<(clicked yet the titles won't display)
by the way here is the code for the script:
$(document).ready(function() {
    $("#nav ul li:not(:has(li.current))").find("ul").hide().end() // Hide all other ULs
    .click(function() {
        if (event.target==this) {
        $(this).children('ul').slideToggle('fast');
            return false;
        }
    });
});

I hope you could help me on this, thank you in advance.
You may kindly check my fiddle, Jquery Slidetoggle
Comment: If you can add your HTML as the PHP generates it here, it would make it easier to determine the issue.
Comment: http://jsfiddle.net/rx9mky6f/6/
Comment: Could you please add a link where you have used this code? Seems like css is creating a problem
Comment: The issue is that event.target in your if statement is 2014 and this == 'li' element. That is why your click handler will never be executed. Actually I think that 'if' statement is redudant here. To solve this issue you need either remove  tag or better remove 'if' statement, you don`t need to check event target in this case.
Comment: i tried removing the  tag and the if statement, still it's not working. Im still wondering why is it that in fiddle the code works well while in my php it doesn't.
Answer: at last, I was able to get the answer.. I added an excess  tag near the title and that's the reason why it doesn't display, upon removing it, now my archives work very good.
<?php
            include("connection/connect.php");

            $select_posts = "SELECT post_id,post_date,post_title, YEAR(post_date) AS YEAR, MONTH(post_date) AS MONTH, COUNT(*) AS postCount FROM posts";

            $run_posts = mysqli_query($con, $select_posts);

            while ($row = mysqli_fetch_array($run_posts)){

            $sql2 = mysqli_query($con, "SELECT DISTINCT YEAR(post_date) FROM posts ORDER BY YEAR(post_date) DESC");
            echo "

";

            while($row2 = mysqli_fetch_assoc($sql2)){
                foreach ($row2 as $year) {
                echo "
$year
"; //year
                    $sql3 = mysqli_query($con, "SELECT DISTINCT MONTH(post_date) FROM posts WHERE YEAR(post_date)='$year' ORDER by MONTH(post_date) DESC");

                    while($row3 = mysqli_fetch_assoc($sql3)){
                        foreach ($row3 as $month) {

                            echo "
".date('F', mktime(0, 0, 0, $month, 1, 2000))."
"; //month

                            $sql4 = mysqli_query($con, "SELECT * FROM posts WHERE MONTH(post_date)='$month' AND YEAR(post_date)='$year' ORDER by post_date DESC");
                            while($row4 = mysqli_fetch_assoc($sql4)){
                                $title2 = $row4['post_title'];
                                echo "
".$title2."
";//title
                            }
                        }
                        echo "

"; //end month
                    }
                echo "

"; //end year
                }
            }
            echo "

";

}
?>

Anyway, thanks to those who tried to bear with my problem.

slidetoggle jquery won't display