Display the name of current user in the horizontal menu

Question: I am using Asp.Net/C#.I am using Asp.Net's built-in Membership Framework.I have a requirement wherein the current(logged-in) user's name should be displayed in the horizontal menu towards the right side.The aspnet_Users table stores the UserName in the form of some code like ppp001 where as the actual name of the user For Example: John Smith is stored in the table which is linked to aspnet_Users table using a Foreign Key constraint.So my question is how do I display  the users name from that table to my menu.Should I use repeater control.
Any suggestions are welcome.
Thanks
Comment: @freebird:of course. don't display anything until user login.
Comment: use session variable instead. Session["LoggedInUser"]= user; because keeping username in session variable is the best approach.
Comment: if you are going to display single user(logged in), then there is no point using repeater control.
Comment: @HenkHolterman , so how do I do that , any other work around.
Comment: @AshwiniVerma , any other alternative.
Comment: @freebird: just access the LinkButton/Label from the Menu and assign the value.
Comment: @AshwiniVerma do you mean that I should assign the value to Label and then display the Label's value in the menu , am I correct ?
Comment: @AshwiniVerma what I did earlier was I stored the name of the user in a global variable after authorization , but the problem was sometimes when the page is posted frequently , the Global variable gets empty.
Comment: @AshwiniVerma I am using Session for my cause , but will I have to take care of timeout and all.I have not used session variables before.
Comment: Session is nothing just session variable, you keep the value which stores on the server side. if you are already using this then I recommend you to hold username to the session. you should not store the larger value to the session. and don't worry about timeout, that is how session works.
Comment: @AshwiniVerma I just used session variable to hold my users name , initially it showed properly , but after few mins or so , it was showing empty.
Comment: @freebird: go through this link for detail:http://msdn.microsoft.com/en-us/library/ms178581.aspx
Answer: The simplest way to do it is to store the first name and last name in the profile provider and then use a label or div which has runat="sever"
in the web.config
<profile enabled="true">
    <properties>
        <add name="FirstName" type="string"/>
        <add name="LastName" type="string"/>
    </properties>
</profile>

then set your div or label
   FirstName.Text = Profile.FirstName;
   LastName.Text = Profile.LastName;

The disadvantage with using the profile provider is that all the profile properties get concatenated into a big string so it's hard to query against that.  The better way to do this is to create your own BasePage class which makes a call to the database to retrieve the first name and last name from a specific table, using the foreign key like you mentioned.  I usually set this to a MyLoggedInUser property of the page.  That way all your pages can get to it via this.Page.MyLoggedInUser.FirstName, etc..


Install Ubuntu on Alienware 15 R3 without disturbing Windows

Question: I have Alienware 15 R3 with:

512GB NVME SSD - Windows 10.
1TB HDD - 300GB free space available.

I would like to install Ubuntu using the free space available in 1TB HDD.
I have experience installing Dual Boot Ubuntu on my old laptop, but after a Windows 10 auto-update, the boot loader got corrupted.
So, how should I install Ubuntu without disturbing anything that links to Windows Boot?
Comment: If Windows 10, it is the newer UEFI and you will want Ubuntu in UEFI boot mode. Is HDD gpt partitioned? Best to always back up before any major system change. Only use Something Else install option. Another Alienware install: https://askubuntu.com/questions/795755/grub-problems-on-dual-boot-windows-10-ubuntu-16-04-laptop-using-samsung-950-pr &  https://help.ubuntu.com/community/UEFI & https://askubuntu.com/questions/221835/installing-ubuntu-alongside-a-pre-installed-windows-with-uefi
Comment: select the "Use freespace"
Answer: The Ubuntu Live-CD when detects another system, it gives the option to install Ubuntu at side of Windows 10. It does everything to you (installs the system in the free space and installs grub too).
So, first of all, you should change the BIOS settings to boot first the Live-CD than the Windows Bootloader (I'm assuming here you've alredy prepared an USB with the Ubuntu Live CD)
After this, you plug the USB and turn on the PC. During the installation, it will detect the Windows installed and will offer you to install Ubuntu at side of Windows 10. Select this and proceed the installation. It will install Ubuntu and grub. That's all! When you turn on PC after the installation, grub will ask what system to boot.
Answer: I followed the below link and was able to install ubuntu 17.10 as dual boot with the original windows 10
https://gist.github.com/awesomebytes/e4556b06bedf860189378428b508c043


Is it possible to active Android Beam "Tab to beam"-screen with a simulated touchevent?

Question: On ICS when you want to beam some NdefMessage you have to touch the screen ("touch to beam"). I would like to know if it is possible to beam data only with some code, without any user touch.
Is it possible to beam some data by simulating a touch?
Comment: I guess you are aware that you can talk to tags without 'the beam'.
Answer: I guess, it is not. Most likely this is kind of a security issue. If you force the User to touch the screen, he is aware, that at least some data is leaving his phone. This way, no-one can sniff the data, you are attempting to send.
The NFC feature on phones is not like a RFID-card, where one is able to write data permanently on the chip. I think NFC on android is more like an interface to NFC. You are able to "pipe" data through it, but storing is not yet possible. In the moment the User "beams" data, internal code is triggered to send the data you prepared.
There may be a way to send it via code, if you root your phone, look at the internals, change them, and build your custom-rom.


What is the easiest way to convert files to an MP4?

