Adding, removing or editing permissions of a user in SSRS 2008 is throwing error ""Response is not well-formed XML

Question: I am totally stumped by a really stubborn problem: When I try to take any action (add, remove, edit) in the Security tab of a report's Properties page on SSRS 2008 UI I get a generic error. All it says is this: Response is not well-formed XML.
Digging in the LogFiles folder at the SSRS installation root, I see this:

role assignment is not valid. The role assignment is either empty,
  specifies a user or group name that is already used in an existing
  role assignment for the current item, or specifies duplicate roles for
  the same user or group. ui!ReportManager_0-1!32c!07/23/2011-15:03:33::
  e ERROR: Response is not well-formed XML.
  ui!ReportManager_0-1!32c!07/23/2011-15:03:33:: e ERROR: HTTP status
  code --> 500
  -------Details-------- System.InvalidOperationException: Response is
  not well-formed XML. ---> System.Xml.XmlException: Unexpected end of
  file has occurred. The following elements are not closed: Message,
  detail, soap:Fault, soap:Body, soap:Envelope. Line 3, position 5470.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ThrowUnclosedElements()
at System.Xml.XmlTextReaderImpl.ParseElementContent()
at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)
at System.Xml.XmlLoader.ReadCurrentNode(XmlDocument doc, XmlReader
  reader)
at System.Xml.XmlDocument.ReadNode(XmlReader reader)
at
  System.Web.Services.Protocols.SoapHttpClientProtocol.ReadSoapException(XmlReader
  reader)
at
  System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage
  message, WebResponse response, Stream responseStream, Boolean
  asyncCall)
at
  System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String
  methodName, Object[] parameters)
--- End of inner exception stack trace ---
at
  System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String
  methodName, Object[] parameters)
at
  Microsoft.SqlServer.ReportingServices2005.ReportingService2005.SetPolicies(String
  Item, Policy[] Policies)
at
  Microsoft.SqlServer.ReportingServices2005.RSConnection.SetPolicies(String
  Item, Policy[] Policies)
at
  Microsoft.ReportingServices.UI.ImageTextButton.RaisePostBackEvent(String
  eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
  sourceControl, String eventArgument)
at System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  library!ReportServer_0-2!a14!07/23/2011-15:03:33:: Call to
  GetSystemPropertiesAction().
  ui!ReportManager_0-1!32c!07/23/2011-15:03:33:: e ERROR: Exception in
  ShowErrorPage: System.Threading.ThreadAbortException: Thread was being
  aborted.    at System.Threading.Thread.AbortInternal()    at
  System.Threading.Thread.Abort(Object stateInfo)    at
  System.Web.HttpResponse.End()    at
  Microsoft.ReportingServices.UI.ReportingPage.ShowErrorPage(String
  errMsg) at    at System.Threading.Thread.AbortInternal()    at
  System.Threading.Thread.Abort(Object stateInfo)    at
  System.Web.HttpResponse.End()    at
  Microsoft.ReportingServices.UI.ReportingPage.ShowErrorPage(String
  errMsg)

The databases  (ReportServer and ReportServerTempDB) came out clean when I ran DBCC CHECKDB.
This error is preventing me to do any of the following actions:
1. Use "Edit Item Security" for a report or folder
2. Delete a User name from the Home folder Security page
3. Add a new user using "New Role Assignment"
The really weird thing is that some of these 3 actions work in some report folders. There is nothing I can see common between the ones that work and those that don't.
Any ideas??
Comment: Almost certainly you should post the resolution as an answer below and mark it as accepted.
Comment: I didn't quite realize where the option to answer it myself was. But it was right below the post and comments! I just posted the Answer but I still can't figure out where to accept it as an answer.Thanks for suggesting :)
Answer: THIS ISSUE HAS BEEN RESOLVED!
Root cause: There was a user who was somehow added 3 times to four different roles under Home folder. Any sub folder using the same permissions as Home (inheritance) suffer the same consequences. Why should SSRS allow this in the first place or not flag it clearly in the error log is beyond me!
Resolution: Removed the duplicates for the user (2 of the 3 entries) on SSRS UI.
Lessons learned:
1. Read each error a few times BUT do not get carried away with the most flagrant error
2. Try and separate symptoms from causes (in this case the existence of duplicate IDs was the cause but in the error logs you will see whole bunch of language like "Unexpected end of file has occurred" that under the stressful circumstances could easily mislead and send you down a rabbit hole!
3. Take any suggestion you get with a pinch of salt but vet it properly
Answer: If possible, I would:

Export the reports from SRSS
Uninstall SRSS
Delete/rename the SRSS databases (backing up would be a good idea too)
Create a new SRSS instance
Add all reports again (manually if you can) and trying to configure preferences.
Comment: That is really not possible for us but I did restore the ReportServer and ReportServerTempDB databases on a new SQL Server and pointed a new SSRS instance to them but I got the same error still!
Comment: That would imply that your SSRS databases are corrupted which only makes my suggestion sit even better. Export the reports from the current instance, import them into a new instance and see if you experience the same problem - if not, it again confirms that your SSRS databases are in a foul state. Your only hope is to reinstall (read: blow away) that instance. Can I ask why its not really possible for you? SSRS isn't very highly integrated with anything and there isn't a lot to lose from reinstalling.


extundelete : How can i recover "recoverable inodes still lost"?

Question: I am using extundelete to recover about 9000 files that were deleted from an AWS EBS volume, accidentally via programmatic error.
The end of the report states
2864 recoverable inodes still lost.

Can anyone explain what this means, and how I can recover the unrecoverable using extundelete
Full shell output
NOTICE: Extended attributes are not restored.
Loading filesystem metadata ... 240 groups loaded.
Loading journal descriptors ... 30077 descriptors loaded.
Searching for recoverable inodes in directory /srv/www/mysite.com/photo-gallery ...
9000 recoverable inodes found.
Looking through the directory structure for deleted files ...
Unable to restore inode 330 (srv/www/mysite.com/photo-gallery/group56/myimage7.jpg): Space has been reallocated.
Unable to restore inode 1179649 (srv/www/mysite.com/photo-gallery/group189/myimage5.jpg): Space has been reallocated.
2864 recoverable inodes still lost.

Comment: I'd love to know what this "Recoverable inodes" thing means too.  The docs for extundelete are no help, nor is the man page.  If anyone could give an explanation as to what it means it would be most helpful.
Answer: From the author of extundelete:

I guess that it is not finding a way to link the inodes with a file name, in which case the --restore-all method is your best shot at getting your files back.

https://sourceforge.net/p/extundelete/mailman/message/30159985/
Based on your question, I would guess that you ran extundelete with --restore directory /srv/www/mysite.com/photo-gallery
If that's the case, then you would replace all of that with --restore-all, e.g.
sudo extundelete /dev/sda1 --restore-all

Although from my experience the output is deceptive because the files (inodes) that are still "lost" are for the whole partition and not just for the directory you specified, meaning that most of what it's able to restore has already been restored. But it doesn't hurt to try --restore-all since it may find some file fragments that it doesn't know the path for.


How to apply the output layer function in a neural network

Question: I am implementing a Neural Network in a somewhat different fashion. I train my neural network locally using a small subset, and export the weights.
My goal is to test the neural network in a distributed parallel programming solution using those exported weights. This means that I have to rebuild the NN topology.
My activation function for the Hidden layer is the logistic function:
$$\frac{1}{1+e^{\theta^TX}}$$
Where $\theta$ is the weight vector and $X$ is the input vector.
Once I calculate that for the hidden layer, I don't know how to proceed to the output layer. What is the next calculation/step that I have to implement?
P.S: my network dimensions are 255-75-1.
Comment: This question isn't answerable without know what activation you're using for the final layer.
Comment: That formula is the output for 1 hidden node. You have 75 of those at hand. Theta is different for each case. After that you plug that 75 outputs from the hidden layer to the same formula (assuming you have logistic at the output as well), again with a different theta vector.
Answer: If you are doing binary classification, the same exact logistic function you gave is an adequate choice for your output neuron. Just use the activation of the hidden layer as your "new $x$" instead. The value this final neuron will output should be interpreted as the probability of the input belonging or not to the class. If you have multiple classes you could instead use a softmax function, which is a generalization of the the logistic, that will output a vector with normalized probabilities for each class.


Unable to connect Express application with Redis container

Question: I have Redis running locally on Docker container. I am trying to connect my Express application with Redis container but unable to connect.
Below is my code:
redi.js
const redis = require('redis');

const redisCon = () => {

const client = redis.createClient('6379','127.0.0.1');

client.on('connect', function () {
    console.log('Connected!');
});

}

module.exports = redisCon;

server.js
const express = require('express');
const config = require("config");
const redisCon = require('./redi');

const app = express();

const port = process.env.PORT || 2222;

redisCon;

app.get('/', (req, res) => {
  res.send(`Current ip is ${ip}`);
});

app.listen(port, () => console.log(`Server is running at ${port}`));

What I am doing wrong in the above code?
Answer: The arguments you are giving .createClient are incorrect. Furthermore, and you are not connecting to Redis, just creating the client.
See the follow for some examples on how to create a client. And on how to connect that client to Redis:
import { createClient } from 'redis';

/* Create a Redis client that *will* connect
   to localhost on port 6379 in one of these ways */
const client = createClient();
const client = createClient({ url: 'redis://localhost:6379' });
const client = createClient({ socket: { host: '127.0.0.1', port: 6379 } });

/* log any errors */
client.on('error', (err) => console.log('Redis Client Error', err));

/* connect to Redis and wait for it to be established */
await client.connect();

There are a lot of arguments you can use when creating a client. You can read about them here.


Is a slight amount of fret buzz acceptable when lowering the action on a guitar

Question: I recently took my Ibanez RG into the shop for new strings (same gauge as original) and asked them to lower the action. It came back with a significant amount of fret buzz (pretty much all over the neck, regardless of pick attack).
When I asked the guitar tech about it, he said it's fine as long as you don't hear it through the amp.
I raised the action a bit myself and now it only buzzes slightly if you pick the strings quite hard. I play mostly lead and generally have a gentle picking attack.
Is either of the following considered a poorly setup string action:
a) The strings buzz quite consistently but not enough to be heard through an amp or,
b) The strings buzz only if you pick the string quite hard and you can bend the strings without any buzz or fretting out.
Is the goal when setting a low action to aim for 100% "buzz free" setup regardless of pick attack. Does it even matter? I assume too much buzzing would wear down the frets and also just make the guitar sound bad, even with distortion/overdrive.
Thanks
Comment: Read the answers to this [related question](http://music.stackexchange.com/questions/2598/what-is-the-downside-of-ultra-low-action). I'd say some light buzz is inevitable if you're going for the lowest action possible, but that's just an opinion.
Comment: If you've ever hear James Hetfield's guitar unplugged, you'll hear that fret buzz is _definitely_ acceptable.
Comment: I agree with you on James Hetfield's unplugged stuff :D
Comment: De gustibus non disputandum.  Set it where you like it.
Answer: The lower the fret action, the more buzz you will get. Your ideal height will be based on what you need. Unamplified, many of the really fast guitarists have fret buzz all over the neck.
Personally, I use a reasonably high action on most of my guitars (about 3mm at 12th fret) because I dislike buzz and have quite a hard picking action. I do have two guitars I use for speed and legato, and these are much lower. Unamplified they sound terrible, but once hooked up through my effect chain they sound great)
So there is no actual goal - if you asked the guitar tech to lower it as much as they could, they have probably aimed for the lowest they see as reasonable based on their experience with many guitars and guitarists. If you ask for less buzz / a higher action next time they will do that for you.
Comment: On one of my basses, the action is quite low to allow for fast playing, and the fret buzz actually adds a great sound to the top end. :D
Comment: Actually, Kyle, that is a sound I really like on some tracks - it seems to give a bit more body to the bass sound, sometimes.
Comment: Definitely agreed with that, if done right it can be a great thing.
Comment: I've never had any fret job on any guitar no matter how expensive be so perfect that all frets start buzzing at a certain action height and no frets buzz above that height. So another factor in determining "buzz tolerance" is how many frets/areas of the neck have to have buzz before your action is too low to tolerate. Again, it's a matter of taste, but if I wanted no buzz (in general) and had mild buzzing on a couple frets, I'd accept that as optimal action for my desired parameters.
Comment: @Kyle Same here, i have an Ibanez K5, the low action is what gives it the intended sound. Overall, it's really just preference of sound.
Comment: Thanks for this reply. I am going to mark this as the correct answer as it has the most up votes and is a nice summary of what others have posted. Thanks
Answer: Fret buzz isn't necessarily a sign of a poor setup, because some players want low action and can accept some fret buzz.  A guitar tech should discuss this with a player before doing a setup.
Having strings fret out when bending is more serious and I would expect a tech to make sure this isn't happening, unless a player said they don't do string bending and want the lowest possible action.  This is normally a problem only on necks with a small radius, like on vintage Telecaster necks.
Since the amount of string buzz also depends a lot on technique (like angle of pick attack), it's possible you're experiencing more buzz than your tech did.
Does fret buzz matter?  Yes, buzz will affect sustain and clarity. Also, I don't like it :-).  I doubt it affects fret wear, but that would be hard to measure.
Dan Erlewine's books on guitar setup and guitar repair go into lots of detail on fret buzz.  A lot of factors besides action affect buzz: neck relief, presence of loose frets, fret wear, string gauge, etc.
Comment: Buzz affects sustain only in the sense that it clamps the maximum initial volume you can get from the string. It doesn't actually constrain the decay length from there. It won't affect feedback-driven sustain, either. After the buzzy attack, the string stops buzzing and then it doesn't matter.
Answer:
The strings buzz quite consistently but not enough to be heard through an amp