Question: I want to convert a MOV file to MP4 file. I have found many ways on YouTube, but in a fix which one will take less time.
Comment: [This answer from a few years back](https://askubuntu.com/a/1128185/1222991) is still valid today. Be sure to test a couple of different settings to ensure the video and audio quality matches your expectations, though.
Comment: You should define easy. You don't want to read endless manpages, then GUI may be easy. Do you want to do this to many files? Then a command line tool which you can use in a script would be easy.
Answer: Handbrake is a good GUI based software for video conversion/transcoding and it should be available to install from the Ubuntu software store and most repositories. If you have lots of videos you can queue up multiple jobs and then leave it to process all of them.


How to click a button without any id or name attributes

Question: Trying to have selenium click a button on a webpage. Cannot find the element to make it click.
<button type="submit" class="xButton xCTA xSubmit">
  Enter
</button>

Comment: Random google for "selenium, find by class": https://www.softwaretestingmaterial.com/how-to-locate-element-by-class-name-locator/
Comment: Can you add the rest of the html to your question?  It will help us to help you better.
Answer: driver.find_element_by_xpath("//button[@class='xButton xCTA xSubmit'].click()
driver.find_element_by_css_selector("button[type='submit']").click()
driver.find_element_by_xpath("//span[contains(text(), 'Enter')]").click()

Any of those should do the trick.
Comment: Hi Chris. I keep getting an "element not visible" error, event after putting a 20 second timeout on the page.
Answer: Though the <button> have no or attribute you can still use the other attributes, e.g. class, innerText, etc.
To click() on the element with text as Enter you need to induce WebDriverWait for the element to be clickable() and you can use either of the following Locator Strategies:

Using Python and CSS_SELECTOR:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.xButton.xCTA.xSubmit[type='submit'] > span"))).click()

Using Java and XPATH:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='xButton xCTA xSubmit']/span[text()='Enter']"))).click();


Swift add action if user click back button

Question: I successfully detect if user clicked on back button by using the following code:
override func viewWillDisappear(animated: Bool) {
    let viewControllers: NSArray = self.navigationController?.viewControllers as! NSArray
    if viewControllers.indexOfObject(self) == NSNotFound {
        self.navigationController?.setNavigationBarHidden(true, animated: true)
    }

    super.viewWillDisappear(animated)
}

but I get the following warning:

Cast from '[AnyObject]?' to unrelated type 'NSArray' always fails

Is there a "neater" way to do this?
Answer: Instead of NSArray, you should use the Swift array - [UIViewController]
Fixed issue:
override func viewWillDisappear(animated: Bool) {
        let viewControllers: [UIViewController] = self.navigationController?.viewControllers as [UIViewController]

        if let index = find(viewControllers, self)
        {
            //your object exists in that is at index

        }
        else
        {
           //your object is not in the navigation controller
           self.navigationController?.setNavigationBarHidden(true, animated: true)
        }

    super.viewWillDisappear(animated)
}

Instead of if let else, you can use:
if find(viewControllers, self) == nil
{
    //your object isnt in the viewControllers array

}

Comment: This will not work. In Swift, navigationController.viewControllers will always contain self.
Comment: There's a much simpler way than looking at the view controllers inside `viewWillDisappear`. Call `isBeingDismissed` inside `viewWillDisappear`.
Answer: Basically the issue is that you are trying to cast to the objective-c array type, NSArray. Swift uses Array instead of NSArray/NSMutableArray. If you want to cast arrays in Swift, you have to specify the type of object inside the array. So the following code:
let viewControllers: [UIViewController] = self.navigationController?.viewControllers as! [UIViewController]

casts it specifically as an Array (Swift array) of UIViewControllers. You can actually write it shorter and just have this:
let viewControllers = self.navigationController?.viewControllers as! [UIViewController]

Comment: I got `[UIViewController] does not have a member named 'indexOfObject'`
Answer: Try the following code:
override func viewWillDisappear(animated: Bool) {
    if let viewControllers = navigationController?.viewControllers as? [UIViewController] {
        if let index = find(viewControllers, self) {
            navigationController?.setNavigationBarHidden(true, animated: true)
        }
    }

    viewWillDisappear(animated)
}

Using find() is more inline with Swift from my opinion. find() will return index of the element if found, nil otherwise.
Comment: I got `Cannot invoke 'find' with an argument list of type '([AnyObject]?,...`


Spark Job is stuck at SUBMITTED when set Driver Memory > 5 GB

Question: I'm working on Spark with Standalone Cluster mode. I need to increase the Driver Memory as I got OOM in t he driver thread. If found that when setting  the Driver Memory to > 5 GB, the submitted job is stuck at Submitted in the driver and the application never starts.
I have 64 GB Memory in my machine and 16 Cores.
I set the driver memory in spark-default.conf
Comment: I found this happens when setting the driver memory much than the executor's one. But still can't understand what is the relation between them !
Answer: from Spark Master UI, the driver should be executed in one of the Executors. That's why its memory shouldn't exceed the Executors memory.


Angular2 what's the benefit using getter method

Question: I can see some examples on the internet that's using getter method.
something like this,
setId(id: number) {
    this._id = id;
}

get id() {
    return this._id;
}

What're the benefits using that? beside using getId()
Comment: Please see https://stackoverflow.com/a/45760862/5468463
Answer: The most common case is not the getter, that's rather a side effect, but the setter allows to execute code (valdiation or similar) when the value is updated.
A common getter example is also fullName where you store first name and last name in two different fields and fullName just returns ${this.firstName} ${this.lastName}.
What you can do with getter and setter can be done with methods as well, but having properties with getters and setters that can be used like simple fields, where it's not obvious there is calculation going on seem more natural.


What does it mean : qq = qq || {}?

Question: I have downloaded a javascript script and one of the first line is :
 qq = qq || {};

What does it mean?
Comment: init the object if it is not initialized
Comment: @Igor There is only one object there, `{}` -- `qq` is just a *variable* (or, if this is in the global context, a *property*)
Comment: @Felix Kling: then click "close" and mark it as a duplicate.
Comment: @JoshDavis: I expect he did, Felix is pretty used to how SO works. The system automatically puts that comment in when you do that.
Comment: @Josh: Yep, these comments are automatically generated. And close votes expire after a while, I voted to close this question a year ago.
Comment: I didn't notice it was from last year, I thought it was from last week. Explains why I got the first "close" vote.
Answer: It checks qq for a pre-existing truthy value or else (||) sets it as an empty object ({}).
In essence, it's purpose is to quickly ensure that any further references to qq will not be undefined, so you can check for properties of the object without your script breaking due to the fact that the variable isn't even a valid object in the first place.
Comment: It checks if it is "falsy" rather than simply whether it is defined or not. This usually works because `undefined` is a falsy value. But if it is defined and it is a falsy value then it will overwrite the existing value. `var qq = false; qq = qq || {}; q // {}`
Comment: **This doesn't check for "existence of the variable".** If the variable (or global property) is not bound this will *result in exception*. The word "exists" should not appear at all in this answer. Consider starting with "Checks the variables value..." or similar.
Comment: Note: 0, and empty string are both considered "falsy".
Comment: Yep, that is true.  Clarified slightly.
Comment: Ok, kinda a technical point, I'm just trying to convey the behavior and purpose in plain language, but I've changed the wording some to be more clear, and used the "truthy" word for exactness.
Comment: Your explanation looks pretty good to me. For the OP's edification, I'd just add that a slightly more correct version of this idiom would be something like `if (Object.prototype.toString.call(qq) !== "[object Object]") { qq = {}; }`, because the version `qq = qq || {}` will behave incorrectly if `qq === true` for example.
Comment: @Tchalvak I like(d) this answer because it's very succinct. The pedantic/pedagogical sides of me just leak out ;-)
Comment: Your answer is good for more info.  I was actually trying to look up the "assignment as an expression" idea to explain that, since I think that's the big thing that makes the code less clear.
Answer: In JavaScript the || (logical-or) operator has this logic-table:

A      | B          | A || B
Truthy | Don't care | A   (guaranteed to be Truthy)
Falsy  | Don't care | B   (may be Truthy or Falsy)

(See Truthy and Falsy in JavaScript for what the terms mean.)
Therefor, in the case of qq = qq || {}:
If qq initially evaluates to a Falsy value then the result of qq || {} is {} and thus ({}, a Truthy value) is assigned to qq. Otherwise, qq was initially a Truthy value and the result of qq || {} (which is the result of evaluating qq) is assigned to qq.
This is an idiomatic guard used to easily protect against "undefined" arguments, properties, and similar.
Some people may prefer to use the following near-equivalent construct instead:
if (!qq) {
  qq = {}
}

This latter case, however, will only assign to qq if qq was initially Falsy; the form qq = qq || {} always makes the assignment, but such "overhead" is so trite it should not be used as justification to not use the approach.
Happy coding.
Answer: Explanation:
    qq = qq || {};
// ^^ is equal to iself, but if it does not exist,
//       then it is equal to an empty object

For example:
for(var i = 0; i < 5; i++){
    qq = qq || {};
    qq[i] = 'something!';
}

Fiddle: http://jsfiddle.net/maniator/dr5Ra/
Comment: Calling `=` 'equal' is a bit misleading: 'assign' is the better term here.
Answer: The answers here so far miss out an important point. The OP says that the script starts with
qq = qq || {};

If so, and if qq hasn't been declared anywhere (no var qq at global scope, no window.qq = ...), that code will throw a ReferenceError. It will not just default qq.
In contrast, if the code were:
var qq = qq || {};

That would be very different indeed. It would do this:

The var qq part would be processed prior to any step-by-step code in the script. If there is already a global qq variable, it will be a no-op. If there isn't, it create a global qq variable with the initial value undefined.
When step-by-step execution reaches that line, the right-hand side of the assignment is evaluated like this:

If qq has a "falsey" value (0, "", undefined, false, NaN, or null), the expression qq || {} evalutes to {}.
If qq has a "truthy" value (anything not falsey), the expression evalutes to qq.

(For more details: JavaScript's Curiously-Powerful || Operator.)
The result of the right-hand-side is assigned to qq.

The var makes a big difference.
Answer: qq will receive qq or will be a new object ({}) if it didn't exist.

What does it mean : qq = qq || {}?


BitTorrent programs killing networking - Broadcom wireless

Question: This started happening after I did a fresh install of 14.04 (previously I was on 13.04). When ever I launch a BitTorrent client my DNS very quickly stops responding, and then the network connection itself stops working completely (to the point of disconnecting and failing to see the network again).
It works just fine on my wired connection, but with wireless (which is a Broadcom; I followed the steps here: http://ubuntuforums.org/showthread.php?t=2218898 to get it working) then it craps out.
Edit: I have verified that I have the correct drivers installed. My output is
<code>09:00.0 Ethernet controller [0200]: Broadcom Corporation NetXtreme BCM5755M Gigabit Ethernet PCI Express [14e4:1673] (rev 02)
0c:00.0 Network controller [0280]: Broadcom Corporation BCM4311 802.11b/g WLAN [14e4:4311] (rev 01)
</code>
and I have linux-firmware-nonfree installed.
Answer: Bittorrent can stress any server or router because it tends to use many connections at once: more than some cheap consumer routers can handle.  The easy solution is to reduce the number of maximum connections your bittorrent software uses in the software itself.  Try various numbers but less than 400 is a reasonable number that should work - as a troubleshooting measure you can try less than 128 in a pinch but that may hurt download speed.
(Good routers allow ~4000 or more simultaneous connections, often ~16000 or more, bad/cheap routers may limit to ~500 or even ~128 in extreme cases - and that is shared by all users of your network, even cellphones on your wifi).
That said, the multiple connections that a bittorrent client uses should not put stress on a DNS server.  It is possible that the DNS problems you are experiencing may just be a side effect of problems with your router handling that many connections, in which case this isn't a DNS issue but DNS problems is just a symptom.  For example, DNS uses a connectionless protocol and such protocols suffer when there is packet loss, which may occur in a router that is overloaded in other ways.
Another strange issue is that you say it works fine over a wired connection but not wireless.  If they are going through the same router either way (eg. the access point and the router is the same device, or if it's a separate access point it has NAT disabled / doesn't use the WAN port) then it should work the same.  Have you done any other testing to see whether there are general problems with wifi on that same PC?
Comment: Thanks for the suggestion. I tried reducing the maximum connections to 64 yet it still happened exactly as before. Prior to changing that setting, it was set at 500 connections maximum.

I strongly suspect at this point that it is related to my Broadcom wireless card, although I don't know exactly what I need to change at this point. It worked in 13.04.


Comment out an element using lxml

Question: Is it possible to comment out an xml element with python's lxml while preserving the original element rendering inside the comment? I tried the following
elem.getparent().replace(elem, etree.Comment(etree.tostring(elem, pretty_print=True)))

but tostring() adds the namespace declaration.
Comment: OK, I understand. But I still think that it is reasonable to request a complete example that demonstrates the problem. Now I have provided an example in my answer.
Comment: What namespace declaration? Please provide a [mcve].
Comment: mzjn: xmlns="foo" etc. In the original xml these declarations are inherited from the root element and are not explicitly present in the children. tostring(), of course, doesn't know that.
Answer: The namespace of the commented-out element is inherited from the root element. Demo:
from lxml import etree

XML = """
<root xmlns='foo'>

  AAA

</root>"""

root = etree.fromstring(XML)
b = root.find(".//{foo}b")
b.getparent().replace(b, etree.Comment(etree.tostring(b)))
print etree.tostring(root)

Result:
<root xmlns="foo">

</root>

Manipulating namespaces is often harder than you might suspect. See https://stackoverflow.com/a/31870245/407651.
My suggestion here is to use BeautifulSoup, which in practice does not really care about namespaces (soup.find('b') returns the b element even though it is in the foo namespace).
from bs4 import BeautifulSoup, Comment

soup = BeautifulSoup(XML, "xml")
b = soup.find('b')
b.replace_with(Comment(str(b)))
print soup.prettify()

Result:
<?xml version="1.0" encoding="utf-8"?>
<root mlns="foo">

</root>

Comment out an element using lxml


Getting freaky error while trying to run Thief:Deadly Shadows?

Question: I'm getting a FREAKY error when I try to start my Thief:Deadly shadows game. It's telling me to select a Just-in-Time Visual studio 2010 debugger, and when I select yes it opens up my Visual studio and gives me a load of error messages. What is this about? I tried uninstalling Visual Studio and it tells me I need a "Just-in-time debugger/compiler"
Specs:
AMD Athlon 64 Processor
512 RAM
2.01 Ghz
NVidia Geforce 200
This shouldn't happen because I meet all graphic requirements to play the game, and NO other game ever gave me this error, it's one of the freakiest errors I have seen in my entire life. Please help.
Comment: Never experienced this so I can't provide a proper answer, but this is the closest thread I could find where people directly mention a JIT debugger error message: http://www.ttlg.com/forums/showthread.php?t=128302
Answer: Ugh, Thief: Deadly Shadows.  This game is kind of a buggy mess.  I played about 75% of the way through it before I finally gave up.  On my system, it would crash to desktop about 2/3rds of the time when launched.
When you have a debugger installed (ie, Visual Studio), and a program crashes in ways that tend to indicate programming bugs, the OS assumes you are savvy enough to want to know why that happened.  So, you'll get a far more detailed error message than normal, and the option to debug it in Visual Studio.  Of course, since you don't have any of the debugging information for the game's compiled code, and you aren't familiar with the game's internals anyhow, this isn't actually useful to you and can be ignored.
Is your system multi-core?  If so, you have to set the core affinity for the game or it won't work, period.  Beyond that, another solution that worked for people was changing settings with T3 Tweaker, like disabling the loading screen tips.
On the whole though, I wish you the best of luck - this game was rife with bugs when it was released, and the intervening years have not been kind.  Compatibility with contemporary hardware/software was iffy when it came out, and compatibility with today's hardware is downright poor.
Comment: Thanks for that. My computer is not dual-core, however I'll try the tweaker.


How to boot into Ubuntu?

Question: I have a Windows 7 computer (I am typing this on it). I put Ubuntu on a USB flash drive, and installed it as I was instructed. After rebooting, it booted back into Windows without asking me if I wanted to boot into Windows or Ubuntu. I booted from the USB drive, and it acted as if I had never installed Ubuntu. Please help!
Answer: Maybe during the installation the Grub wasn't properly installed. Maybe if you use the flash drive again and try to install the Ubuntu, it will tell if it's installed or not. If it is, maybe you can try to reinstall it.
Answer: You may need to interrupt the boot process by pressing e.g. the escape key or one of the function keys to get into GRUB.
Answer: If you're absolutely positive that you installed Ubuntu you could try the boot rescue disk
This will reinstall your grub and make it visible for 10 seconds during each boot (you can change this with grub customizer).
If it doesn't work you'll have to reinstall your Ubuntu.

How to boot into Ubuntu?


Do I need a pulley extractor to replace the small drive belt (225-5M) for SnowJoe SJ625E?

Question: First let me say that I called the SnowJoe technical support and they could not help.
I am trying to replace the belt that goes around the pulley marked with a red arrow in the below diagram (from their manual). The problem is that the flanged pulley has a shoulder that forces you to fully install the belt around it before trying to install it around the driver pulley. (see the second picture for terminology)

This is for terminology reference, I hope I am using the right names for these parts, I am not a mechanic

Here is what it looks like with no belt

And here is how close I can get without forcing it

To me it seems that the only way to put this back is to use a pulley extractor. Is there a better way?
Comment: Youtube videos make stuff look easy.  What they don't show is you probably need more than two hands.  Being a weight lifter helps.  Even using a gear puller, you still have the problem of getting the gear back on and will need to lever it back in place.
Comment: It is nice to dream.  That belt will hold the pulley at angle at best when trying to put it back on
Comment: @Ruskes - Probably don't need a tensioner for a cogged belt like that, since it doesn't rely on belt-to-pulley friction for operation.
Comment: I think I'm seeing a hex socket in the hub of the larger pulley...? Plus the C clip holding the smaller one. I suspect that both should come off without a gear puller unless they're rusted in place
Comment: It does not seems to have tension adjustment, or I do not see it, it is strange not to have tension adjustment
Comment: yes it a POS assembly and the belt is very rigid this method does not work here https://www.youtube.com/watch?v=6Cd8Np26_qU&ab_channel=WrenchTurner
Comment: I can not see well, but is there a slot going from smaller to the larger
Comment: My expectation would be that the belt fits tight around the two pulleys (driver and flange pulley) and I should be able to push/hammer it it back into position using a piece of wood to absorb the hit (the pulley seem to be made of aluminum
Comment: they are made of aluminum . the flange pulley had a hex nut that came out easy but the pulley did not move. It might be a better idea to try to extract the driver pulley although that is mounted on the motor so putting it back might affect the rotor if hammered. I think the C clamp is there just in case. You do not want that pulley to freely spin by itself when the motor is started so there must be a way to hold it in  position to avoid this
Comment: Heating the belt will make it larger and more stretchy, might be enough to make the difference.  A hot air gun or hair dryer should work. Likewise, get the metal parts cold first, keeping it outside overnight for example, that will make them smaller. Fun fact: the wing hinge pin on an F-14 tomcat needs soaked in liquid nitrogen before inserting...
Answer: Page 13 and 14 clearly show how to do it
manual
To remove or install the belt, you would put it over the drive pulley first, then partially (as much you can) over the auger pulley, then start turning the auger (while pushing the belt down to make the belt slip over it.
No tools neded

Use your right hand to press the belt with the ribbed side down. While holding the belt down with your right hand, use your left hand to turn the auger forward so that the auger pulley rotates in a clockwise direction. The belt will be gradually pushed down onto the pulley. When the belt is seated on the pulley, adjust it so that the ribs of the belt match the grooves on the pulley. (Fig. 29).

Wrench hold
Comment: Can you see the red arrow in my diagram ? There is a short belt there . You are looking at the wrong belt
Comment: @MiniMe same method applies,
Comment: @MiniMe What I was showing you is for the smaller belt, the larger one is called Pulley, the smaller is called Auger -pulley. Same method (slip over) applies to both to install the belt. Fig 31 and 32
Comment: That is the usual approach, yes. And yes, stretching the belt into position this way can sometimes take a significant amount of force. Putting a long-handled wrench on the bolt holding the pulley may give you a better lever arm while the belt stretches into place
Comment: tried with a long screw driver and used the end of the shaft that protrudes out of the driver pulley as leverage point and I had no luck. It requires a lot of force to stretch that belt enough to get it in place and you may damage it that way
Comment: @Ruskes that pulley has two levels. One that represents the driver for the bigger pulley ..they are mixing the terms ... the manual is a POS
Comment: @MiniMe see my updated answer/picture
Comment: @MiniMe I know it has two belts, take look at the smallest cog, it has a cut in it so you can use a wrench to assist you. you put first the belt on the small then force it over the bigger one by turning with wrench assistance,
Comment: You can not get even close to putting the belt on the edge of the flanged pulley because that has a shoulder that is larger in diameter than the pulley ...that is why you can't see it
Answer: Possible (can't see anything that's "for certain" that the parts might have a less-obvious tensioning method, like an eccentric mount, where something can be loosened to allow a collar around the shaft to rotate, and the hole for the shaft is off-center in that part, so the distance changes.
However, if you want to pull the small cogged pulley, the C-clip implies that it will probably come off without requiring a puller once you remove the C-clip.
Before you go there:
Rather than the ham-fisted approach shown in your you-tube clip, might try a nail or rod somewhat smaller than your pulley teeth engaged at one side of the pulley and belt inside the belt, outside the pulley, coming "straight up" from your picture) and rotating the assembly to pull that around the small pulley while pushing down on the belt to work it onto the pulley. Perhaps it's too tight to work, but more likely to than clumsy screwdriver-ing.
Comment: I considered that but (using a nail) but a nail that thin will bent before bringing the belt into the desired position.
Comment: You considered it; but did you **actually try** it? That's a healthy cog size, and the nail doesn't need to end the day as straight as it started if it will let you get the edge of the belt on the pulley, at which point you keep rotating and pushing (without the nail in there.)
Comment: I just did. There is no way you can use a nail or a thin rod for this. I tried to use a screw driver and that gets the belt on the driver pulley for a little bit there is now way to rotate or to push it down, it springs back imediately
Answer: OK after some wresting with this thing I managed to fix it. Here is how you do it:
The flanged pulley is key here, that one must be removed and then the belt can be installed. Depending on your luck it might come out easy or not. The third picture shows a nut that you need to remove, be careful with that you need to unscrew it as you would normally tighten it (it is designed to tighten itself as the shaft is spinning). After removing that nut you should be able to pull the flange out, it it is not coming off then use two prybars and push it upward evenly and at the same time. If it is still not moving do not force it as the piece is made of aluminum allow and it might crack (I came across reports/reviews saying that they tried to force the belt in as suggested in some of the below answers and the flanged pulley cracked). So to safely do that you need to remove the blue plastic cover so you can have free access to the pulley from all sides. They you can use a pulley remover as shown in the picture. In my case this as not needed as after having complete access to the pulley I was able to find better angles from my pry bars and I was able to pry it out a little. The pulley remover must have thin tips as it needs to get under the flange and there is not a lot or room there (less than 1/4" and the pulley remover might not get the right angle in order to get the grip there).
As you can see in the below pictures I was able to replace the belt easily after that.


What paint for a tire swing?

Question: I just bought a big used tire and hung it as a tire swing. I pressure washed it, but it still sheds a little black residue. I'd love to seal it/paint it, but am not sure what would stick to a tire and not crack over time in the sun. Any recommendations?
Comment: I have paint pens that stick to rubber (dive gear)  uni paint ,px-20 it is an oil based paint not sure if you can find more on the type but it holds up over hundreds of dives.
Answer: You could try the type of tire dressing like auto detailers use to spruce up the sidewalls of the tires on cars/trucks. You can find this online by searching for "tire dressing" or "tire shine". It should also be available at your local auto parts store.
My experience with products of this type is that they give the rubber of the tire a surface that is glossy look and a smooth feel. Exposure to sun and weather will likely require re-application from time to time but should certainly reduce the amount of "rub off" coming off the tire.
Answer: I'd try two things. First, I'd wax it with auto wax. This will result in a dry finish that probably won't rub off more than the tire itself did.
If that doesn't work, try polishing the surface with a torch. Maybe by melting it slightly you'll get a more sealed finish.
Answer: A few companies (e.g., Krylon and Rust-OLeum that I know of) make paint specifically designed for plastics.  They're for uses such as refinishing lawn furniture.  They're tough, flexible, and bond with the plastic.
I have no idea how well it would bond with a tire since tires are designed to not be affected by the hydrocarbon solvents that are used as vehicle fuels and additives.  But the paint is readily available at big hardware chains, and it would be relatively inexpensive to try.

What paint for a tire swing?


Issues with dualbooting after installing windows 8 (boot-repair not working!)

Question: I used to dual boot ubuntu and windows 7 before I decided to format my windows partition and install windows 8 instead. As always, my grub went missing (only windows loading) and I run boot-repair-disk from usb. However, the recommended repair fails with the message:

You have installed on sda5 a Linux version which is not EFI-compatible. It is probably incompatible with your computer. Please install an EFI-compatible system. For example, Linux-Secure-Remix-64bit and Ubuntu-64bit are EFI-compatible systems.

So it turns out that my  newly installed windows is 64-bit and with EFI while my installed ubuntu is not EFI compatible (so it must be 32-bit?).
After reading around, it seems that this is actually the kind of thing that boot-repair should solve by default, yet I get that message. I couldn't really find any posts with the same problem so I'm stuck.
I was thinking of reinstalling ubuntu with a 64-bit version as suggested by the message but I would have to back up data from my home folder first which seems to be not doable at the moment (I stupidly encrypted that partition some time ago and do not a key...).
This is the log generated by boot-repair.
http://paste.ubuntu.com/6692233/
Please help!
Answer: You guessed correctly :) According to line 673 of the Boot-Repair log, you have installed a 32bit version of Ubuntu.
You can reinstall Ubuntu-64bit above the current 32bit one while reusing your old /home. See https://help.ubuntu.com/community/UbuntuReinstallation


Different execution time for same function with different names Matlab

Question: Suppose I have a function called Test in Matlab as follow:
function [f, varargout] = Test(I,varargin)
When I run this function on a specific input, the execution time is 0.019661 Sec.
If I copy the whole body of the function and paste it in a new .m file and name it as Tes1, I would have the same function with a different name like
function [f, varargout] = Test1(I,varargin)
Now, when I run function Test1 with same input as Test, the execution time is 0.055111 Sec.
The question is: what is the reason for that?
Your answer is appreciated.
Comment: First of all, I'd suggest to run these functions in the loop like 1000 times to see if there is significant difference between execution times. Single comparison can not be measured as solid proof. Also, there is a difference between data storage schemes -  [this page](http://www.mathworks.com/help/matlab/matlab_prog/scripts-and-functions.html)
Comment: @aryodgh That initial jump in computation time is probably from Matlab compiling the new m-file (since it took twice a long, I don't think it was a system thing).  But yeah, as a rule of thumb, a dozen (for intensive function) to a few thousand (for less-taxing functions) iterations is a better measure of performance.
Comment: Thanks very much Pavel, your comment worked completely.
So: Elapsed time for Test: 0.013483 Sec. Elapsed time for Test1: 0.013518 Sec
Answer: This is likely due to various caching effects. First of all, your operating might cache the file, so the second time you read it it will be faster. Second, also Matlab itself might do tricks, like running the Just-in-Time compiler the first time you call a function, and caching the results for the next time you call it.
Better than writing some for-loop by hand to time a function would be to use the timeit function. This always runs the function several times to 'warm up the cache', and then calls it a certain number of times in a loop, depending on how much time it takes (i.e. a handful of times for a slow function, or 100000 times for a really fast one). It is included in recent versions of Matlab, for older versions it is available on the file-exchange.


Creating Key Bindings for an Xbox One controller on Mac

Question: I am really looking for a way to create key binding for an xbox one controller connected to a Mac. I know this is kind of a weird request, but I really want to try playing Guild Wars 2 with a controller. While, granted, it is probably better to use a keyboard and mouse, I really want to try it with a controller, but this game does not support a controller. I was wondering if there was any way to create key bindings to the Xbox One Controller buttons.
For instance: left stick as WASD and ABXY for 1234. Combinations would be helpful as well, like Rt + A = 5, and that sort of thing. I have a driver for the controller, but that is only useful for compatible games on steam and OS X. I am currently using Xone-OSX from FranticRain on Github, but am open to other programs.
Comment: Xpadder  is typically mentioned for doing this, but I don't know if it works on Mac, and I have no experience with it to make an answer. I definitely suggest using the new action cam setting for playing with a controller.
Comment: I've managed to do this using the Steam Controller, by adding a 'Non-steam game' shortcut and mapping the controller to the keyboard controls.
Answer: Joystick Mapper is an app on the Mac app store that allows you to map your controller. It has 3 stars and is 5 dollars. Here's the website: https://joystickmapper.com/.


We have 1,000+ visits per day (September 2013)

Question: In January 2013 we passed 500 visit per day.
Towards the end of September 2013, we passed 1,000 visits per day.
I just thought it was good to celebrate the growth of the site. Presumably most of this traffic is coming from Google deciding that answers on our site are relevant to what people are searching for. I look forward to when we reach 1,500 visits per day and move another one of our Area 51 statistics into the "green".
Comment: Bring out the party hats!
Answer: This is very good on that statistic - however, answer rates and especially question per day rate are a but concerning, aren't they?
How can these be improved?  Is it possible to build on the growing visits per day?
Comment: Yeah, we've had a lot of discussions about those issues. Personally, my main desire is for the question to be clear. I'm not too fussed about the need to show prior research. And more broadly I like the idea of making this a friendly place to ask questions. Of course, there are quality and focus concerns on occasion, but I tend to associate such issues more with occasional users of the site.
Comment: I agree; good point. If anything the answer rate has been improving over the last 6 months or so; at one point it was sitting on 80%. That said, it would be great to get it even higher.  In terms of questions per day, it went up really high there about a month ago up to about 8 questions per day, but it seems to have returned to the more long running trend of around 3 per day. Perhaps we could encourage some of the regular users  to ask a few more questions.
Comment: @JeromyAnglim with asking questions, on occasion there is some nitpicking about how the questions are written, and if Wikipedia needs to be consulted etc - that is very off-putting.  As is having unreplied questions - so, really the two issues are linked.
Comment: As a side point, if you're getting 2,3,4+ upvotes for your typical questions, then clearly the larger voting group of this site are appreciating your questions.
Comment: @JeromyAnglim I understand that, my point is that when questions go unanswered.
Comment: Personally, I don't think there is a major trade-off between number of questions asked and answer rate. I think questions vary in ease of answering, and that more questions means more answers, but that some questions don't get answers because they are difficult or unclear or for some other random reason.


not in %!in% not working? Change after update?

Question: on an old script, I had a line of code:
harris_residential_hmgpmatch <- subset(harris_residential_hmgpmatch, ID %!in% selecting_good$ID) #357

I need to rerun this script now, but the %!in% is no longer working:
Error in ID %!in% selecting_good$ID : could not find function "%!in%"

I have updated R since I initially wrote and ran this script - could that be the culprit, or am I missing something simple?
Comment: The "not in" operator is not included in base R. Many packages include a version of it though. Apparently in at least one of them it's called `%!in%`: https://stackoverflow.com/a/64139714/2854608 . Or if you do not want to load the package just use `!(ID %in% selecting_good$ID)`
Answer: Maybe you can customize your function like this
`%!in%` <- Negate(`%in%`)

Answer: Try adding the ! operator to the entire argument:
harris_residential_hmgpmatch <- subset(harris_residential_hmgpmatch, !(ID %!in% selecting_good$ID))


WCF Certificate Configuration with ASP.NET

Question: Briefly, here's the scenario.  I have an ASP.NET application using forms authentication and a custom membership provider.  I've created a WCF client and an ASP.NET ServiceHost using ServiceHostFactory.  Everything works perfectly so far, but to deploy this in the real world, I will need to have it secured.  I cannot seem to find out how to set the certificate for the service.  I want to use the certificate already associated with the ASP.NET application that is hosting my service.
How do I set the certificate in a way that will automatically set the certificate to the hosting web app's certificate without having to manually identify the certificate. It would be a real PITA if the user has to install the WCF assemblies and make changes to the configuration file and have to know something about what certificate is installed.
Here's what I mustered up so far, but haven't been able to get it to work and it isn't configurable during installation without recompilation.
serviceHost.Credentials.ServiceCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByIssuerDistinguishedName, "mycertificate");

Is there a ASP.NET Api that would return the certificate associated with the hosting app that I can pass to SetCertificate?  Also, how do I handle the situation where no certificate is installed, but I still want WCF to connect, albeit insecurely?
Answer: This depends on whether you want to use Transport or Message level security. If you just want your web services to work over https like any other web page, then in your WCF configuration, you do not need to specify the certificate, you simply enable transport security, like:
  <basicHttpBinding>
    <binding name="basicHttpsSecured" sendTimeout="00:02:00">
      <security mode="Transport">
        <transport clientCredentialType="None" />
      </security>
    </binding>
  </basicHttpBinding>

Then in IIS, you set the SSL certificate on the web site just like you would have for any other ASP.NET site. If you were not hosting this through IIS, but were instead making it a self-hosted windows service or something, then you would have to set the certificate in your configuration, but when hosting in IIS, you can let IIS do the work.
If instead you want to do message level security, which means that you are transporting over non-secure regular http, but your message contents are encrypted, then you would set
<security mode="Message">

on the binding, and specify the certificate to use to encrypt the message. However it sounds like you are talking about using ssl / https for your web service.
Comment: Do you think using the conventional ssl/https is sufficient best practice to transmit financial data?  If I do use message security, will I have to provide a certificate? If so, can I keep my certificate where my .svc file is located? If so, how do I tell WCF where it is?  I want to make deployment as easy as possible.
Comment: For sensitive financial and/or credit card data, you might want to use both transport and message security. However to do message security, the client would need the certificate.  With some credit card processing companies I've dealt with in the past, they go as far as issuing a unique certificate to every customer, so no 2 web service users use the same certificate, so can not decrypt each others messages.
Comment: Also, this MSDN article might help, it has sort of a step-by-step approach to setting up certificate authentication: http://msdn.microsoft.com/en-us/library/ff648360.aspx
Comment: Just to argue the other side of the coin, if you enter your credit card number into Amazon, or your bank info into PayPal, you are just transmitting it over HTTPS, which would be the equivalent of transport security in WCF. Plenty of people use that and it is sufficient.  So it comes down to a business / security decision on your part.
Comment: One problem just discovered. The service.svc file lives under the admin folder and it's protected with Forms Authentication using a custom membership provider.  If I put it in the root, it will automatically change my URL to he http instead of https.  This is a third party product and I don't have control over it.


MVVM with complex Models

Question: When utilising the MVVM pattern I am coming into some trouble when the Model objects become complex, that is, when they contain Properties which are non-primitive / not built-in. In my particular instance I have a ModelA which contains a collection of ModelB objects which themselves contains a collection of ModelC objects:
class ModelA
{
    public string Name { get; set; }
    public OberservableCollection<ModelB> Bs { get; set; }
}

class ModelB
{
    public string Make { get; set; }
    public ObservableCollection<ModelC> Cs { get; set; }
}

class ModelC
{
    public string Brand{ get; set; }
}

I have a ModelAViewModel which permits access to the collection of ModelB Bs property. In this instance I have not created a ViewModel for ModelB. I have styled the ModelB and ModelC collections (and individual instances) by using DataTemplates:
<DataTemplate x:Key="modelATemplate">
    <Grid Margin="5">
        <Grid.RowDefinitions>
            <RowDefinition />
        </Grid.RowDefinitions>
        <ScrollViewer Grid.Row="2" VerticalScrollBarVisibility="Auto">
            <ItemsControl  ItemsSource="{Binding Bs}" ItemTemplate="{StaticResource modelBTemplate}"/>
        </ScrollViewer>
    </Grid>
</DataTemplate>

<DataTemplate x:Key="modelBTemplate">
    <Grid Margin="5" HorizontalAlignment="Center">
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <TextBlock Grid.Row="0" Text="{Binding Make}">
        <ItemsControl Grid.Row="1" ItemsSource="{Binding Mode=OneWay, Path=Cs}"
                  ItemTemplate="{StaticResource ResourceKey=modelCTemplate}">
        </ItemsControl>
    </Grid>
</DataTemplate>

I have been advised that this is not the MVVM way of doing things and that each entity, that is, ModelB and ModelC should have their own ViewModel. I have been told to keep the Model classes but create ViewModels for them. I am unable to visualise how this is going to work.
If I create a ModelBViewModel:
public class ModelBViewModel
{
     ModelB MyModelB { get; set; }
}

I have a predicament - I already have ModelB instances within the ModelA class, I would now have other ModelB instances in the ModelBViewModel. Is it necessary to iterate through the original ModelB collection within ModelA and create the ModelBViewModels, setting the MyModelB property to match that in ModelA as I go? It seems a bit complicated for what should be rather simple?
Comment: Your models are using `ObservableCollection` (to rise notification), but you didn't implement notification of any kind for e.g. `ModelB.Make`, `ModelB.Cs` and `ModelC.Brand` changes. So while technically you display them it's not MVVM. Typically models have to provide a mechanism to inform ViewModel (`INotifyPropertyChanged` is good), while ViewModels nearly `must` implement `INotifyPropertyChanged`.  Probably the easier is to make `ModelB`/`ModelC` implementing `INotifyPropertyChanged`, then they are actually become ViewModels which can be used directly for bindings.
Comment: See [this](http://stackoverflow.com/q/7767218/1997232) for why binding to something not implementing `INotifyPropertyChanged` is working. TLDR; changes made to models will only be visible in the view if view itself made them.
Comment: @Sinatr Not raising a notification does not mean that "it's not MVVM".
Answer: MVVM means "Model View ViewModel". As you can see, the name contains Model and ViewModel. The idea is to have a dedicated ViewModel class for every Model class you have.
The ViewModel should contain view-specific properties and logic while the Model class should contain business model specfic properties and logic.
And: Yes, for some very simple MVVM examples this might be overhead. However you benefit from this seperation as soon as your view logic starts to diverge from your business logic.
If it is necessary to iterate through the original properties: I would say: Yes!
I usually do it this way:
public class ModelBViewModel
{
    private ModelB _model;

    public ObservableCollection<ModelCViewModel> CVms { get; set; }

    public ModelBViewModel(ModelB model) {
        _model = model;
        CVms = new ObservableCollection();
        foreach(var modelC in model.Cs) {
            CVms.Add(new ModelCViewModel(modelC));
        }
    }
}

Comment: I always thought that one should create a ViewModel for each View not for each Model. Otherwise what good does it provide besides MVC
Comment: Use Linq:  `CVms = new ObservableCollection(model.Cs.Select(c=> new ModelCViewModel(c)));`
Comment: Yes, you should create a view model for each view. However, when you want to display your model data in more than one view it can make it easier to reuse your view model code when you have a view model for each model.
Comment: @makzr do you possibly have a larger example that puts what you've written here in context? I have pretty much the *exact* same question as OP, and I also feel that manually iterating through the collection to create a VM for each model instance seems clunky next to, say, setting a data template and then just using a contentcontrol, which is so much more, like, "automatic".

MVVM with complex Models


How to capture a square size photo in android app

Question: I'm now developing an android app. In this app, user can take a photo and then upload it. But in the user interface, I want the photo be square size and also be displayed as square size. The following is my camerapreview code, I don't know where to add size parameters:
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    private static final String TAG = "CameraPreview";
    private SurfaceHolder mHolder;
    private Camera mCamera;

    public static final int MEDIA_TYPE_IMAGE = 1;
    private Uri outputMediaFileUri;
    private String outputMediaFileType;
    public File pic;
    public Uri uri;

    public CameraPreview(Context context) {
        super(context);
        mHolder = getHolder();
        mHolder.addCallback(this);
    }

    private static Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e) {
            Log.d(TAG, "camera is not available");
        }
        return c;
    }

    public void surfaceCreated(SurfaceHolder holder) {
        mCamera = getCameraInstance();
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        mHolder.removeCallback(this);
        mCamera.setPreviewCallback(null);
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null;
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        int rotation = getDisplayOrientation();
        mCamera.setDisplayOrientation(90);
    }

    private File getOutputMediaFile(int type) {
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), TAG);
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d(TAG, "failed to create directory");
                return null;
            }
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        if (type == MEDIA_TYPE_IMAGE) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                    "prescription" + ".jpg");
            outputMediaFileType = "image/*";
        } else {
            return null;
        }
        outputMediaFileUri = Uri.fromFile(mediaFile);
        return mediaFile;
    }

    public Uri getOutputMediaFileUri() {
        return outputMediaFileUri;
    }

    public String getOutputMediaFileType() {
        return outputMediaFileType;
    }

    public void takePicture() {
        mCamera.takePicture(null, null, new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
                Log.i("camera", "file done");
                if (pictureFile == null) {
                    Log.d(TAG, "Error creating media file, check storage permissions");
                    return;
                }
                try {
                    Log.i("camera", "do outputstream");
                    FileOutputStream fos = new FileOutputStream(pictureFile);
                    Log.i("camera", "after outputstream");
                    s = getOutputMediaFileUri().toString();
                    fos.write(data);
                    fos.close();

                } catch (FileNotFoundException e) {
                    Log.d(TAG, "File not found: " + e.getMessage());
                } catch (IOException e) {
                    Log.d(TAG, "Error accessing file: " + e.getMessage());
                }
            }
        });

    }

    public int getDisplayOrientation() {
        Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        int rotation = display.getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        android.hardware.Camera.CameraInfo camInfo =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, camInfo);

        int result = (camInfo.orientation - degrees + 360) % 360;
        return result;
    }

}

If I want to make sure the size of the photo and the camera preview are square size, where should I modify? Thanks.
Answer: I use Picasso to work with images, it is very effective.
implementation 'com.squareup.picasso:picasso:2.71828'
Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);
Picasso.get()
    .load(url)
    .resize(50, 50)//resize image
    .centerCrop()
    .into(imageView)

http://square.github.io/picasso/
Regards!


Java: map of concurrently incremented counters

Question: I need to implement a map of counters (like Map) in my application. However this structure is supposed to be accessed by several threads.
It looks like ConcurrentHashMap<Key, Long> is not a proper solution, right?
I thought about ConcurrentHashMap<Key, AtomicLong> instead.
But there is a problem - requests for increment are not spread evenly. Few most popular Keys could have up to 95% of all increment requests to this data structure.
As far as I understand this will lead to concurrent access to single AtomicLong instances and there many locks should occur which will somewhat decrease efficiency.
Question 1: Is there any better solution - perhaps, better data type instead of AtomicLong, which allows short accumulation of increments or something like this?
Question 2: I want to persist the structure to disk periodically (perhaps, every minute), and I want to persist its "actual" state (with all recent updates settled?) - what is most straightforward way for it?
Answer: What makes you think AtomicLong uses locks internally? That is not true, it's mostly built on CAS operations. My advice would be to implement it with AtomicLong and profile the implementation later. If (and only if) your counter will be a bottleneck, then consider replacing it with any other implementation.
"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil"    - Donald Knuth
As of state persistence the simplest approach is to serialize your map:
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(out);
objOut.writeObject(map);
objOut.close();