Strings buzzing not only puts you off playing but it will prevent the string from resonating for as long and lower your tone quality.
In my opinion nobody should create fret buzz when you ask them to lower your action.
One thing you could try is a higher gauge string, but that will likely affect your playing more than the original action did.

The strings buzz only if you pick the string quite hard and you can bend the strings without any buzz or fretting out.

This sounds ideal for your playing style and what you wanted in your action.
Personally I prefer the action slightly further away from buzz range and compensate with picking technique.

Is the goal when setting a low action to aim for 100% "buzz free" setup regardless of pick attack. Does it even matter

Its always up to personal taste at the end of the day, but I think that is a good goal to aim for. I hate fret buzz and wouldn't take it over low action any day.
Does it matter? Again, up to you. To me it does.
Comment: Thanks Robbie, this is definitely sounds like a taste thing, but I do find that buzzing can affect the tone quite significantly. I will be playing the guitar through my amp later and listening to the tone. I may try to get the action as low as it will go without buzzing, or minimal buzzing.
Comment: It's worth nothing that I rarely play with distortion, so the natural tone is quite important to me
Answer: Fret buzz is not only not necessarily bad, but actually a part of the guitar tone. The guitar is partially a percussive instrument, and one percussive aspect of that (in addition to knocking or tapping on the body of an acoustic guitar or hollow-body electric) is the snap produced by string-on-fret action. Slap guitar technique in particular exploits this way of producing a sound. Aggressive "Rasgueado" strumming in Flamenco also exploits the percussive noise of strings hitting frets.

Is either of the following considered a poorly setup string action:
a) The strings buzz quite consistently but not enough to be heard through an amp or,
b) The strings buzz only if you pick the string quite hard and you can bend the strings without any buzz or fretting out.

These statements aren't wrong. The important thing is for the buzz to be approximately the same everywhere, hinted at by your (a). If you lower the action, and you get buzzing on all the frets at the same time in any given general area of the neck, across all strings, that indicates good setup.  How much buzz you allow is an artistic decision. There is an objective "too much", when you can't produce a tone at all.
Uneven buzz is bad, indicating that a fret is not properly seated, or there is uneven fret wear that requires leveling.
Regarding (b): whether you can bend a string without buzzing out depends a lot on the radius of the fingerboard. This is why "shred" guitars have flatter radii, and why the "compound radius" became popular in the 1980's, whereby the fingerboard is basically the section of a cone (tighter radius at the nut, wider at the body). With the compound radius, the guitar has some of the characteristics of a Fender Stratocaster for chording in the low positions, while allowing for bends with low action in the high positions.
The best fretboard shape for good bending with low action is infinite radius: perfectly flat. If the fretboard is flat and the frets are straight lines, then bending a note doesn't bring the string any closer to any fret, and so there is no onset of buzz.
Thus, what might be "too low" on one guitar can work great on another.


How do I match the string value only in tree-sitter?

Question: Given that I have the code below in JavaScript/Typescript:
findOne('testing', () => {
});

findLegacy('testing2', () => {
});

findOne('testing3', () => {
});

I want to match the string value only using a tree-sitter query.
Here's where I got to, it matches the whole string, including the quotes
(call_expression
  arguments: (arguments ((string)+ @desc))
)

Can I match testing and not 'testing'?
Answer: This is just not possible in tree-sitter


Can you give me a hint for the following?

Question: I am a first year uni student learning about linear transformations I encountered the following question if $$T^2=T$$ such that T is from V to V  proof or disproof that T is an Injective function  , what I understood is that  $$T^2$$ is a composition of T on T
secondly I deduced that t can be  the identity function since when applying the transformation twice its the same as applying it once  , it can also be the transformation to 0 such that I am getting zero no matter the input , so I concluded that the sentence is wrong but I am not sure how to deal with this formally , I tried writing something such as  $$T(v1)+T(v2)=T(v1)^2+T(v2)^2$$
$$T(v1)^2-T(v1)+T(v2)^2-T(v2)=0$$
$$ T(T(v1+v2))=T(T(v1))+T(T(v2))$$
I just could not  figure out how to continue
Comment: All you need is one non-injective example to prove that $T$ need not be injective.  As you remark, one of your examples is clearly non-injective (at least, assuming that $V$ has positive dimension).
Comment: but if I can't  think of a counterexample like I did , I would like to have some ability  to use the properties and reach a conclusion
Comment: non positive means 0D?
Comment: Proof by counterexample is a terrific method, when it works.  Here, well...as you have noticed, some $T$ that satisfy the properties are injective and others aren't. So you can't get a general proof that injectivity is impossible.
Comment: As a general rule for these things, try a simple case ($n=1$) first. A linear function in the scalar case is $T(x) = \alpha x$ for some scalar $\alpha$. If the equation is true for all $x$ then $\alpha^2 = \alpha$. Ask yourself if this means that $T$ necessarily injective.
Comment: Yes.  The vector space just containing $0$ is zero dimensional.  And in that case, all maps $V\to V$ are injective.  Obviously, a degenerate case.
Comment: If you want to prove something general, prove that $T^2=T$ implies that $T$ is a projection.  That is, prove that the image of $T$ is a subspace fixed by $T$.  Such a map, like coordinate projection, is clearly not injective in general.
Comment: oh I see this is really helpful,  can I suggest another  case and write my reasoning to get  some intuition?
Comment: Sure.  You can even post it as a solution to your question.  That way people here can comment on it and the site can close the question.
Comment: thanks I did not know about the feature I will try to now  ,
Answer: I tried to imagine 2 more scenarios and answer them to get a good intuition on the matter , I may be wrong and I would love nothing more than to be corrected ,
case 1: if $T(x)^2=0$ does $T(x)=0$ have to be zero as well ?,
I went and started with the thinking if there is a case where this is not true could not think of anything, I switched the formate for the case to $$T(T(x))=0 $$
I know that if T(x) is 0 then for certainT(T(x) is zero because  T(0) =0 from the properties of a linear transformation
now I tried to imagine the opposite I where T(x) is not zero and see what happens from there T(num)=num T(num)=0 this case can't always work so I deduced that the T(x) have to be 0
,
case2:
I tried to think of a question similar to the first if $$T(x)^2$$ is injective  does T(x) have to be injective  $$T(v1)^2=T(v1)^2$$ if $$v1=v2$$
$$T(T(v1))=T(T(v2)$$
I see it working for zero  and identity transformation for composition and since it can't be zero according to the condition above it have to be true?
Comment: Welcome to Mathematics Stack Exchange.  Consider $T=\pmatrix{0&0\\1&0}$
Comment: I.e., $T(x,y)=(y,0)$


"Data element too large" error when compiling+assembling with fpc (on OSX)

Question: How can I troubleshoot and fix a fatal Data element too large error when compiling and assembling with fpc (Free Pascal compiler) in a 64-bit Mac/OSX environment?
It seems that the cause of the error is probably an array[0..MaxInt] call (see below for more details), but if so, I don't to how to fix it or work around it.
Details: I'm getting that error when running the build.sh script from https://github.com/whatwg/wattsi using fpc 3.0.0-rc1 installed from ftp://freepascal.stack.nl/pub/fpc/beta/3.0.0-rc1/i386-macosx/ (from the pc-3.0.0rc1.intel-macosx.dmg image). (Note: The README.md file says I need to use 3.0.0-rc1 specifially—instead of, I guess, v2.6.4, the latest stable?).
The build runs fine until, after compiling the https://github.com/whatwg/wattsi/blob/master/src/html/htmlparser.pas source, it fails with that Data element too large error when trying to assemble that source.
Specifically, it logs this: htmlparser.pas(336,42) Error: Data element too large. And lines 333 to 336 of that htmlparser.pas file look like this:
type
    TBlob = Pointer;
    PBlobArray = ^TBlobArray;
    TBlobArray = array[0..MaxInt] of TBlob;

…so I suspect that Data element too large error is caused by it running into a system limit of some kind, due to the array[0..MaxInt]?
The extent of my troubleshooting attempts so far is that in the https://github.com/whatwg/wattsi/blob/master/src/lib/compile.sh file that gets sourced by the build, there's a line with ulimit -v 800000 which I thought could possibly be over-restricting the memory resources—so I  removed that line and re-ran the build script, but I still got the Data element too large error at exactly the same point.
Answer: More recent FPC's do a form of compiletime rangechecking. This rangechecking determines compiletime that the type is too big, even though it is never actually allocated (always used using pointers, older Delphi versions couldn't overindex pointers, so this construct was used)
That is a known limitation of the technique, and strictly the original source is buggy.
Since the type is probably never allocated simply readjust the bounderies to fit, e.g.
 TBlobArray = array[0..MaxInt div sizeof(tblob)] of TBlob;

(maybe subtract a few elements to be sure, I don't know if 2GB-2 is the real limit, IIRC old delphis had lower limits)
or even simply
 TBlobArray = array[0..0] of TBlob;

And disable runtime checks where you access it. The high upper bound is an artificial construct to not run into runtime checks
Answer: Try to change the DEFINES line in src/build.sh from
DEFINES="-dUSEROPES -dLINES -dPARSEERROR"
to
DEFINES="-dUSEROPES -dLINES -dPARSEERROR -Px86_64"
this is actually a fresh note added to the repo origin README.md
Comment: Thanks, I'm aware of the change to the readme—I'm actually the one who added it :-) I just haven't had time to post the explanation as an answer here myself but will try to make to do that right now.


evaluation of this logarithmic integrals

Question: what is the value $$ \int_{a}^{\infty} \frac{\log^{n}(x)}{x^{2}}\mathrm{d}x $$
'a' is a positive integer and so is 'n'
my gues with a change of variable $ x=e^{t} $ is that this integral would be related to the incomplete gamma function $$ \Gamma (n.\log(a)) $$
Comment: @Julián Aguirre. I am living next to you ! Un abrazo.
Comment: I am living next to you too ! Un abrazo.
Answer: Hint
Integrate by parts using $u=\log^n(x)$, $dv=\frac{dx}{x^2}$. You will arrive to a splendid recurrence relation.
I am sure that you can take from here.
Answer: Mathematica gave:
$$\int_{a}^{\infty} \frac{\log^{n}(x)}{x^{2}}\mathrm{d}x=\Gamma(n+1,\log(a))$$


storyboard?.instantiateViewController(withIdentifier: " ") as! viewcontroller

Question: I have as a Menu tableview in my custom navigation bar. If i click on one cell , it should take me to another view controller. But my app crashes when i click on it.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return menu_items.count  //It has 5 values
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")

    cell.textLabel?.text = menu_items[indexPath.row]
    cell.textLabel?.textColor = .white

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let item = menu_items[indexPath.row]

    if (item == "Patienten") {

         tableView.removeFromSuperview()

        let vc =  self.storyboard?.instantiateViewController(withIdentifier: "patientView") as! patientViewVC //App crashes here
        self.present(vc, animated: false, completion: nil)

    } else if (item == "Mitarbeiter") {

    } else if (item == "Kalender") {

    } else if (item == "Tourenplanung") {

       tableView.removeFromSuperview()

        let vc =  storyboard?.instantiateViewController(withIdentifier: "tour") as! tourVC //App crashes here
        self.present(vc, animated: false, completion: nil)

    }else if (item == "Abmelden") {

        let vc = self.storyboard?.instantiateViewController(withIdentifier: "loginvc") as! LoginVC  //App crashes here
        self.present(vc, animated: false, completion: nil)
    }

    let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
    selectedCell.contentView.backgroundColor = colorLightGreen

}

}
I have many times verified all Identifier names and view controller names are correct.
Comment: It crashes? What's the error message in the console? Are the `UIViewController` on the same storyboard as the current one?
Comment: are you sure you have  `patientViewVC` in same storyboard where tableview is ?
Comment: @Larme i don't see any error message in console , I see EXC_BAD_INSTRUCTION on that line .
Comment: @JonSnow yes, I have only one storyboard. And all view controllers are in same
Comment: could show us more the error message in console? there should be something.
Comment: @MuhammadFauziMasykur I get only `(lldb)` nothing else
Comment: Is the custom class set in storyboard Identity inspector to proper type for each scene?
Comment: check `self.storyboard` are you getting nil or not
Comment: @JonSnow yes I do get nil . Why is it so?
Comment: Probably the class you are calling it from is not instantiated from storyboard.
Comment: I'm not an expert in Swift, but `let vc = self.storyboard?.instantiateViewController(withIdentifier: "loginvc") as! LoginVC` That line is calling for a crash if `self.storyboard?.instantiateViewController(withIdentifier: "loginvc")` returns nil, or if it's not of the correct class, correct? Then, could you decompose these lines with an if let and check each case?
Comment: I am not aware about the actual reason may be @jonaszmclaren  is right  .Only one solution left is create Storyboard with name -> initiate with identifier and present it
Comment: @jonaszmclaren , its not true . all the classes are instantiated from storyboard.
Comment: If the class you are calling this code from is instantiated from storyboard, then `storyboard` cannot be nil.
Comment: A solution would be to manually instantiate UIStoryboard instance and it should work, but you should think why is `storyboard` nil.
Comment: Is there any other way to reach viewcontrollers mother than `self.storyboard?.instantiateViewController(withIdentifier: "")` ?
Comment: @swiftuser123 From where you are showing This view controller (TableView not patientViewVC) check there `self.storybaord`
Comment: `let storyBoard = UIStoryboard(name: "StoryboardName", bundle: nil)`
Comment: `self.storyboad` gets current storyboard, provided that current view controller is instantiated from storyboard. The code from @JonSnow is another way of getting a storyboard instance, but as I said, something is not right here.
Answer: Make sure you load a correct storyboard before instantiating the viewController.
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let item = menu_items[indexPath.row]

    if (item == "Patienten") {
        tableView.removeFromSuperview()

        let storyBoard = UIStoryboard(name: "StoryboardName", bundle: nil)
        let vc =  storyBoard.instantiateViewController(withIdentifier: "patientView") as! patientViewVC
        self.present(vc, animated: false, completion: nil)

    } else if (item == "Mitarbeiter") {

    } else if (item == "Kalender") {

    } else if (item == "Tourenplanung") {

        tableView.removeFromSuperview()
        let storyBoard = UIStoryboard(name: "StoryboardName", bundle: nil)
        let vc =  storyBoard.instantiateViewController(withIdentifier: "tour") as! tourVC //App crashes here
        self.present(vc, animated: false, completion: nil)

    }else if (item == "Abmelden") {
        let storyBoard = UIStoryboard(name: "StoryboardName", bundle: nil)
        let vc = storyBoard.instantiateViewController(withIdentifier: "loginvc") as! LoginVC  //App crashes here
        self.present(vc, animated: false, completion: nil)
    }

    let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
    selectedCell.contentView.backgroundColor = colorLightGreen

}