Comment: Thanks for pointing the fact that AtomicLong works differently than I thought! About persisting the main question was not technical writing the map, but rather "whether I need to undertake some measures to ensure all last updates will be persisted with simple serializing of this data structure?" I am sorry for not making me clear enough.
Comment: As far as I know no specific measures are necessary. When doing serialization CHM locks segments one by one, so all the latest updates should be included. Serialization, however, is not itself atomic. If some updates will be done in the midle of the serialization process, they may or may not be included in resulting snaphot depending on how lucky you are. If this matters for you, consider the Stephen's advice in the post below to swap the map.
Answer: Firstly, you are at risk of "premature optimization" here.  There is a good chance that the concurrency hotspot/bottleneck that you are worried about won't be significant.
Having said that:
A ConcurrentHashMap<Key, AtomicLong> sounds a good option unless the concurrency hotspots are a major issue.  The ConcurrentHashMap should largely avoid problems with the concurrency of the map, and an AtomicLong will give good performance unless there is extreme contention on a single counter.

Is there any better solution - perhaps, better data type instead of AtomicLong, which allows short accumulation of increments or something like this?

That might work.  (For instance, each thread could have its own (non-concurrent) map, and use Long or a non-synchronized custom long holder class, rather than AtomicLong.)
However, the downsides of doing this are:

The memory usage could be significantly greater.
You would have have the additional overhead of combining multiple maps into one to get the final counts.  That step is most likely going to involve a serial computation.

All in all, I'd be surprised if this improved performance unless you have a huge number of cores and a very high rate of counting.

I want to persist the structure to disk periodically (perhaps, every minute), and I want to persist its "actual" state (with all recent updates settled?) - what is most straightforward way for it?

The most straightforward way to do it is to stop everything while you persist.
If that is not acceptable, then you need to do something like this:

Decide to persist.
Create a new ConcurrentHashMap<Key, AtomicLong> instance.
Atomically replace the existing map with the new one ... so that you can accumulate counts.
Persist the old map.
Iterate the old map, atomically transferring the counts for each key to the new map.
Discard the old map.


Hibernate GenerationType.IDENTITY vs GenerationType.SEQUENCE

Question: I'm looking for clarification on this question: @GeneratedValue(strategy="IDENTITY") vs. @GeneratedValue(strategy="SEQUENCE") (nearly a decade old has anything changed?)
Getting started with learning jpa, the following generation types both seem to auto-increment the primary keys that get generated by 1.
Identity:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

Sequence:
@Id
@SequenceGenerator(
    name = "my_sequence",
    sequenceName = "my_sequence",
    allocationSize = 1
)
@GeneratedValue(
    strategy = GenerationType.SEQUENCE,
    generator = "my_sequence"
)
private Long id;