StoryboardName above is the name of the storyboard that contains the patientViewVC, tourVC, LoginVC
Comment: Wow, You saved me!  `let storyBoard = UIStoryboard(name: "StoryboardName", bundle: nil)`  works like charm!
Comment: @swiftuser123 : Always welcome buddy :) Happy coding
Answer: A view controller in storyboard needs to have a custom class set in Identity inspector:

Then you can cast it to desired type. If all the view controllers are in the same storyboard, you can instantiate them with storyboard property of self. If they are in different storyboard, you have to instantiate UIStoryboard instance with corresponding name and use it.
Btw, why are you calling tableView.removeFromSuperview() after cell selection?


Given the ranks of $Q$ and $QP$, how to find the rank of $P$?

Question: Let $P$ and $Q$ be two real matrices of size $4\times6$ and $5\times4$, respectively . If $\operatorname{rank} Q = 4$ and $\operatorname{rank} QP = 2$, what is the rank of $P$?
Answer: Hint:
By Sylvester's rank inequality,
$$\operatorname{rank}(P)+\operatorname{rank}(Q)-4 \leq \operatorname{rank}(QP)$$
which implies that
$$\operatorname{rank}(P) \leq \operatorname{rank}(QP)=2$$
Can you find a lower bound for $\operatorname{rank}(P)$?
Comment: @user1551 The second line comes from the first line. Did I make a mistake?
Comment: Oh, I see what you meant now. I thought you were quoting two separate inequalities.
Comment: @user1551 Thanks for checking. Let's hope OP can figure out the lower bound. =)
Comment: Can we do this : Since rank Q = 4,where Q is a 5*4 matrix , then rank QP = rank P and so rank P = 2...but here shouldn't Q be non singular,which is not possible as Q is not a square matrix ?
Comment: Yes, it is due to $Q$ has full column rank, hence $rank(QP)=rank(P)$. you are right that $Q$ can't be non singular as it is not a square matrix.
Comment: Please note that when you are writing an operation on an argument, say rank(P), when formatting in Mathjax, please use `\operatorname{rank}(P)` with renders as follows: $\operatorname{rank}(P)$ which is much more appropriate than `rank(P)`: $rank P$.
Comment: Thank you for the tips!


Terminal-based Python editor like IPython Notebook

Question: Is there anything like IPython Notebook that operates 100% in a terminal window? I would like to be able to see and edit Python code blocks, navigate between the code blocks, execute individual code blocks at will, and have output from the code blocks displayed just below each code block. Obviously stuff like %matplotlib inline couldn't be supported. Ideally I would be able to open a functional *.ipynb file with this program and work with it in the terminal window, but I would still be happy if it had a different extension that isn't compatible with IPython Notebook.
I'm interested in this because I like the IPython Notebook concept, but it can be slow when using it interactively on a remote server.
Comment: Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Comment: What about the IPython QtConsole?
Comment: @ρss OK, thanks for letting me know. In the future, where would you recommend I go to ask for software or library recommendations then?
Comment: @Jim I didn't know about IPython QtConsole, so thanks for bringing that up, but from a quick glance it doesn't look quite like what I want. Pretty much any GUI I use while SSH-ing into a remote machine lags a bit, including QtConsole. More importantly, it doesn't look like I can edit and re-execute previous code blocks.
Comment: @BenLindsay You can edit and re-execute by pressing the up and down arrows. Either way the only other viable solution is the plain ol' IPython interactive shell which offers less capabilities than the gui and web options but runs through the command line.
Answer: It doesn't appear that there is anything precisely fitting your requirements. However, the Python mode of emacs fit most of your requirements, I routinely use this to develop and debug Python on a remote server.
Another option may be to use the Remote features of PyDev if you're an Eclipse user. This is described further in another question:
Creating a remote project with PyDev
Comment: Thanks for the suggestions. I'm a Vim user, so my solution will probably be to try to get Vim configured as a good Python IDE. I see a lot of posts that make it look doable.
Comment: If you are doing a lot of remote work you may find tmux useful, in addition to the pudb debugger (full screen terminal).  Your only problem may be viewing matplotlib output but you could redirect it to a secured web-accessible directory.
Comment: I think I'll start trying out emacs as an IDE. I've heard good things about it elsewhere.


exam problem on continuity

Question: 1) Let $f: \mathbb{R}\rightarrow \mathbb{R}$ be a continuous function such that $f(r+1/n)=f(r)$ for any rational number $r$ and positive integer $n$. Prove that $f$ is constant.
2) Let $f: \mathbb{R}\rightarrow \mathbb{R}$ be a continuous periodic function of period $1.$  Show that there exist $x_0 \in \mathbb{R}$ such that $f(x_0 +\pi )=f(x_0)$
For 1) I consider $g(x)=f(x+1/n)-f(x)$. Then $g(r)=0$ for every rational $r$ and this imply $g(x)=0$ for every $x$, follows from the continuity of $g$. so we have $f(x+1/n)=f(x)$ for every $x$ and for every $n$. so $f$ is constant.
For 2) I tried with considering the function $g(x)=f(x +\pi)-f(x)$ and try to use Balzano theorem but I failed.
Please verify for the proof of (1) and help me on solving problem (2). thanks
Answer: Your proof for (1) looks correct in principle, though a simpler way of putting it would just to be note that the conditions imply that $f$ is a constant function when restricted to the rationals, and continuity means that it is also constant over the reals.
For (2), we can find integers $n$ such that $n\pi$ is arbitrarily close to an integer, and therefore (because $f$ is continuous) such that $f(x + n\pi) - f(x) = \sum_{k=0}^{n-1} g(x + k\pi)$ is arbitrarily close to zero, which is impossible if $g$ is uniformly positive or uniformly negative. The continuity of $g$ and the Intermediate Value Theorem prove the rest.
Comment: I have some problem on understanding the hint of problem 2. Can u elaborate little more?
Comment: where you use the condition that the function have period $1.$
Comment: If $f$ is continuous with period 1, $n$ is an integer, and $\epsilon$ is small, then $f(x+n+\epsilon)  - f(x) = f(x + \epsilon) - f(x)$ is also small.
Comment: @ Connor Harris, Ok but how can I call $\pi $ to the picture?

exam problem on continuity


Jazz vs Classical interpretation of this V7c vs iv-m6 chord in a common chord progress?

Question: Here is a progression in a song I am playing

On the 3rd beat of the second measure there is a Dm6 or G9/D chord (or B half diminished first inversion): at least that's what Carl Kress is playing there. I usually hear the 3rd inversion V chord there (E7/D here) in this type of progression, at least in more classical style pieces, but I have often seen this substitution or other substitutions when the bass note reaches the 4th of the scale.
I guess other options would be D diminished or D major.
Here are my questions:

Is this a common enough thing that there is a standard analysis of this chord?

What is the best name for this chord?

What would be other common substitutions when you have this basic baseline and pattern.