I understand that the sequence object created by GenerationType.SEQUENCE is not tied directly to a table in the way GenerationType.IDENTITY is. The old question mentions that sequence can be more flexible. Are there any objective pros or cons to choosing one of these strategies over the other? Also anything new considering the age of the question being referenced?
Answer: As it's stated in the hibernate documentation:

It is important to realize that using IDENTITY columns imposes a runtime behavior where the entity row must be physically inserted prior to the identifier value being known.
This can mess up extended persistence contexts (long conversations). Because of the runtime imposition/inconsistency, Hibernate suggests other forms of identifier value generation be used (e.g. SEQUENCE).
There is yet another important runtime impact of choosing IDENTITY generation: Hibernate will not be able to batch INSERT statements for the entities using the IDENTITY generation.
The importance of this depends on the application-specific use cases. If the application is not usually creating many new instances of a given entity type using the IDENTITY generator, then this limitation will be less important since batching would not have been very helpful anyway.


How to call mongoose's CRUD methods inside an instance method

Question: The mongoose documentation shows this example to create a new document
var Tank = mongoose.model('Tank', yourSchema);

var small = new Tank({ size: 'small' });
small.save(function (err) {
  if (err) return handleError(err);
  // saved!
})

// or

Tank.create({ size: 'small' }, function (err, small) {
  if (err) return handleError(err);
  // saved!
})

The problem I am having is that I do not yet have a Tank. I am defining an instance method and I want to do a Tank.create() inside of it. How can I call this create and other similar methods from within an instance method?
Comment: In general, it probably is not a best practice to call Tank.create from within an instance method. You can refer to the instance with `this` and call `save` on it to update the instance, but the creation of a new tank should not really happen from the instance of another tank.
Answer: This works but seems like a hack:
this.constructor.create()
Edit: These are custom instance methods (not built in) so the the model needs to be called.
this.model('Tank').create()


Choosing a data type as a parameter?