As I understand it, this progression is a substitution for simply play 4 bars of A, and the soloist in this song is certainly treating these bars that way.
I'm thinking that I could look at this as an E7 with upper extensions, so this chord being
E plus D-B-F-A
this could be a E11b9 or something as well.
Here is a version of the score with my playing my version: Bart on Musescore
Comment: Is the E7/D in parentheses on your sheet added by you? That chord has different notes and sound in this passage than a Dm6 and IMO makes the progression less interesting than the Dm6,  just I V I V etc. with a moving bass line.
Comment: I am using a transcription, there is no sheet music. It sounds like Kress was playing the Dm6, but as I mentioned, I think fundamentally the chord is just 4 Bars of A. I added the E7/B because George M Smith has a lot of exercises that go like that, so it helps me remember what is happening there.
Answer: Although you already accepted an answer I have thoughts on this. I listened to the original recording. The E7/B chords are not that but actually Bm chords thus this is a progression and not all A. It is a partially diatonic walk up and back down from A to Dm6. In answer to your numbered questions:

iv (or IVm6) is a common non-diatonic chord used in major keys and comes from borrowing the iv chord from Am, the parallel minor.

It's simply a Dm6.

The E7/B you mentioned would work as a substitution for the Bm since there is no clash with the F# E's in the melody there.

You're right on as far as melodically it is a simple melody in A major. Since they don't play an F# melody note against the Dm6 it works great.
It's a fantastic recording, thanks for asking and sharing.
Comment: Thanks for this answer. Knowing Kress's playing style somewhat from "Master's of the Plectrum Guitar" and listening to him a lot, there is a good chance that the E7/B is E9/B voiced as B-G#-D-F#, which is very close to a Bminor chord. Kress also probably played something hipper than A/C#, but A-E7/B-A/C#/E/D was very common at the time, and you can hear Kress play something similar in Gb on "Pickin' My Way" at the "Trio" part. I wish I could accept both answer!
Answer: The observation that the entire passage is, in effect, a prolonged A chord, is accurate, and that would be the broad "classical" interpretation. The E chords and D (or B) are functioning as prolongational chords rather serving dominant or pre-dominant functions, respectively.
At that level, one could substitute any chord that can serve a "prolonging" function: A tritone sub for A (Eb); any chord rooted by B, D, or E; even a C# minor or F# minor chord could work, since they share two notes in common with the A chord; a bII chord (Bb) might be a possibility.
Appropriate substitutions — perhaps with extensions or alterations to accommodate the overall A major sound — would depend on context and, when improvising, sufficient understanding (explicit or implicit) between the ensemble members.
See also Tritone substitution to a major chord?


Qual a forma correta de declarar um encadeamento de métodos e impedir que um mesmo método seja usado fora de escopo?

Question: Nas minhas últimas perguntas estava criando alguns métodos para automatizar algumas consultas. Está legal, mas agora preciso controlar o acesso aos métodos especificando uma sequência.
Ao usar o método Select(), eu não posso ter acesso à ele novamente. Após o método Where() eu não posso ter acesso aos métodos LeftJoin() e InnerJoin(). Isso até que se chegue definitivamente ao método ToList();
Minha classe funcionará criando comandos sql´s de forma encadeada como o Linq to Lambda.
Assim:
var pessoas = pessoaDAO.Select()
    .LeftJoin(x => x.Telefones, (telefones, pessoa) => telefones.PessoaId == pessoa.Id)
    .Where(x => x.Ativo)
    .OrderBy(x => x.Nome)
    .ToList();

Seria errado permitir isso:
var pessoas = pessoaDAO
    .Select(x =>
        x.Id,
        x => x.Pessoa,
        x => x.Ativo,
        x => x.Telefones)
    .Where(x => x.Ativo)
    .Select()
    .ToList();

Ou seja, um Select() após um Where() e até mesmo um Select() já ter sido chamado.
Para resolver essa questão, estou tentando separar os métodos por interface. Assim:
public interface IQueryBuilder<TModel> : ICustomQueryBuilder<TModel>
    where TModel : class
{
    ICustomQueryBuilder<TModel> Select();
    ICustomQueryBuilder<TModel> Select(params Expression<Func<TModel, object>>[] members);
}

public interface ICustomQueryBuilder<TModel> :
    IQueryBuilderJoin<TModel>,
    IQueryBuilderFilter<TModel>,
    IQueryBuilderOrder<TModel>,
    IQueryBuilderExecute<TModel>
    where TModel : class
{
}

IQueryBuilder que será a interface usada para implementar minha classe herda de ICustomQueryBuilder, e os métodos Select() devolvem o tipo ICustomQueryBuilder para que então eu não possa ter acesso ao método Select() novamente.
IQueryBuilder herda de ICustomQueryBuilder e esta das demais interfaces porque preciso ter um tipo implementado na classe para fazer o retorno.
Já, ICustomQueryBuilder herda de:
public interface IQueryBuilderJoin<TModel> :
    IQueryBuilderFilter<TModel>,
    IQueryBuilderOrder<TModel>,
    IQueryBuilderExecute<TModel>
    where TModel : class
{
    IQueryBuilderJoin<TModel> LeftJoin<TMemberJoin>(
        Expression<Func<TModel, TMemberJoin>> member,
        Expression<Func<TMemberJoin, TModel, bool>> filter);

    IQueryBuilderJoin<TModel> LeftJoin<TMemberJoin>(
        Expression<Func<TModel, IEnumerable<TMemberJoin>>> member,
        Expression<Func<TMemberJoin, TModel, bool>> filter);

    IQueryBuilderJoin<TModel> InnerJoin<TMemberJoin>(
        Expression<Func<TModel, TMemberJoin>> member,
        Expression<Func<TMemberJoin, TModel, bool>> filter);

    IQueryBuilderJoin<TModel> InnerJoin<TMemberJoin>(
        Expression<Func<TModel, IEnumerable<TMemberJoin>>> member,
        Expression<Func<TMemberJoin, TModel, bool>> filter);
}

Em sequência de:
public interface IQueryBuilderFilter<TModel> : IQueryBuilderOrder<TModel>
    where TModel : class
{
    IQueryBuilderFilter<TModel> Where(Expression<Func<TModel, bool>> filter);
}

public interface IQueryBuilderOrder<TModel> : IQueryBuilderExecute<TModel>
    where TModel : class
{
    IQueryBuilderOrder<TModel> OrderBy(params Expression<Func<TModel, object>>[] members);
    IQueryBuilderOrder<TModel> OrderByDesc(params Expression<Func<TModel, object>>[] members);
}

public interface IQueryBuilderExecute<TModel>
    where TModel : class
{
    List<TModel> ToList();
}

Por fim, teria:
public class QueryBuilder<TModel> : IQueryBuilder<TModel>
    where TModel : class
{
   // ... implementações
}

É correto fazer esse tipo de implementação?
Para ilustrar melhor a necessidade do retorno, exemplo:
public class PessoaDAO : GenericDAO<Pessoa>
{
    // ... outros métodos

    public IQueryBuilderFilter<Pessoa> Where(Expression<Func<TModel, bool>> filter)
    {
       // ... implementações
       return this;
    }

    // ... outros métodos
}

Ou seja, isso é necessário para o encadeamento dos métodos e o tipo deve ser um tipo já implementado, caso contrário o cast automático não será aceito.
Comment: A segregação de interfaces é uma boa prática de modelagem OO. Aplicar isso na construção de DSL é muito interessante. Vários frameworks usam a técnica e eu mesmo usei algumas vezes. Dependendo da complexidade da solução é interessante fazer um diagrama de estados para ilustrar o comportamento. Com cada estado representando uma interface você poderá deixar bem claro através de setas quais os métodos que continuam na mesma interface (estado) e quais causam a transição para um novo estado sem volta. Também poderá ver nisso se o código atende tudo o que precisa e se está coerente.
Answer: É correto fazer esse tipo de implementação?
Do ponto de vista apenas do objetivo da implementação, sim. Aliás, eu diria que esta é a forma performática (elegante) de permitir ou não o encadeamento dos métodos.
Entretanto, considero que essa organização possa caracterizar uma perda de funcionalidade. Não há nada de errado em permitir um OrderBy() depois de um Where(), ou um Where() depois de um Select(). Entendo que a normatização serve para deixar o conjunto dos métodos de extensão o mais parecido com uma linguagem SQL ANSI, mas a ideia dos métodos de extensão não é se aproximar do SQL: a ideia é trabalhar com a manipulação agnóstica de conjuntos.
Comment: OrderBy() depois de um Where(), ou um Where() depois de um Select(), ok. Mas eu apresentei um Select().Where().Select().. isso que disse não ser legal. Obrigado!
Comment: @user18098 Por que? Não é SQL.
Comment: Não é SQL mas é para criar. Só para o que quero acho não ser interessante.
Comment: Obrigado! Até...


Where can the automatic set of a proxy_variable be located?

Question: I'm logging in as root, remotely, via SSH to a computer at work. The computer has set the http_proxy variable, which I need to unset every time I log in, as the proxy server does not exist anymore. However I can't find where the variable is being set. The .bashrc for the root user is basically empty and there is nothing in the /etc/profile. So any ideas? The system is a Debian stretch distribution.
Answer: Quick solution: put an unset in your .bashrc
Solution: Try 'grep'ing http_proxy in /etc/profile.d/ and the rest of /etc if not found. They comment it out or edit as you wish
Comment: Grepping did not work. I'm going the temporary solution. Thanks


Adding price values in webform with Twig

Question: I'm using Drupal 10.2.4 with webform 6.2.2
I have a content type extras with a field_prix
langcode: fr
status: true
dependencies:
  config:
    - field.storage.node.field_prix
    - node.type.extras
id: node.extras.field_prix
field_name: field_prix
entity_type: node
bundle: extras
label: Prix
description: ''
required: true
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  min: null
  max: null
  prefix: ''
  suffix: €
field_type: decimal

i have a form with 2 fields :
--extras for the end user to select the extras he wishes
--prix_extras to add up the prices of the selected extras with a calculated twig
    extras:
  '#type': entity_checkboxes
  '#title': 'Extras :'
  '#title_display': before
  '#target_type': node
  '#selection_handler': 'default:node'
  '#selection_settings':
    target_bundles:
      extras: extras
    sort:
      field: title
      direction: ASC