Question: Is there a way to specify a data type (specifically: int, text, byte, char) as a parameter?
For example: (this doesn't work)
public void myclass(System.Object ChoosenType)
{
    switch (ChoosenType)
        case System.Text:
        case System.Byte:
        case System.Int32:
        case Sustem.Char:
}

Comment: Sounds like a [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What are you trying to achieve? Looks like a pretty bad code smell to me.
Comment: Sorry about the duplicate. I am somewhat new so my vocabulary is lacking.
Answer: You can, by using the Type class. However, you can't use a switch statement since you can't switch on Type objects.

CS0151 A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type

You also need to change your comparison method, as the "type name" of a type is not a Type object. You have to use typeof:
public void someMethod(Type theType)
{
    if (theType == typeof(Int32))
    {
    }
    else if (theType == typeof(Char))
    {
    }
    ...
}

Also note that System.Text is not a type, but a namespace. System.String on the other hand is a type.
Answer: Also worth noting that in addition to using the Type class, you could replace the System.Int32 with it's alias, int.  This works because int is really just a "nickname" for the fully qualified System.Int32 class.
ex-
public void myClass(Type x)
{
    if (x == typeof(int))
    {
        Console.WriteLine("int");
    }
    else if (x == typeof(bool))
    {
        Console.WriteLine("bool");
    }
    else if (x == typeof(string))
    {
        Console.WriteLine("string");
    }
    //additional Type tests can go here
    else Console.WriteLine("Invalid type");
}

Choosing a data type as a parameter?


Repeated sub-messages in protobuf-c

Question: Can somebody give me an example of packing\unpacking message with repeating sub-message in protobuf-c?
Official documentation in empty on this matter.
Answer: message B {
  required int64 i = 1;
};

message A {
  repeated B numbers = 1;
};

A a;
a.ParseFromString(<str>)
for (int i = 0; i < a.numbers_size(); ++i) {
  const B& b = a.numbers(i);
  printf("%d\n", b.i());
}

Answer: proto:
message SubMsg {
  bytes value = 1;
}

message MainMsg {
  repeated SubMsg msgs = 1;
}

pack (do not forget to free memory (free(...)):
MainMsg mainMsg = { };
main_msg__init(&mainMsg);
SubMsg **subMsgs = calloc(LEN, sizeof(SubMsg*));
for (int i = 0; i < LEN; i++) {
    subMsgs[i] = calloc(1, sizeof(SubMsg));
    sub_msg__init(subMsgs[i]);
    subMsgs[i]->value.data = DATA;
    subMsgs[i]->value.len = DATALEN;
}
mainMsg.msgs = subMsgs;
mainMsg.n_msgs = LEN;
...
main_msg__pack(&mainMsg, BUFFER);

unpack (do not forget to free memory (..._free_unpacked(...)):
MainMsg* mainMsg = main_msg__unpack(nullptr, BUFFERLEN, BUFFER);
if (! mainMsg) {
    // error
    return;
}

SubMsg **subMsgs = mainMsg->msgs;
...

Answer: proto:
message A {
  optional uint32 key = 1;
  optional uint64 value = 2;
}

message B {
  repeated A msg = 1;
}

if have optional XXX field, try to set has_XXX true;
  B msg;
  filebackup__heartbeat_content__init(&msg);
  A **subs = (A**)malloc(N * sizeof(A*));
  void *buf;
  unsigned len,i;
  for (int i = 0; i < N; ++i) {
    subs[i] = (A*)malloc(sizeof(A));
    filebackup__job_status__init(subs[i]);
    subs[i]->key = i + 1;
    subs[i]->has_key = 1;
    subs[i]->value = (i + 1) * 100;
    subs[i]->has_value = 1;
  }
  msg.msg = subs;
  msg.n_msg = N;
  len =  filebackup__heartbeat_content__get_packed_size(&msg);
  buf = malloc(len);
  filebackup__heartbeat_content__pack(&msg, (uint8_t *)buf);

Answer: "Reading A Message" section of Google's C++ tutorial has relevant sample code:
  http://code.google.com/apis/protocolbuffers/docs/cpptutorial.html
Also, STL's for_each also appears to work OK (syntactic sugar, more-or-less):
    std::for_each(a.numbers().begin()
                 ,a.numbers().end()
                 ,[](const B& b) {
                    std::cout << b.i() << std::endl ;
                  }
                 ) ;
Comment: The question is about protobuf-c, not protobuf. And about C, not C++.

Repeated sub-messages in protobuf-c


Does the solution of any differential equation (without boundary conditions) is always smooth

Question: Pardon me if this question sounds silly. Consider any differential equation without any boundary conditions. Does the solution of it is always smooth ?
Comment: of course not. Just take $y'(x) = g(x)$ for some prescribed function $g$. If $g$ is not $C^{k}$, then $y$ cannot be $C^{k+1}$. I assume you need some assumptions on the coefficients.
Comment: No. Consider the ODE $y'(x) = F(x,y)$. By coefficients we refer to the function $F:\mathbb{R}^2\to\mathbb{R}$. The terminology is inherited from the case where $F(x,y)$ is a polynomial in $y$, in which case $F$ is real analytic in the $y$ variable, and the regularity of $F$ depends essentially only on the regularity of the coefficients of the polynomial.
Comment: @Willie : Is there any notion as differentiability of a differential equation and something like a smooth differential equation.
Comment: Like I said, smoothness of the coefficients. Give a (scalar) ODE $y'(x) = F(x,y)$, you can formally take derivatives $y''(x) = \partial_xF(x,y) + \partial_yF(x,y)y'$ etc. If at the level of each derivative you have that the RHS is Lifschitz continuous, then you can apply the Picard-Lindelof theorem to gain derivatives. Of course, the solution may exist only for a small time. For example, $y' = y^2$ is an ODE with real analytic coefficients, and has real analytic solution for short time. But if you take positive initial data, the solution will blow-up in finite time.
Comment: @Willie : By coefficients is it assumed that the differential equation looks like a polynomial (eg. $D^2-xD+1 = 0$). What if the DE cannot be represented as a polynomial in $D$ with finite terms ?
Answer: One particular sub-class of PDE deserves mention, namely, "elliptic" PDE with smooth coefficients, such as $(\Delta+\lambda)u=f$ where $\Delta$ is the usual Laplacian on $\mathbb R^n$, for example. A simple smoothness assertion here is that, if $f$ is smooth, then $u$ is smooth, and, in particular, any solution of $(\Delta+\lambda)u=0$ is smooth. This is a simple case of "elliptic regularity" (a reasonable keyword/phrase to google).
For contrast, another standard: the wave operator $\Delta-\frac{\partial^2}{\partial t^2}$ is definitely not elliptic, but, instead, is "hyperbolic". Without giving that definition either, note that in 1-D, any function of the form $F(x,t)=f(x+t)+g(x-t)$ seems to satisfy the wave equation, even when $f,g$ are not differentiable, etc. This example was known before 1800, to Euler and others, and was some of the ammunition in arguments over the notion of "function" and the notion of "solution" of a differential equation. In particular, even tho' the coefficients are smooth, there can be very non-smooth solutions (if we allow distributional derivatives...)
Answer: No, "smooth" means infinitely differentiable. Solutions to differential equations of finite order only need to have finitely many derivatives.


Plot SVM margins using MATLAB and libsvm

Question: I am using svmlib to classify linearly two dimensional non-separable data. I am able to train the svm and obtain w and b using svmlib. Using this information I can plot the decision boundary, along with the support vectors, but I am not sure about how to plot the margins, using the information that svmlib gives me.
Below is my code:
model = svmtrain(Y,X, '-s 0 -t 0 -c 100');

w = model.SVs' * model.sv_coef;
b = -model.rho;
if (model.Label(1) == -1)
    w = -w; b = -b;
end
y_hat = sign(w'*X' + b);

sv = full(model.SVs);

% plot support vectors
plot(sv(:,1),sv(:,2),'ko', 'MarkerSize', 10);

% plot decision boundary
plot_x = linspace(min(X(:,1)), max(X(:,1)), 30);
plot_y = (-1/w(2))*(w(1)*plot_x + b);
plot(plot_x, plot_y, 'k-', 'LineWidth', 1)

Comment: The margin is the distance between the decision boundary and the support vectors. How would you like to plot it?
Answer: It depends on what you mean by "the margins". It also depends on what SVM version you are talking about (separable on non-separable), but since you mentioned libsvm I'll assume you mean the more general, non-separable version.
The term "margin" can refer to the Euclidean distance from the separating hyperplane to the hyperplane defined by wx+b=1 (or wx+b=-1). This distance is given by 1/norm(w).
"Margin" can also refer to the margin of a specific sample x, which is the Euclidean distance of x from the separating hyperplane. It is given by

(wx+b)/norm(w)

note that this is a signed distance, that is it is negative/positive, depending on which side of the hyperplane the point x resides. You can draw it as a line from the point, perpendicular to the hyperplane.
Another interesting value is the slack variable xi, which is the "algebraic" distance (not Euclidean) of a support vector from the "hard" margin defined by wx+b=+1 (or -1). It is positive only for support vectors, and if a point is not a support vector, its xi equals 0. More compactly:

xi = max(0, 1 - y*(w'*x+b))

where y is the label.
Comment: I think I'm just not understanding the svm theory correctly. Given your equations, how do i know which support vector to use to obtain the margin? Would it be the correctly classified support vector that is farthest from the decision boundary?
Comment: I'll edit my answer since it's not short enough for a comment


How can we identify a unique record in Cassandra for tables which don't have a primary key defined?

Question: I have Cassandra database and some tables within it. Tables don't have primary key / unique key / composite key defined. How can we identify a unique record in a table?
Like oracle has concept of ROWID , in same way do we have something for Cassandra database. N/A
Comment: There must be a primary key on the table (consisting of a partition key and potentially a clustering key) - but its not possible to not have a primary key.
Answer: It isn't possible to create Cassandra tables without a primary key defined.
The partition key in the primary key dictates how each record is "partitioned" or distributed among nodes in the cluster. Without a partition key, Cassandra doesn't know how to store the data in the cluster.
Here's an example table that is partitioned by email address:
<code>CREATE TABLE users_by_email (
    email text,
    firstname text,
    lastname text,
    PRIMARY KEY (email)
)
</code>
In this example, it will not be possible to read or write to the table without knowing a user's email address.
For more info on how Cassandra distributes data across nodes in a cluster, see Partitioners in Cassandra. There is also this short video on how Cassandra stores data in partitions (extracted from the DS201 Cassandra Foundations course at DataStax Academy). Cheers!


Unable to create an option menu with items in left side, with an icon for each item

Question: This is my .xml file. How do I set icons for them?

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:showAsAction="never"
    android:title="@string/action_settings"/>
<item

    android:drawable="@android:color/white"
    android:id="@+id/Home"
    android:showAsAction="withText"
    android:icon="@drawable/homep"
    android:orderInCategory="1"
    android:title="@string/home"/>
<item
    android:showAsAction="withText"
    android:icon="@drawable/examp"
    android:id="@+id/Exam_not"
    android:orderInCategory="2"
    android:title="@string/exam"/>
<item
    android:icon="@drawable/newsp"
    android:id="@+id/L_news"
    android:orderInCategory="3"
    android:showAsAction="withText"
    android:title="@string/L_news"/>
<item
    android:icon="@drawable/galleryp"
    android:id="@+id/gallery"
    android:orderInCategory="4"
    android:showAsAction="withText"
    android:title="@string/gallery"/>

How to set icons for them and create the menu on left side of device?
It should look like this:
Comment: any one plz help me ???
Answer: What you're showing appears to be a NavigationDrawer with either a number LinearLayout based rows, or backed by a ListView.
Refer to this tutorial from Google for more info: https://developer.android.com/training/implementing-navigation/nav-drawer.html


The string members become empty if use *pt = &stu1

Question: sorry for the title. The code below may help to describe the problem.
I've alreay set up a Student class.
if doing in this way:
Student stu1(score, "sam",5, "aaa", "email@example.com","156412", "518105" );
Student *tempSt = &stu1;

I try to cout the string members of tempSt, it works.
But the string members become empty when:
tempSt = &Student(score, "sam",6, "aaa", "email@example.com","156412", "518105" );

What is happening?
Hope you understand my poor description :)
update:
the problem stems from this:
void myList::add(Student *a) {
slistNode *tempNode = new slistNode();
tempNode->data = a;

if(lastNode == NULL) {
    headNode = tempNode;
    lastNode = tempNode;
} else {
    lastNode->next = tempNode;
    lastNode = tempNode;
}

++listLength;

}
I try to put those objs into a list, So I want those obj to be temporary(actually I want them no name). I don't want to make a lot objs like stu1, stu2, stu3....
slistNode class:
class slistNode {
public:
slistNode() {
    next = NULL;
}
Student *data;
slistNode *next;
};

Comment: Yup. Temporary -> destroyed -> UB.
Answer: You get a pointer to a temporary object. The object this pointer points to will be destructed before code reaches next line. As the object is destroyed of course accessing the string members invokes undefined behavior.
Comment: @chbdetta: when you have a `const &` to your constructed object, like in `const Student& s = Student(...)` it will live as long as your variable is in scope.  But don't rely on such behavior.
Comment: In what situation a temporary object won't be destructed?
Comment: There is no such situation. That is why it is **temporary**
Answer: In the second case, this:
Student(score, "sam",6, "aaa", "firstname.lastname@example.com","156412", "518105" );

constructs a temporary object. That's destructed right after its construction. Taking its address invokes undefined behavior.
(If you started with C instead of C++, the compiler wouldn't even permit you to commit suicide. Yay for brainless design decisions in C++!)
Comment: @chbdetta it would. And then what?
Comment: @chbdetta You stick with the first option: assign it to a variable.
Comment: If I want to build a lot of obj, wouldn't that way takes a lot memory?
Comment: how to prevent large memory use..? :)
Comment: @chbdetta Design your algorithms well?
Comment: @chbdetta: Lots of objects takes lots of memory. That's pretty clearly unavoidable.
Comment: @chbdetta: Pointers aren't free, they also require memory in addition to the objects they point to.


Leak issue, downstairs neighbor

Question: I think I posted this in the wrong place initially.
I am having an issue with my downstairs neighbor. The neighbor has a damaged leaking ceiling with brownish color (might be an issue from a long time) and is saying that the wet ceiling was observed just a few days ago. We have had heavy rain pouring over the past few days. The neighbor continues insisting that it is my fault even though I do not have a leak on my end. I contacted the property management right away and called a plumber. He came in and inspected my 2 bathrooms and found NO leak. He suggested it might be an issue with the roof or the ventilation but I still provided my insurance to the neighbor. I communicated this to the association but now he doesn't believe my plumber's inspection and he personally is making an accusation that this issue is from my unit. I find this not acceptable because the property manager is not a plumber but he has these demands and tells me that the plumber needs to remove my toilet and take a look. Why would they come in and mess with my toilet if it turns out it is not actually the toilet but the roof instead? Let me know what you think but I believe they should cut into my neighbors ceiling and figure out the source of the leak and if it is my toilet okay go ahead and fix it. Especially when I already provided my insurance
Comment: I'm voting to close this question because unfortunately, this sounds like more of a legal issue than a DIY issue. You should carefully read your lease to see what your responsibilities and rights are in this situation. I hate to say it, but you may need to consider getting some legal representation.
Comment: In most cases, this is the building manager's problem, not yours. They may need and ard entitled to access to your unit to diagnose the problem ... Unless you are in an upstairs)downstairs condo with no building manager, in which case you and the neighbor need to cooperate to find and fix the problem because it's damaging both of your investments.
Comment: This is probably not the right place either.  We deal mainly with fixing problems of a DIY type.  The place of the leak will need to be found before we can begin.  Even then this is mainly for owned homes, since multi-family dwellings usually need licensed contractors.  There might be a local tenants/condos group/association or city hall that might help with the local regulations.
Comment: Removing a toilet to check for a leak is an order of magnitude easier operation than cutting a hole in (and subsequently repairing) a ceiling.
Comment: I will need to agree with @FreeMan.  Too many(maybe fake) stories online that getting a  lawyer early would help.  Having your plumber's report contested is one reason.
Comment: Why do you think this is a fake story?
Answer: Neither you nor your downstairs neighbor is right, because nobody knows where the leak is coming from. It could very well be your toilet (albeit unlikely), or the roof. The thing with leaks is that water travels, so you could be having a leak, then it showing up in your neighbor's ceiling several feet away from the source. Or it could have nothing to do with you. The poor guy downstairs is having his ceiling destroyed by a leak, so let him send someone to check your toilet for Pete's sake. Either the leak is coming from your place or it's not, so it's not like checking your place will increase your liability. Giving him your insurance information does not stop the leak. If it's not your toilet, then they'll have to break through his ceiling and trace it.
Answer: You seem to be occupying the same building as another person.  Take it from Ukraine and Russia: The first law of being neighbors is don't be a selfish jerk.
You are saying "I don't want ANY intrusion into my home, I deny everything, they must go to extremes to prove their claim, not my problem until they prove it". That can backfire on you two ways.
First, when at great expense they tear up their ceilings to find that it is your fault after all, you will need to pay for all that.   When you argue "But I shouldn't have to pay for heavy ceiling repair when it could've been fixed by changing a $5 wax ring on my toilet", the court will laugh at you, saying you were given that opportunity and you refused it.
And second, you'll have to live everyday with a neighbor who hates your guts.  And I know that sounds like a small price to pay right now for the prospect of not having plumbers trudging through your home, but try living with the consequences for 5++ more years when you can't ask that person for anything, and have to suffer either direct retaliation, or always wondering if that thing that happened was them being passive-aggressive.  Creating such hostility is extremely short-sighted - easy to do but hard to live with.
Put up with the mild intrusion - it's part of living in a community. If you don't want to live in a community, get a single-family home farther out that you can afford, and make sure it's not in an HOA.
The right answer is "Sure bro, it's probably not me, but of course I'll help you out. I'm sure you'd do the same for me if the situation was reversed."
Comment: What are you talking about? Court? Who mentioned anything about court over a leak? I was just basically asking what do you think the steps are to resolve this issue. Since the ceiling downstairs is already messed up, it makes more sense to cut it and see if it even leaks from my toilet. If the issue is my toilet, I will cover the expenses yes
Comment: @abc123 Hope for the best, but plan for the worst.  Thinking about how it would go in court is also illustrative to what the right thing is.   Since you are not a plumber you do not actually know the best answer.  But your strong reluctance about having your pipes examined creates the risk of "confirmation bias" in your imagination of the best solution.  I would leave such things to the professionals. But mostly, don't let the matter come between you and a neighbor.
Comment: These days, wouldn't one just drill/poke a small hole in the damaged area of the neighbor's ceiling and run an endoscope camera up there to see what's going on?  No big new damage to fix, and photos showing exactly where the liquid is coming from.

Leak issue, downstairs neighbor


Platform for c++ cross compile application

Question: Currently, we are using MS Visual Studio and .NET to develop out applications on Window. We are in the process of porting the application to other OS (Linux, Android...etc) and want to get rid of MS Visual Studio and .NET stuff (they have been a pain to work with).
Is there any good development platform that you would recommend?
Thanks,
ABS
Comment: Of course it's my personal opinion, but VS is still one of the best IDE, don't expect to easily reduce your pain :)
Answer: I would port the Visual Studio's solution/project files to CMake (in the downloads list you can get binaries for Windows and Linux), which allows you to generate project files for different platforms, allowing cross-toolset development. Eg:
On Windows, running CMake would detect Visual Studio and would generate solution and project files accordingly.
On Linux: running CMake would find, for instance, gcc or g++ and would generate makefiles accordingly.
I have not tried it, but for android's NDK there's this: android-cmake
[UPDATE Information on gcc/make for windows]
If you want to drop Visual Studio completely, you can try to set up the gcc/make toolchain for Windows with MinGW - Minimalist GNU for Windows, and port your solution/project files to makefiles.
Comment: I agree, CMake is fantastic!!
Comment: I just installed MinGW, but how do i port the MS visual studio project to makefile?
Answer: Moving from Windows to other OS'es may shock you at first, but with time you'll get used to it: You do not need a "platform" or "IDE" per se.
What you will need, is cmake, gcc/g++, a decent text editor and perhaps a debugger frontend.
Optionally you may find ctags useful, Doxygen, an svn repo and a profiler (such as Valgrind/KCachegrind).
I am unaware of how exactly you can port .net stuff to C/C++ (other than re-writing from scratch).
Linux and OSX have many similarities, so porting from one to another should not be that hard. Android is a different story, although C++ for android has become a possibility.
The closest thing to what you are looking for, would probably be Eclipse or Netbeans, but again, the simpler you keep those things, the better IMHO.
Answer: As to getting rid of .NET, If your .NET code base is not in managed C++ in its entirety, I would try out Mono/Xamarin with Xamarin Studio IDE first before embarking on a full port of .NET code base to standardized C++.


Local Jenkins can't authenticate remote Gitlab private repository

Question: I installed Jenkins on windows with all addons that I need, I think so. When i create a new job and in Repository URL i write my url
http://git.*****.org/*****/seleniumproject.git
and it shows
Help for feature: Repository URL
Failed to connect to repository : Command "C:\Program Files (x86)\Git\bin\git.exe ls-remote -h http://git.*****.org/*****/seleniumproject.git HEAD" returned status code 128:
stdout:
stderr: fatal: Authentication failed for 'http://git.*****.org/*****/seleniumproject.git'`

My question: how can I authenticate to my remote gitlab?! I have folder with .ssh with all keys but don't know what to do...
Update: strange because my TortoiseGit is working perfectly
My Fix :

Go to jenkins path and save .ssh folder in root example
C:\Jenkins\.ssh .ssh folder u can find in C:\Users\yourname\.ssh
Go to Jenkins > Manage Jenkins > Manage Credentials, here you can
add your private key or select from the jenkins master !/.ssh
Go to Jenkins > Manage Jenkins > Configure System in git executable wrote this C:\Program Files (x86)\Git\cmd\git.exe path must be with cmd
Create new job and in repository url add
ssh://email@example.com:/name/projet.git
Answer: My Fix :

Go to jenkins path and save .ssh folder in root example
C:\Jenkins.ssh .ssh folder u can find in C:\Users\yourname.ssh
Go to Jenkins > Manage Jenkins > Manage Credentials, here you can
add your private key or select from the jenkins master !/.ssh
Go to Jenkins > Manage Jenkins > Configure System in git executable
wrote this C:\Program Files (x86)\Git\cmd\git.exe path must be with
cmd
Create new job and in repository url add
ssh://email@example.com:/name/projet.git
Comment: Excellent feedback. +1. More accurate than [my answer](http://stackoverflow.com/a/18636384/6309)
Comment: Hello, I have 2 questions. What is `C:\Jenkins`? Home dir for Jenkins? What do you mean in `C:\Program Files (x86)\Git\cmd\git.exe path must be with cmd`? Where can I set it?
Answer:
I have folder with .ssh with all keys

Those keys won't never been read, if you keep using an http(s) url.
You should use an ssh url, and first make sure that this works properly:
ssh -Tv ssh://git@git.*****.org

(assuming the user account you need on the server side is 'git')

Note that the section on SSH of this guide is of interest here:
you have installed TortoiseGIT

If you have ever installed TortoiseGit on the computer you're setting up your keys on, you may encounter problems.
TortiseGit creates an environment variable that configures Plink as your SSH keystore, which may conflict when you try to use Git and SSH.
  No matter how you change your config or uninstall TortoiseGit, that environment variable persists and until you delete it, Git will not look to your regular .ssh directory to find the proper key.
In our case environment variable looked like this:

GIT_SSH=c:\Program Files\Putty\plink.exe.

Environment variables can be found here:

Windows XP: Control Panel → System Properties → Advanced → Environment variables
Windows 7: Control Panel → System → Advanced system settings → Environment variables
Comment: Jenkins is sending url always with C:\Program Files (x86)\Git\bin\git.exe ls-remote so i can't use -Tv because of this ls-remote
Comment: @AndrianDurlestean the `-Tv` is just for you to test ssh with the ssh `-Tv`. But once this is working, you don't need `-Tv` in your `ls-remote`.
Comment: i get: no address associated with name
Comment: ssh://git@git.****.org:9999/ my connection is with port =( i saw in my tortoisegit
Comment: Can you try: `ssh -Tv git@git.****.org:9999` (no `ssh://` and no final `/`)?
Comment: sad same problem =(, if Im trying with no port i get msg port 22: Bad file number, but my git server is with port 9999
Comment: @AndrianDurlestean I have edited my answer to address git in an environment where TortoiseGit was already there.
Answer: Try using C:\Program Files (x86)\Git\cmd\gitk.cmd instead of \bin\git.exe. If not solved, then Here is information how to configure ssh. Sometimes you may also get public key error, which is solved here. If you want to generate new ssh keys, this article will help you.


Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Receiver () has no segue with identifier

Question: I've searched this problem extensively and none of the suggestions have worked for me.  I'm also very new at this so the problem could be something very basic.  I'm trying to create a segue from a table view controller to a view controller that has a table view on it.  When I run it in the simulator it crashes when I click on a cell and gives me this error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Receiver () has no segue with identifier.
Here's my code:
var conditions = [Condition]()

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    for Location in locations {
        for Condition in Location.conditions {
            conditions.append(Condition)
        }
    }
            let selectedCondition = conditions[indexPath.row]
            let destinationVC = TestTableViewController()
            destinationVC.condition = selectedCondition
            destinationVC.performSegueWithIdentifier("FirstSegue", sender: self)
}

I've tried deleting the app on the simulator, doing Product -> clean, renaming the storyboard, and I'm sure the segue is named correctly.
Thanks!
Answer: Instead of destinationVC.performSegueWithIdentifier:, you want to perform it on self: self.performSegueWithIdentifier, because it's the presenter who presents the destination, not the destination presenting itself.