prix_extras:
  '#type': computed_twig
  '#title': 'Montant des Extras : '
  '#title_display': before
  '#template': |
    {# Initialize total price variable #}
    {% set total_price = 0 %}

    {# Get the raw price values of selected extras using webform_token() #}
    {% set raw_prix_extras = webform_token('[webform_submission:values:extras:entity:field_prix]', webform_submission, [], options) %}

    raw_prix_extras {{ raw_prix_extras }}

    {# Check if raw prices of extras are not empty #}
    {% if raw_prix_extras is not empty %}
        {# Remove the currency symbol '€' and trim raw prices #}
        {% set cleaned_prices = raw_prix_extras|replace({'€': ''})|trim %}
        cleaned_prices {{ cleaned_prices }}

        {# Split cleaned prices into an array #}
        {% set prices_array = cleaned_prices|split(',') %}
        prices_array {{ prices_array }}

        {# Loop through prices array to sum up the total price #}
        {% for price in prices_array %}
            {% set total_price = total_price + price|replace({' ': ''})|number_format(0, '.', '') %}
        {% endfor %}
    {% endif %}

    total_price {{ total_price }} €
  '#whitespace': spaceless
  '#store': true
  '#ajax': true

I have 2 extras : A = 20€ and B = 10€
If i select one or the other it returns the right price
If i select both it retuns only the price of A
how to you get calculated twig to loop through the extras and add up the prices of each ?
Answer: It seems that the issue lies in the way the prices are added to the total_price variable. The prices are being concatenated as strings rather than being summed up as numbers. To correct this, we need to ensure that the prices are converted to numbers before adding them to total_price.
{# Initialize total price variable #}
{% set total_price = 0 %}

{# Get the raw price values of selected extras using webform_token() #}
{% set raw_prix_extras = webform_token('[webform_submission:values:extras:entity:field_prix]', webform_submission, [], options) %}

raw_prix_extras {{ raw_prix_extras }}

{# Check if raw prices of extras are not empty #}
{% if raw_prix_extras is not empty %}
    {# Remove the currency symbol '€' and trim raw prices #}
    {% set cleaned_prices = raw_prix_extras|replace({'€': ''})|trim %}
    cleaned_prices {{ cleaned_prices }}

    {# Split cleaned prices into an array #}
    {% set prices_array = cleaned_prices|split(',') %}
    prices_array {{ prices_array }}

    {# Loop through prices array to sum up the total price #}
    {% for price in prices_array %}
        {% set total_price = total_price + price|float %}
    {% endfor %}
{% endif %}

total_price {{ total_price }} €
{# Initialize total price variable #}
{% set total_price = 0 %}

{# Get the raw price values of selected extras using webform_token() #}
{% set raw_prix_extras = webform_token('[webform_submission:values:extras:entity:field_prix]', webform_submission, [], options) %}

raw_prix_extras {{ raw_prix_extras }}

{# Check if raw prices of extras are not empty #}
{% if raw_prix_extras is not empty %}
    {# Remove the currency symbol '€' and trim raw prices #}
    {% set cleaned_prices = raw_prix_extras|replace({'€': ''})|trim %}
    cleaned_prices {{ cleaned_prices }}

    {# Split cleaned prices into an array #}
    {% set prices_array = cleaned_prices|split(',') %}
    prices_array {{ prices_array }}

    {# Loop through prices array to sum up the total price #}
    {% for price in prices_array %}
        {% set total_price = total_price + price|float %}
    {% endfor %}
{% endif %}

total_price {{ total_price }} €

In this adjusted code, price|float ensures that each price is treated as a float (number) before being added to total_price. This should correctly sum up the prices as numbers.
let me know
Comment: it doesnot work. the array stays empty. it does not return multiple values. Only the 1st select item in the list....


Trouble inserting html form data into phpmyadmin database

Question: I'm having trouble inserting form data into my database. It connects successfully to the database, but the data just doesn't get inserted into my MySQL database. Hope you can help! Thank you in advance!
This is the form code:
<form id="score" method="post" action="process.php">
 <fieldset>

    <legend>Your details</legend>

            Name
            <input id=name name=name type=text placeholder="First and last name" required autofocus>

            Email
            <input id=email name=email type=email placeholder="firstname.lastname@example.com" required>

            Phone (country code if overseas)
            <input id=phone name=phone type=tel placeholder="Eg. +447500000000" required>

</fieldset>
<fieldset style="border: none;">
    <button type=submit>Continue</button>
</fieldset>
</form>

This is the php code (filename process.php):
<?php
if( $_POST )
{
$con = mysql_connect("localhost","database_user","password");

if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("database_name", $con);

$insert_query = "insert into feedback(
                name,
                phone,
                email
                    ) values (
            ".$_POST['name'].",
            ".$_POST['phone'].",
            ".$_POST['email'].")";

($insert_query);

echo "
Thank you for your feedback!
";

mysql_close($con);
}
?>

Comment: ***NOTE:*** You should avoid the `mysql_*` api as it is depreciated. You should instead be looking at implementing your code with [**`PDO`**](http://www.php.net//manual/en/book.pdo.php) or [**`MySQLi`**](http://www.php.net//manual/en/book.mysqli.php)
Comment: Also, if you are using this code in production it is a good practice to filter the data which user has posted. Use mysql_real_escape_string function. before putting it in a query.
Comment: mysql_query($insert_query)
Comment: thanks for the tip! will use it. :)
Answer: You have missed mysql_query function :
Use this way:
$retval = mysql_query( $insert_query, $con );
if(! $retval )
{
  die('Could not enter data: ' . mysql_error());
}

Reference link
Answer: Try this way:
<?php
if( $_POST )
{
$con = mysql_connect("localhost","database_user","password");

if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("database_name", $con);

$insert_query = "insert into feedback(
                name,
                phone,
                email
                    ) values (
            '".$_POST['name']."',
            '".$_POST['phone']."',
            '".$_POST['email']."')";

mysql_query($insert_query);

echo "
Thank you for your feedback!
";

mysql_close($con);
}
?>

mysql_query() Is missing.
Also close the query variables with ''. Since they're strings you need to have them with that or else will fail.
Cheers
Comment: this really worked! thank you Daniel! you sure took my panic away lol. i wish there was a way to repay this awesome help!
Comment: No problem m8 ;) anytime
Answer: mysql_query() is missing. Replace
($insert_query);

with
mysql_query($insert_query);

Comment: thanks for bothering to reply! will remember the tip! :)


disable select no cakephp

Question: Tenho 2 selects, e quero fazer com que quando um dos select estiver com uma opção diferente de vazio, o outro select entre em disable.
Segue meu código:

<form method="get" action="/financeiro/gerar_relatorios">

FILTRAR COMISSÕES POR PERÍODO

                <?= $this->Form->input('data_inicio', array('class' => 'form-control mask_date','value'=> @$_GET['data']['data_inicio'])); ?>

                <?= $this->Form->input('data_fim', array('class' => 'form-control mask_date','value'=> @$_GET['data']['data_fim'])); ?>

                 <?= $this->Form->input('colaborador_id', array('class' => 'form-control','empty'=>'Filtrar todos colaboradores','value'=> @$_GET['data']['colaborador_id'])); ?>

                 <?= $this->Form->input('agente_id', array('class' => 'form-control','empty'=>'Filtrar todos agentes','value'=> @$_GET['data']['agente_id'])); ?>

                 <?= $this->Form->input('compra', array('class' => 'form-control','placeholder' => 'Filtre pelo número da compra','value'=> @$_GET['data']['compra'])); ?>

        <?= $this->Form->submit('Filtrar', array('class' => 'btn btn-info')); ?>

</form>

A minha dúvida é, como instanciar essa função js no select?
Answer: Tente da seguinte maneira:
<?= $this->Form->input('compra',
                    array('class' => 'form-control',
                          'placeholder' => 'Filtre pelo número da compra',
                          'value' => @$_GET['data']['compra'],
                          'onchange' => "handleSelect(this);")
                   ); ?>

Comment: Fiz desta maneira, mas quando seleciono a opção que o value é 30, o select `agente_id`, continua habilitado.
Comment: ok, mas ele está entrando na função do handleSelect ? caso esteja veja o que vem no this.value e poste aqui
Comment: estou tentando debugar no fireBug, mas no console não mostra nada.
Comment: coloque um console.log dentro da função antes da condição
Comment: desta maneira?
`        function handleSelect() {
          console.log(this);
          if (this.value == '30') {
          document.getElementById('agente_id').disabled = true;
     }
 }`
Comment: @MichelHenriq isso, só pra ver se está ta entrando na função, se estiver entrando e me dê o retorno
Comment: No console não aparece nada, e eu deixei o outro select disabled, e eu seleciono a opção que tem o value 30, e o select não sai do disabled..
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/29671/discussion-between-thiago-friedman-and-michel-henriq).

disable select no cakephp


attempt to index local 'rkgdat' (a nil value)

Question: fala pessoal, estou tentando gravar algumas informações em um .json mas estou recebendo este erro:
data.lua:12: attempt to index local 'rkgdat' (a nil value)
local triggers = {
''
}

local action = function(msg)

local rkgdat = load_data('data/ranking/' .. msg.chat.id .. '.json')

if not rkgdat[msg.from.id] then
rkgdat[msg.from.id] = {
    ['primeiro_nome'] = msg.from.first_name .. ' (' .. msg.from.id ..  ')',
    ['mensagens']     = 1
}

save_data('data/ranking/' .. msg.chat.id .. '.json', rkgdat)
else
rkgdat[msg.from.id] = {
    ['primeiro_nome'] = msg.from.first_name .. ' (' .. msg.from.id ..     ')',
    ['mensagens']     = rkgdat[msg.from.id]['mensagens'] + 1
}

save_data('data/ranking/' .. msg.chat.id .. '.json', rkgdat)
end

return true

end

return {
action = action,
triggers = triggers,
}

Função carregada de outro arquivo
load_data = function(filename)

local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)

return data

end

save_data = function(filename, data)

local s = JSON.encode(data)
local f = io.open(filename, 'w')
if file==nil then
print("Couldn't open file: "..f)
else
f:write(s)
f:close()
end
end

https://core.telegram.org/bots/api
http://www.lua.org/pil/21.2.html
Answer: A função "load_data" falhou, e a variável "rkgdat" foi inicializada com nil.
Você precisa colocar um teste logo após "load_data":
local rkgdat = load_data('data/ranking/' .. msg.chat.id .. '.json')

if not rkgdat then
   return false
end

if not rkgdat[msg.from.id] then
  -- etc

Analisando a lógica de "load_data", provavelmente foi "JSON.decode" que falhou, portanto você precisa também colocar um teste de nil logo após chamar "JSON.decode":
local data = JSON.decode(s)
if not data then data = {} end
return data

Comment: Opa valeu amigo, Resolvido !


how to delete {} but keep the dictionary value

Question: I tried to learn about dictionaries and sets today but I don't know how to use join properly.
brandin = []
for x in range(int(input("New brand total: "))):
    brand = input("Brand Name: ")
    brandin.append(brand)

brandinset = set(brandin)
print("list: ", ', '.join(brandin))
print("set: ", ', '.join(brandinset))

brandtotal = {}
for brand in brandin:
    if brand in brandtotal:
        brandtotal[brand] += 1
    else:
        brandtotal[brand] = 1

print((brandtotal))

and heres the output:
New brand total: 7
Brand Name: nike
Brand Name: adidas
Brand Name: nike
Brand Name: vans
Brand Name: adidas
Brand Name: nb
Brand Name: puma
list:  nike, adidas, nike, vans, adidas, nb, puma
set:  nike, vans, puma, nb, adidas
{'nike': 2, 'adidas': 2, 'vans': 1, 'nb': 1, 'puma': 1}

How do I make {'nike': 2, 'adidas': 2, 'vans': 1, 'nb': 1, 'puma': 1}
become like nike: 2, adidas: 2, vans: 1, nb: 1, puma: 1
I tried to use join but it deleted the value.
Comment: One option: `print(','.join(f"{key}: {value}" for key,value in brandtotal.items()))`
Comment: @JohnnyMopp thank you!!!! btw what the f does there??
Comment: It's an [f-string](https://www.python.org/dev/peps/pep-0498/). A simpler way to format strings. You could also use `format()` or string concatenation but I prefer f-strings.
Comment: Addendum to @JohnnyMopp's comment (that really seems like it should be an answer): If you're just `print`ing it, and don't need the complete string to exist in memory, you could do: `print(*(f"{k}: {v}" for k, v in brandtotal.items()), sep=', ')` and let `print` handle printing the individual items and inserting the separator on your behalf.
Answer: You need to use join() :
brandtotal = {'nike': 2, 'adidas': 2, 'vans': 1, 'nb': 1, 'puma': 1}
', '.join(k+': '+str(brandtotal[k]) for k in brandtotal.keys())

The output is this string:
'nike: 2, adidas: 2, vans: 1, nb: 1, puma: 1'

Comment: Rather than repeated string concatenation (which is both harder to read and asymptotically slower), I'd suggest using f-strings or `str.format`. I'd also suggest iterating over `.items()` to avoid unnecessary lookups of each key, ending with the faster/simpler: `', '.join(f'{k}: {v}' for k, v in brandtotal.items())`.


Finding inner product and expression for norm

Question: We define the functions, $f_n$, $n=0,1,2,3,...,$ on $[-1,1]$ by
$$f_n(x)=x^n$$
Then I have to find the inner product for $\langle f_n,f_m \rangle$  for all values of $n, m$ and I have in particular, to show that:
$$||f_n||=(n+\frac{1}{2})^{-\frac{1}{2}}$$
But I'm not sure how to do that? I'm confused, what is m? I think to show the norm I have to use $||f_n||=\sqrt{\langle f_n|f_n\rangle}$ ? But how do I find the inner product and use it finding the norm? I hope anyone can help me?
Answer: Assuming you are using the standard $L^2$-inner product $\langle f, g\rangle = \int_{-1}^1 f(x)g(x)\, dx$, we have that
\begin{align*}
\|f_n\|^2 = \langle f_n, f_n\rangle = \int_{-1}^1 x^{2n}\, dx = \frac{x^{2n + 1}}{2n + 1}\bigg|_{-1}^1 = \frac{2}{2n + 1} = \frac{1}{(n + 1/2)}.
\end{align*}
Comment: @Lifeni It is exactly what you written down. You would then have to analyse different cases of $n$ and $m$. Since $n, m$ are both nonnegative, there is only two cases to consider: $n + m$ odd or $n + m$ even.
Comment: Nice, that makes sense. But with the expression for $\langle f_n,f_m \rangle$ then be if for example n and m is different?
Comment: @Lifeni That is correct (:
Comment: Yeah but will the integral then be $\langle f_n,f_m \rangle=\int_{-1}^1x^nx^mdx$ or what will the expression for  $\langle f_n,f_m \rangle$ be when n and m are different?
Comment: Nice, that makes sense. Thank you for the help :-)


Serving over the sideline

Question: As far as I know in table tennis, it is not allowed to serve over the sideline i.e. on the first hit of the ball, it is not allowed that the ball will go over the side of the table on the opponents side. It should reach the far end of the table.
My question is if in tennis there is a similar rule? I could not find anything here: Serve (tennis).
Comment: You are incorrect regarding table tennis, a serve is allowed to go over the side of the table on the oppenents side and that is also a very common serve to do.
Comment: You need to be behind the baseline and for this fact to be easily visible you have to stay within the sideline boundaries.
Answer: There is no similar rule.
From the USTA's Friend at Court:

SERVING

[...]
  The service shall pass over the net and hit the service court diagonally opposite, before the receiver returns it.

There is no requirement for it to exit the court via the baseline.  In fact, it is very common for serves to be sent close to the sideline to make them more difficult to return.
There is a tennis strategy article that discusses some advantages of hitting very wide serves.
Comment: You are correct, but there is a rule about from where a serve can take place - `both
feet behind the baseline and within the imaginary extensions of the centre mark and the sideline.` https://www.itftennis.com/media/298557/298557.pdf

Serving over the sideline


Finding a third degree equation that fits two points with given slopes

Question: I'm trying to find an easy way of getting coefficients of a third degree polynomial $y = ax^3 + bx^2 + cx + d$ with given points $(x_1,y_1)$ and $(x_2,y_2)$ the slopes are also given $k_1$, $k_2$. I have asked the question before in Stackoverflow but couldn't understand it: https://stackoverflow.com/questions/5577527/finding-a-third-degree-equation-that-fits-two-points-with-given-slopes-in-javascr.
Comment: I wasn't implying anything of the sort; it seems a lot of foreigners translate it as "polynom", and was letting you know. But it seems you rather proclaim  to the four winds that the issue is that you are just too lazy to bother typing the word correctly, so thanks for that "clarification."
Comment: In English they are called "polynomials" (singular "polynomial"), not "polynoms" (fake singular "polynom").
Answer: Assuming $k_1$ is the slope in $x_1$ and $k_2$ is the slope in $x_2$.
Okay, say your polynomial is $y = a_3 x^3 + a_2 x^2 + a_1 x + a_0$. As shamovich already have  stated you get a system of equations $Xa = y$ where $X$ is a matrix and $y$ and $a$ are vectors:
$$
\underbrace{
\begin{pmatrix}
x_1^3  & x_1^2  & x_1 & 1 \\
x_2^3  & x_2^2  & x_2 & 1 \\
3x_1^2 & 2x_1   & 1   & 0 \\
3x_2^2 & 2x_2   & 1   & 0
\end{pmatrix}
}_{=X}
\underbrace{
\begin{pmatrix}
a_3 \\ a_2 \\ a_1 \\ a_0
\end{pmatrix}
}_{=a}
=
\underbrace{
\begin{pmatrix}
y_1 \\ y_2 \\ k_1 \\ k_2
\end{pmatrix}
}_{=y}
$$
The first two rows are simply the equations $y_i = a_3 x_i^3 + a_2x_i^2 + a_1x_i + a_0$ and the last two rows are the equations $k_i = 3a_3 x_i^2 + 2a_2 x_i + a_1$.
I assume you know your points $(x_i, y_i)$ for $i = 1,2$ and $k_1, k_2$, so $X$ and $y$ are known. Solve for $x$ (you can use e.g. Matlab or Mathematica for this). As long as $x_1 \neq x_2$ there is a solution, since the determinant of the matrix is $-(x_1 - x_2)^4$.
You can derive the inverse $X^{-1}$. It has the form:
$$X^{-1} =
\begin{pmatrix}
 \frac{2}{\left(-x_1+x_2\right){}^3} & \frac{2}{\left(x_1-x_2\right){}^3} & \frac{1}{\left(x_1-x_2\right){}^2} & \frac{1}{\left(x_1-x_2\right){}^2} \\
 \frac{3 \left(x_1+x_2\right)}{\left(x_1-x_2\right){}^3} & -\frac{3 \left(x_1+x_2\right)}{\left(x_1-x_2\right){}^3} & -\frac{x_1+2 x_2}{\left(x_1-x_2\right){}^2} & -\frac{2 x_1+x_2}{\left(x_1-x_2\right){}^2} \\
 -\frac{6 x_1 x_2}{\left(x_1-x_2\right){}^3} & \frac{6 x_1 x_2}{\left(x_1-x_2\right){}^3} & \frac{x_2 \left(2 x_1+x_2\right)}{\left(x_1-x_2\right){}^2} & \frac{x_1 \left(x_1+2 x_2\right)}{\left(x_1-x_2\right){}^2} \\
 \frac{\left(3 x_1-x_2\right) x_2^2}{\left(x_1-x_2\right){}^3} & \frac{x_1^2 \left(x_1-3 x_2\right)}{\left(x_1-x_2\right){}^3} & -\frac{x_1 x_2^2}{\left(x_1-x_2\right){}^2} & -\frac{x_1^2 x_2}{\left(x_1-x_2\right){}^2}
\end{pmatrix}$$
So $a = X^{-1} y$ (but, as always, if you are using software, it is better to use built-in solvers than using the inverse explicitly).
Explicit formulas for the coefficients one by one is given by:
$$\begin{align}
a_3 &= \frac{\left(k_1+k_2\right) \left(x_1-x_2\right)-2 y_1+2 y_2}{\left(x_1-x_2\right){}^3} \\
a_2 &= \frac{-k_1 \left(x_1-x_2\right) \left(x_1+2 x_2\right)+k_2 \left(-2 x_1^2+x_1 x_2+x_2^2\right)+3 \left(x_1+x_2\right) \left(y_1-y_2\right)}{\left(x_1-x_2\right){}^3} \\
a_1 &= \frac{k_2 x_1 \left(x_1-x_2\right) \left(x_1+2 x_2\right)-x_2 \left(k_1 \left(-2 x_1^2+x_1 x_2+x_2^2\right)+6 x_1 \left(y_1-y_2\right)\right)}{\left(x_1-x_2\right){}^3} \\
a_0 &= \frac{x_2 \left(x_1 \left(-x_1+x_2\right) \left(k_2 x_1+k_1 x_2\right)-x_2 \left(-3 x_1+x_2\right) y_1\right)+x_1^2 \left(x_1-3 x_2\right) y_2}{\left(x_1-x_2\right){}^3}
\end{align}$$
Comment: $a_3, a_2, a_1, a_0$ are what in the question are called $a, b, c, d$ (in that order).
Comment: If you have *Mathematica* to begin with, Hermite interpolation (which is what the OP apparently wants) is easy with `InterpolatingPolynomial[]`. Of course, solving the (confluent) Vandermonde system is the most straightforward if you're deriving by hand. On the other hand, the solution looks neater if you express the polynomial as powers of $(x-x_1)$ or $(x-x_2)$, whatever your preference may be.
Answer: Basically what they've told you at StackOverflow is that to find $a,b,c,d$ you need to solve the system of linear equations:
$a x_1^3 + b x_1^2 + c x_1 +d = y_1$
$a x_2^3 + b x_2^2 + c x_2 +d = y_2$
$3 a x_1^2 + 2 b x_1 + c = k_1$
$3 a x_2^2 + 2 b x_2 + c = k_2$
Comment: No I dont want that formula. The first answer is what I need. The other is to cumbersome.
Comment: Isn't there any formula for this?
Comment: Can you get the coeffecients formulas solving the above equations? I have trouble with it
Comment: So do you or don't you want the formula? I don't understand...
Comment: Well I want the formula for the coefficients, but also how you derive it
Comment: The formula is a bit complex to write down properly here. But actually since you know $(x_1,y_1)$, $(x_2,y_2)$ and $K1,k2$, the system of equations described above is just a linear system. It can be solved using any math software, for example Mathematica. Use the function "LinearSolve"
Comment: If you look at the first answer in StackOverflow is it correct? I dont know what he did.

Shamovic, I'm creating an application that you might be using in the future, for that I need the formula for the coefficients, I'm a programmer and designer I don't use Mathematica. But could you please post the formula somewhere? I really need it
Comment: The formula will be used in javascript code
Comment: http://www.js-x.com/page/javascripts__example.html?view=1068


Quadratic Covariation

Question: I am not sure about the answer to this question. For a Brownian motion $B_t$ and a process $M$ defined by $M_t=B_{t-s}$ if $t>s$ and 0 else, what is the Quadratic Covariation $[B,M]_t$ ?
I find $(t-s)$ if $t>s$ and $0$ else, but the right answer shall be 0 and I can't figure out where I missed something.
Best regards
Answer: Well, we'd like to show that the following limit
$$\lim_{n\to\infty} \sum_{k=0}^{\lfloor 2^n t \rfloor}(M_{(k+1)2^{-n}}-M_{k2^{-n}})(B_{(k+1)2^{-n}}-B_{k2^{-n}})$$
 exists a.s., since this would then equal $[B, M]_t$. Rewrite the limit as
$$
\lim_{n\to\infty} \sum_{k=\lceil 2^ns\rceil}^{\lfloor 2^n t \rfloor}(B_{(k+1)2^{-n}-s}-B_{k2^{-n}-s})(B_{(k+1)2^{-n}}-B_{k2^{-n}})\\
$$
and see that it's the limit of random variables $X_n$, with  $\mathbb{E}(X_n) = 0$ and  $\text{Var}(X_n)\to 0$. (Then show convergence in the usual way, with the first Borel-Cantelli lemma.)
When I first tried this question, I didn't do this - I tried to show that $MB$ was a continuous local martingale. The trouble with this - as far as I can see - is that you have to find a filtration with respect to which both $M$ and $B$ are semimartingales. $M$ doesn't seem to be a semimartingale w.r.t. the natural filtration of $B$.

Quadratic Covariation


How to convert unioned generic list to generic list?

Question: I have two generic list that have been unioned.  Say listA and listB, both of type List<SomeType>.
listA.Union(listB);

The unioned set is of type System.Linq.Enumerable.UnionIterator<string>, which isn't the same as List<SomeType>.
I have tried casting:
listA.Union(listB).ToList<SomeType>();

and
(List<SomeType>)listA.Union(listB);

Both fail.  I tried to access ForEach(), thinking I could add the result to a new list.  .Foreach() isn't available.
I could use a traditional foreach and add each item to a List<SomeType> variable.  However, is there a lambda statement that can do the conversion in one line, assigning to a variable of type List<SomeType>?
Comment: please post your code.  The code you've posted would result in a `UnionIterator`, so ToList would solve your problem.  Since the actual object is a `UnionIterator`, you must have something else going on -- a projection, perhaps, or some other confusion between SomeType and string.  (also, this will prevent you from pursuing the "traditional foreach" approach you mentioned).
Comment: Add .ToList() on the end listA.Union(listB).ToList();
Comment: Just so you know Union() will remove duplicate objects (If SomeType.Equals() is true) that are in both lists. If you want to keep duplicates you should use Concat()
Answer: You don't have to explicitly cast the List in ToList method. If both the list are of same type, you can simply do ToList in the end to get a List of the same type.
List<MyClass> listA = new List<MyClass>();
List<MyClass> listB = new List<MyClass>();
List<MyClass> temp = listA.Union(listB).ToList(); //Just do ToList at the end.

Explicitly specifying the type in ToList method should work as well. I am not sure why its not working.
Answer: Union is an extension method on IEnumerable<T> interface, not on List<T>, so it doesn't know or care that you are trying to connect lists and thus does not create one as a result unless you call ToList explicitly.
If you want to 'attach' one list to another, you might want to use AddRange method instead.


ASP.NET C# Maior idade passada pela url

Question: Seguinte, tenho uma página que recebe parâmetros de idade que podem variar em quantidade.
Exemplo:

url/page.aspx?idade=x&idade=y&idade=z

Minha ideia é pegar todas as idades passadas pela url e selecionar apenas a maior, veja o código abaixo:
var idadePax = Request.QueryString["idade"];
var maxAge = idadePax.Max();

Porém, se eu passar 44, 50 e 80 pela url, me retorna como maior o número 8, tipo ele não reconhece a dezena 80 apenas o primeiro número como maior. Eu havia tentado utilizar
foreach(String n in idadePax) Int32.Parse(n)

para converter cada campo para inteiro, mas não consegui aplicar a lógica do maior para isso, se alguém puder me dar uma ajuda ou uma dica sobre em que estou pecando?
Comment: @VirgilioNovic webform
Comment: Se está usando web forms ou mvc?
Answer: Quando é feito uma requisição como demonstrado no seu exemplo é retornado na linha:
var idadePax = Request.QueryString["idade"];

um dado texto com os valores separados por virgula, exemplo:
44,50,80

Então precisa separar os dados (com o método Split que vai quebrar esse texto em um array) e com linq converter os dados e pegar o maior com Max, exemplo:
if (Request.QueryString["idade"] != null)
{
    var idades = Request.QueryString["idade"];
    var idadeMax = idades.Split(',').Select(x => Convert.ToInt32(x)).Max();
}

esse código só vai servir se os dados são sempre número, foi uma maneira de descrever que o retorno da sua Request.QueryString retorna um string com os dados separados por uma virgula.
Um maneira verificando se o dado realmente é um número:
if (Request.QueryString["idade"] != null)
{
    var idadeMax = int.MinValue;
    var idades = Request.QueryString["idade"];
    var idadesSplit = idades.Split(',');
    foreach (var item in idadesSplit)
    {
        if (int.TryParse(item.ToString(), out int n))
        {
            if (n > idadeMax) idadeMax = n;
        }
    }
}

Comment: Nossa igual do javascript... @Virgilio Novic, só agradeço! Aqui funcionou perfeito. No caso eu estava passando a string inteira para o método Max() correto? ai quando uso o split ele transforma em um array e ai é possível verificar qual a idade é maior. é isso?
Comment: @MSHijo isso ... eu editei e coloque o link para leituras adicionais.

ASP.NET C# Maior idade passada pela url


Distribution fitting to given loss data

Question: I am into risk management and deal with Operational risk. As a part of BASEL II guidelines, we need to arrive at the capital charge the banks must set aside to counter any operational risk, if it happens. As a part of Loss Distribution Approach (LDA), we need to collate past loss events and use these loss amounts. The usual process as being practiced in the industry is as follows -
Using these historical loss amounts and using the various statistical tests like KS test, AD test, PP plot, Q-Q plot etc, we try to identify best statistical (continuous) distribution fitting this historical loss data. Then using these estimated parameters w.r.t. the statistical distribution, we simulate say 1 million loss amounts and then taking appropriate percentile (say 99.9%), we arrive at the capital charge.
However, many a times, loss data is such that fitting of distribution to loss data is not possible. May be loss data is multimodal or has significant variability, making the fitting of distribution impossible. Can someone guide me how to deal with such data and what can be done to simulate losses using this historical loss data in R.
My data is as follows
<code>mydat <- c(829.53,4000,6000,1000,1063904,102400,22000,4000,4200,2000,10000,400, 459006, 7276,4000,100,4000,10000,613803.36, 825,1000,5000,4000,3000,84500,200, 2000,68000,97400,6267.8, 49500,27000,2100,10489.92,2200,2000,2000,1000,1900, 6000,5600,100,4000,14300,100,94100,1200,7000,2000,3000,1100,6900,1000,18500,6000,2000,4000,8400,11200,1000,15100,23300,4000,13100,4500,200,2000,50000,3900,3200,2000,2000,67000,2000,500,2000,1000,1900,10400,1900,2000,3200,6500,10000,2900,1000,14300,1000,2700,1500,12000,40000,25000,2800,5000,15000,4000,1000,21000,15000,16000,54000,1500,19200,2000,2000,1000,39000,5000,1100,18000,10000,3500,1000,10000,5000,14000,1800,4000,1000,300,4000,1000,100,1000,4400,2000,2000,12000,200,100,1000,1000,2000,1600,2000,4000,14000,4000,13500,1000,200,200,1000,18000,23000,41400,60000,500,3000,21000,6900,14600,1900,4000,4500,1000,2000,2000,1000,4100,2000,1000,2000,8000,3000,1500,2000,2000,3500,2000,2000,1000,3800,30000,55000,500,1000,1000,2000,62400,2000,3000,200,2000,3500,2000,2000,500,3000,4500,1000,10000,2000,3000,3600,1000,2000,2000,5000,23000,2000,1900,2000,60000,2000,60000,20000,2000,2000,4600,1000,2000,1000,18000,6000,62000,68000,26800,50000,45900,16900,21500,2000,22700,2000,2000,32000,10000,5000,138000,159700,13000,2000,17619,2000,1000,4000,2000,1500,4000,20000,158900,74100,6000,24900,60000,500,1000,40000,10000,50000,800,4000,4900,6500,5000,400,500,3000,32300,24000,300,11500,2000,5000,1000,500,5000,5500,17450,56800,2000,1000,21400,22000,60000,3000,7500,3000,1000,1000,2000,1500,83700,2000,4000,170005,70000,6700,1500,3500,2000,10563.97,1500,25000,2000,2000,2267.57,1100,3100,2000,3500,10000,2000,6000,1500,200,20000,4000,46400,296900,150000,3700,7500,20000,48500,3500,12000,2500,4000,8500,1000,14500,1000,11000,2000,2000,120000,20000,7600,3000,2000,8000,1600,40000,2000,5000,34187.67,279100,9900,31300,814000,43500,5100,49500,4500,6262.38,100,10400,2400,1500,5000,2500,15000,40000,32500,41100,358600,109600,514300,258200,225900,402700,274300,75000,1000,56000,10000,4100,1000,15000,100,40000,7900,5000,105000,15100,2000,1100,2900,1500,600,500,1300,100,5000,5000,10000,10100,7000,40000,10500,5000,9500,1000,15200,2000,10000,10000,100,7800,3500,189900,58000,345000,151700,11000,6000,7000,15700,6000,3000,5000,10000,2000,1000,36000,1000,500,8000,9000,6000,2000,26500,6000,5000,97200,2000,5100,17000,2500,25500,24000,5400,90000,41500,6200,7500,5000,7000,41000,25000,1500,40000,5000,10000,21500,100,32000,32500,70000,500,66400,21000,5000,5000,12600,3000,6200,38900,10000,1000,60000,41100,1200,31300,2500,58000,4100,58000,42500)
</code>
Sorry for the inconvenience. I do understand fitting of distribution to such data is not a full proof method, but this is what is the procedure that has been followed in the risk management risk industry. Please note that my question is not pertaining to operational risk. My question if if distributions are not fitting to a particular data, how do we proceed further to simulate data based on this data.
Answer: Firstly, I would recommend taking the logarithm of your data. This is because you are interested in financial losses that cannot go negative.
As illustrated in the figure below, I do not think a well known distribution will fit nicely to your data.
You can try non (or semi) parametric solutions (kernel density estimation is the method generating the figure below).
For your particular case however, I would personally consider using a lognormal distribution (which is equivalent to using a normal distribution for the logarithms). Even if your data will not pass normality tests, this law is easy to simulate and may still provide good results.
Comment: Then, you can go for the kernel density estimation. You can simulate log-losses by inverting the kernel cumulative distribution function. You can check this answer http://stats.stackexchange.com/questions/108342/how-to-get-percentiles-from-empirical-density-in-r for more information on these computations.
Comment: Thanks a lot for your suggestion. As suggested, I took log of the data and tried to fit some distribution. Unfortunately, it didn't. It's not unfortunately I can select Log normal just like that as client wont be convinced. If I try Kernel density estimation, will I be able to simulate say 50000 losses? Can you guide me please. Regards

Distribution fitting to given loss data


Finding zeros of a Fourier series

Question: I have a short Fourier series on a homework problem,
$$
\begin{align*}
S(v_1, v_2, v_3) & =
      1 + \exp[-i \pi (v_2 + v_3)]+ \exp[-i \pi (v_1 + v_3)] + \exp[-i \pi (v_1 + v_2)] \\
      & \hspace{3em} + \exp[-i \pi (v_1 + v_2 + v_3) / 2] + \exp[-i \pi (v_2 + v_3) / 2] \\
      & \hspace{3em} + \exp[-i \pi (v_1 + v_3) / 2] + \exp[-i \pi (v_1 + v_2) / 2],
\end{align*}
$$
where $$v_1, v_2, v_3 \in \mathbb{Z}.$$
I'm tasked with finding the zeros of $S$, but I am not sure how to go about breaking up each $v_i$ into cases. I could begin by splitting each $v_i$ into the cases $v_i = 4k_i, 4k_i + 1, 4k_i + 2, 4k_i+3$, but this would mean working out several pages by hand (and I expect the problem to be shorter than that).
How can I go about reducing the complexity of this problem?
Answer: Let's show how you can reduce the complexity of your problem. First, notice that your sum is invariant under any permutation: $$S(a,b,c)=S(a,c,b)=S(b,a,c)=S(b,c,a)=S(c,a,b)=S(c,b,a)$$
Now let's use $$v_1+v_2=x\\v_1+v_3=y\\v_2+v_3=z$$
Also note that these are all integers. So
$$S(v_1,v_2,v_3)\to S'(x,y,z)=1+(-1)^x+(-1)^y+(-1)^z+(-i)^x+(-i)^y+(-i)^z+(-i)^{(x+y+z)/2}$$
Two things to notice here. First $S'$ is also invariant under permutations. Second, $x+y+z=2(u_1+u_2+u_3)$ is an even number. That means either all are even or one is even and two odds.
Case 1 all even. Then the first 4 terms are all $+1$, and we want the next 4 terms to be $-1$. That means all $x,y,z$ are of the form $2(2k+1)$. The last term however is the $i$ to some odd power, so the sum is never $0$.
Case 2 $x=2k, y=2l+1, z=2m+1$. In this case$$S'(x,y,z)=1+1-1-1+(-1)^k+(-1)^l(-i)+(-1)^m(-i)+(-i)^{k+l+m+1}$$
Notice that you need $l$ and $m$ to be one even and one odd, otherwise you can't cancel all the terms with $i$. This also yields $k$ is even, so the last term has to be $-1$. Since the order does not matter, $x=4p, y=4q+1, z=4r+3$.
$$v_1+v_2=4p\\v_1+v_3=4q+1\\v_2+v_3=4r+3$$
Subtracting the first from the second, and adding the third yields:
$$2v_3=4(r+p-q)+4$$
Therefore $v_3=2\ (\mod 4)$, $v_2=1\ (\mod 4)$, $v_1=3\ (\mod 4)$. Since the order does not matter, the zeros of $S$ are the form: $$(4\alpha+1,4\beta+2,4\gamma+3)$$
with $\alpha,\beta,\gamma\in\mathbb Z$, and any permutation.

Finding zeros of a Fourier series


Como obter somente a data, sem a hora, de um DateTime?

Question: Convertendo um campo utilizando ToDateTime ele traz a data e a hora.
parcelamento.data_vencimento = Convert.ToDateTime(reader["data_vencimento"]);

Existe alguma conversão direta para trazer somente a data sem a hora?
Comment: Qual é o tipo de `parcelamento.data_vencimento`? Isto é importante para saber como você precisa obter a data. Até tem outras coisas que precisariam ser analisadas pra ver se pode usar o `Convert.ToDateTime`, eu tenho quase certeza que isto é um erro. Fazer o que foi sugerido na resposta abaixo não muda nada: https://dotnetfiddle.net/TX6n3c
Comment: Se me responder isso, eu melhoro a resposta.
Comment: Obrigado já deu certo..
Comment: Mas seria bom esclarecer para poder ajudar outras pessoas. Aproveite e dê uma olhada no [tour] para conhecer mais como o site funciona.
Comment: A minha variavel data_vencimento esta no formato DateTime, e por padrão o gridview, ao renderizar, chama o .ToString() do campo.
Eu tive que mudar esse comportamento utilizando o datastringformat no próprio campo da gridview
Comment: Alguma das respostas resolveu o problema? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso. Você estaria ajudando a comunidade identificando a melhor solução. Só pode aceitar uma delas, mas pode votar em qualquer coisa no site todo.
Answer: Tudo depende do tipo de parcelamento.data_vencimento. Ele é um DateTime? Então não tem nada para ser feito, se o tipo diz que deve ter uma data e uma hora, é isso que terá nele. O que você pode fazer quando precisar apresentar é pegar só a data, sem o horário, mas isto é questão de apresentação.
Não confunda dado armazenado com dado a ser apresentado. São duas coisas distintas. Dado apresentado sempre é uma string e pode estar no formato que achar melhor. Tanto não importa que a outra resposta não faz nada útil, veja.
O parcelamento.data_vencimento é string? Duvido. Se for, vai ter dificuldade de manipulá-lo. Se precisa só para apresentar mesmo, então .ToString("dd/MM/yyyy") resolve.
using static System.Console;
using static System.Convert;

public class Program {
    public static void Main() => WriteLine(ToDateTime("03/25/2015").ToString("dd/MM/yyyy"));
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Quase sempre armazenar só a data é um erro e precisaria ter um bom motivo para fazer isto. Os motivos que vejo as pessoas "terem" para usar um tipo só com a data costumam ser furados. Se quiser mesmo fazê-lo, aconselho usar uma biblioteca que faça isto bem, como a NodaTime do Jon Skeet.
Me parece que tem alguma estrutura só com a data em algum lugar do .Net ou alguma biblioteca ligada a ele, mas para uso bem específico, provavelmente banco de dados, não para uso geral, por isso não é fácil de achar.
Se for corajoso, crie uma estrutura para isto.
Dependo do que for usar precisaria analisar como construir uma data nova, se precisa passar os membros da data isoladamente, se deve passar uma string, se pode ser formatada, se pode passar um DateTime para ele converter.
Outra coisa que deve analisar é se pode usar o Convert.ToDateTime(). Esta não é uma boa opção para pegar strings externas que você não possui controle total.
Answer: Recomendo que você dê uma olhada na documentação da struct DateTime na MSDN.
Mas o que você deseja pode ser obtido através da propriedade Date de uma instância de DateTime. Essa propriedade retorna um DateTime que possui apenas a parte da data com as horas zeradas (00:00:00 ou 12:00:00 AM).
parcelamento.data_vencimento = Convert.ToDateTime(reader["data_vencimento"]).Date;

Answer: Simples, para pegar apenas a data é só usar a função DateValue.
Exemplo no .NET
Dim MyDate
MyDate = DateValue("#1/3/2024 7:26:00 AM#")
Debug.Print(MyDate) '"#1/3/2024"

Em c# tente algo como:
MyDate = new DateValue();
MyDate.value = "#1/3/2024 7:26:00 AM#";
Console.WriteLine(MyDate); '"#1/3/2024"


How can I attack this definite integral - roots problem?

Question: I have this problem:
Let $f(x)$ be continuous on the interval $[0,1] .$ Prove that if
$$
  \int_{0}^{1} f(x) d x=\int_{0}^{1} x f(x) d x=0
  $$
then $f$ has at least two different roots in (0,1)
Is it better to start with parts integration on second one? or triying
$$
  \int_{0}^{1} f(x) d x=\int_{0}^{1} x f(x) d x=0\Rightarrow \int_{0}^{1} f(x) -x f(x) d x=0 ?
 $$
If I use mean value Theorem I coul get
$$
\int_{0}^{1} (1-x) f(x) d x=(1-\xi)\int_{0}^{1}  f(x) d x=0
$$
With $\xi\in[0,1]$
Therefore
$$
  \int_{0}^{1} f(x) d x=0\qquad  or\qquad \xi =1
 $$
But doesn't seems to help, I already know
$$
  \int_{0}^{1} f(x) d x=0
 $$
and $\xi=1$ has no further use
So I'm kind of stuck right now
I'll appreciate any help or suggestion
Thanks in advance
Comment: See https://math.stackexchange.com/questions/112017/prove-that-exists-ab-s-t-fa-fb-0-when-int-01fxdx-int-01xfxdx and https://math.stackexchange.com/questions/360503/continuous-function-on-0-1-has-at-least-two-zeroes
Answer: With $\int_0^1 f = 0$ we get that there is at least one root $x_0$. In fact, $f$ can't be always positive or always negative or the integral wouldn't be $0$ (i exclude the trivial case where $f=0$).
Let's suppose it is the only root. Then since $\int_0^1 f = 0$ and $\int_0^1 xf(x) dx = 0$, we have that $\int_0^1 \pm(x-x_0) f(x) dx = 0$. Let's say for instance that $f$ is positive before $x_0$, and negative after. Then $x\mapsto (x-x_0) f(x)$ is always positive. Since its integral is $0$, this means the function is $0$, which is contradictory.
So there are at least two roots.
Answer: for a (non-zero) function over this range there must be two areas that "cancel out" i.e. there is a $0<x_0<1$ where $f(x_0)=0$ which suggests:
$$0=\int_0^1f(x)dx=\int_0^{x_0}f(x)dx-\int_{x_0}^1f(x)dx$$
If there is one root in a domain then there must be a positive and negative area, and if there are two roots there must be three regions, 2 positive/negative and 1 the opposite.
On the other hand if we define a function $g(x)=xf(x)$ we know that $g(0)=0$ which means for the regions to cancel out again we must have 3 roots in the function $g$, one being $x=0$ which suggests that $f$ has 2 roots.
I am not sure how much sense this makes so I will try and define it slightly differently, lets say we have a function:
$$\begin{matrix}f_n(x)=\prod_{i=1}^n(x-x_i) & 0\le x_i\le1\end{matrix}$$
this represents a polynomial with $n$ roots in the domain $x\in[0,1]$

If we assume that $f=f_1$ we have the expression:
$$\int f(x)dx=\int_0^1x-x_idx=\left[\frac{x^2}{2}-x_ix\right]_0^1=\frac{1}{2}-x_i=0$$
so there is an $x_i$ which satisfies this solution. If we now try and do the second integral:
$$\int xf(x)dx=\int_0^1x^2-x_ixdx=\left[\frac{x^3}{3}-\frac{x_i}{2}x^2\right]_0^1=\frac{1}{3}-\frac{1}{2}x_i=0$$
and whilst this does have a solution that makes this work it does not match the one from the first integral, suggesting that if this is a polynomial it must have at least two roots.
Comment: Thanks very much for the help


How to handle "class type redefinition"

Question: I've trying to work with an open source VC++ code.
I'm trying to add a new project to an existing VC++ solution which turned to be a nightmare.
One of the problems I'm facing is fixing "type redefinition" errors, I already fixed a few but now I'm stuck on some others. The code base is huge so no snippests...
My questions is, is there any "best practice" to track down these errors?
Thanks.
Answer: By type redefinition, I assume that there are same name classes or typedefs defined in your workspace projects and they are causing problem while compilation (not to confuse with multiple definition linker error).
The best practice is to always enclose them into namespace on module or project bases.
e.g.
// project1.h
namespace project1 {
  class X {};
}

// project2.h
namespace project2 {
  class X {};
}

Comment: 10x, Please see my comment to @sharptooth. The "included" code is not mine so I can't add namespaces. I'm just looking for a way to track down the redefinitions.
Answer: My advice would be to put all code in the separate projects in separate namespaces. Then you wouldn't have to worry about clashes. It might be a lot of work if you have a lot of header and source files, but it might be worth it in the long run.
And you don't have to add the namespace to all functions/classes, just add namespace foo { at the top in all header/source file, and a corresponding } at the bottom.
Comment: 10x. Please see my comment to @sharptooth
Answer: When you try to include the same header file in two or more different programs, like
A calling B and B calling C, and if you include C in both A and B, then this kind of error occur. same happened with me, and resolved it.

How to handle "class type redefinition"


SQL: Getting the minute value from calculating current datetime - datetime value from table

Question: Is there a way to retrieve the minute value from calculating the current time (system clock) to the DateTime value from the database
example
LogID     Timestamp
1         2012-08-06 23:35
2         2012-08-06 23:39

Current system date time is: 2012-08-06 23:50
output should be
LogID     Minutes
1         15
2         11

Any ideas?
Answer: SELECT LogID, [Timestamp],
    [Minutes] = DATEDIFF(MINUTE, [Timestamp], CURRENT_TIMESTAMP)
  FROM dbo.table_name;

Comment: That was ridiculously fast! Thanks.


Is the row space the annihilator of the null space?

Question: Is the row space of a matrix $A$ the annihilator of the null space of the matrix? I guess I'm assuming that solutions to the vector equation $AX = 0$ are vectors in some vector space $V$ and that the rows of matrix $A$ may represent linear functionals so that the span of the rows of $A$ represents a subspace of $V^*$.
Answer: Yes, if we interpret linear functionals in the usual way for matrices (dot product). This is one of the so-called "fundamental theorems" for linear algebra; see this article. In particular, if $A$ is a matrix (viewed as a linear transformation between Euclidean vector spaces), then
$$
R(A^T) = N(A)^{\perp},
$$
where $R(A^T)$ is the range of the transpose of $A$, which is the same as the row space, $N(A)$ is the null space, and the symbol $\perp$ indicates the orthogonal complement, which is the same as the annihilator when using the dot product as the realization of the dual space.
To prove this: If $x \in R(A^T)$, then $x = A^T z$ for some vector $z$. Now take any $y \in N(A)$. Then
$$
\langle x,y \rangle = x^T y = z^T A y = z^T (0) = 0,
$$
where we used the fact that $Ay = 0$ since $y \in N(A)$. This proves that each element of $R(A^T)$ is orthogonal to every element of $N(A)$; that is, $R(A^T) \subseteq N(A)^{\perp}$.
To get equality, it suffices to prove that the two subspaces have equal dimension.
Comment: Amazing answer. Thank you so much!