qid
int64 1
74.7M
| question
stringlengths 15
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 4
30.2k
| response_k
stringlengths 11
36.5k
|
---|---|---|---|---|---|
28,167 | **In Short**
I’m wondering if there is any research to support the idea that paying for a child to attend college leads to a more desirable outcome than allowing them to pay their own way (either via working, via scholarships, or via student loans). This could be shown in terms of mid-career income, unemployment numbers, happiness index, etc. An answer that compares and contrasts the advantages and disadvantages to each side (as supported by hard evidence) would be even better.
**Background**
I believe I had an atypical upbringing that I erroneously assumed was normal. Most of my aunts and uncles, and my parents, worked their own way through school. I always believed this was the norm, though I’m now questioning that assumption.
When I started my associates degree I choose a community college for cost efficiency, but refused to let my parents pay after the first semester. I worked 24 hours a week around schooling, then moved up to full time work while attending night school at a local university to earn my BS. I believe that this experience was immeasurably valuable as I graduated with 5 years of industry experience on my resume, no debt, and a working understanding of how to apply classroom theory to industry practice, leading to good career prospects and high pay. Further, a 40-hour workweek with nights free after graduation seemed like a vacation to me which reduced my long-term stress levels, and knowing that my parents didn’t need to sacrifice of their retirement did wonders for my happiness (not to mention confidence in myself).
I have several friends who paid most of their college tuition via scholarships, and this seemed to provide different valuable benefits. As the scholarship was a results of their own accomplishments it provided a sense of agency in their lives and provided a boost to confidence and pride. I don’t know anyone who came out with substantial student loan debt, but I would imagine that paying it off could have a similar effect to my working my way through college: a sense of ownership and agency and pride.
I now have two children and I’ve heard a lot from seemingly everyone about planning for their college, and almost every other parent I’ve met has created college accounts for their children. This mindset seems both alien and counterproductive to me, and anecdotal evidence from my own past and family history indicates that this may not be optimal to my children’s long-term success. However, I also seem to be in the extreme minority and I’ve learned that when in that position it makes a lot of sense to question your own position and fully research and understand the other side to make sure you’re not simply biased towards the familiar. So I would like to know if there is validity in setting up a college fund and helping my children pay for college or if this is just an unsupported fad of our parenting generation.
I’m not sure if it’s relevant, but my children are currently in their early teens. I have setup small investment accounts for them that I'm trying to contribute to more and more, but those accounts are currently set to transfer well past college age. The kids know about them and I always refer to them as retirement accounts, but I’m wondering if there’s value in modifying them to be college accounts instead. Before considering doing so I’d like very clear evidence that it would make a substantial positive impact, as $50,000 (for example) put into college now takes $1,500,000 (~$400,000 in today’s dollars adjusted for expected inflation) away from their retirement.
**Addressing College Cost**
I'd like to take a moment to address a common theme in the comments and answers that I don't think has been properly fleshed out.
I think we can all agree that education is extremely expensive. However, I feel it is tangential to the heart of this question, if we assume that paying for one's own education is at least possible, even if difficult.
According to <http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us> studying at a Community College will run $3,347 per year, plus room and board. Studying at a state college will run $9,139 per year, plus room and board. For the purposes of the question we can assume that we're talking about financial assistance with tuition, and that students are welcome to live at home and commute. Therefore we can place a lower limit on a four year degree at $24,972. Even with room and board the numbers work out to $59,990.
We can reasonably assume a work schedule of 15 hours per week during school semesters (9 months of the year) and 40 hours per week during breaks (3 months of the year) for a total of 1020 hours per year. If we assume a student attends 12 credit hours per semester all year round and works 30 hours per week, that comes to 1440 hours per year. I know several people that put in more hours than this, including myself in the past and my nephews in the present, so I believe it to be more than reasonable.
Assuming a pay rate of $10 / hour, the student will have a annual gross income of $10,200 - $14,400, or $40,800 - $57,600 over the course of the four year degree. Alternately, setting aside 10% (average tithe suggested by certain major religions, showing that it is possible to do for many) of the US average annual income of $50,000 (those with degrees average much higher) would allow a student to pay off a fully financed degree at a rate of $5,000 per year, or 5-12 years. Based on these numbers it is clear that with the proper choices the student can come out with no debt load or a manageable debt load, even if they don't stay with parents.
To be clear on a few points:
* Average budgets for college students **are** higher than this, but it doesn't necessarily follow that they **must** be if there are financial pressures on the student to budget responsibly and control costs.
* I do not mean to imply that this is in any way easy. It will, in fact, be very difficult. But it is often the most difficult challenges that allow us to grow and succeed.
* All points about costs, difficulties, long-term debt, etc are valid concerns, but they are not necessarily salient to the question as they may be offset by positive consequences of equal value (industry experience, practical time/life management, etc). Which leads me to:
* The crux of the original question is what hard evidence tells us about whether the long term results of paying for college for our children are overall positive, and if so if they are positive enough to offset a massive loss in retirement savings. This is regardless of whether life might be difficult during or recently after. | 2016/12/14 | [
"https://parenting.stackexchange.com/questions/28167",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/7735/"
] | My husband and I helped our son with undergraduate college so that he wouldn't have so much debt from student loans but only because he was committed to his education. I am all for helping your children with this if you have the resources, but only if they are committed to their education too. I paid for my own college costs with student loans, but I did see some students at that time that were not very committed to their education because their parents were footing the bill. I guess that you have to weigh in all factors. | Split the cost with the child
=============================
My parents and I had a deal with regards to college. They would pay for 50% of the costs of college, including tuition/fees/room/board. I had to pay the other 50%, however there was the stipulation that any scholarships I earned went into my 50%. Since I was able to receive a full ride scholarship, my parents even gave me the 50% they had saved for me so I could keep it in savings.
If I failed to keep my scholarships, I would have had to take out student loans or started working. This arrangement incentives your children to maintain good grades knowing that they'll have to pay extra if they goof around and start failing classes. It also means that if they're dedicated and get lots of scholarships, they won't have to have a job in college and are able to spend more time on their studies.
You also mention the student working part time in college. This is do-able, however the potential gains from scholarships are so much greater than working part time. My parents' philosophy while I was in high school was that my full time job was doing activities/maintaining grades that would get me good scholarships. If you get a full ride, that's essentially saving you anywhere from $100k - $500k. I was able to get a full ride for my first year via ROTC. I decided that I didn't want to join the military, but since I had good grades, I was able to apply for (and get) a bunch of other scholarships that continued to pay for all my tuition and fees. Then my parents payed for housing. I had 1 part time job in college during a lighter semester, but instead of working in college, I was able to graduate with 3 degrees in 4 years, study abroad, and get an honors degree. All of these experiences were way more beneficial to me than working a part time job would have been. |
28,167 | **In Short**
I’m wondering if there is any research to support the idea that paying for a child to attend college leads to a more desirable outcome than allowing them to pay their own way (either via working, via scholarships, or via student loans). This could be shown in terms of mid-career income, unemployment numbers, happiness index, etc. An answer that compares and contrasts the advantages and disadvantages to each side (as supported by hard evidence) would be even better.
**Background**
I believe I had an atypical upbringing that I erroneously assumed was normal. Most of my aunts and uncles, and my parents, worked their own way through school. I always believed this was the norm, though I’m now questioning that assumption.
When I started my associates degree I choose a community college for cost efficiency, but refused to let my parents pay after the first semester. I worked 24 hours a week around schooling, then moved up to full time work while attending night school at a local university to earn my BS. I believe that this experience was immeasurably valuable as I graduated with 5 years of industry experience on my resume, no debt, and a working understanding of how to apply classroom theory to industry practice, leading to good career prospects and high pay. Further, a 40-hour workweek with nights free after graduation seemed like a vacation to me which reduced my long-term stress levels, and knowing that my parents didn’t need to sacrifice of their retirement did wonders for my happiness (not to mention confidence in myself).
I have several friends who paid most of their college tuition via scholarships, and this seemed to provide different valuable benefits. As the scholarship was a results of their own accomplishments it provided a sense of agency in their lives and provided a boost to confidence and pride. I don’t know anyone who came out with substantial student loan debt, but I would imagine that paying it off could have a similar effect to my working my way through college: a sense of ownership and agency and pride.
I now have two children and I’ve heard a lot from seemingly everyone about planning for their college, and almost every other parent I’ve met has created college accounts for their children. This mindset seems both alien and counterproductive to me, and anecdotal evidence from my own past and family history indicates that this may not be optimal to my children’s long-term success. However, I also seem to be in the extreme minority and I’ve learned that when in that position it makes a lot of sense to question your own position and fully research and understand the other side to make sure you’re not simply biased towards the familiar. So I would like to know if there is validity in setting up a college fund and helping my children pay for college or if this is just an unsupported fad of our parenting generation.
I’m not sure if it’s relevant, but my children are currently in their early teens. I have setup small investment accounts for them that I'm trying to contribute to more and more, but those accounts are currently set to transfer well past college age. The kids know about them and I always refer to them as retirement accounts, but I’m wondering if there’s value in modifying them to be college accounts instead. Before considering doing so I’d like very clear evidence that it would make a substantial positive impact, as $50,000 (for example) put into college now takes $1,500,000 (~$400,000 in today’s dollars adjusted for expected inflation) away from their retirement.
**Addressing College Cost**
I'd like to take a moment to address a common theme in the comments and answers that I don't think has been properly fleshed out.
I think we can all agree that education is extremely expensive. However, I feel it is tangential to the heart of this question, if we assume that paying for one's own education is at least possible, even if difficult.
According to <http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us> studying at a Community College will run $3,347 per year, plus room and board. Studying at a state college will run $9,139 per year, plus room and board. For the purposes of the question we can assume that we're talking about financial assistance with tuition, and that students are welcome to live at home and commute. Therefore we can place a lower limit on a four year degree at $24,972. Even with room and board the numbers work out to $59,990.
We can reasonably assume a work schedule of 15 hours per week during school semesters (9 months of the year) and 40 hours per week during breaks (3 months of the year) for a total of 1020 hours per year. If we assume a student attends 12 credit hours per semester all year round and works 30 hours per week, that comes to 1440 hours per year. I know several people that put in more hours than this, including myself in the past and my nephews in the present, so I believe it to be more than reasonable.
Assuming a pay rate of $10 / hour, the student will have a annual gross income of $10,200 - $14,400, or $40,800 - $57,600 over the course of the four year degree. Alternately, setting aside 10% (average tithe suggested by certain major religions, showing that it is possible to do for many) of the US average annual income of $50,000 (those with degrees average much higher) would allow a student to pay off a fully financed degree at a rate of $5,000 per year, or 5-12 years. Based on these numbers it is clear that with the proper choices the student can come out with no debt load or a manageable debt load, even if they don't stay with parents.
To be clear on a few points:
* Average budgets for college students **are** higher than this, but it doesn't necessarily follow that they **must** be if there are financial pressures on the student to budget responsibly and control costs.
* I do not mean to imply that this is in any way easy. It will, in fact, be very difficult. But it is often the most difficult challenges that allow us to grow and succeed.
* All points about costs, difficulties, long-term debt, etc are valid concerns, but they are not necessarily salient to the question as they may be offset by positive consequences of equal value (industry experience, practical time/life management, etc). Which leads me to:
* The crux of the original question is what hard evidence tells us about whether the long term results of paying for college for our children are overall positive, and if so if they are positive enough to offset a massive loss in retirement savings. This is regardless of whether life might be difficult during or recently after. | 2016/12/14 | [
"https://parenting.stackexchange.com/questions/28167",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/7735/"
] | 1. People with degrees statistically have a [better income](http://study.com/articles/How_Much_More_Do_College_Graduates_Earn_Than_Non-College_Graduates.html) than those without degrees.
2. If assisting your child financially is the difference as to whether they can acquire a degree or not then it seems logical that you should consider helping them in whatever way you can.
<http://www.pewsocialtrends.org/2014/02/11/the-rising-cost-of-not-going-to-college/>
<https://assets.publishing.service.gov.uk/government/uploads/system/uploads/attachment_data/file/229498/bis-13-899-the-impact-of-university-degrees-on-the-lifecycle-of-earnings-further-analysis.pdf>
<https://www.abc.net.au/news/2012-10-24/uni-graduates-likely-to-earn-one-million-more-over-lifetime/4330506> | As you note in your question, college tuition has risen significantly faster than inflation over the past decade or two. This makes it more difficult to cover all one's college costs just from work during college. If you can afford it, you might put enough away to take some of the burden off of them, while still depending on them to do some work to avoid debt.
Be aware that many universities take into account how much money a student has available when determining student aid. It pays to be aware of these policies and to put as much of your money as possible into things the universities won't or can't take into account. For example, they are not allowed to take your retirement accounts into account, and most will not take your housing equity into account, though universities differ on the latter. |
28,167 | **In Short**
I’m wondering if there is any research to support the idea that paying for a child to attend college leads to a more desirable outcome than allowing them to pay their own way (either via working, via scholarships, or via student loans). This could be shown in terms of mid-career income, unemployment numbers, happiness index, etc. An answer that compares and contrasts the advantages and disadvantages to each side (as supported by hard evidence) would be even better.
**Background**
I believe I had an atypical upbringing that I erroneously assumed was normal. Most of my aunts and uncles, and my parents, worked their own way through school. I always believed this was the norm, though I’m now questioning that assumption.
When I started my associates degree I choose a community college for cost efficiency, but refused to let my parents pay after the first semester. I worked 24 hours a week around schooling, then moved up to full time work while attending night school at a local university to earn my BS. I believe that this experience was immeasurably valuable as I graduated with 5 years of industry experience on my resume, no debt, and a working understanding of how to apply classroom theory to industry practice, leading to good career prospects and high pay. Further, a 40-hour workweek with nights free after graduation seemed like a vacation to me which reduced my long-term stress levels, and knowing that my parents didn’t need to sacrifice of their retirement did wonders for my happiness (not to mention confidence in myself).
I have several friends who paid most of their college tuition via scholarships, and this seemed to provide different valuable benefits. As the scholarship was a results of their own accomplishments it provided a sense of agency in their lives and provided a boost to confidence and pride. I don’t know anyone who came out with substantial student loan debt, but I would imagine that paying it off could have a similar effect to my working my way through college: a sense of ownership and agency and pride.
I now have two children and I’ve heard a lot from seemingly everyone about planning for their college, and almost every other parent I’ve met has created college accounts for their children. This mindset seems both alien and counterproductive to me, and anecdotal evidence from my own past and family history indicates that this may not be optimal to my children’s long-term success. However, I also seem to be in the extreme minority and I’ve learned that when in that position it makes a lot of sense to question your own position and fully research and understand the other side to make sure you’re not simply biased towards the familiar. So I would like to know if there is validity in setting up a college fund and helping my children pay for college or if this is just an unsupported fad of our parenting generation.
I’m not sure if it’s relevant, but my children are currently in their early teens. I have setup small investment accounts for them that I'm trying to contribute to more and more, but those accounts are currently set to transfer well past college age. The kids know about them and I always refer to them as retirement accounts, but I’m wondering if there’s value in modifying them to be college accounts instead. Before considering doing so I’d like very clear evidence that it would make a substantial positive impact, as $50,000 (for example) put into college now takes $1,500,000 (~$400,000 in today’s dollars adjusted for expected inflation) away from their retirement.
**Addressing College Cost**
I'd like to take a moment to address a common theme in the comments and answers that I don't think has been properly fleshed out.
I think we can all agree that education is extremely expensive. However, I feel it is tangential to the heart of this question, if we assume that paying for one's own education is at least possible, even if difficult.
According to <http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us> studying at a Community College will run $3,347 per year, plus room and board. Studying at a state college will run $9,139 per year, plus room and board. For the purposes of the question we can assume that we're talking about financial assistance with tuition, and that students are welcome to live at home and commute. Therefore we can place a lower limit on a four year degree at $24,972. Even with room and board the numbers work out to $59,990.
We can reasonably assume a work schedule of 15 hours per week during school semesters (9 months of the year) and 40 hours per week during breaks (3 months of the year) for a total of 1020 hours per year. If we assume a student attends 12 credit hours per semester all year round and works 30 hours per week, that comes to 1440 hours per year. I know several people that put in more hours than this, including myself in the past and my nephews in the present, so I believe it to be more than reasonable.
Assuming a pay rate of $10 / hour, the student will have a annual gross income of $10,200 - $14,400, or $40,800 - $57,600 over the course of the four year degree. Alternately, setting aside 10% (average tithe suggested by certain major religions, showing that it is possible to do for many) of the US average annual income of $50,000 (those with degrees average much higher) would allow a student to pay off a fully financed degree at a rate of $5,000 per year, or 5-12 years. Based on these numbers it is clear that with the proper choices the student can come out with no debt load or a manageable debt load, even if they don't stay with parents.
To be clear on a few points:
* Average budgets for college students **are** higher than this, but it doesn't necessarily follow that they **must** be if there are financial pressures on the student to budget responsibly and control costs.
* I do not mean to imply that this is in any way easy. It will, in fact, be very difficult. But it is often the most difficult challenges that allow us to grow and succeed.
* All points about costs, difficulties, long-term debt, etc are valid concerns, but they are not necessarily salient to the question as they may be offset by positive consequences of equal value (industry experience, practical time/life management, etc). Which leads me to:
* The crux of the original question is what hard evidence tells us about whether the long term results of paying for college for our children are overall positive, and if so if they are positive enough to offset a massive loss in retirement savings. This is regardless of whether life might be difficult during or recently after. | 2016/12/14 | [
"https://parenting.stackexchange.com/questions/28167",
"https://parenting.stackexchange.com",
"https://parenting.stackexchange.com/users/7735/"
] | Split the cost with the child
=============================
My parents and I had a deal with regards to college. They would pay for 50% of the costs of college, including tuition/fees/room/board. I had to pay the other 50%, however there was the stipulation that any scholarships I earned went into my 50%. Since I was able to receive a full ride scholarship, my parents even gave me the 50% they had saved for me so I could keep it in savings.
If I failed to keep my scholarships, I would have had to take out student loans or started working. This arrangement incentives your children to maintain good grades knowing that they'll have to pay extra if they goof around and start failing classes. It also means that if they're dedicated and get lots of scholarships, they won't have to have a job in college and are able to spend more time on their studies.
You also mention the student working part time in college. This is do-able, however the potential gains from scholarships are so much greater than working part time. My parents' philosophy while I was in high school was that my full time job was doing activities/maintaining grades that would get me good scholarships. If you get a full ride, that's essentially saving you anywhere from $100k - $500k. I was able to get a full ride for my first year via ROTC. I decided that I didn't want to join the military, but since I had good grades, I was able to apply for (and get) a bunch of other scholarships that continued to pay for all my tuition and fees. Then my parents payed for housing. I had 1 part time job in college during a lighter semester, but instead of working in college, I was able to graduate with 3 degrees in 4 years, study abroad, and get an honors degree. All of these experiences were way more beneficial to me than working a part time job would have been. | I think you should, because I wouldn't be able to study aboard for university without my parents' help. But you need to let your children understand you are not giving them free money.
I think the key point is to let your children understand the value of their education, and that university degree doesn't just fall from the sky. It comes from your hard work.
You can also tell them that this is a loan from you with no interest (or low interest), but you expect them to to pay you back in `x` years. So that they will feel pressure and value their time in university. When we get something for free, we usually take it granted; but when it comes at a price, we usually treat it more carefully. You don't necessarily actually need them to pay you back the loan, but don't let them know that before they graduate.
You can actually start teaching them value of money now, by asking them to get some part-time job.
---
As others have mentioned, average tuition in US is very expensive. Googling shows that
>
> published tuition fees for 2014/15 at state colleges are an average of
> US$9,139 for state residents, and $22,958 for everyone else. This
> compares to an average of $31,231 at private non-profit colleges.
>
>
>
(<http://www.topuniversities.com/student-info/student-finance/how-much-does-it-cost-study-us>)
So even if they go to a local one, by working around 1000 hours a week (20 hr/week \* 50 weeks) at $7.25 minimal wage, they can barely cover their tuition, not to mention other expenses (say the university is out of town, then they'll need housing). |
8,242,229 | I just downloaded SOAPUI 4.0.1 and tried to run it in Ubuntu 11.10. I run the file soapui.sh. The application started up and the window actually appeared, but then after a few seconds it closed. Looking at the terminal I saw that the JVM crashed. Below are the details of the error:
```
(process:4183): GLib-GObject-CRITICAL **: /build/buildd/glib2.0-2.30.0/./gobject/gtype.c:2708: You forgot to call g_type_init()
(process:4183): GLib-GObject-CRITICAL **: g_object_new: assertion `G_TYPE_IS_OBJECT (object_type)' failed
(process:4183): GLib-GObject-CRITICAL **: g_object_ref: assertion `G_IS_OBJECT (object)' failed
Problematic frame:
C [libgconf-2.so.4+0x15b99] gconf_enum_to_string+0xd59
```
Can anyone help? Thanks. | 2011/11/23 | [
"https://Stackoverflow.com/questions/8242229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1045107/"
] | Look here: <http://www.eviware.com/forum/viewtopic.php?f=13&t=7736>
Look in ..../soapui-4.0.1/bin/soapui.sh:
```
#uncomment to disable browser component
#JAVA_OPTS="$JAVA_OPTS -Dsoapui.jxbrowser.disable=true" <- uncomment this line
```
if you are usising soapui.sh to start soapUI. If you used installer and using launcher than
in soapUI-\*.vmoptions add -Dsoapui.jxbrowser.disable=true
that should do the trick. | I also have the same issue
```
--
DUMP
...
# JRE version: 6.0_33-b03
# Java VM: Java HotSpot(TM) Server VM (20.8-b03 mixed mode linux-x86 )
# Problematic frame:
# C [libgconf-2.so.4+0x176aa] __float128+0x176aa
...
OS:Fedora release 16 (Verne)
uname:Linux 3.3.2-6.fc16.i686 #1 SMP Sat Apr 21 13:23:12 UTC 2012 i686
libc:glibc 2.14.90 NPTL 2.14.90
...
--
```
This jxbrowser...jar is working with xulrunner-2.8...jar and native code doesn't full compatible with your OS dependencies.
jxbrowser it's used for 'HTML rendering' but works also without it.
--
It works also in FC16 |
7,076,901 | In my web application I am validating the url from glabal.asax . I want to validate the url and need to redirect to an action if needed. I am using Application\_BeginRequest to catch the request event.
```
protected void Application_BeginRequest(object sender, EventArgs e)
{
// If the product is not registered then
// redirect the user to product registraion page.
if (Application[ApplicationVarInfo.ProductNotRegistered] != null)
{
//HOW TO REDIRECT TO ACTION (action=register,controller=product)
}
}
```
Or is there any other way to validate each url while getting requests in mvc and redirect to an action if needed | 2011/08/16 | [
"https://Stackoverflow.com/questions/7076901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461561/"
] | All above will not work you will be in the loop of executing the method `Application_BeginRequest`.
You need to use
```
HttpContext.Current.RewritePath("Home/About");
``` | Besides the ways mentioned already. Another way is using URLHelper which I used in a scenario once error happend and User should be redirected to the Login page :
```
public void Application_PostAuthenticateRequest(object sender, EventArgs e){
try{
if(!Request.IsAuthenticated){
throw new InvalidCredentialException("The user is not authenticated.");
}
} catch(InvalidCredentialException e){
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
Response.Redirect(urlHelper.Action("Login", "Account"));
}
}
``` |
7,076,901 | In my web application I am validating the url from glabal.asax . I want to validate the url and need to redirect to an action if needed. I am using Application\_BeginRequest to catch the request event.
```
protected void Application_BeginRequest(object sender, EventArgs e)
{
// If the product is not registered then
// redirect the user to product registraion page.
if (Application[ApplicationVarInfo.ProductNotRegistered] != null)
{
//HOW TO REDIRECT TO ACTION (action=register,controller=product)
}
}
```
Or is there any other way to validate each url while getting requests in mvc and redirect to an action if needed | 2011/08/16 | [
"https://Stackoverflow.com/questions/7076901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461561/"
] | Besides the ways mentioned already. Another way is using URLHelper which I used in a scenario once error happend and User should be redirected to the Login page :
```
public void Application_PostAuthenticateRequest(object sender, EventArgs e){
try{
if(!Request.IsAuthenticated){
throw new InvalidCredentialException("The user is not authenticated.");
}
} catch(InvalidCredentialException e){
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
Response.Redirect(urlHelper.Action("Login", "Account"));
}
}
``` | I had an old web forms application I had to convert to MVC 5 and one of the requirements was supporting possible {old\_form}.aspx links. In Global.asax Application\_BeginRequest I set up a switch statement to handle old pages to redirect to the new ones and to avoid the possible undesired looping to the home/default route check for ".aspx" in the request's raw URL.
```
protected void Application_BeginRequest(object sender, EventArgs e)
{
OldPageToNewPageRoutes();
}
/// <summary>
/// Provide redirects to new view in case someone has outdated link to .aspx pages
/// </summary>
private void OldPageToNewPageRoutes()
{
// Ignore if not Web Form:
if (!Request.RawUrl.ToLower().Contains(".aspx"))
return;
// Clean up any ending slasshes to get to the old web forms file name in switch's last index of "/":
var removeTrailingSlash = VirtualPathUtility.RemoveTrailingSlash(Request.RawUrl);
var sFullPath = !string.IsNullOrEmpty(removeTrailingSlash)
? removeTrailingSlash.ToLower()
: Request.RawUrl.ToLower();
var sSlashPath = sFullPath;
switch (sSlashPath.Split(Convert.ToChar("/")).Last().ToLower())
{
case "default.aspx":
Response.RedirectToRoute(
new RouteValueDictionary
{
{"Controller", "Home"},
{"Action", "Index"}
});
break;
default:
// Redirect to 404:
Response.RedirectToRoute(
new RouteValueDictionary
{
{"Controller", "Error"},
{"Action", "NotFound"}
});
break;
}
}
``` |
7,076,901 | In my web application I am validating the url from glabal.asax . I want to validate the url and need to redirect to an action if needed. I am using Application\_BeginRequest to catch the request event.
```
protected void Application_BeginRequest(object sender, EventArgs e)
{
// If the product is not registered then
// redirect the user to product registraion page.
if (Application[ApplicationVarInfo.ProductNotRegistered] != null)
{
//HOW TO REDIRECT TO ACTION (action=register,controller=product)
}
}
```
Or is there any other way to validate each url while getting requests in mvc and redirect to an action if needed | 2011/08/16 | [
"https://Stackoverflow.com/questions/7076901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461561/"
] | ```
Response.RedirectToRoute(
new RouteValueDictionary {
{ "Controller", "Home" },
{ "Action", "TimeoutRedirect" }} );
``` | You can try with this:
Context.Response.Redirect();
Nt sure. |
7,076,901 | In my web application I am validating the url from glabal.asax . I want to validate the url and need to redirect to an action if needed. I am using Application\_BeginRequest to catch the request event.
```
protected void Application_BeginRequest(object sender, EventArgs e)
{
// If the product is not registered then
// redirect the user to product registraion page.
if (Application[ApplicationVarInfo.ProductNotRegistered] != null)
{
//HOW TO REDIRECT TO ACTION (action=register,controller=product)
}
}
```
Or is there any other way to validate each url while getting requests in mvc and redirect to an action if needed | 2011/08/16 | [
"https://Stackoverflow.com/questions/7076901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461561/"
] | Try this:
```
HttpContext.Current.Response.Redirect("...");
``` | In my case, i prefer not use Web.config. Then i created code above in Global.asax file:
```
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
//Not Found (When user digit unexisting url)
if(ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
{
HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "NotFound");
IController controller = new ErrorController();
RequestContext requestContext = new RequestContext(contextWrapper, routeData);
controller.Execute(requestContext);
Response.End();
}
else //Unhandled Errors from aplication
{
ErrorLogService.LogError(ex);
HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
IController controller = new ErrorController();
RequestContext requestContext = new RequestContext(contextWrapper, routeData);
controller.Execute(requestContext);
Response.End();
}
}
```
And thtat is my ErrorController.cs
```
public class ErrorController : Controller
{
// GET: Error
public ViewResult Index()
{
Response.StatusCode = 500;
Exception ex = Server.GetLastError();
return View("~/Views/Shared/SAAS/Error.cshtml", ex);
}
public ViewResult NotFound()
{
Response.StatusCode = 404;
return View("~/Views/Shared/SAAS/NotFound.cshtml");
}
}
```
And that is my ErrorLogService.cs based on mason class
```
//common service to be used for logging errors
public static class ErrorLogService
{
public static void LogError(Exception ex)
{
//Do what you want here, save log in database, send email to police station
}
}
``` |
7,076,901 | In my web application I am validating the url from glabal.asax . I want to validate the url and need to redirect to an action if needed. I am using Application\_BeginRequest to catch the request event.
```
protected void Application_BeginRequest(object sender, EventArgs e)
{
// If the product is not registered then
// redirect the user to product registraion page.
if (Application[ApplicationVarInfo.ProductNotRegistered] != null)
{
//HOW TO REDIRECT TO ACTION (action=register,controller=product)
}
}
```
Or is there any other way to validate each url while getting requests in mvc and redirect to an action if needed | 2011/08/16 | [
"https://Stackoverflow.com/questions/7076901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461561/"
] | Besides the ways mentioned already. Another way is using URLHelper which I used in a scenario once error happend and User should be redirected to the Login page :
```
public void Application_PostAuthenticateRequest(object sender, EventArgs e){
try{
if(!Request.IsAuthenticated){
throw new InvalidCredentialException("The user is not authenticated.");
}
} catch(InvalidCredentialException e){
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
Response.Redirect(urlHelper.Action("Login", "Account"));
}
}
``` | ```
Response.RedirectToRoute(
new RouteValueDictionary {
{ "Controller", "Home" },
{ "Action", "TimeoutRedirect" }} );
``` |
7,076,901 | In my web application I am validating the url from glabal.asax . I want to validate the url and need to redirect to an action if needed. I am using Application\_BeginRequest to catch the request event.
```
protected void Application_BeginRequest(object sender, EventArgs e)
{
// If the product is not registered then
// redirect the user to product registraion page.
if (Application[ApplicationVarInfo.ProductNotRegistered] != null)
{
//HOW TO REDIRECT TO ACTION (action=register,controller=product)
}
}
```
Or is there any other way to validate each url while getting requests in mvc and redirect to an action if needed | 2011/08/16 | [
"https://Stackoverflow.com/questions/7076901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461561/"
] | Use the below code for redirection
```
Response.RedirectToRoute("Default");
```
"Default" is route name. If you want to redirect to any action,just create a route and use that route name . | Try this:
```
HttpContext.Current.Response.Redirect("...");
``` |
7,076,901 | In my web application I am validating the url from glabal.asax . I want to validate the url and need to redirect to an action if needed. I am using Application\_BeginRequest to catch the request event.
```
protected void Application_BeginRequest(object sender, EventArgs e)
{
// If the product is not registered then
// redirect the user to product registraion page.
if (Application[ApplicationVarInfo.ProductNotRegistered] != null)
{
//HOW TO REDIRECT TO ACTION (action=register,controller=product)
}
}
```
Or is there any other way to validate each url while getting requests in mvc and redirect to an action if needed | 2011/08/16 | [
"https://Stackoverflow.com/questions/7076901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461561/"
] | Try this:
```
HttpContext.Current.Response.Redirect("...");
``` | I do it like this:
```
HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Home");
routeData.Values.Add("action", "FirstVisit");
IController controller = new HomeController();
RequestContext requestContext = new RequestContext(contextWrapper, routeData);
controller.Execute(requestContext);
Response.End();
```
this way you wrap the incoming request context and redirect it to somewhere else without redirecting the client. So the redirect won't trigger another BeginRequest in the global.asax. |
7,076,901 | In my web application I am validating the url from glabal.asax . I want to validate the url and need to redirect to an action if needed. I am using Application\_BeginRequest to catch the request event.
```
protected void Application_BeginRequest(object sender, EventArgs e)
{
// If the product is not registered then
// redirect the user to product registraion page.
if (Application[ApplicationVarInfo.ProductNotRegistered] != null)
{
//HOW TO REDIRECT TO ACTION (action=register,controller=product)
}
}
```
Or is there any other way to validate each url while getting requests in mvc and redirect to an action if needed | 2011/08/16 | [
"https://Stackoverflow.com/questions/7076901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461561/"
] | Besides the ways mentioned already. Another way is using URLHelper which I used in a scenario once error happend and User should be redirected to the Login page :
```
public void Application_PostAuthenticateRequest(object sender, EventArgs e){
try{
if(!Request.IsAuthenticated){
throw new InvalidCredentialException("The user is not authenticated.");
}
} catch(InvalidCredentialException e){
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
Response.Redirect(urlHelper.Action("Login", "Account"));
}
}
``` | I do it like this:
```
HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Home");
routeData.Values.Add("action", "FirstVisit");
IController controller = new HomeController();
RequestContext requestContext = new RequestContext(contextWrapper, routeData);
controller.Execute(requestContext);
Response.End();
```
this way you wrap the incoming request context and redirect it to somewhere else without redirecting the client. So the redirect won't trigger another BeginRequest in the global.asax. |
7,076,901 | In my web application I am validating the url from glabal.asax . I want to validate the url and need to redirect to an action if needed. I am using Application\_BeginRequest to catch the request event.
```
protected void Application_BeginRequest(object sender, EventArgs e)
{
// If the product is not registered then
// redirect the user to product registraion page.
if (Application[ApplicationVarInfo.ProductNotRegistered] != null)
{
//HOW TO REDIRECT TO ACTION (action=register,controller=product)
}
}
```
Or is there any other way to validate each url while getting requests in mvc and redirect to an action if needed | 2011/08/16 | [
"https://Stackoverflow.com/questions/7076901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461561/"
] | Besides the ways mentioned already. Another way is using URLHelper which I used in a scenario once error happend and User should be redirected to the Login page :
```
public void Application_PostAuthenticateRequest(object sender, EventArgs e){
try{
if(!Request.IsAuthenticated){
throw new InvalidCredentialException("The user is not authenticated.");
}
} catch(InvalidCredentialException e){
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
Response.Redirect(urlHelper.Action("Login", "Account"));
}
}
``` | Try this:
```
HttpContext.Current.Response.Redirect("...");
``` |
7,076,901 | In my web application I am validating the url from glabal.asax . I want to validate the url and need to redirect to an action if needed. I am using Application\_BeginRequest to catch the request event.
```
protected void Application_BeginRequest(object sender, EventArgs e)
{
// If the product is not registered then
// redirect the user to product registraion page.
if (Application[ApplicationVarInfo.ProductNotRegistered] != null)
{
//HOW TO REDIRECT TO ACTION (action=register,controller=product)
}
}
```
Or is there any other way to validate each url while getting requests in mvc and redirect to an action if needed | 2011/08/16 | [
"https://Stackoverflow.com/questions/7076901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461561/"
] | Try this:
```
HttpContext.Current.Response.Redirect("...");
``` | ```
Response.RedirectToRoute(
new RouteValueDictionary {
{ "Controller", "Home" },
{ "Action", "TimeoutRedirect" }} );
``` |
64,364,342 | I am trying to explore AD integration and was able to succesfully complete the setup as described in [AWS blog post](https://aws.amazon.com/blogs/security/how-to-enable-ldaps-for-your-aws-microsoft-ad-directory/), and verified that SSL connection is working fine from "Management box".
Based on my understanding, ldp.exe from Management box is working fine because management box is joined to this AD and certificates are propagated properly.
I have use case where another linux box (which can't be joined to AD) but should use LDAPS over SSL to do some user search. For this to work, I need to export SSL and install it on Linux box. I couldn't quite figure out how to find and export certificates in this example? Are those certificates are available on RootCA (or) SubordinateCA and how to export them? appreciate any help. | 2020/10/15 | [
"https://Stackoverflow.com/questions/64364342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1094597/"
] | I'm assuming you generated the SSL cert in AWS via Amazon Certificate Services (ACS). Although ACS won't allow you to export the private key from ACS, you shouldn't need it. All you need to do is import the public certificate into the certificate trust store that your Linux box is using when it connects to the AD server. I can't tell you how to do that (not sure what the application is), but you should be able to extract the public cert using openssl. You'll point openssl to the ad server, and have it output the public cert.
I'm pretty sure this is the openssl command line that would do that:
openssl s\_client -showcerts -connect activedirectory.yourdomain.com:636 | ```
You can download the certificate from the ldaps end point and install it as follows.
Install openldap client
sudo yum install -y openldap-clients
• Download and Add Server Certificate to the openldap cert path
openssl s_client -connect <LDAPSURL>:636 -showcerts </dev/null 2>/dev/null | openssl x509 -outform PEM > server.crt
• Configure LDAP Details
Vi /etc/openldap/ldap.conf
BASE dc=corp,dc=example,dc=com
URI ldaps://corp.example.com
TLS_CACERT /etc/openldap/certs/server.crt
``` |
379,128 | How would someone who really knows how to take advantage of dynamic programming languages approach programming differently than someone working in a static language?
I'm familiar with the whole debate over static versus dynamic typing, but that's not what I'm getting at. I'd like to discuss problem solving techniques that are practical in dynamic languages but not in static languages.
Most of the code I've seen written in dynamic programming languages isn't very different than code written in static programming languages. As the saying goes, you can write FORTRAN in any language, and many people do. But some people use dynamic programming languages to solve problems in a way that wouldn't easily translate into, for example, C++. What are some of their techniques?
What are some good resources that discuss how to use dynamic programming languages? Not books on language syntax or API reference, but resources on problem solving approaches that take advantage of dynamic language capabilities.
EDIT (1/5/2009): I appreciate the answers below, but they don't seem to account for the huge increases in productivity that dynamic language advocates say they experience. | 2008/12/18 | [
"https://Stackoverflow.com/questions/379128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25188/"
] | It comes down to one of my favorite ratios: How much time I spend thinking about solving a problem, vs. how much time I spend thinking about the tool I'm using to solve the problem. Think of it as equivalent to S/N ratios.
With duck-typing languages (which I consider to be the factor that helps me the most with productivity), I simply am able to spend more time thinking about my problem and its solution (and write code that addresses those specifically), and I spend less time keeping the language artifacts straight.
Then there's a lot of code I just don't write, involving declarations and especially type-casts.
But it's mainly keeping my focus in the sweet spot. | More libraries and more important *more useable libraries*.
My guess is that the "Duck Typing" usually associated with dynamic languages helps simplify the code significantly and makes writing generic code much easier. You are not constrained by a strict class hierarchy and thus are able to more easily compose components from different libraries together. |
379,128 | How would someone who really knows how to take advantage of dynamic programming languages approach programming differently than someone working in a static language?
I'm familiar with the whole debate over static versus dynamic typing, but that's not what I'm getting at. I'd like to discuss problem solving techniques that are practical in dynamic languages but not in static languages.
Most of the code I've seen written in dynamic programming languages isn't very different than code written in static programming languages. As the saying goes, you can write FORTRAN in any language, and many people do. But some people use dynamic programming languages to solve problems in a way that wouldn't easily translate into, for example, C++. What are some of their techniques?
What are some good resources that discuss how to use dynamic programming languages? Not books on language syntax or API reference, but resources on problem solving approaches that take advantage of dynamic language capabilities.
EDIT (1/5/2009): I appreciate the answers below, but they don't seem to account for the huge increases in productivity that dynamic language advocates say they experience. | 2008/12/18 | [
"https://Stackoverflow.com/questions/379128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25188/"
] | I like slim's answer. I do spend a crazy amount of time in Java and C++ crafting custom data structures that are just free in Python/Ruby. And crafting specialized functions to process these custom data structures. Yes, in C++, STL is really nice. Yes, Generics in Java are nice. They help create custom data structures much faster, however they still require a lot of thought and consideration.
However, there is a more fundamental reason why dynamic languages are easier to work with. It is a deep idea which is called duck typing. Some comments above refer to duck typing, but please take time to reflect on what duck typing is. It is a fundamentally different way to view the world. A view that is incompatible with languages like Java and C++.
Duck typing means that you waste not time in defining what a duck is. By not having to formally define your objects you save a lot of time and energy. Getting definitions right is hard. Have a look at this blog post of mine where I give examples: [Formal definitions are less useful than you think](http://www.daniel-lemire.com/blog/archives/2007/12/05/formal-definitions-are-less-useful-than-you-think/)
Duck typing has proven extremely useful. The ["Must Ignore" principle in XML](http://www.tbray.org/ongoing/When/200x/2006/01/09/On-XML-Language-Design) is what has made XML so significant and useful on the web. But that's just an instance of duck typing.
Another way to express duck typing is by the Web mantra "Be strict in what you send, generous in what you accept". That is also a very fundamental idea.
Finally, you may want to back to a long blog post of mine where I explain duck typing and how it relates to things like AI and modelling: [Duck Typing, Artificial Intelligence and Philosophy](http://www.daniel-lemire.com/blog/archives/2007/01/27/duck-typing-artificial-intelligence-and-philosophy/) | Dynamic Languages can change the object at run time, you can add methods, properties...
One good example of Dynamic Languages magic is this Groovy code snippet which call a method on a webservice in just two lines of code:
```
def proxy = new SoapClient("http://localhost:6980/MathServiceInterface?wsdl");
def result = proxy.add(1.0, 2.0);
```
This is another Groovy snippet that extract data from XML:
```
def contacts = new XmlParser().parseText("<contacts><name>Bahaa Zaid</name></contacts>");
def myName = contacts.name[0].text();
```
You cannot do this in Static Languages. Dynamic Language can change the objects to reflect the actual runtime condition. |
379,128 | How would someone who really knows how to take advantage of dynamic programming languages approach programming differently than someone working in a static language?
I'm familiar with the whole debate over static versus dynamic typing, but that's not what I'm getting at. I'd like to discuss problem solving techniques that are practical in dynamic languages but not in static languages.
Most of the code I've seen written in dynamic programming languages isn't very different than code written in static programming languages. As the saying goes, you can write FORTRAN in any language, and many people do. But some people use dynamic programming languages to solve problems in a way that wouldn't easily translate into, for example, C++. What are some of their techniques?
What are some good resources that discuss how to use dynamic programming languages? Not books on language syntax or API reference, but resources on problem solving approaches that take advantage of dynamic language capabilities.
EDIT (1/5/2009): I appreciate the answers below, but they don't seem to account for the huge increases in productivity that dynamic language advocates say they experience. | 2008/12/18 | [
"https://Stackoverflow.com/questions/379128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25188/"
] | Fast iterations make happier programmers, and they don't come any faster than an interactive interpreter. Good interpreter exploitation gives you sandbox, testing, and prototyping at the same time.
Beware programming by permutation, however. My personal rule of thumb is that it's just because it works doesn't mean it's ready, when you can explain why it works it's ready. | Read "Higher Order Perl" by Mark Jason Dominus. It only discusses Perl but it does give techniques that are natural to Perl that would be less natural in most static languages.
```
All languages obviously have their strengths and weaknesses and dymanic vs static
```
is only one of many ways to classify a language. I would not make the argument that dynamic languages as a whole are better or worse then static languages. But I do think this book is
very good at showing different ways of approaching problems using Perl that would be more
difficult or impossible in most Static languages. |
379,128 | How would someone who really knows how to take advantage of dynamic programming languages approach programming differently than someone working in a static language?
I'm familiar with the whole debate over static versus dynamic typing, but that's not what I'm getting at. I'd like to discuss problem solving techniques that are practical in dynamic languages but not in static languages.
Most of the code I've seen written in dynamic programming languages isn't very different than code written in static programming languages. As the saying goes, you can write FORTRAN in any language, and many people do. But some people use dynamic programming languages to solve problems in a way that wouldn't easily translate into, for example, C++. What are some of their techniques?
What are some good resources that discuss how to use dynamic programming languages? Not books on language syntax or API reference, but resources on problem solving approaches that take advantage of dynamic language capabilities.
EDIT (1/5/2009): I appreciate the answers below, but they don't seem to account for the huge increases in productivity that dynamic language advocates say they experience. | 2008/12/18 | [
"https://Stackoverflow.com/questions/379128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25188/"
] | It comes down to one of my favorite ratios: How much time I spend thinking about solving a problem, vs. how much time I spend thinking about the tool I'm using to solve the problem. Think of it as equivalent to S/N ratios.
With duck-typing languages (which I consider to be the factor that helps me the most with productivity), I simply am able to spend more time thinking about my problem and its solution (and write code that addresses those specifically), and I spend less time keeping the language artifacts straight.
Then there's a lot of code I just don't write, involving declarations and especially type-casts.
But it's mainly keeping my focus in the sweet spot. | Dynamic languages are capable of executing code which was created at run-time. This is very dangerous if malicious code is injected. But very powerful if you can sanitize the environment.
I think Javascript people do this by executing JSON files. |
379,128 | How would someone who really knows how to take advantage of dynamic programming languages approach programming differently than someone working in a static language?
I'm familiar with the whole debate over static versus dynamic typing, but that's not what I'm getting at. I'd like to discuss problem solving techniques that are practical in dynamic languages but not in static languages.
Most of the code I've seen written in dynamic programming languages isn't very different than code written in static programming languages. As the saying goes, you can write FORTRAN in any language, and many people do. But some people use dynamic programming languages to solve problems in a way that wouldn't easily translate into, for example, C++. What are some of their techniques?
What are some good resources that discuss how to use dynamic programming languages? Not books on language syntax or API reference, but resources on problem solving approaches that take advantage of dynamic language capabilities.
EDIT (1/5/2009): I appreciate the answers below, but they don't seem to account for the huge increases in productivity that dynamic language advocates say they experience. | 2008/12/18 | [
"https://Stackoverflow.com/questions/379128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25188/"
] | I like slim's answer. I do spend a crazy amount of time in Java and C++ crafting custom data structures that are just free in Python/Ruby. And crafting specialized functions to process these custom data structures. Yes, in C++, STL is really nice. Yes, Generics in Java are nice. They help create custom data structures much faster, however they still require a lot of thought and consideration.
However, there is a more fundamental reason why dynamic languages are easier to work with. It is a deep idea which is called duck typing. Some comments above refer to duck typing, but please take time to reflect on what duck typing is. It is a fundamentally different way to view the world. A view that is incompatible with languages like Java and C++.
Duck typing means that you waste not time in defining what a duck is. By not having to formally define your objects you save a lot of time and energy. Getting definitions right is hard. Have a look at this blog post of mine where I give examples: [Formal definitions are less useful than you think](http://www.daniel-lemire.com/blog/archives/2007/12/05/formal-definitions-are-less-useful-than-you-think/)
Duck typing has proven extremely useful. The ["Must Ignore" principle in XML](http://www.tbray.org/ongoing/When/200x/2006/01/09/On-XML-Language-Design) is what has made XML so significant and useful on the web. But that's just an instance of duck typing.
Another way to express duck typing is by the Web mantra "Be strict in what you send, generous in what you accept". That is also a very fundamental idea.
Finally, you may want to back to a long blog post of mine where I explain duck typing and how it relates to things like AI and modelling: [Duck Typing, Artificial Intelligence and Philosophy](http://www.daniel-lemire.com/blog/archives/2007/01/27/duck-typing-artificial-intelligence-and-philosophy/) | I can't cite this right now (my memory is failing me), but I've heard something along the lines of:
>
> The closest the programming industry has come to a silver bullet is
> managed languages – freeing the programmer from having to worry about
> the details of memory management and letting them focus more energy
> on solving the problem at hand.
>
>
>
So, I might venture a guess and say it's not so much that you program *differently*, it's that you can devote more of your brain to "solving the problem" rather than the solution's implementation details. |
379,128 | How would someone who really knows how to take advantage of dynamic programming languages approach programming differently than someone working in a static language?
I'm familiar with the whole debate over static versus dynamic typing, but that's not what I'm getting at. I'd like to discuss problem solving techniques that are practical in dynamic languages but not in static languages.
Most of the code I've seen written in dynamic programming languages isn't very different than code written in static programming languages. As the saying goes, you can write FORTRAN in any language, and many people do. But some people use dynamic programming languages to solve problems in a way that wouldn't easily translate into, for example, C++. What are some of their techniques?
What are some good resources that discuss how to use dynamic programming languages? Not books on language syntax or API reference, but resources on problem solving approaches that take advantage of dynamic language capabilities.
EDIT (1/5/2009): I appreciate the answers below, but they don't seem to account for the huge increases in productivity that dynamic language advocates say they experience. | 2008/12/18 | [
"https://Stackoverflow.com/questions/379128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25188/"
] | I can't cite this right now (my memory is failing me), but I've heard something along the lines of:
>
> The closest the programming industry has come to a silver bullet is
> managed languages – freeing the programmer from having to worry about
> the details of memory management and letting them focus more energy
> on solving the problem at hand.
>
>
>
So, I might venture a guess and say it's not so much that you program *differently*, it's that you can devote more of your brain to "solving the problem" rather than the solution's implementation details. | I do not have a specific answer, just a suggestion: have a look at the book "[Design patterns in Ruby](http://designpatternsinruby.com)" : it goes over most of the classic design patterns (à la Gamma et al., and more) and express them, quite succinctly, in Ruby :) |
379,128 | How would someone who really knows how to take advantage of dynamic programming languages approach programming differently than someone working in a static language?
I'm familiar with the whole debate over static versus dynamic typing, but that's not what I'm getting at. I'd like to discuss problem solving techniques that are practical in dynamic languages but not in static languages.
Most of the code I've seen written in dynamic programming languages isn't very different than code written in static programming languages. As the saying goes, you can write FORTRAN in any language, and many people do. But some people use dynamic programming languages to solve problems in a way that wouldn't easily translate into, for example, C++. What are some of their techniques?
What are some good resources that discuss how to use dynamic programming languages? Not books on language syntax or API reference, but resources on problem solving approaches that take advantage of dynamic language capabilities.
EDIT (1/5/2009): I appreciate the answers below, but they don't seem to account for the huge increases in productivity that dynamic language advocates say they experience. | 2008/12/18 | [
"https://Stackoverflow.com/questions/379128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25188/"
] | John, just based on your update edit of 1/5/09, you might find [AMOP](http://en.wikipedia.org/wiki/The_Art_of_the_Metaobject_Protocol) an interesting read, and more on the line you're thinking of. It's pretty lisp-centric, but after all many of the good dynamic ideas started there. So if you can enjoy (or get past) that aspect, the authors do discuss the dynamic aspects needed and used to do something like this. It's pretty powerful stuff. | Dynamic languages are capable of executing code which was created at run-time. This is very dangerous if malicious code is injected. But very powerful if you can sanitize the environment.
I think Javascript people do this by executing JSON files. |
379,128 | How would someone who really knows how to take advantage of dynamic programming languages approach programming differently than someone working in a static language?
I'm familiar with the whole debate over static versus dynamic typing, but that's not what I'm getting at. I'd like to discuss problem solving techniques that are practical in dynamic languages but not in static languages.
Most of the code I've seen written in dynamic programming languages isn't very different than code written in static programming languages. As the saying goes, you can write FORTRAN in any language, and many people do. But some people use dynamic programming languages to solve problems in a way that wouldn't easily translate into, for example, C++. What are some of their techniques?
What are some good resources that discuss how to use dynamic programming languages? Not books on language syntax or API reference, but resources on problem solving approaches that take advantage of dynamic language capabilities.
EDIT (1/5/2009): I appreciate the answers below, but they don't seem to account for the huge increases in productivity that dynamic language advocates say they experience. | 2008/12/18 | [
"https://Stackoverflow.com/questions/379128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25188/"
] | Fast iterations make happier programmers, and they don't come any faster than an interactive interpreter. Good interpreter exploitation gives you sandbox, testing, and prototyping at the same time.
Beware programming by permutation, however. My personal rule of thumb is that it's just because it works doesn't mean it's ready, when you can explain why it works it's ready. | For me it's turnaround speed. The dynamic languages I use (Python and a bit of JavaScript at the moment) are interpreted. This means I can try things out on the fly. If I want to see how a certain bit of the API behaves I can just hack away at the interpreter for a couple of minutes.
If I wanted to do the same in a language like C# I'd have to fire up VS, make a project, then compile it. If I want to test a part of a bigger piece of software I'm working on I probably have to compile that, which can take ages. Fortunately in .Net I can load up assemblies from the big project in IronPython and get some of the same benefits (i.e. quickly testing out different parts of the API) of interpreted languages. |
379,128 | How would someone who really knows how to take advantage of dynamic programming languages approach programming differently than someone working in a static language?
I'm familiar with the whole debate over static versus dynamic typing, but that's not what I'm getting at. I'd like to discuss problem solving techniques that are practical in dynamic languages but not in static languages.
Most of the code I've seen written in dynamic programming languages isn't very different than code written in static programming languages. As the saying goes, you can write FORTRAN in any language, and many people do. But some people use dynamic programming languages to solve problems in a way that wouldn't easily translate into, for example, C++. What are some of their techniques?
What are some good resources that discuss how to use dynamic programming languages? Not books on language syntax or API reference, but resources on problem solving approaches that take advantage of dynamic language capabilities.
EDIT (1/5/2009): I appreciate the answers below, but they don't seem to account for the huge increases in productivity that dynamic language advocates say they experience. | 2008/12/18 | [
"https://Stackoverflow.com/questions/379128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25188/"
] | My biggest gains are in mapping between databases and objects (ORM).
If there is no concept of a type, it becomes very easy to say assign every column in a row to a value in an object. Of course the trade off is that there can be a mismatch between the type of value you think is there and what type the computer does. | More libraries and more important *more useable libraries*.
My guess is that the "Duck Typing" usually associated with dynamic languages helps simplify the code significantly and makes writing generic code much easier. You are not constrained by a strict class hierarchy and thus are able to more easily compose components from different libraries together. |
379,128 | How would someone who really knows how to take advantage of dynamic programming languages approach programming differently than someone working in a static language?
I'm familiar with the whole debate over static versus dynamic typing, but that's not what I'm getting at. I'd like to discuss problem solving techniques that are practical in dynamic languages but not in static languages.
Most of the code I've seen written in dynamic programming languages isn't very different than code written in static programming languages. As the saying goes, you can write FORTRAN in any language, and many people do. But some people use dynamic programming languages to solve problems in a way that wouldn't easily translate into, for example, C++. What are some of their techniques?
What are some good resources that discuss how to use dynamic programming languages? Not books on language syntax or API reference, but resources on problem solving approaches that take advantage of dynamic language capabilities.
EDIT (1/5/2009): I appreciate the answers below, but they don't seem to account for the huge increases in productivity that dynamic language advocates say they experience. | 2008/12/18 | [
"https://Stackoverflow.com/questions/379128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25188/"
] | I like slim's answer. I do spend a crazy amount of time in Java and C++ crafting custom data structures that are just free in Python/Ruby. And crafting specialized functions to process these custom data structures. Yes, in C++, STL is really nice. Yes, Generics in Java are nice. They help create custom data structures much faster, however they still require a lot of thought and consideration.
However, there is a more fundamental reason why dynamic languages are easier to work with. It is a deep idea which is called duck typing. Some comments above refer to duck typing, but please take time to reflect on what duck typing is. It is a fundamentally different way to view the world. A view that is incompatible with languages like Java and C++.
Duck typing means that you waste not time in defining what a duck is. By not having to formally define your objects you save a lot of time and energy. Getting definitions right is hard. Have a look at this blog post of mine where I give examples: [Formal definitions are less useful than you think](http://www.daniel-lemire.com/blog/archives/2007/12/05/formal-definitions-are-less-useful-than-you-think/)
Duck typing has proven extremely useful. The ["Must Ignore" principle in XML](http://www.tbray.org/ongoing/When/200x/2006/01/09/On-XML-Language-Design) is what has made XML so significant and useful on the web. But that's just an instance of duck typing.
Another way to express duck typing is by the Web mantra "Be strict in what you send, generous in what you accept". That is also a very fundamental idea.
Finally, you may want to back to a long blog post of mine where I explain duck typing and how it relates to things like AI and modelling: [Duck Typing, Artificial Intelligence and Philosophy](http://www.daniel-lemire.com/blog/archives/2007/01/27/duck-typing-artificial-intelligence-and-philosophy/) | Read "Higher Order Perl" by Mark Jason Dominus. It only discusses Perl but it does give techniques that are natural to Perl that would be less natural in most static languages.
```
All languages obviously have their strengths and weaknesses and dymanic vs static
```
is only one of many ways to classify a language. I would not make the argument that dynamic languages as a whole are better or worse then static languages. But I do think this book is
very good at showing different ways of approaching problems using Perl that would be more
difficult or impossible in most Static languages. |
62,490,259 | I am trying to use selenium + python to enter credit card values into a Shopify site. The boxes to enter the card values are in an iframe and I am unsure how to switch to this iframe.
I currently have this code:
```
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,
'//*[@id="card-fields-number-950kvfi9pbn00000"]'))
).send_keys(card_number, Keys.TAB, name_on_card, Keys.TAB,expiry_date, cvv)
driver.switch_to.default_content()
```
But this returns the error:
```
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(...
selenium.common.exceptions.TimeoutException: Message:
```
So effectively, the element could not be found...
This is the HTML of the page:
(<https://gyazo.com/80d9d3c941c62ededc81d5fbc327a71f>)
I would like some help on how to access this element, I have also tried accessing it by changing the id to a parent of this tag. I have also added a `time.sleep(20)` so I can be sure the page has fully loaded and I still got the same error. | 2020/06/20 | [
"https://Stackoverflow.com/questions/62490259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13554838/"
] | See [Knuth–Morris–Pratt algorithm](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm), which has the time complexity of $O(n)$
One possible implementation:
```py
def kmp(pattern, text):
n = len(pattern)
m = len(text)
next_v = [0] * n
for i in range(1, n):
j = next_v[i - 1]
while j > 0 and pattern[i] != pattern[j]:
j = next_v[j - 1]
if pattern[i] == pattern[j]:
j += 1
next_v[i] = j
j = 0
for i in range(m):
while j > 0 and text[i] != pattern[j]:
j = next_v[j - 1]
if text[i] == pattern[j]:
j += 1
if j == n:
return i - n + 1
return -1
```
`pattern` can be used as the sub-list to check while `text` can be used as the entire list. | Convert `l1` and `l2` to strings, and then do the search:
```
l1 = [1,2,3,4]
l2 = [3,5,6,1,2,3,4,6]
l1 = str(l1)
l2 = str(l2)
# This will return a string of the data only without the '[',']'
l1 = l1.split('[')[1].split(']')[0]
l2 = l2.split('[')[1].split(']')[0]
# Using string find function
if l2.find(l1) > 0 :
print('l1 is a sublist of l2')
``` |
62,490,259 | I am trying to use selenium + python to enter credit card values into a Shopify site. The boxes to enter the card values are in an iframe and I am unsure how to switch to this iframe.
I currently have this code:
```
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,
'//*[@id="card-fields-number-950kvfi9pbn00000"]'))
).send_keys(card_number, Keys.TAB, name_on_card, Keys.TAB,expiry_date, cvv)
driver.switch_to.default_content()
```
But this returns the error:
```
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(...
selenium.common.exceptions.TimeoutException: Message:
```
So effectively, the element could not be found...
This is the HTML of the page:
(<https://gyazo.com/80d9d3c941c62ededc81d5fbc327a71f>)
I would like some help on how to access this element, I have also tried accessing it by changing the id to a parent of this tag. I have also added a `time.sleep(20)` so I can be sure the page has fully loaded and I still got the same error. | 2020/06/20 | [
"https://Stackoverflow.com/questions/62490259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13554838/"
] | See [Knuth–Morris–Pratt algorithm](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm), which has the time complexity of $O(n)$
One possible implementation:
```py
def kmp(pattern, text):
n = len(pattern)
m = len(text)
next_v = [0] * n
for i in range(1, n):
j = next_v[i - 1]
while j > 0 and pattern[i] != pattern[j]:
j = next_v[j - 1]
if pattern[i] == pattern[j]:
j += 1
next_v[i] = j
j = 0
for i in range(m):
while j > 0 and text[i] != pattern[j]:
j = next_v[j - 1]
if text[i] == pattern[j]:
j += 1
if j == n:
return i - n + 1
return -1
```
`pattern` can be used as the sub-list to check while `text` can be used as the entire list. | Here is what you can do:
```
l1 = [1,2,3,4]
l2 = [3,5,6,1,2,3,4,6]
found = False
for i in range(len(l2)-len(l1)+1):
if l2[i:i+len(l1)] == l1:
found = True
if found:
print('found')
else:
print('not found')
```
Output:
```
found
```
---
**Another way:**
```
l1 = [1,2,3,4]
l2 = [3,5,6,1,2,3,4,6]
if str(l1)[1:-1] in str(l2)[1:-1]:
print('found')
else:
print('not found')
```
Output:
```
found
``` |
57,941,441 | I am trying to find a REGEX expression (or multiple ones) that i can use in Notepad++ (Windows) that will change different parts of URLs based on specific symbols that divide them.
Basically i have this type of URLs in a big file, they are scaterred around:
```
domain.com/folder/random-text-1?REPLACE-THIS-1=REPLACE-THIS-2=REPLACE-THIS-3&REPLACE-THIS-4
```
The REPLACE-THIS-1/-2/-3/-4 always differs from each other, even between different URLs, like this:
```
domain.com/folder/random-text-2?A1=A2=A3&A4
domain.com/folder/random-text-2?B1=B2=B3&B4
etc
```
(Note: "folder" stays the same all the time)
This is what I am trying to do with REGEX expression(s):
* "REPLACE-THIS-1" with "REPLACED-1"
Note: so basically when it finds the first "?" it will replace the "REPLACE-THIS-1" after it with a specific one "REPLACED-1" up to it gets to "=" symbol
* "REPLACE-THIS-2" with "REPLACED-2"
Note: this one is between first "=" found, and second "=" found
* "REPLACE-THIS-3" with "REPLACED-3"
Note: this is the text after second "=" found
* "REPLACE-THIS-4" with "REPLACED-4"
Note: the problem is that "REPLACE-THIS-4" includes sometimes the "=" symbol as well, but i want to replace all of the text after the "REPLACE-THIS-3&"
Note: REPLACED-1/REPLACED-2/REPLACED-3/REPLACED-4 are always the same, they don't change
The biggest problem i am facing is that all these replace-1/-2-/3/-4 are different amongst each other (i mean the all URLs have different values), so it'd be great if i can use a regex/multiple regex formulas to replace!
Thank you so much! | 2019/09/15 | [
"https://Stackoverflow.com/questions/57941441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11064864/"
] | The function *parentheses* expects an lvalue in the std::string parameter, i.e. a named variable. However, you have supplied an rvalue (temporary) in this call:
parentheses(n,"",0,0);
An empty string object is created and passed to parentheses. You can avoid this problem by changing the definition of parentheses like so:
```
void parentheses (int n, const string& str, int left, int right)
```
Here str will bind to an rvalue/temporary, but you won't be able to change its value in the function. However, if you want to change the value of str you have to define a string variable and pass that to the function.
Example:
```
void solve(int n){
std::string str;
parentheses(n,str,0,0);
}
```
Note: no need to assign str to "" as a string is empty by default. | the function needs a memory to change, you didn't specify which.
declare a string to hold what you want to pass and where to get the output to.
```
string s = "";
```
and pass it to the function |
57,941,441 | I am trying to find a REGEX expression (or multiple ones) that i can use in Notepad++ (Windows) that will change different parts of URLs based on specific symbols that divide them.
Basically i have this type of URLs in a big file, they are scaterred around:
```
domain.com/folder/random-text-1?REPLACE-THIS-1=REPLACE-THIS-2=REPLACE-THIS-3&REPLACE-THIS-4
```
The REPLACE-THIS-1/-2/-3/-4 always differs from each other, even between different URLs, like this:
```
domain.com/folder/random-text-2?A1=A2=A3&A4
domain.com/folder/random-text-2?B1=B2=B3&B4
etc
```
(Note: "folder" stays the same all the time)
This is what I am trying to do with REGEX expression(s):
* "REPLACE-THIS-1" with "REPLACED-1"
Note: so basically when it finds the first "?" it will replace the "REPLACE-THIS-1" after it with a specific one "REPLACED-1" up to it gets to "=" symbol
* "REPLACE-THIS-2" with "REPLACED-2"
Note: this one is between first "=" found, and second "=" found
* "REPLACE-THIS-3" with "REPLACED-3"
Note: this is the text after second "=" found
* "REPLACE-THIS-4" with "REPLACED-4"
Note: the problem is that "REPLACE-THIS-4" includes sometimes the "=" symbol as well, but i want to replace all of the text after the "REPLACE-THIS-3&"
Note: REPLACED-1/REPLACED-2/REPLACED-3/REPLACED-4 are always the same, they don't change
The biggest problem i am facing is that all these replace-1/-2-/3/-4 are different amongst each other (i mean the all URLs have different values), so it'd be great if i can use a regex/multiple regex formulas to replace!
Thank you so much! | 2019/09/15 | [
"https://Stackoverflow.com/questions/57941441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11064864/"
] | the function needs a memory to change, you didn't specify which.
declare a string to hold what you want to pass and where to get the output to.
```
string s = "";
```
and pass it to the function | If you want to change the values of your string for any string that is passed as a paramenter (lvalue, as well rvalue), just initialize a variable with the intended content and pass it to your function.
But if you want to treat lvalue strings diferently from rvalue strings, just overload your original function. i.e.:
```
void parentheses (int n, string& str, int left, int right){
... irrelevant... // change strings values as desired
}
void parentheses (int n, string&& str, int left, int right){
... irrelevant... // string as rvalue
}
``` |
57,941,441 | I am trying to find a REGEX expression (or multiple ones) that i can use in Notepad++ (Windows) that will change different parts of URLs based on specific symbols that divide them.
Basically i have this type of URLs in a big file, they are scaterred around:
```
domain.com/folder/random-text-1?REPLACE-THIS-1=REPLACE-THIS-2=REPLACE-THIS-3&REPLACE-THIS-4
```
The REPLACE-THIS-1/-2/-3/-4 always differs from each other, even between different URLs, like this:
```
domain.com/folder/random-text-2?A1=A2=A3&A4
domain.com/folder/random-text-2?B1=B2=B3&B4
etc
```
(Note: "folder" stays the same all the time)
This is what I am trying to do with REGEX expression(s):
* "REPLACE-THIS-1" with "REPLACED-1"
Note: so basically when it finds the first "?" it will replace the "REPLACE-THIS-1" after it with a specific one "REPLACED-1" up to it gets to "=" symbol
* "REPLACE-THIS-2" with "REPLACED-2"
Note: this one is between first "=" found, and second "=" found
* "REPLACE-THIS-3" with "REPLACED-3"
Note: this is the text after second "=" found
* "REPLACE-THIS-4" with "REPLACED-4"
Note: the problem is that "REPLACE-THIS-4" includes sometimes the "=" symbol as well, but i want to replace all of the text after the "REPLACE-THIS-3&"
Note: REPLACED-1/REPLACED-2/REPLACED-3/REPLACED-4 are always the same, they don't change
The biggest problem i am facing is that all these replace-1/-2-/3/-4 are different amongst each other (i mean the all URLs have different values), so it'd be great if i can use a regex/multiple regex formulas to replace!
Thank you so much! | 2019/09/15 | [
"https://Stackoverflow.com/questions/57941441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11064864/"
] | The function *parentheses* expects an lvalue in the std::string parameter, i.e. a named variable. However, you have supplied an rvalue (temporary) in this call:
parentheses(n,"",0,0);
An empty string object is created and passed to parentheses. You can avoid this problem by changing the definition of parentheses like so:
```
void parentheses (int n, const string& str, int left, int right)
```
Here str will bind to an rvalue/temporary, but you won't be able to change its value in the function. However, if you want to change the value of str you have to define a string variable and pass that to the function.
Example:
```
void solve(int n){
std::string str;
parentheses(n,str,0,0);
}
```
Note: no need to assign str to "" as a string is empty by default. | I'm not really sure what the purpose is of passing `""` by reference is, as any value put there will get lost.
Anyway, to answer your question, create a variable and pass it instead:
```
void solve(int n){
std::string tmp = "";
parentheses(n,tmp,0,0);
}
```
If you don't care about the value stored in `tmp`, you can just ignore it. But you need *some* type of variable there, even if you don't care about what gets eventually put there by the routine. |
57,941,441 | I am trying to find a REGEX expression (or multiple ones) that i can use in Notepad++ (Windows) that will change different parts of URLs based on specific symbols that divide them.
Basically i have this type of URLs in a big file, they are scaterred around:
```
domain.com/folder/random-text-1?REPLACE-THIS-1=REPLACE-THIS-2=REPLACE-THIS-3&REPLACE-THIS-4
```
The REPLACE-THIS-1/-2/-3/-4 always differs from each other, even between different URLs, like this:
```
domain.com/folder/random-text-2?A1=A2=A3&A4
domain.com/folder/random-text-2?B1=B2=B3&B4
etc
```
(Note: "folder" stays the same all the time)
This is what I am trying to do with REGEX expression(s):
* "REPLACE-THIS-1" with "REPLACED-1"
Note: so basically when it finds the first "?" it will replace the "REPLACE-THIS-1" after it with a specific one "REPLACED-1" up to it gets to "=" symbol
* "REPLACE-THIS-2" with "REPLACED-2"
Note: this one is between first "=" found, and second "=" found
* "REPLACE-THIS-3" with "REPLACED-3"
Note: this is the text after second "=" found
* "REPLACE-THIS-4" with "REPLACED-4"
Note: the problem is that "REPLACE-THIS-4" includes sometimes the "=" symbol as well, but i want to replace all of the text after the "REPLACE-THIS-3&"
Note: REPLACED-1/REPLACED-2/REPLACED-3/REPLACED-4 are always the same, they don't change
The biggest problem i am facing is that all these replace-1/-2-/3/-4 are different amongst each other (i mean the all URLs have different values), so it'd be great if i can use a regex/multiple regex formulas to replace!
Thank you so much! | 2019/09/15 | [
"https://Stackoverflow.com/questions/57941441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11064864/"
] | I'm not really sure what the purpose is of passing `""` by reference is, as any value put there will get lost.
Anyway, to answer your question, create a variable and pass it instead:
```
void solve(int n){
std::string tmp = "";
parentheses(n,tmp,0,0);
}
```
If you don't care about the value stored in `tmp`, you can just ignore it. But you need *some* type of variable there, even if you don't care about what gets eventually put there by the routine. | If you want to change the values of your string for any string that is passed as a paramenter (lvalue, as well rvalue), just initialize a variable with the intended content and pass it to your function.
But if you want to treat lvalue strings diferently from rvalue strings, just overload your original function. i.e.:
```
void parentheses (int n, string& str, int left, int right){
... irrelevant... // change strings values as desired
}
void parentheses (int n, string&& str, int left, int right){
... irrelevant... // string as rvalue
}
``` |
57,941,441 | I am trying to find a REGEX expression (or multiple ones) that i can use in Notepad++ (Windows) that will change different parts of URLs based on specific symbols that divide them.
Basically i have this type of URLs in a big file, they are scaterred around:
```
domain.com/folder/random-text-1?REPLACE-THIS-1=REPLACE-THIS-2=REPLACE-THIS-3&REPLACE-THIS-4
```
The REPLACE-THIS-1/-2/-3/-4 always differs from each other, even between different URLs, like this:
```
domain.com/folder/random-text-2?A1=A2=A3&A4
domain.com/folder/random-text-2?B1=B2=B3&B4
etc
```
(Note: "folder" stays the same all the time)
This is what I am trying to do with REGEX expression(s):
* "REPLACE-THIS-1" with "REPLACED-1"
Note: so basically when it finds the first "?" it will replace the "REPLACE-THIS-1" after it with a specific one "REPLACED-1" up to it gets to "=" symbol
* "REPLACE-THIS-2" with "REPLACED-2"
Note: this one is between first "=" found, and second "=" found
* "REPLACE-THIS-3" with "REPLACED-3"
Note: this is the text after second "=" found
* "REPLACE-THIS-4" with "REPLACED-4"
Note: the problem is that "REPLACE-THIS-4" includes sometimes the "=" symbol as well, but i want to replace all of the text after the "REPLACE-THIS-3&"
Note: REPLACED-1/REPLACED-2/REPLACED-3/REPLACED-4 are always the same, they don't change
The biggest problem i am facing is that all these replace-1/-2-/3/-4 are different amongst each other (i mean the all URLs have different values), so it'd be great if i can use a regex/multiple regex formulas to replace!
Thank you so much! | 2019/09/15 | [
"https://Stackoverflow.com/questions/57941441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11064864/"
] | The function *parentheses* expects an lvalue in the std::string parameter, i.e. a named variable. However, you have supplied an rvalue (temporary) in this call:
parentheses(n,"",0,0);
An empty string object is created and passed to parentheses. You can avoid this problem by changing the definition of parentheses like so:
```
void parentheses (int n, const string& str, int left, int right)
```
Here str will bind to an rvalue/temporary, but you won't be able to change its value in the function. However, if you want to change the value of str you have to define a string variable and pass that to the function.
Example:
```
void solve(int n){
std::string str;
parentheses(n,str,0,0);
}
```
Note: no need to assign str to "" as a string is empty by default. | If you want to change the values of your string for any string that is passed as a paramenter (lvalue, as well rvalue), just initialize a variable with the intended content and pass it to your function.
But if you want to treat lvalue strings diferently from rvalue strings, just overload your original function. i.e.:
```
void parentheses (int n, string& str, int left, int right){
... irrelevant... // change strings values as desired
}
void parentheses (int n, string&& str, int left, int right){
... irrelevant... // string as rvalue
}
``` |
57,941,441 | I am trying to find a REGEX expression (or multiple ones) that i can use in Notepad++ (Windows) that will change different parts of URLs based on specific symbols that divide them.
Basically i have this type of URLs in a big file, they are scaterred around:
```
domain.com/folder/random-text-1?REPLACE-THIS-1=REPLACE-THIS-2=REPLACE-THIS-3&REPLACE-THIS-4
```
The REPLACE-THIS-1/-2/-3/-4 always differs from each other, even between different URLs, like this:
```
domain.com/folder/random-text-2?A1=A2=A3&A4
domain.com/folder/random-text-2?B1=B2=B3&B4
etc
```
(Note: "folder" stays the same all the time)
This is what I am trying to do with REGEX expression(s):
* "REPLACE-THIS-1" with "REPLACED-1"
Note: so basically when it finds the first "?" it will replace the "REPLACE-THIS-1" after it with a specific one "REPLACED-1" up to it gets to "=" symbol
* "REPLACE-THIS-2" with "REPLACED-2"
Note: this one is between first "=" found, and second "=" found
* "REPLACE-THIS-3" with "REPLACED-3"
Note: this is the text after second "=" found
* "REPLACE-THIS-4" with "REPLACED-4"
Note: the problem is that "REPLACE-THIS-4" includes sometimes the "=" symbol as well, but i want to replace all of the text after the "REPLACE-THIS-3&"
Note: REPLACED-1/REPLACED-2/REPLACED-3/REPLACED-4 are always the same, they don't change
The biggest problem i am facing is that all these replace-1/-2-/3/-4 are different amongst each other (i mean the all URLs have different values), so it'd be great if i can use a regex/multiple regex formulas to replace!
Thank you so much! | 2019/09/15 | [
"https://Stackoverflow.com/questions/57941441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11064864/"
] | The function *parentheses* expects an lvalue in the std::string parameter, i.e. a named variable. However, you have supplied an rvalue (temporary) in this call:
parentheses(n,"",0,0);
An empty string object is created and passed to parentheses. You can avoid this problem by changing the definition of parentheses like so:
```
void parentheses (int n, const string& str, int left, int right)
```
Here str will bind to an rvalue/temporary, but you won't be able to change its value in the function. However, if you want to change the value of str you have to define a string variable and pass that to the function.
Example:
```
void solve(int n){
std::string str;
parentheses(n,str,0,0);
}
```
Note: no need to assign str to "" as a string is empty by default. | Your `parentheses()` function takes a **non-const reference** to a `std::string` object, so it expects an actual `std::string` object on the other side of the reference - an lvalue (something that can be assigned to).
But your `solve()` function is not passing a `std::string` object, it is passing a string literal instead. So the compiler creates a *temporary* `std::string` object - an rvalue - which then fails to bind to the reference, because a temporary object can't be bound to a *non-const* reference, only to a *const* reference. That is what the error message is telling you:
>
> cannot bind **non-const lvalue reference** of type std::\_\_cxx11::string& ... to an **rvalue** of type ‘std::\_\_cxx11::string
>
>
>
`solve()` needs to explicitly create an actual `std::string` object to pass to `parentheses()`:
```cpp
void solve(int n){
std::string s = "";
parentheses(n,s,0,0);
}
``` |
57,941,441 | I am trying to find a REGEX expression (or multiple ones) that i can use in Notepad++ (Windows) that will change different parts of URLs based on specific symbols that divide them.
Basically i have this type of URLs in a big file, they are scaterred around:
```
domain.com/folder/random-text-1?REPLACE-THIS-1=REPLACE-THIS-2=REPLACE-THIS-3&REPLACE-THIS-4
```
The REPLACE-THIS-1/-2/-3/-4 always differs from each other, even between different URLs, like this:
```
domain.com/folder/random-text-2?A1=A2=A3&A4
domain.com/folder/random-text-2?B1=B2=B3&B4
etc
```
(Note: "folder" stays the same all the time)
This is what I am trying to do with REGEX expression(s):
* "REPLACE-THIS-1" with "REPLACED-1"
Note: so basically when it finds the first "?" it will replace the "REPLACE-THIS-1" after it with a specific one "REPLACED-1" up to it gets to "=" symbol
* "REPLACE-THIS-2" with "REPLACED-2"
Note: this one is between first "=" found, and second "=" found
* "REPLACE-THIS-3" with "REPLACED-3"
Note: this is the text after second "=" found
* "REPLACE-THIS-4" with "REPLACED-4"
Note: the problem is that "REPLACE-THIS-4" includes sometimes the "=" symbol as well, but i want to replace all of the text after the "REPLACE-THIS-3&"
Note: REPLACED-1/REPLACED-2/REPLACED-3/REPLACED-4 are always the same, they don't change
The biggest problem i am facing is that all these replace-1/-2-/3/-4 are different amongst each other (i mean the all URLs have different values), so it'd be great if i can use a regex/multiple regex formulas to replace!
Thank you so much! | 2019/09/15 | [
"https://Stackoverflow.com/questions/57941441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11064864/"
] | Your `parentheses()` function takes a **non-const reference** to a `std::string` object, so it expects an actual `std::string` object on the other side of the reference - an lvalue (something that can be assigned to).
But your `solve()` function is not passing a `std::string` object, it is passing a string literal instead. So the compiler creates a *temporary* `std::string` object - an rvalue - which then fails to bind to the reference, because a temporary object can't be bound to a *non-const* reference, only to a *const* reference. That is what the error message is telling you:
>
> cannot bind **non-const lvalue reference** of type std::\_\_cxx11::string& ... to an **rvalue** of type ‘std::\_\_cxx11::string
>
>
>
`solve()` needs to explicitly create an actual `std::string` object to pass to `parentheses()`:
```cpp
void solve(int n){
std::string s = "";
parentheses(n,s,0,0);
}
``` | If you want to change the values of your string for any string that is passed as a paramenter (lvalue, as well rvalue), just initialize a variable with the intended content and pass it to your function.
But if you want to treat lvalue strings diferently from rvalue strings, just overload your original function. i.e.:
```
void parentheses (int n, string& str, int left, int right){
... irrelevant... // change strings values as desired
}
void parentheses (int n, string&& str, int left, int right){
... irrelevant... // string as rvalue
}
``` |
67,992,086 | Here's my code for an express server:
```
const express=require('express');
express();
const app=express();
app.get('/',(req,res)=>{
res.send('Welcome to API xyz!');
});
app.listen(3000,()=>{
console.log('Listening on port 3000...');
});
```
Running the server from a git bash terminal, in the app's directory, using:
```
nodemon index.js
```
initially gives the message:
```
[nodemon] starting `node index.js`
Listening on port 3000...
```
Whenever I save a change to the output of `res.send()` as follows:
```
res.send('Welcome to API abc!');
```
and save the index.js file, I get this message:
```
[nodemon] restarting due to changes...
```
but I do not get the `console.log()` text, and when I reload `localhost:3000` in Chrome, I still get the output:
```
Welcome to API xyz!
```
How can I get the server to update in response to saved changes without having to stop nodemon and restart it (which is the whole point of running nodemon in the first place)?
EDIT: I noticed that when nodemon restarts, I get:
```
restarting due to changes...
```
but I don't get
```
starting `node index.js`
```
after that. I only get
```
starting `node index.js`
```
when I first run nodemon.
EDIT 2: thinking that maybe this is related to the same issue that other nodemon users have experienced, as noted [here](https://github.com/remy/nodemon/issues/1854) in its Github issues log? | 2021/06/15 | [
"https://Stackoverflow.com/questions/67992086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619177/"
] | >
> I expected the values to be 1, what am I doing wrong in my source code? why all values are 2?
>
>
>
You observed twice. If you're using `observeDuration` you don't also need `observe`.
>
> How can I set the buckets to use ranges, instead of <=?
>
>
>
You can't, this is how `histogram_quantile` expects the buckets to be. | I think one way you can achieve this, is through regex. For example,
```regex
le=~"([1-9]+)\\..*"
```
will give you all values that are greater than 0.9999 |
119,958 | Maybe I misundertand something, but I find Greg Egan's treatment of the simultaneity problem between distant clones in Diaspora problematic, strangely at odds with the overall technically detailed rigorous style of the book. Consider this in Chapter 11:
>
> Elena had chose not to wake if any other versions of her had already encountered life. Whatever fate befell each of the remaining ships, every other version of him would have to live without her.
>
>
>
But this is surely unattainable, given the clones are tens of light years dispersed into different directions! Let's say clone #1 just encountered life, and clone #2 seventy light years away is about to encounter life very soon. **There's no way** to prevent #2 from waking because by the time message of encountering life from #1 arrived 70 years later, it would be too late.
Special relativity 101 tells us in cases like these, there will be some frame of reference from whose perspective #1 encounter life first, and another frame of reference from whose perspective #2 encounter life first. **There's no objective claim to which clone encountered life first, and both clones will end up waking!** Given fragmentation of identity is a major theme and pathos of the story, I find it unlikely that GE is just sweeping this basic limitation under the rug for (in)convenience.
I hope I'm not being too serious, because this is a wonderfully super-technical serious story ;-P | 2016/02/19 | [
"https://scifi.stackexchange.com/questions/119958",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/60790/"
] | There's no indication in the novel how Elena's scheme was implemented but absent superluminal signaling, her various exoselves would likely adopt the following strategy.
Sort the Carter-Zimmerman polis expeditions by estimated time of arrival. Each exoself in each polis waits for news from all the trips with earlier arrival times before waking their copy of Elena. If after all the returns come in there is no news of a life discovery from an expedition with an earlier arrival time, then that exoself can wake its copy of Elena if life is discovered on that particular expedition. | The crafts were going significantly slower than the speed of light, so I think it's plausible that for *nearly* all pairs of crafts going to two destinations A and B, if the first craft sent a signal at the moment it arrived at A, and the signal moved at the speed of light, then the signal would reach B before the other craft did.
We can estimate the typical speed of their interstellar craft--in Chapter 10 we see a clone of Paolo Venetti about to leave Earth on 31 December 3999, and in Chapter 11 we see him arrive at the star Vega on 10 September 4309, so the trip took about 310 years, rounded off. And according to the [wikipedia article on Vega](http://en.wikipedia.org/wiki/Vega), this star is about 25 light-years from Earth, so the average speed must have been 25/310 times the speed of light, or about 8%.
Now, suppose that another craft had gone in the opposite direction on 31 December 3999, to a star 30 light-years from Earth. Then at 8% the speed of light, it would arrive 375 years after it left, or 65 years after the first craft reached Vega. But the distance between this star and Vega would be 30 + 25 = 55 light years, so if the craft that arrived at Vega immediately sent a signal towards this other star, then despite their lying in exactly opposite directions, the signal would still beat the second craft to the star by 10 years.
Only if two craft happened to be going to star systems almost *exactly* the same distance from Earth would you get a situation where this wouldn't work--and the wiggle room in "almost exactly" would be largest if the two systems happened to lie in opposite directions from Earth, if they were closer to the same direction, the match in distances would have to be even more exact. For the case of stars in opposite directions, it's easy enough to figure out a formula--if one star is a distance D1 and the other a larger distance D2, then the difference in time between the two craft arriving will be (D2 - D1)/0.08c, while the time for a light signal to go from one to the other will be (D1 + D2)/c. In this case, the largest value for the difference in distance, (D2 - D1) that would allow for the second craft to arrive at the same moment or earlier than the light signal would be when (D1 + D2)/c = (D2 - D1)/0.08c, and a little algebra shows this means D2/D1 = (1 + 0.08)/(1 - 0.08) = 1.174. So if the two stars are in opposite directions, the second star's distance must be less than 1.174 times the distance of the first in order to prevent the light signal from beating the second craft, and if they are not in opposite directions the maximum possible difference in distance would be even less. |
49,969 | [](https://i.stack.imgur.com/jQr8T.png)
So... I have a set up as below. I ping PC7 from the router. obviously an ARP is sent to determine PC7's MAC address. but it doesnt work. i then decide to set packettracer to simulation mode. i ping pc7 again and then. i notice that the switch drops the arp for some reason. I dont get why. someone out there in the world should know why.
[](https://i.stack.imgur.com/IUENH.png)
notice how it says gigabit ethernet is blocked by STP. It seems i lack in understanding of STP. some wiser being please save me.
since i think its an issue on the switch. here is its running-config
!
!
!
spanning-tree mode pvst
spanning-tree extend system-id
!
interface FastEthernet0/1
switchport access vlan 10
switchport mode access
!
interface FastEthernet0/2
switchport access vlan 32
switchport mode access
!
interface FastEthernet0/3
switchport access vlan 64
switchport mode access
!
interface FastEthernet0/4
switchport access vlan 96
switchport mode access
!
interface FastEthernet0/5
!
interface FastEthernet0/6
!
interface FastEthernet0/7
!
interface FastEthernet0/8
!
interface FastEthernet0/9
!
interface FastEthernet0/10
!
interface FastEthernet0/11
!
interface FastEthernet0/12
!
interface FastEthernet0/13
!
interface FastEthernet0/14
!
interface FastEthernet0/15
!
interface FastEthernet0/16
!
interface FastEthernet0/17
!
interface FastEthernet0/18
!
interface FastEthernet0/19
!
interface FastEthernet0/20
!
interface FastEthernet0/21
!
interface FastEthernet0/22
!
interface FastEthernet0/23
!
interface FastEthernet0/24
!
interface GigabitEthernet0/1
switchport trunk allowed vlan 10,32,64,96
spanning-tree portfast
!
interface GigabitEthernet0/2
!
interface Vlan1
no ip address
shutdown
! | 2018/04/18 | [
"https://networkengineering.stackexchange.com/questions/49969",
"https://networkengineering.stackexchange.com",
"https://networkengineering.stackexchange.com/users/46304/"
] | Yeeei. I'm so thrilled i found my mistake. I didn't makeg that port on the switch to the router a trunking port... i'm so sorry i didn't tell you guys about all the VLANS i had in there... i see how there was no way you could have seen that. anyways:
```
!
interface GigabitEthernet0/1
switchport trunk allowed vlan 10,32,64,96
spanning-tree portfast
!
```
this plase should have been:
```
!
interface GigabitEthernet0/1
switchport mode trunk
switchport trunk allowed vlan 10,32,64,96
spanning-tree portfast
!
```
Thank you guys for trying to help me here. it would have depressed me to death. you saved my life | You just need to wait for the port to goes in forwarding mode.
By default on Cisco switches (and it seems in packet tracer), when a port goes UP, the STP process block the port until it determines that the network is loop-free, by listening for BPDU on this port.
To avoid this you can configure ports that are connected to hosts (I.E. not other switches) with the `spanning-tree portfast`command.
This will cause the port to goes in forwarding mode immediately upon connection, but still run STP discovery and block the port if a loop is detected. |
1,417,842 | let $x\_1= a+ib,x\_2= c+id,k=$scalar
$f(x\_1,x\_2)=f(x\_1) + f(x\_2)$
$f(a+ib + c + id)=(a+c)-i(b+d)$
$f(a+ib)+f(c+id)=(a+c) - i(b+d)$
$f(kx\_1)=kf(x\_1)$
$f(k(a+ib))= k(a-ib)$
$kf(x\_1)=k(a-ib)$
Looks linear to me, but tutor said it wasn't. please help. | 2015/09/02 | [
"https://math.stackexchange.com/questions/1417842",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/265853/"
] | There is a distinction between $\mathbb{R}$-linear and $\mathbb{C}$-linear.
So, here, for instance, if we take $w$ to be a scalar in $\mathbb{C}$, then
$$f(wz) = \bar{w} f(z).$$
Now, if $\Im w = 0$, then this is the required relation for linearity, but if $\Im w \neq 0$, then we don't have linearity. Therefore, $f$ is $\mathbb{R}$-linear but not $\mathbb{C}$-linear.
Regarding field automorphisms. Lets say we have fields $K$ and $L$ and $L\subseteq K$. If $\phi:K \to K$ is a field automorphism and $\phi(L) = L$, then $\phi$ is always $L$ linear, but only $K$ linear if it is the identity map. | $T(z) = \overline{z}$
$T(wz) = (w\overline{z}) = (\overline{w}\overline{z}) = \overline{w}f(z) \ne wf(z)$
Therefore not linear (consider the bar on the right of w and z as it is on the upper). |
583,434 | Like when you download node.js there is a long list of shasums for each download, windows, osx, linux.
<http://blog.nodejs.org/>
Why is that?
I know you can check a file sha1sum and thereby check if the file is exactly like the developers wanted it to be, but who does that? Is that the reason?
I have never tried downloading a file and it was corrupt or something. | 2013/04/16 | [
"https://superuser.com/questions/583434",
"https://superuser.com",
"https://superuser.com/users/166362/"
] | Reason 1
--------
Allows you to check if the file wasn't corrupted during download.
Reason 2
--------
Allows you to check if the file wasn't tampered with by a third party. | >
> I know you can check a file sha1sum and thereby check if the file is exactly like the developers wanted it to be, but who does that? Is that the reason? I have never tried downloading a file and it was corrupt or something.
>
>
>
Just because it has never happened to you doesn't mean it can't happen, and you *wouldn't* want it to happen if you're putting the file up on an extremely busy production server. Corruptions can occur anywhere in the transfer chain, and it's enough that one piece of hardware in the line has a malfunction. |
33,840 | Dans un dossier de postulation j'ai rencontré la phrase :
>
> Pour en faciliter la lecture, ce document est structuré en cinq chapitres que j'ai voulu concis.
>
>
>
En googlant, je ne trouve pas quelque part l'expression *que j'ai voulu concis*. Est-elle erronée ou a-t-elle une connotation qui m'échapperait ? | 2019/02/14 | [
"https://french.stackexchange.com/questions/33840",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/16020/"
] | Il n'y a pas d'erreur ; c'est un usage de « vouloir » assez courant, que l'on trouve au TLFi ;
>
> [Avec un attribut du compl. d'obj. dir.] Souhaiter avoir, proposer une chose qui présente certaines qualités. Vouloir un steack saignant. La merluche se réduit en une espèce de crème. Si vous la voulez verte, vous pilez des épinards dont vous joignez le suc (Gdes heures cuis. fr., Grimod de la Reynière, 1838, p. 159):
>
> Cet art, il le veut conforme à ce qu'il appelle la réalité: c'est pourquoi il garde la nostalgie de certains aspects du réalisme. Il le veut agréable à sa sensibilité, brillant, luisant et quelque peu voluptueux...
> CASSOU, Arts plast. contemp., 1960, p. 16.
>
>
>
Il y a cependant une erreur dans l'accord du participe passé parce que le COD est placé avant : « que j'ai voulu**s** concis ». | Ce n'est pas une faute, c'est juste que ce style de formulation est assez peu répandu.
On entendrait plus régulièrement ce genre de phrase :
>
> Pour en faciliter la lecture, ce document est structuré en cinq chapitres que j'ai voulu **rendre plus concis**.
>
>
>
Ce qui signifie, ici, *le résumer pour en rendre la lecture plus accessible* |
33,840 | Dans un dossier de postulation j'ai rencontré la phrase :
>
> Pour en faciliter la lecture, ce document est structuré en cinq chapitres que j'ai voulu concis.
>
>
>
En googlant, je ne trouve pas quelque part l'expression *que j'ai voulu concis*. Est-elle erronée ou a-t-elle une connotation qui m'échapperait ? | 2019/02/14 | [
"https://french.stackexchange.com/questions/33840",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/16020/"
] | Il n'y a pas d'erreur ; c'est un usage de « vouloir » assez courant, que l'on trouve au TLFi ;
>
> [Avec un attribut du compl. d'obj. dir.] Souhaiter avoir, proposer une chose qui présente certaines qualités. Vouloir un steack saignant. La merluche se réduit en une espèce de crème. Si vous la voulez verte, vous pilez des épinards dont vous joignez le suc (Gdes heures cuis. fr., Grimod de la Reynière, 1838, p. 159):
>
> Cet art, il le veut conforme à ce qu'il appelle la réalité: c'est pourquoi il garde la nostalgie de certains aspects du réalisme. Il le veut agréable à sa sensibilité, brillant, luisant et quelque peu voluptueux...
> CASSOU, Arts plast. contemp., 1960, p. 16.
>
>
>
Il y a cependant une erreur dans l'accord du participe passé parce que le COD est placé avant : « que j'ai voulu**s** concis ». | La phrase est correcte.
Ce n'est pas une expression proprement dite mais juste l'adjectif "Concis" utilisé ici et signifiant "bref" ou "de forme réduite".
Le [CNRTL](http://www.cnrtl.fr/definition/concis) en donne la définition: "Qui est réduit à l'essentiel et l'exprime en peu de mots". |
338,563 | In my basic understanding of ByteArrays the benefit is that it is smaller in file size.
The down size of a ByteArray is that for any given format you have to know the about the file format to get information out of it. You need a specification and software tools or software to find information.
For example, to get information about a JPEG you have to know what to look for (markers) and have knowledge of how to get that information (such as decoding a byte array, reading the bytes, looking for patterns, etc):
[](https://i.stack.imgur.com/9GxP4.png)
[](https://i.stack.imgur.com/3krJM.gif)
I've been working with XML and to me there are clear benefits. The main one is that it's human readable. So you can sometimes find information without knowing about the structure of a file format.
If we were to write the specification for JPEG now in XML it might look like this:
```
<s:Image xmlns="www.w3c.org" width="1000" height="600" bits="8">
<s:BitmapData>0F8320100830F0A0230B09CC0...</s:BitmapData>
</s:Image>
```
My question is, if XML was created around the same time as the JPG and PNG and file size was not as much an issue (bandwidth was a huge issue in the early days of the internet) would they have used XML to save JPEG information or would they have chosen to write data to a byte array using specific markers for storing information?
What would you do if it was your choice? | 2016/12/21 | [
"https://softwareengineering.stackexchange.com/questions/338563",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/48061/"
] | It is certainly possible that the JPEG and PNG people might have used XML-based *headers* if file size were not an issue. Using text would make it more obvious what all the fields mean and so forth.
But for storing the actual file data, almost certainly not. The data elements of JPEG/PNG images is a sequence of bytes, not XML elements that explain what that data means. So storing that as characters, even in base64 or some such, is simply pointless. It makes processing take longer than needed (since you have to do a lot of text-to-binary conversion), and all to nobody's benefit. It wouldn't make the data portion easier to understand; you'd still have to look up the actual compression algorithm and such.
Indeed, processing time would probably be the reason to avoid even XML headers. Sure, text parsing isn't that expensive, but it's not *nearly* as cheap as blasting some data into memory, casting a pointer, and reading a struct. | Two things:
1. The benefits of your scheme are small and questionable: yes I can parse and extract metadata a bit more easily. But you only really need one C library to parse an image format and then it's a solved problem.
2. Even with modern bandwidth image size is a huge concern. Think about browsing Facebook from a mobile phone -- there will be hundreds of images being constantly loaded. You don't want it to take way longer and eat through your data plan because the developers found this XML format moderately easier to work with.
Just to stress what a difference there is: by encoding the data as a hex string you are using 4 times as much space. In many contexts that's completely unacceptable and it's really not buying you much. |
338,563 | In my basic understanding of ByteArrays the benefit is that it is smaller in file size.
The down size of a ByteArray is that for any given format you have to know the about the file format to get information out of it. You need a specification and software tools or software to find information.
For example, to get information about a JPEG you have to know what to look for (markers) and have knowledge of how to get that information (such as decoding a byte array, reading the bytes, looking for patterns, etc):
[](https://i.stack.imgur.com/9GxP4.png)
[](https://i.stack.imgur.com/3krJM.gif)
I've been working with XML and to me there are clear benefits. The main one is that it's human readable. So you can sometimes find information without knowing about the structure of a file format.
If we were to write the specification for JPEG now in XML it might look like this:
```
<s:Image xmlns="www.w3c.org" width="1000" height="600" bits="8">
<s:BitmapData>0F8320100830F0A0230B09CC0...</s:BitmapData>
</s:Image>
```
My question is, if XML was created around the same time as the JPG and PNG and file size was not as much an issue (bandwidth was a huge issue in the early days of the internet) would they have used XML to save JPEG information or would they have chosen to write data to a byte array using specific markers for storing information?
What would you do if it was your choice? | 2016/12/21 | [
"https://softwareengineering.stackexchange.com/questions/338563",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/48061/"
] | It is certainly possible that the JPEG and PNG people might have used XML-based *headers* if file size were not an issue. Using text would make it more obvious what all the fields mean and so forth.
But for storing the actual file data, almost certainly not. The data elements of JPEG/PNG images is a sequence of bytes, not XML elements that explain what that data means. So storing that as characters, even in base64 or some such, is simply pointless. It makes processing take longer than needed (since you have to do a lot of text-to-binary conversion), and all to nobody's benefit. It wouldn't make the data portion easier to understand; you'd still have to look up the actual compression algorithm and such.
Indeed, processing time would probably be the reason to avoid even XML headers. Sure, text parsing isn't that expensive, but it's not *nearly* as cheap as blasting some data into memory, casting a pointer, and reading a struct. | Byte arrays are human readable. I've been reading them since I was 10 and I've been human for longer than that. This was before I even had a fancy hex editor. Peek and Poke commands are old friends.
What an xml document gives you isn't human readability. It gives you a reasonably predictable encoding (ASCII, UTF-8, etc) that lets you use notepad or vi as your editor, and it gives you meta information right there in the file.
[](https://i.stack.imgur.com/3krJM.gif)
The hex editor image you posted of the byte array has lots of lovely meta information. This meta information you added, using some paint program, simply isn't in the byte array. You only know that info because you know this is a JPEG and you know how JPEG's are structured. You had to go look that up in a specification document. Sometimes programmers aren't in a position to publish and distribute meta information separately from the data file. My tick tack toe games' file format is unlikely to show up in Wikipedia any time soon.
Being able to leave out meta information and being able to use every value of a byte means byte array's are smaller. But it's a O(0.6n) kind of smaller. If that really is an issue you can always use compression. Seriously, size is really not the primary issue.
Look at excel spread sheets for example. Change their extension to .zip and extract them and you find a ton of xml files hiding underneath.
A byte array file can be just as dynamically structured as an xml or json file can be. But unless the markers of that dynamic structure are published somewhere, good luck figuring out the structure.
The JPEG structure is already well known so converting it to XML so you can distribute that structure as meta information is solving a non problem.
I use XML or JSON when I don't feel like publishing a spec to define my structure. I use byte arrays when I don't care if anyone else ever figures out my structure or when I figure my structure is something I can get published. |
338,563 | In my basic understanding of ByteArrays the benefit is that it is smaller in file size.
The down size of a ByteArray is that for any given format you have to know the about the file format to get information out of it. You need a specification and software tools or software to find information.
For example, to get information about a JPEG you have to know what to look for (markers) and have knowledge of how to get that information (such as decoding a byte array, reading the bytes, looking for patterns, etc):
[](https://i.stack.imgur.com/9GxP4.png)
[](https://i.stack.imgur.com/3krJM.gif)
I've been working with XML and to me there are clear benefits. The main one is that it's human readable. So you can sometimes find information without knowing about the structure of a file format.
If we were to write the specification for JPEG now in XML it might look like this:
```
<s:Image xmlns="www.w3c.org" width="1000" height="600" bits="8">
<s:BitmapData>0F8320100830F0A0230B09CC0...</s:BitmapData>
</s:Image>
```
My question is, if XML was created around the same time as the JPG and PNG and file size was not as much an issue (bandwidth was a huge issue in the early days of the internet) would they have used XML to save JPEG information or would they have chosen to write data to a byte array using specific markers for storing information?
What would you do if it was your choice? | 2016/12/21 | [
"https://softwareengineering.stackexchange.com/questions/338563",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/48061/"
] | It is certainly possible that the JPEG and PNG people might have used XML-based *headers* if file size were not an issue. Using text would make it more obvious what all the fields mean and so forth.
But for storing the actual file data, almost certainly not. The data elements of JPEG/PNG images is a sequence of bytes, not XML elements that explain what that data means. So storing that as characters, even in base64 or some such, is simply pointless. It makes processing take longer than needed (since you have to do a lot of text-to-binary conversion), and all to nobody's benefit. It wouldn't make the data portion easier to understand; you'd still have to look up the actual compression algorithm and such.
Indeed, processing time would probably be the reason to avoid even XML headers. Sure, text parsing isn't that expensive, but it's not *nearly* as cheap as blasting some data into memory, casting a pointer, and reading a struct. | You example XML isn't even a good example, as you're still using a byte array. A 'true' XML for an image, to contrast with byte arrays, would be something like:
```
<s:Image xmlns="www.w3c.org" width="1000" height="600" bits="8">
<s:pixels>
<s:row>
<pixel>000000<pixel>
<pixel>000001<pixel>
<pixel>000002<pixel>
<s:row>
<s:row>
<pixel>000010<pixel>
<pixel>000011<pixel>
<pixel>000012<pixel>
<s:row>
...
</s:pixels>
</s:Image>
```
Or some similar unholy creation. Even if disk space is cheap, that is a pretty serious cost of lots of angle brackets. Now sure, you could .zip or compress your XML file, but then you're introducing a tooling requirement to see what's up with the file, so at that point you might as well instead make the file format more sensible and have tooling move the data in the right direction.
To elaborate on some of [Nicol Bolas' answer](https://softwareengineering.stackexchange.com/a/338567/6644 "Nicol Bolas' answer"), with an example of image formats, or anything involving compression, you instantly lose any sort of human readable aspect, as the better the compression, the more incomprehensible the result. The format I had in my example is a bitmap. A jpeg is not going to be human readable in any format, as it's data is many steps removed from what the pixel values are by some serious math.
An additional behavior you can do with byte arrays, but is impossible with XML, is lossy data transfers. Common in signal processing applications, sometimes it's not important to, and is required to be able to, read and utilize a stream of data even when not every bit is correctly transfered. Streaming video is one such application. In the case of an XML file this is not acceptable as missing a single bit where you expect a closing ">" and your whole data structure will fail to parse. |
67,337,853 | Is there a way in javascript in which you can remove the empty lines from a text. And if there is, is the only option iterating over the text to check if there is an empty line or is there a straightforward way. Any help is appreciated. Thanks in advance.
For example:
```
This
is
an
example
```
would change to
```
this
is
an
example
```
some rough code:
```
var aStr = 'this\nis\n\nan\n\nexample'
var myre = (/[\r\n]+/g, '\n\n');
var bStr = aStr.replace(myre,"");
//string with no empty line
console.log(bStr)
``` | 2021/04/30 | [
"https://Stackoverflow.com/questions/67337853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15656320/"
] | You can separate the lines and filter over them.
```js
let str = `This
is
an
example`;
let res = str.split('\n').filter(Boolean).join('\n');
console.log(res);
``` | You can use [`String.prototype.replaceAll`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) with a RegExp pattern to get what you need:
```
const str = `This
is
an
example`;
console.log(str.replaceAll(/\n\n+/ig, `\n`, str);
``` |
67,337,853 | Is there a way in javascript in which you can remove the empty lines from a text. And if there is, is the only option iterating over the text to check if there is an empty line or is there a straightforward way. Any help is appreciated. Thanks in advance.
For example:
```
This
is
an
example
```
would change to
```
this
is
an
example
```
some rough code:
```
var aStr = 'this\nis\n\nan\n\nexample'
var myre = (/[\r\n]+/g, '\n\n');
var bStr = aStr.replace(myre,"");
//string with no empty line
console.log(bStr)
``` | 2021/04/30 | [
"https://Stackoverflow.com/questions/67337853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15656320/"
] | You can separate the lines and filter over them.
```js
let str = `This
is
an
example`;
let res = str.split('\n').filter(Boolean).join('\n');
console.log(res);
``` | You can use the following code:
```
text = `This
is
an
example`
cleaned_text = text.split('\n').filter(x=> x !== '').join('\n');
```
The split makes an array with the text separated by the '\n' token, then filters the empty strings and then join again with an '\n' character |
67,337,853 | Is there a way in javascript in which you can remove the empty lines from a text. And if there is, is the only option iterating over the text to check if there is an empty line or is there a straightforward way. Any help is appreciated. Thanks in advance.
For example:
```
This
is
an
example
```
would change to
```
this
is
an
example
```
some rough code:
```
var aStr = 'this\nis\n\nan\n\nexample'
var myre = (/[\r\n]+/g, '\n\n');
var bStr = aStr.replace(myre,"");
//string with no empty line
console.log(bStr)
``` | 2021/04/30 | [
"https://Stackoverflow.com/questions/67337853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15656320/"
] | You can use the following code:
```
text = `This
is
an
example`
cleaned_text = text.split('\n').filter(x=> x !== '').join('\n');
```
The split makes an array with the text separated by the '\n' token, then filters the empty strings and then join again with an '\n' character | You can use [`String.prototype.replaceAll`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll) with a RegExp pattern to get what you need:
```
const str = `This
is
an
example`;
console.log(str.replaceAll(/\n\n+/ig, `\n`, str);
``` |
51,640,799 | Been bouncing back and forth between Swift and C# and I'm not sure if I'm forgetting certain things, or if C# just doesn't easily support what I'm after.
Consider this code which calculates the initial value for `Foo`:
```
// Note: This is a field on an object, not a local variable.
int Foo = CalculateInitialFoo();
static int CalculateInitialFoo() {
int x = 0;
// Perform calculations to get x
return x;
}
```
Is there any way to do something like this without the need to create the separate one-time-use function and instead use an instantly-executing lambda/block/whatever?
In Swift, it's simple. You use a closure (the curly-braces) that you instantly execute (open and closed parentheses), like this:
```
int Foo = {
int x = 0
// Perform calculations to get x
return x
}()
```
It's clear, concise and doesn't clutter up the object's interface with functions just to initialize fields.
*Note: To be clear, I do **NOT** want a calculated property. I am trying to initialize a member field which requires multiple statements to do completely.* | 2018/08/01 | [
"https://Stackoverflow.com/questions/51640799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/168179/"
] | I wouldn't suggest doing this, but you could use an anonymous function to initialize
```
int _foo = new Func<int>(() =>
{
return 5;
})();
```
Is there a reason you would like to do it using lambdas rather than named functions, or as a calculated property?
I assume you want to avoid calculated properties because you want to either modify the value later, or the computation is expensive and you want to cache the value.
```
int? _fooBacking = null;
int Foo
{
get
{
if (!_fooBacking.HasValue)
{
_fooBacking = 5;
}
return _fooBacking.Value;
}
set
{
_fooBacking = value;
}
}
```
This will use what you evaluate in the conditional the first time it is gotten, while still allowing the value to be assigned.
If you remove the setter it will turn it into a cached calculation. Be careful when using this pattern, though. Side-effects in property getters will be frowned upon because they make the code difficult to follow. | You could initialize your field in the constructor and declare `CalculateInitialFoo` as local function.
```
private int _foo;
public MyType()
{
_foo = CalculateInitialFoo();
int CalculateInitialFoo()
{
int x = 0;
// Perform calculations to get x
return x;
}
}
```
This won't change your code too much but you can at least limit the scope of the method to where it's only used. |
51,640,799 | Been bouncing back and forth between Swift and C# and I'm not sure if I'm forgetting certain things, or if C# just doesn't easily support what I'm after.
Consider this code which calculates the initial value for `Foo`:
```
// Note: This is a field on an object, not a local variable.
int Foo = CalculateInitialFoo();
static int CalculateInitialFoo() {
int x = 0;
// Perform calculations to get x
return x;
}
```
Is there any way to do something like this without the need to create the separate one-time-use function and instead use an instantly-executing lambda/block/whatever?
In Swift, it's simple. You use a closure (the curly-braces) that you instantly execute (open and closed parentheses), like this:
```
int Foo = {
int x = 0
// Perform calculations to get x
return x
}()
```
It's clear, concise and doesn't clutter up the object's interface with functions just to initialize fields.
*Note: To be clear, I do **NOT** want a calculated property. I am trying to initialize a member field which requires multiple statements to do completely.* | 2018/08/01 | [
"https://Stackoverflow.com/questions/51640799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/168179/"
] | To solve the problem in the general case you'd need to create and then execute an anonymous function, which you can technically do as an expression:
```
int Foo = new Func<int>(() =>
{
int x = 0;
// Perform calculations to get x
return x;
})();
```
You can clean this up a bit by writing a helper function:
```
public static T Perform<T>(Func<T> function)
{
return function();
}
```
Which lets you write:
```
int Foo = Perform(() =>
{
int x = 0;
// Perform calculations to get x
return x;
});
```
While this is better than the first, I think it's pretty hard to argue that *either* is better than just writing a function.
In the non-general case, many specific implementations can be altered to run on a single line rather than multiple lines. Such a solution may be possible in your case, but we couldn't possibly say without knowing what it is. There will be cases where this is *possible* but undesirable, and cases where this may actually be preferable. Which are which is of course subjective. | You could initialize your field in the constructor and declare `CalculateInitialFoo` as local function.
```
private int _foo;
public MyType()
{
_foo = CalculateInitialFoo();
int CalculateInitialFoo()
{
int x = 0;
// Perform calculations to get x
return x;
}
}
```
This won't change your code too much but you can at least limit the scope of the method to where it's only used. |
695,755 | Am getting an error mentioned below when I call my WCF service?How do i get rid of it?
There was an error while trying to serialize parameter <http://tempuri.org/:MyWCFSvc.svc>
The InnerException message was 'Type 'System.String[]' with data contract name 'ArrayOfstring:<http://schemas.microsoft.com/2003/10/Serialization/Arrays>'
is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.\*
I tried using [ServiceKnownType(typeof(string[]))] in my WCF service interface but no luck | 2009/03/30 | [
"https://Stackoverflow.com/questions/695755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68717/"
] | A year late, but I had the same issue and here is what you need to do
```
List<SomeClass> mylist = new List<SomeClass>();
DataContractSerializer dcs = new DataContractSerializer(mylist.GetType());
XmlWriter writer = XmlWriter.Create(sb, XWS);
dcs.WriteObject(writer, query);
writer.Close();
```
The problem is when you construct your serializer with the typeof your class, the serialzer does not see it as an arrray, it only sees a single object.
If found it by doing this first:
```
DataContractSerializer dcs = new DataContractSerializer(SomeClass.GetType());
XmlWriter writer = XmlWriter.Create(sb, XWS);
dcs.WriteObject(writer, query[0]); // Only get the first record from linq to sql
writer.Close();
``` | There's no reason for you to have to KnownType an array of strings. The serializer should already know about that, and arrays are not a problem. I'm moving Lists of things around in WCF without an issue. Could you post a representative sample of what you're doing? |
695,755 | Am getting an error mentioned below when I call my WCF service?How do i get rid of it?
There was an error while trying to serialize parameter <http://tempuri.org/:MyWCFSvc.svc>
The InnerException message was 'Type 'System.String[]' with data contract name 'ArrayOfstring:<http://schemas.microsoft.com/2003/10/Serialization/Arrays>'
is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.\*
I tried using [ServiceKnownType(typeof(string[]))] in my WCF service interface but no luck | 2009/03/30 | [
"https://Stackoverflow.com/questions/695755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68717/"
] | I too had the same issues but after qualifiying the OperationContract with `[ServiceKnownType(typeof(string[]))]` and `[ServiceKnownType(typeof(int[]))]` fixed the issue.
Eg:
```
[ServiceContract]
public interface IReportService
{
[OperationContract]
[ServiceKnownType(typeof(string[]))]
[ServiceKnownType(typeof(int[]))]
bool GenerateReport(int clientId, int masterId, string reportType, int[] vtIds, DateTime initialDate, DateTime finalDate,
bool descending, string userName, string timeZoneId, bool embedMap,
object[] vtExtraParameters, object[] vtScheduleParameters, string selectedCriteria,
out long reportID, out int scheduleID, out string message);
``` | There's no reason for you to have to KnownType an array of strings. The serializer should already know about that, and arrays are not a problem. I'm moving Lists of things around in WCF without an issue. Could you post a representative sample of what you're doing? |
695,755 | Am getting an error mentioned below when I call my WCF service?How do i get rid of it?
There was an error while trying to serialize parameter <http://tempuri.org/:MyWCFSvc.svc>
The InnerException message was 'Type 'System.String[]' with data contract name 'ArrayOfstring:<http://schemas.microsoft.com/2003/10/Serialization/Arrays>'
is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.\*
I tried using [ServiceKnownType(typeof(string[]))] in my WCF service interface but no luck | 2009/03/30 | [
"https://Stackoverflow.com/questions/695755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68717/"
] | A year late, but I had the same issue and here is what you need to do
```
List<SomeClass> mylist = new List<SomeClass>();
DataContractSerializer dcs = new DataContractSerializer(mylist.GetType());
XmlWriter writer = XmlWriter.Create(sb, XWS);
dcs.WriteObject(writer, query);
writer.Close();
```
The problem is when you construct your serializer with the typeof your class, the serialzer does not see it as an arrray, it only sees a single object.
If found it by doing this first:
```
DataContractSerializer dcs = new DataContractSerializer(SomeClass.GetType());
XmlWriter writer = XmlWriter.Create(sb, XWS);
dcs.WriteObject(writer, query[0]); // Only get the first record from linq to sql
writer.Close();
``` | Configuring service references on your client provides "Data Type" options that allow you to specify different types for Collection/Dictionary Types. What settings do you have in there? |
695,755 | Am getting an error mentioned below when I call my WCF service?How do i get rid of it?
There was an error while trying to serialize parameter <http://tempuri.org/:MyWCFSvc.svc>
The InnerException message was 'Type 'System.String[]' with data contract name 'ArrayOfstring:<http://schemas.microsoft.com/2003/10/Serialization/Arrays>'
is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.\*
I tried using [ServiceKnownType(typeof(string[]))] in my WCF service interface but no luck | 2009/03/30 | [
"https://Stackoverflow.com/questions/695755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68717/"
] | I too had the same issues but after qualifiying the OperationContract with `[ServiceKnownType(typeof(string[]))]` and `[ServiceKnownType(typeof(int[]))]` fixed the issue.
Eg:
```
[ServiceContract]
public interface IReportService
{
[OperationContract]
[ServiceKnownType(typeof(string[]))]
[ServiceKnownType(typeof(int[]))]
bool GenerateReport(int clientId, int masterId, string reportType, int[] vtIds, DateTime initialDate, DateTime finalDate,
bool descending, string userName, string timeZoneId, bool embedMap,
object[] vtExtraParameters, object[] vtScheduleParameters, string selectedCriteria,
out long reportID, out int scheduleID, out string message);
``` | Configuring service references on your client provides "Data Type" options that allow you to specify different types for Collection/Dictionary Types. What settings do you have in there? |
695,755 | Am getting an error mentioned below when I call my WCF service?How do i get rid of it?
There was an error while trying to serialize parameter <http://tempuri.org/:MyWCFSvc.svc>
The InnerException message was 'Type 'System.String[]' with data contract name 'ArrayOfstring:<http://schemas.microsoft.com/2003/10/Serialization/Arrays>'
is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.\*
I tried using [ServiceKnownType(typeof(string[]))] in my WCF service interface but no luck | 2009/03/30 | [
"https://Stackoverflow.com/questions/695755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68717/"
] | A year late, but I had the same issue and here is what you need to do
```
List<SomeClass> mylist = new List<SomeClass>();
DataContractSerializer dcs = new DataContractSerializer(mylist.GetType());
XmlWriter writer = XmlWriter.Create(sb, XWS);
dcs.WriteObject(writer, query);
writer.Close();
```
The problem is when you construct your serializer with the typeof your class, the serialzer does not see it as an arrray, it only sees a single object.
If found it by doing this first:
```
DataContractSerializer dcs = new DataContractSerializer(SomeClass.GetType());
XmlWriter writer = XmlWriter.Create(sb, XWS);
dcs.WriteObject(writer, query[0]); // Only get the first record from linq to sql
writer.Close();
``` | I too had the same issues but after qualifiying the OperationContract with `[ServiceKnownType(typeof(string[]))]` and `[ServiceKnownType(typeof(int[]))]` fixed the issue.
Eg:
```
[ServiceContract]
public interface IReportService
{
[OperationContract]
[ServiceKnownType(typeof(string[]))]
[ServiceKnownType(typeof(int[]))]
bool GenerateReport(int clientId, int masterId, string reportType, int[] vtIds, DateTime initialDate, DateTime finalDate,
bool descending, string userName, string timeZoneId, bool embedMap,
object[] vtExtraParameters, object[] vtScheduleParameters, string selectedCriteria,
out long reportID, out int scheduleID, out string message);
``` |
25,937,806 | What is the preferred way of producing a String which holds a sequence of whitespaces of an arbitrary length? Is it this way:
```
final String spaces = " "; //three white spaces
```
or is there a better way? | 2014/09/19 | [
"https://Stackoverflow.com/questions/25937806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2200045/"
] | I'd say personal preference, as long as the person that will maintain the code after you know what's happening that's what is most important.
Here is another option:
```
final String spaces = String.format("%"+ 3 +"s", " ");
```
Just to add on from @Freiheit, this would be another solution to the problem.
```
final String spaces = StringUtils.leftPad("", 3).toString();
``` | I assume you want to pad or indent other Strings. Using something like [Apache StringUtils.leftPad](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#leftPad(java.lang.String,%20int)) is a much better option than having whitespace String variables. |
3,059,013 | I'm aware that this kind of question should be asked in Computer Science Stack Exchange. But I decided to ask here because there should be more effective answers here with more experienced people with solid math background that might have taught themselves some computer science.
I decided to ask this question after being attracted by how much one can do with the knowledge in computer science, including iOS application development, game(or mods) development, website creating, etc., but having trouble with matching what I learned with what I really understood.
Realizing the lack of knowledge in programming, I once decided to learn programming in a specific language, like Objective-C and Swift. After I tried every single textbook on OC programming, I found myself wasting time in the "explanation" part and getting lost with the real "theoretical" part. It seems to me that those textbooks prefer a long and loose explanation in describing a concept without telling me what exactly it is(Like the notion of "Object" and "Pointer") and skip the real important "thinking" before the implementation of the code. Although after many times of reading I could create a very simple application(like a simple calculator), I was still very lost in how it really works.
That reminds me how I began to learn mathematics. In middle school "function" is just "$y=f(x)$", where $f(x)$ can be $x^2$, $\sin(x)$, and other operations about $x$. However, now for me $f$ is a set of tuples satisfying the unique mapping property, or an arrow with domain and codomain. More generally, I can give a affirmative response to every question like "what is (the definition of) this?(in a math sentence.)" So I asked myself, "what is most basic among all subjects in computer science"?
Based on the belief that computer system and programming can be completely theoretical, I decided to learn from the very basic. Where is the code for my programming environment?(For me, Xcode) and how can I understand it? What is a computer made of (up to the transistors), and how do them work together?
But then I found out that there is no book with the name similar to "how a computer works" that reach my satisfaction, which I thought is my vocabulary problem.
I hope that in the book I'm looking for, every keyword is rigorously defined, and without any waste of time in explaining what a notion "means" or how it is developed stage by stage historically. I expect that it gives only the goals(like the adding machine) and how to build it from the given definitions(a graph with the nodes of value "0" or "1"). Every textbooks in mathematics(like the GTM series) reach this goal, and for me, that is MUCH easier to read and understand. I think most of the math student like me will prefer this style of learning.
What is a good (book) route for a math student to self study computer science from the basic? I wish there are some theoretical textbooks that build the whole operation system, compiler, or some of this kind, that is readable to math students. Any answer would be much appreciated. Thank you. | 2019/01/02 | [
"https://math.stackexchange.com/questions/3059013",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/413924/"
] | >
> Based on the belief that computer system and programming can be completely theoretical, I decided to learn from the very basic.
>
>
>
It's a bit arrogant to stick too tightly to such a belief when you're still learning the field don'tcha think?
*Some* areas of computer science can be called "completely theoretical". Computability theory and complexity theory come close, as do some of the more wild-eyed branches of programming language research. They merge into parts of logic and category theory that could be called "computer science by conquest" because computer scientists are interested in them -- though at the best conferences you will also find people with Dept. of Mathematics affiliations, and some even use blackboards for their talks!
However, in *most* of computer science as a field, the lifeblood of the science is the *tension* between nice theoretical models on one hand, and the need to build systems that work on actual physical devices that can be produced economically on the other hand. To insist on studying only the theoretical side amounts to throwing out not just half of the field, but the entire crunchy middle too.
In your position you probably ought to start by a **computer architecture** textbook, and then learn (really learn) a low-level programming language such as C. Though this will offer you copious opportunity to shoot yourself in the foot, it might also be the only way to satisfy your (in itself laudable) desire to understand the entire stack of abstractions *all the way down*. And the mistakes you'll make with C might help you understand the point of the more abstract concepts of more modern languages. | If you are at a university offering computer science degrees, you could find out the names of a few courses that are required for 2nd or 3d year students, get a copy of the text book for one of them, and try to read it.
One thing making your task harder is that computer science is a very wide field, and no one book covers everything important. In part because "computer science" is an amalgam of computer engineering, of computer practice, of applied mathematics, and so on: unlike (say) linear algebra, there is no small set of basic axioms that can be neatly explained and exploited in a few hundred pages. Rather, imagine you wanted to systematically and efficiently learn automobile science. You might find a book that explains car engines and the related chemistry of combustion and pollution control, but says nothing about motion planning or an automobile's HVAC system, etc.
Added, after a few minutes. The comments following Henning Makholm's completely reasonable answer seem to me to illustrate the point I made above: computer science is so complex a subject that it is hard to agree what is most essential.
Let me add a particular recommendation: I have noticed that some of my colleagues do not know about the connection between DFAs and regular languages. This seems to me to be as fundamental a result in theoretical CS as (say) the Pythagorean theorem is in geometry, or as integration by parts
in calculus. And more important than many computer hardware implementation details. If you don't know *that*, you don't know squat. So your goal might be, read enough of Aho, Hopcroft, and Ullman (or equivalent textbook) to understand this important result. |
3,059,013 | I'm aware that this kind of question should be asked in Computer Science Stack Exchange. But I decided to ask here because there should be more effective answers here with more experienced people with solid math background that might have taught themselves some computer science.
I decided to ask this question after being attracted by how much one can do with the knowledge in computer science, including iOS application development, game(or mods) development, website creating, etc., but having trouble with matching what I learned with what I really understood.
Realizing the lack of knowledge in programming, I once decided to learn programming in a specific language, like Objective-C and Swift. After I tried every single textbook on OC programming, I found myself wasting time in the "explanation" part and getting lost with the real "theoretical" part. It seems to me that those textbooks prefer a long and loose explanation in describing a concept without telling me what exactly it is(Like the notion of "Object" and "Pointer") and skip the real important "thinking" before the implementation of the code. Although after many times of reading I could create a very simple application(like a simple calculator), I was still very lost in how it really works.
That reminds me how I began to learn mathematics. In middle school "function" is just "$y=f(x)$", where $f(x)$ can be $x^2$, $\sin(x)$, and other operations about $x$. However, now for me $f$ is a set of tuples satisfying the unique mapping property, or an arrow with domain and codomain. More generally, I can give a affirmative response to every question like "what is (the definition of) this?(in a math sentence.)" So I asked myself, "what is most basic among all subjects in computer science"?
Based on the belief that computer system and programming can be completely theoretical, I decided to learn from the very basic. Where is the code for my programming environment?(For me, Xcode) and how can I understand it? What is a computer made of (up to the transistors), and how do them work together?
But then I found out that there is no book with the name similar to "how a computer works" that reach my satisfaction, which I thought is my vocabulary problem.
I hope that in the book I'm looking for, every keyword is rigorously defined, and without any waste of time in explaining what a notion "means" or how it is developed stage by stage historically. I expect that it gives only the goals(like the adding machine) and how to build it from the given definitions(a graph with the nodes of value "0" or "1"). Every textbooks in mathematics(like the GTM series) reach this goal, and for me, that is MUCH easier to read and understand. I think most of the math student like me will prefer this style of learning.
What is a good (book) route for a math student to self study computer science from the basic? I wish there are some theoretical textbooks that build the whole operation system, compiler, or some of this kind, that is readable to math students. Any answer would be much appreciated. Thank you. | 2019/01/02 | [
"https://math.stackexchange.com/questions/3059013",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/413924/"
] | >
> Based on the belief that computer system and programming can be completely theoretical, I decided to learn from the very basic.
>
>
>
It's a bit arrogant to stick too tightly to such a belief when you're still learning the field don'tcha think?
*Some* areas of computer science can be called "completely theoretical". Computability theory and complexity theory come close, as do some of the more wild-eyed branches of programming language research. They merge into parts of logic and category theory that could be called "computer science by conquest" because computer scientists are interested in them -- though at the best conferences you will also find people with Dept. of Mathematics affiliations, and some even use blackboards for their talks!
However, in *most* of computer science as a field, the lifeblood of the science is the *tension* between nice theoretical models on one hand, and the need to build systems that work on actual physical devices that can be produced economically on the other hand. To insist on studying only the theoretical side amounts to throwing out not just half of the field, but the entire crunchy middle too.
In your position you probably ought to start by a **computer architecture** textbook, and then learn (really learn) a low-level programming language such as C. Though this will offer you copious opportunity to shoot yourself in the foot, it might also be the only way to satisfy your (in itself laudable) desire to understand the entire stack of abstractions *all the way down*. And the mistakes you'll make with C might help you understand the point of the more abstract concepts of more modern languages. | >
> I wish there are some theoretical textbooks that build the whole
> operation system, compiler, or some of this kind, that is readable to
> math students.
>
>
>
I highly recommend reading [The Elements of Computing Systems](https://rads.stackoverflow.com/amzn/click/0262640686) by Nisan and Schocken, and doing all the projects. You make a computer from scratch, starting with NAND gates. Along the way you make a compiler and a simple operating system. In the end you make a simple video game such as Tetris that can run on the computer you've designed. The book's companion website is [www.nand2tetris.org](https://www.nand2tetris.org/).
It is my favorite textbook on any subject.
You might also be interested in Knuth's [The Art of Computer Programming](https://www-cs-faculty.stanford.edu/~knuth/taocp.html), though I haven't read it myself. |
73,154,413 | symbolic model function passing
Hi!
I stuck in my fitting due to my symbolic function,
Please kindly let me know how this issue could be solved here is my code, I need to pass tow independent\_var which are xCl and XI and a is parameter:
```
import numpy as np
import lmfit
import sympy as sp
anion = {'I': 1, 'Cl': 1}
xa = {'xI': 0.2, 'xCl': 0.3}
xCl = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
xI = [0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.1, 0.8, 0.11, 0.12]
def g(xa, anion, a):
xzc = 0
for k1, k2 in zip(anion, xa):
xzc += sp.symbols(f"x{k1}") * sp.symbols(f"x{k2}") + a
return xzc
obj = lmfit.Model(g, independent_vars=['xCl', 'xI'])
pars = obj.make_params(a=0.1)
result = mod.fit(ydat, pars, xCl, xI)
print(result.fit_report())
```
but I' ve found;
```
**************************************************
Traceback (most recent call last):
File "F:\Zohreh\MainZohreh\postdoc-field\CSU\pythonProject\simple_Lmfit.py", line 36, in <module>
obj = lmfit.Model(g, independent_vars=['xCl', 'xI'])
File "C:\Users\Zohreh\AppData\Roaming\Python\Python310\site-packages\lmfit\model.py", line 277, in __init__
self._parse_params()
File "C:\Users\Zohreh\AppData\Roaming\Python\Python310\site-packages\lmfit\model.py", line 541, in _parse_params
raise ValueError(self._invalid_ivar % (arg, fname))
ValueError: Invalid independent variable name ('xCl') for function g
*********************************************************
``` | 2022/07/28 | [
"https://Stackoverflow.com/questions/73154413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19370106/"
] | We can do an outer join on the `id` fields and then use `coalesce()` to prioritize the fields from `dfn`.
```
columns = ['id', 'neighbor_sid', 'neighbor', 'division']
dfo. \
join(dfn, 'id', 'outer'). \
select(*['id'] + [func.coalesce(dfn[k], dfo[k]).alias(k) for k in columns if k != 'id']). \
orderBy('id'). \
show()
# +---+------------+------------+-----------+
# | id|neighbor_sid| neighbor| division|
# +---+------------+------------+-----------+
# | a1| 1100| Naalehu| Hawaii|
# |a10| 1202|bay-terraces| California|
# | a2| 1111|key-largo-fl| Miami|
# | a3| 1103| grapevine| Texas|
# | a4| 1115| meriden-ct|Connecticut|
# +---+------------+------------+-----------+
``` | Id do a full outer join then coalesce to choose the second table where necessary:
```
# imports and creating data example
from pyspark.sql import functions as F, Window as W
cols = ["id", "neighbor_sid", "neighbor", "division"]
data1 = [
["a1", 1100, 'Naalehu', 'Hawaii'],
["a2", 1101, 'key-west-fl', 'Miami'],
["a3", 1102, 'lubbock', 'Texas'],
["a10", 1202, 'bay-terraces', 'California'],
]
data2 = [
['a1',1100,'Naalehu','Hawaii'],
['a2',1111,'key-largo-fl','Miami'],
['a3',1103,'grapevine','Texas'],
['a4',1115,'meriden-ct','Connecticut'],
]
df0 = spark.createDataFrame(data1, cols)
dfN = spark.createDataFrame(data2, cols)
# solution
merge_df = df0.alias("a").join(dfN.alias('b'), on='id', how='outer')
d = (
merge_df
.select(
"id",
F.coalesce("b.neighbor_sid", "a.neighbor_sid").alias("neighbor_sid"),
F.coalesce("b.neighbor", "a.neighbor").alias("neighbor"),
F.coalesce("b.division", "a.division").alias("division")
)
.sort("neighbor_sid")
)
display(d)
``` |
27,718,032 | I have very basic issue and have following code. In rare cases, we are not able to call setDriver(set driver object) and call getDriver function for calling driver class function which resultant memory crash( as setdriver has not set). is it possible to check getdriver object. I have tried to set NULL but as we are returning reference it's not appropriate/feasible.
```
include<iostream>
#include<string>
using namespace std;
class Driver {
private:
string name;
public:
void setname(string name);
void display();
};
void Driver::setname(string name)
{
this->name = name;
}
void Driver::display()
{
cout<<" This driver is .."<<name<<endl;
}
class sample {
protected:
Driver *m_d;
public:
void setDriver(Driver *driver);
Driver& getDriver();
};
void sample::setDriver(Driver *driver)
{
m_d = driver;
}
Driver& sample::getDriver()
{
return *m_d;
}
int main()
{
sample s;
Driver *d = new Driver;
d->setname("test");
s.setDriver(d);
Driver &d1 = s.getDriver();
// How can I check if d1 is exist or not
d1.display();
}
```
**After getting input from below discussion, I have modified code into following way. will it be correct solution?**
```
#include<iostream>
#include<string>
using namespace std;
class Driver {
private:
string name;
public:
void setname(string name);
void display();
};
void Driver::setname(string name)
{
this->name = name;
}
void Driver::display()
{
cout<<" This driver is .."<<name<<endl;
}
class sample {
protected:
Driver *m_d;
public:
void setDriver(Driver *driver);
Driver& getDriver();
sample();
};
sample::sample()
{
m_d = NULL;
}
void sample::setDriver(Driver *driver)
{
m_d = driver;
}
Driver& sample::getDriver()
{
if(m_d)
return *m_d;
else
throw "Error";
}
int main()
{
sample s;
Driver *d = new Driver;
d->setname("test");
s.setDriver(d);
try{
Driver &d1 = s.getDriver();
d1.display();
}
catch(...)
{
cout<<" object is not prsent"<<endl;
}
``` | 2014/12/31 | [
"https://Stackoverflow.com/questions/27718032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3996232/"
] | References can't point to nothing so I suggest two options:
a) throw an exception - this for me is clearly the best solution; this is an edge case and very appropriate for exception handling
b) Include a method driver.isLoaded() which the caller can check - in the case when you can't allocate a driver return a stub driver which returns this value as false
Alternately you need to change the nature of the call to return a pointer (so that you can return null) or pass your driver as a reference parameter and return a boolean to indicate success. Neither of these options seems as good as a above to me. | A safe way to don't have to check if pointer is null is to force it to never be:
```
class sample {
public:
// No default constructor
explicit sample(Driver &driver) m_d(&driver) {}
void setDriver(Driver &driver) { m_d = &driver; }
Driver& getDriver() { return *m_d; }
private:
Driver *m_d;
};
```
Usage:
```
int main()
{
Driver d1;
d1.setname("test1");
Driver d2;
d2.setName("test2");
sample s(d1);
s.getDriver().display();
s.setDriver(d2);
s.getDriver().display();
}
``` |
60,889,245 | What does this mean, and how do I fix it, I know for a fact my code is correct and nothing is wrong with it, I checked with multiple friends. I have no idea why this is happening and I need my bot to start working soon. | 2020/03/27 | [
"https://Stackoverflow.com/questions/60889245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12055789/"
] | This is an error happening within the discord.js library if a web request is stuck for a long time, which might happen due to an outage or bad internet connection. Those connections are killed with that error message to free resources.
Those errors should not be fatal and can be ignored. | Expanding flame’s point - put your code in a try catch statement e.g.
```js
try {
//code
} catch (error) {
//error code for example
console.log('an error has occurred')
//if you want no error has occurred log
console.log('')
// ^ will not log anything
}
```
Alternatively, I’ve researched that it could be something to do with a directory not being referenced properly, so check your code for that.
Hope I helped |
155,933 | I saw some kind of workflow in vim:
Vim had a file open. Then some combination of keys made vim disappear and the user was in the command line working in cli mode, then opened another file and then suddenly returned to the previously opened file exactly at the place/line he was.
It reminded me the switch among windows we do in Windows.
Does anyone know how this worflow is done in vim? | 2014/09/16 | [
"https://unix.stackexchange.com/questions/155933",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/42132/"
] | There are several options to do so:
* You can use a terminal multiplexer like [screen](http://en.wikipedia.org/wiki/GNU_Screen) or [tmux](http://en.wikipedia.org/wiki/Tmux).
In screen, for example, the shortcut `Ctrl`+`a` - `a`, has the same functiononality as `Alt`+`Tab` in graphical environments: switch to the last screen.
* Or you use `vim`'s internal function.
Type `:!command` in `vim`'s command mode. For example: `:!ls -l`. After the command finishes press `Enter` to switch back to `vim`.
* There is one more option: [Job conrol](http://tldp.org/LDP/abs/html/x9644.html).
Press `Ctrl`+`z` to stop the current process (`vim`). You will find yourself in a terminal. To bring the stopped process back to the foreground type `fg`.
For me, I prefer screen. I have an unwritten rule for myself: "Always open a screen." | I don't know about the "suddenly returned ..." part, but the first bit is fairly trivial. The `:shell` command opens your shell. For me, it opens at wherever I was when I opened `vim`, so it is inheriting settings from `vim`, [as G-Man notes](https://unix.stackexchange.com/questions/155933/switching-among-cli-and-vim-and-other-files-workflow#comment255048_155936). That gives you the CLI mode. You can also open another `vim` from it. Quitting this shell returns you to wherever you where in `vim` originally. You can always bind a shortcut to `:shell`. |
155,933 | I saw some kind of workflow in vim:
Vim had a file open. Then some combination of keys made vim disappear and the user was in the command line working in cli mode, then opened another file and then suddenly returned to the previously opened file exactly at the place/line he was.
It reminded me the switch among windows we do in Windows.
Does anyone know how this worflow is done in vim? | 2014/09/16 | [
"https://unix.stackexchange.com/questions/155933",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/42132/"
] | There are several options to do so:
* You can use a terminal multiplexer like [screen](http://en.wikipedia.org/wiki/GNU_Screen) or [tmux](http://en.wikipedia.org/wiki/Tmux).
In screen, for example, the shortcut `Ctrl`+`a` - `a`, has the same functiononality as `Alt`+`Tab` in graphical environments: switch to the last screen.
* Or you use `vim`'s internal function.
Type `:!command` in `vim`'s command mode. For example: `:!ls -l`. After the command finishes press `Enter` to switch back to `vim`.
* There is one more option: [Job conrol](http://tldp.org/LDP/abs/html/x9644.html).
Press `Ctrl`+`z` to stop the current process (`vim`). You will find yourself in a terminal. To bring the stopped process back to the foreground type `fg`.
For me, I prefer screen. I have an unwritten rule for myself: "Always open a screen." | You can press `Ctrl-z` to stop vim and go to CLI, do whatever you need to (edit another vim file perhaps), then press `fg` on command line to return back into vim at the same place you left off at. If you didn't see the command `fg` being typed, then it's very likely that [screen](http://www.gnu.org/software/screen/) was being used. |
72,434,598 | we are trying to get the content of the attachment's of the in the rtf mail but I have tried to search using different terms but have not found any reliable solution . can someone please help me to get the source of the attachment's as we get them in the html format. | 2022/05/30 | [
"https://Stackoverflow.com/questions/72434598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9808048/"
] | I think the error in the second for loop
change :
```
x < SystemInformation.VirtualScreen.Height
```
To :
```
y < SystemInformation.VirtualScreen.Height
```
Like This
```
for (int x = 0; x < SystemInformation.VirtualScreen.Width; x++)
{
for (int y = 0; y < SystemInformation.VirtualScreen.Height; y++)
{
``` | It's an excellent way to learn how to debug.
The exception is thrown on this line:
```
Color currentPixelColor = bitmap.GetPixel(x, y);
```
And it clearly states that the error is on `y`. If you put your mouse over the `y`, you'll see `1080` (probably, depending on your screen resolution), which is, indeed, out of the [0, 1079] range.
"But I just checked that it was within the range just before..."
If you put your mouse over `SystemInformation.VirtualScreen.Height`, you'll see, as expected `1080`. But if you put your mouse over `<`, you'll see that the condition is `true`. **That**'s not expected...
What are you comparing `1080` to? Put your mouse on the variable and you see... `0`. And we saw just before that `y` was `1080`. Then you'll see your typo. In your second `for` loop, your condition checks the value of `x`, instead of `y`.
So you just have to replace
```
for (int y = 0; x < SystemInformation.VirtualScreen.Height; y++)
```
with
```
for (int y = 0; y < SystemInformation.VirtualScreen.Height; y++)
``` |
72,434,598 | we are trying to get the content of the attachment's of the in the rtf mail but I have tried to search using different terms but have not found any reliable solution . can someone please help me to get the source of the attachment's as we get them in the html format. | 2022/05/30 | [
"https://Stackoverflow.com/questions/72434598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9808048/"
] | I think the error in the second for loop
change :
```
x < SystemInformation.VirtualScreen.Height
```
To :
```
y < SystemInformation.VirtualScreen.Height
```
Like This
```
for (int x = 0; x < SystemInformation.VirtualScreen.Width; x++)
{
for (int y = 0; y < SystemInformation.VirtualScreen.Height; y++)
{
``` | This worked. I don't know if this is the best thing to do, what do you guys think
```
try
{
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(bitmap as Image);
graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
Color desiredPixelColor = ColorTranslator.FromHtml(hexcode);
while (true)
{
for (int x = 0; x < SystemInformation.VirtualScreen.Width; x++)
{
for (int y = 0; x < SystemInformation.VirtualScreen.Height; y++)
{
Color currentPixelColor = bitmap.GetPixel(x, y);
label1.Text = "Current colour: " + currentPixelColor;
if (desiredPixelColor == currentPixelColor)
{
label2.Text = "On colour : Yes";
return true;
}
}
}
label2.Text = "On colour: No";
return false;
}
}
catch { return false; }
``` |
72,434,598 | we are trying to get the content of the attachment's of the in the rtf mail but I have tried to search using different terms but have not found any reliable solution . can someone please help me to get the source of the attachment's as we get them in the html format. | 2022/05/30 | [
"https://Stackoverflow.com/questions/72434598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9808048/"
] | It's an excellent way to learn how to debug.
The exception is thrown on this line:
```
Color currentPixelColor = bitmap.GetPixel(x, y);
```
And it clearly states that the error is on `y`. If you put your mouse over the `y`, you'll see `1080` (probably, depending on your screen resolution), which is, indeed, out of the [0, 1079] range.
"But I just checked that it was within the range just before..."
If you put your mouse over `SystemInformation.VirtualScreen.Height`, you'll see, as expected `1080`. But if you put your mouse over `<`, you'll see that the condition is `true`. **That**'s not expected...
What are you comparing `1080` to? Put your mouse on the variable and you see... `0`. And we saw just before that `y` was `1080`. Then you'll see your typo. In your second `for` loop, your condition checks the value of `x`, instead of `y`.
So you just have to replace
```
for (int y = 0; x < SystemInformation.VirtualScreen.Height; y++)
```
with
```
for (int y = 0; y < SystemInformation.VirtualScreen.Height; y++)
``` | This worked. I don't know if this is the best thing to do, what do you guys think
```
try
{
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(bitmap as Image);
graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
Color desiredPixelColor = ColorTranslator.FromHtml(hexcode);
while (true)
{
for (int x = 0; x < SystemInformation.VirtualScreen.Width; x++)
{
for (int y = 0; x < SystemInformation.VirtualScreen.Height; y++)
{
Color currentPixelColor = bitmap.GetPixel(x, y);
label1.Text = "Current colour: " + currentPixelColor;
if (desiredPixelColor == currentPixelColor)
{
label2.Text = "On colour : Yes";
return true;
}
}
}
label2.Text = "On colour: No";
return false;
}
}
catch { return false; }
``` |
16,202,436 | merge list of lists for example
```
list_of_lists = [['NA','NA','NA','0,678'], ['0.327','NA','NA','NA'], ...]
```
I want
```
merged = ['0.327','NA','NA','0,678']
```
Please comment. | 2013/04/24 | [
"https://Stackoverflow.com/questions/16202436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2150169/"
] | Use a list comprehension with a nested generator expression to pick the first non-`NA` element, together with `zip()`:
```
merged = [next((el for el in elements if el != 'NA'), 'NA') for elements in zip(*list_of_lists)]
```
Demo:
```
>>> list_of_lists = [['NA','NA','NA','0,678'], ['0.327','NA','NA','NA']]
>>> [next((el for el in elements if el != 'NA'), 'NA') for elements in zip(*list_of_lists)]
['0.327', 'NA', 'NA', '0,678']
```
The `next((...), default)` call expression will pick the *first* element that is not equal to `'NA'`, falling back to `'NA'` if no such element exists. | Assuming that there both list do not have values in the same position (as suggested by Martijn Pieters) then you could use:
```
for i in range(len(l1)):
l1[i] = l2[i] if l1[i] == 'NA' and l2[i] != 'NA' else l1[i]
```
Hope this helps! |
16,202,436 | merge list of lists for example
```
list_of_lists = [['NA','NA','NA','0,678'], ['0.327','NA','NA','NA'], ...]
```
I want
```
merged = ['0.327','NA','NA','0,678']
```
Please comment. | 2013/04/24 | [
"https://Stackoverflow.com/questions/16202436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2150169/"
] | Use a list comprehension with a nested generator expression to pick the first non-`NA` element, together with `zip()`:
```
merged = [next((el for el in elements if el != 'NA'), 'NA') for elements in zip(*list_of_lists)]
```
Demo:
```
>>> list_of_lists = [['NA','NA','NA','0,678'], ['0.327','NA','NA','NA']]
>>> [next((el for el in elements if el != 'NA'), 'NA') for elements in zip(*list_of_lists)]
['0.327', 'NA', 'NA', '0,678']
```
The `next((...), default)` call expression will pick the *first* element that is not equal to `'NA'`, falling back to `'NA'` if no such element exists. | ```
>>> list_of_lists = [['NA','NA','NA','0,678'], ['0.327','NA','NA','NA']]
>>> from itertools import ifilter # Py3k doesn't need import, use filter built-in
>>> [next(ifilter('NA'.__ne__, col), 'NA') for col in zip(*list_of_lists)]
['0.327', 'NA', 'NA', '0,678']
``` |
9,362,324 | ```
protected function button1_clickHandler(event:MouseEvent):void
{
Security.allowDomain("*.googleapis.com" );
Security.allowDomain("*.google.com" );
var q : URLLoader = new URLLoader();
q.addEventListener( Event.COMPLETE, onGeocodingComplete );
q.load( new URLRequest( 'http://maps.googleapis.com/maps/api/geocode/json?latlng=40.548555,24.558466&sensor=false' ) );
}
protected function onGeocodingComplete( event : Event ) : void
{
Alert.show( 'geocoding succeed' );
}
```
I try with the code above, but it throw me :
```
sandbox violationError #2044: Unhandled securityError:. text=Error #2048: Security sandbox violation...
```
* how can I directly access reverse geocoding services trought Flash?
*because the geocoder with Flash API doesnt providing sufficient data.* | 2012/02/20 | [
"https://Stackoverflow.com/questions/9362324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767942/"
] | ```
Cell = Cell.Select(s => System.Web.HttpUtility.HtmlEncode(s)).ToList();
```
or
shorter:
```
Cell = Cell.Select(System.Web.HttpUtility.HtmlEncode).ToList();
``` | you could create an extension method that does the trick
```
public static class MyCustomListMethod
{
public static void Add(this IList<string> list, string item,bool htmlEndode){
list.Add(System.Web.HttpUtility.HtmlEncode(item));
}
}
```
and then
```
public static void Main()
{
string e = "<p>Test Text<p/>";
List<string> mylist = new List<string>();
mylist.Add(e,true);
}
```
using the new extension method you will be able to add item to a list already encoded instead of converting all of them |
9,362,324 | ```
protected function button1_clickHandler(event:MouseEvent):void
{
Security.allowDomain("*.googleapis.com" );
Security.allowDomain("*.google.com" );
var q : URLLoader = new URLLoader();
q.addEventListener( Event.COMPLETE, onGeocodingComplete );
q.load( new URLRequest( 'http://maps.googleapis.com/maps/api/geocode/json?latlng=40.548555,24.558466&sensor=false' ) );
}
protected function onGeocodingComplete( event : Event ) : void
{
Alert.show( 'geocoding succeed' );
}
```
I try with the code above, but it throw me :
```
sandbox violationError #2044: Unhandled securityError:. text=Error #2048: Security sandbox violation...
```
* how can I directly access reverse geocoding services trought Flash?
*because the geocoder with Flash API doesnt providing sufficient data.* | 2012/02/20 | [
"https://Stackoverflow.com/questions/9362324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767942/"
] | You could use the [`ConvertAll<T>`](http://msdn.microsoft.com/en-us/library/73fe8cwf.aspx) extension method :
```
Cell = Cell.ConvertAll<string>(s => System.Web.HttpUtility.HtmlEncode(s));
```
or shorter :
```
Cell = Cell.ConvertAll<string>(System.Web.HttpUtility.HtmlEncode);
``` | you could create an extension method that does the trick
```
public static class MyCustomListMethod
{
public static void Add(this IList<string> list, string item,bool htmlEndode){
list.Add(System.Web.HttpUtility.HtmlEncode(item));
}
}
```
and then
```
public static void Main()
{
string e = "<p>Test Text<p/>";
List<string> mylist = new List<string>();
mylist.Add(e,true);
}
```
using the new extension method you will be able to add item to a list already encoded instead of converting all of them |
57,346,913 | I'm creating simple web automation using JavaScript and selenium for homework purposes.
The purpose of the exercise is really simple, click on a link and fill a web form in the new page.
The problem is that I'm not able to fill this form even though I'm able to locate the web element correctly ( I think ).
I tried to use both the Xpath and CSS selectors to locate the web element.
```
const driver = new selenium.Builder().forBrowser("chrome").build();
const form = driver.findElement(By.linkText("Form Authentication")).click;
const username = driver.findElement(By.xpath("//form/div/div/input[@id = "username"]")).sendKeys("some text");
driver.get(url);
```
The expected result should be the form Username/password filled with some text.
no errors show up, just no action, | 2019/08/04 | [
"https://Stackoverflow.com/questions/57346913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11812367/"
] | Please replace below line of code:
```
const username = driver.findElement(By.xpath("//form/div/div/input[@id = "username"]")).sendKeys("some text");
```
with this line:
```
const username = driver.findElement(By.xpath("//form/div/div/input[@id = 'username']")).sendKeys("some text");
```
Since you are using double quotes inside double quotes, it must be giving you error.
Hope it helps :) | I see a number of problems with this code. I'm not sure what the `url` variable holds at runtime, but I suspect it holds the URL to the login page. You want to go to the URL first, then fill in fields.
```
const driver = new selenium.Builder().forBrowser("chrome").build();
driver.get(url);
```
Next, you need to make sure you are calling methods in JavaScript correctly.
```
const form = driver.findElement(By.linkText("Form Authentication")).click;
```
This line of code assigned a reference to the `click` function to the `form` variable. I don't think this is what you want. You want to click the link:
```
driver.findElement(By.linkText("Form Authentication")).click();
```
Next, you are improperly nesting double quotes:
```
const username = driver.findElement(By.xpath("//form/div/div/input[@id = 'username']")).sendKeys("some text");
```
Use single quotes around `@id = 'username'`.
Furthermore, the id attribute in HTML is already inherently unique. You can simplify your last XPATH expression to:
```
By.xpath("//input[@id = 'username']")
```
You are also missing a step. After typing in the username and password, you need to submit the form, usually by clicking on a submit button. |
675,294 | ```
\documentclass{article}
\usepackage{hyperref}
\usepackage{expl3}
\hypersetup{
colorlinks=true,
linkcolor=blue,
filecolor=magenta,
urlcolor=cyan,
pdftitle={Overleaf Example},
pdfpagemode=FullScreen,
}
\ExplSyntaxOn
\NewDocumentCommand{\curl}{m}{
\tl_set:Nn \l_tmpa_tl {#1}
\regex_extract_once:nnN {\/([a-z0-9]{10})} {#1} \l_uiy_result_seq
\seq_map_inline:Nn \l_uiy_result_seq {\href{#1}{##1}}
}
\ExplSyntaxOff
\begin{document}
\curl{https://www.facebook.com/reel/1a1c6e99h60a3169h86816}
\end{document}
```
Using this code I'm getting match & match group one after one.
Example
```
\curl{https://www.facebook.com/reel/1a1c6e99h60a3169h86816}
```
Output is
[](https://i.stack.imgur.com/LGTFN.png)
Where First `/1a1c6e99h6` is match & second half is match group `1a1c6e99h6`
**How can I only map match group `1a1c6e99h6`** | 2023/02/15 | [
"https://tex.stackexchange.com/questions/675294",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/289984/"
] | Here is how to pop left the sequence such as to obtain `1a1c6e99h6`.
```
\documentclass{article}
\usepackage{hyperref}
\usepackage{expl3}
\hypersetup{
colorlinks=true,
linkcolor=blue,
filecolor=magenta,
urlcolor=cyan,
pdftitle={Overleaf Example},
pdfpagemode=FullScreen,
}
\ExplSyntaxOn
\NewDocumentCommand{\curl}{m}{
\regex_extract_once:nnN {\/([a-z0-9]{10})} {#1} \l_uiy_result_seq
% One good example of use of l_tmpa_tl.
\seq_pop_left:NNTF \l_uiy_result_seq \l_tmpa_tl {
\seq_map_inline:Nn \l_uiy_result_seq {\href{#1}{##1}}
}{
No ~ match!
}
}
\ExplSyntaxOff
\begin{document}
\curl{https://www.facebook.com/reel/1a1c6e99h60a3169h86816}
\curl{PB}
\end{document}
``` | I think you don't want extraction, but just replacement:
```
\documentclass{article}
\usepackage{hyperref}
\usepackage{expl3}
\hypersetup{
colorlinks=true,
linkcolor=blue,
filecolor=magenta,
urlcolor=cyan,
pdftitle={Overleaf Example},
pdfpagemode=FullScreen,
}
\ExplSyntaxOn
\NewDocumentCommand{\curl}{m}
{
\tl_set:Nn \l_tmpa_tl {#1}
\regex_replace_once:nnN {.*\/([a-z0-9]{10}).*} {\1} \l_tmpa_tl
\href{#1}{\l_tmpa_tl}
}
\ExplSyntaxOff
\begin{document}
\curl{https://www.facebook.com/reel/1a1c6e99h60a3169h86816}
\end{document}
```
[](https://i.stack.imgur.com/Np2GQ.png) |
13,729,199 | New web developer here so please bear with me...
I'm creating an FAQ page on our site with 10-15 questions that I would like to display the answer to after clicking on the question.
Example:
Q. What is your name?
(after clicking the question, the answer will slide down displaying the text)
Adam
I would also like for you to be able to click the question again to hide the answer once the viewer has read it.
Thank you for your time!
HTML:
```
<p>Q. WHO IS REQUIRED TO PARTICIPATE? </p>
<p>Everyone must participate. </p>
```
JS:
```
$(document).ready(function() {
$("p").click(function() {
$("p").slideToggle(200);
});
});
``` | 2012/12/05 | [
"https://Stackoverflow.com/questions/13729199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1879937/"
] | It is better if you encase the question and corresponding answer inside a Separate div..
**HTML**
```
<div>
<p class="question">Q. WHO IS REQUIRED TO PARTICIPATE?</p>
<p class="answer">Everyone must participate. </p>
</div>
<div>
<p class="question">Q. MINIMUM AGE OF THE PARTICIPANT ?</p>
<p class="answer">26. </p>
</div>
```
**JS**
```
$('.question').on('click', function(){
$(this).next('.answer').slideToggle(200);
});
```
**[Check Fiddle](http://jsfiddle.net/sushanth009/dBG6E/)**
| ### Try using this code.
Even though you are a beginner, using semantic tags like, `UL` and `LI` is semantic and good. Giving `H3` and `P` for the questions and answers are useful because, it works even when the CSS is not present.
**HTML:**
```
<ul class="faq">
<li>
<h3><a href="#">Question 1</a></h3>
<p>Answer</p>
</li>
<li>
<h3><a href="#">Question 2</a></h3>
<p>Answer</p>
</li>
</ul>
```
**JavaScript**
```
$('.faq > li > h3 > a').click(function(){
$(this.parentNode).next().slideToggle(200);
return false;
});
```
### Fiddle: <http://jsfiddle.net/bhvZx/> |
582,019 | I am creating some cockburn tables using this [wonderful site](https://www.tablesgenerator.com/) suggested to me. The problem I encountered is that the table below looks like this:
[](https://i.stack.imgur.com/ZtvB4.png)
What do I expect
[](https://i.stack.imgur.com/P8DVe.png)
As you can see, the table is very narrow and has overlaid text. I have no idea how to fix it.
Attached I leave you the code that the site itself has generated. **As always thanks for your time.**
```
\usepackage[table,xcdraw]{xcolor}
\usepackage{graphicx}
\usepackage{natbib}
\usepackage{graphicx}
\usepackage{tabularx}
\usepackage[thinlines]{easytable}
\begin{table}[H]
\centering
\resizebox{\textwidth}{!}{%
\begin{tabular}{|l|l|l|l|}
\hline
\rowcolor[HTML]{EFEFEF}
\textbf{Use Case #2} &
\multicolumn{3}{l|}{\cellcolor[HTML]{EFEFEF}Effettua registrazione con email} \\ \hline
\textbf{Goal in context} &
\multicolumn{3}{l|}{L'utente vuole effettuare la registrazione alla piattaforma con la propria email} \\ \hline
\textbf{Precondition} &
\multicolumn{3}{l|}{L'utente non è autenticato} \\ \hline
\textbf{Success End Condition} &
\multicolumn{3}{l|}{L'utente riesce a registrarsi alla piattaforma} \\ \hline
\textbf{Failed End Condition} &
\multicolumn{3}{l|}{L'utente non si registra alla piattaforma} \\ \hline
\textbf{Primary Actor} &
\multicolumn{3}{l|}{Ospite} \\ \hline
\textbf{Trigger} &
\multicolumn{3}{l|}{L'utente preme il pulsante "profilo" della bottombar dell'APP_HOME} \\ \hline
\multicolumn{1}{|c|}{} &
\cellcolor[HTML]{EFEFEF}\textbf{Step} &
\cellcolor[HTML]{EFEFEF}\textbf{Ospite} &
\cellcolor[HTML]{EFEFEF}\textbf{Sistema} \\ \cline{2-4}
\multicolumn{1}{|c|}{} &
1 &
\begin{tabular}[c]{@{}l@{}}L'utente preme il pulsante "profile"\\ della bottombar della APP_HOME\end{tabular} &
\\ \cline{2-4}
\multicolumn{1}{|c|}{} &
2 &
&
\begin{tabular}[c]{@{}l@{}}Il sistema mostra dialogIscriptionRequest \\ che avvisa l'utente che per usufruire di tutte le funzionalità presenti\\ deve essere iscritto\end{tabular} \\ \cline{2-4}
\multicolumn{1}{|c|}{} &
3 &
\begin{tabular}[c]{@{}l@{}}L'utente preme il pulsante "iscriviti"\\ della dialogIscriptionRequest\end{tabular} &
\\ \cline{2-4}
\multicolumn{1}{|c|}{} &
4 &
&
Mostra la schermata di autenticazione APPM_AUTHENTICATION \\ \cline{2-4}
\multicolumn{1}{|c|}{} &
5 &
Preme il pulsante "Accedi con email" &
\\ \cline{2-4}
\multicolumn{1}{|c|}{} &
6 &
&
Mostra la schermata per l'accesso \\ \cline{2-4}
\multicolumn{1}{|c|}{} &
7 &
Preme il pulsante "Registrati" &
\\ \cline{2-4}
\multicolumn{1}{|c|}{} &
8 &
&
Mostra la schermata per la registrazione APPM_SIGNUP \\ \cline{2-4}
\multicolumn{1}{|c|}{} &
9 &
Compila i campi necessari &
\\ \cline{2-4}
\multicolumn{1}{|c|}{} &
10 &
Preme il pulsante "Iscriviti" &
\\ \cline{2-4}
\multicolumn{1}{|c|}{\multirow{-12}{*}{\textbf{Description}}} &
11 &
&
Mostra schermata home APPM_HOME \\ \hline
&
\cellcolor[HTML]{EFEFEF}\textbf{Step} &
\cellcolor[HTML]{EFEFEF}\textbf{Ospite} &
\cellcolor[HTML]{EFEFEF}\textbf{Sistema} \\ \cline{2-4}
&
3.1 &
Preme il pulsante "Più tardi" &
\\ \cline{2-4}
\multirow{-3}{*}{\begin{tabular}[c]{@{}l@{}}EXTENSION #1\\ L'utente preme il pulsante \\ "Più tardi" annullando \\ l'operazione\end{tabular}} &
4.1 &
&
Torna alla schermata iniziale APP_HOME e termina il caso d'uso \\ \hline
&
\cellcolor[HTML]{EFEFEF}\textbf{Step} &
\cellcolor[HTML]{EFEFEF}\textbf{Ospite} &
\cellcolor[HTML]{EFEFEF}\textbf{Sistema} \\ \cline{2-4}
\multirow{-2}{*}{\begin{tabular}[c]{@{}l@{}}EXTENSION #2\\ L'utente inserisce un'email\\ già presente nel sistema\end{tabular}} &
11.2 &
&
Mosra un Toast di errore \\ \hline
&
\cellcolor[HTML]{EFEFEF}\textbf{Step} &
\cellcolor[HTML]{EFEFEF}\textbf{Ospite} &
\cellcolor[HTML]{EFEFEF}\textbf{Sistema} \\ \cline{2-4}
&
9.3 &
\begin{tabular}[c]{@{}l@{}}Preme il pulsante \\ "Back" \\ dell'APPM_SIGNUP\end{tabular} &
\\ \cline{2-4}
&
10.3 &
&
Torna alla schermata APPM_AUTHENTICATION \\ \cline{2-4}
&
11.3 &
Preme il pulsante "Accedi come ospite" &
\\ \cline{2-4}
\multirow{-5}{*}{\begin{tabular}[c]{@{}l@{}}EXTENSION #3\\ L'utente decide\\ di non voler effettuare \\ l'autenticazione\end{tabular}} &
12.3 &
&
Torna alla schermata APPM_HOME e termina il caso d'uso \\ \hline
\end{tabular}%
}
\caption{Effettua registrazione con email}
\label{tab:tck_registrazione_email}
\end{table}
``` | 2021/02/05 | [
"https://tex.stackexchange.com/questions/582019",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/234567/"
] | * your table is huge
* page layout is unknow
* in following suggestion is assumed:
+ that font size in table can be smaller, i.e. be of `\footnotesize
+ line spread can be reduced
+ page layout is defined by `geometry` package default settings:
```
\documentclass{article}
\usepackage{geometry}
\usepackage[table,xcdraw]{xcolor}
\usepackage[column=O]{cellspace}
\setlength\cellspacetoplimit{3pt}
\setlength\cellspacebottomlimit{3pt}
\usepackage{multirow, xltabular}
\newcolumntype{C}[1]{>{\hsize=#1\hsize%
\centering\arraybackslash}X}
\newcolumntype{L}[1]{>{\hsize=#1\hsize%
\raggedright\arraybackslash\hspace{0pt}%
}X}
\addparagraphcolumntypes{L}
%---------------- show page layout. don't use in a real document!
\usepackage{showframe}
\renewcommand\ShowFrameLinethickness{0.15pt}
\renewcommand*\ShowFrameColor{\color{red}}
%---------------------------------------------------------------%
\begin{document}
\begin{table}[ht]
\centering
\footnotesize\linespread{0.84}\selectfont
\begin{tabularx}{\linewidth}{|O{L{1}}|C{0.3}|O{L{1}}|O{L{1.7}}|}
\hline
\rowcolor{gray!30}
\textbf{Use Case \#2} &
\multicolumn{3}{l|}{Effettua registrazione con email} \\ \hline
\textbf{Goal in context} &
\multicolumn{3}{L{3.2}|}{L'utente vuole effettuare la registrazione alla piattaforma con la propria email} \\ \hline
\textbf{Precondition} &
\multicolumn{3}{l|}{L'utente non è autenticato} \\ \hline
\textbf{Success End Condition} &
\multicolumn{3}{l|}{L'utente riesce a registrarsi alla piattaforma} \\ \hline
\textbf{Failed End Condition} &
\multicolumn{3}{l|}{L'utente non si registra alla piattaforma} \\ \hline
\textbf{Primary Actor} &
\multicolumn{3}{l|}{Ospite} \\ \hline
\textbf{Trigger} &
\multicolumn{3}{L{3.2}|}{L'utente preme il pulsante "profilo" della bottombar dell'APP\_HOME}
\\ \hline
\rowcolor{gray!30}
\cellcolor{white}
& \textbf{Step}
& \textbf{Ospite} & \textbf{Sistema} \\ \cline{2-4}
& 1 & L'utente preme il pulsante "profile" della bottombar della APP\_HOME
& \\ \cline{2-4}
& 2 & & Il sistema mostra dialogIscriptionRequest che avvisa l'utente che per usufruire di tutte le funzionalità presenti deve essere iscritto \\ \cline{2-4}
& 3 & L'utente preme il pulsante "iscriviti" della dialogIscriptionRequest
& \\ \cline{2-4}
& 4 & & Mostra la schermata di autenticazione APPM\_AUTHENTICATION \\ \cline{2-4}
& 5 & Preme il pulsante "Accedi con email"
& \\ \cline{2-4}
& 6 & & Mostra la schermata per l'accesso \\ \cline{2-4}
& 7 & Preme il pulsante "Registrati"
& \\ \cline{2-4}
& 8 & & Mostra la schermata per la registrazione APPM\_SIGNUP \\ \cline{2-4}
& 9 & Compila i campi necessari
& \\ \cline{2-4}
& 10& Preme il pulsante "Iscriviti"
& \\ \cline{2-4}
\multirow{-34}{=}{\textbf{Description}}
&11 & & Mostra schermata home APPM\_HOME
\\ \hline
\rowcolor{gray!30}
\cellcolor{white}
& \textbf{Step}
& \textbf{Ospite}
& \textbf{Sistema}
\\ \cline{2-4}
&3.1& Preme il pulsante "Più tardi"
& \\ \cline{2-4}
\multirow{-5}{=}{EXTENSION \#1:\newline
L'utente preme il pulsante "Più tardi" annullando l'operazione}
&4.1& & Torna alla schermata iniziale APP\_HOME e termina il caso d'uso
\\ \hline
\rowcolor{gray!30}
\cellcolor{white}
& \textbf{Step}
& \textbf{Ospite}
& \textbf{Sistema}
\\ \cline{2-4}
& 11.2 & & Mosra un Toast di errore
\\
\multirow{-4}{=}{EXTENSION \#2\newline
L'utente inserisce un'email già presente nel sistema}
& & & \\ \hline
\rowcolor{gray!30}
\cellcolor{white}
& \textbf{Step}
& \textbf{Ospite}
& \textbf{Sistema}
\\ \cline{2-4}
& 9.3 & Preme il pulsante "Back" dell'APPM\_SIGNUP
& \\ \cline{2-4}
& 10.3 & & Torna alla schermata APPM\_AUTHENTICATION
\\ \cline{2-4}
& 11.3 & Preme il pulsante "Accedi come ospite"
& \\ \cline{2-4}
\multirow{-5}{=}{EXTENSION \#3\newline
L'utente decide di non voler effettuare l'autenticazione}
& 12.3 & & Torna alla schermata APPM\_HOME e termina il caso d'uso
\\ \hline
\end{tabularx}
\caption{Effettua registrazione con email}
\label{tab:tck_registrazione_email}
\end{table}
\end{document}
```
Note: your table code fragment doesn't reproduce showed table, but this mismatch you can correct yourself.
If you compare both table codes, you can observe:
* For table is used `tabularx` table environment
* From `X` column type are derived are two new column type: `C` and `L`. They enable simple settings of their width ratios.
* To cells are added vertical space by help of `cellspace` package.
* Thee way of table coloring is changed. `\cellcolor` is used only in the first column, others are replaced by `rowcolor. This make code a not so small bit shorter.
* For `multirow` cells is used its new syntax `\multirow{-...}{=}{...}` (observe `=`). By this nested tables in those cells become superfluous.
[](https://i.stack.imgur.com/Lo3Hq.png)
(red lines indicate page layout) | The table presented looks like part of a project documentation, perhaps a GUI. That means it will be a living document,
with changes and additions throughout the life of the project.
So it will be a futile exercise trying to fit this particular table on a single page. It won't last the first draft.
Looking closely, it seems to me that there are three parts to the table, each of which conveys a different type of information.
(1) The upper part, with a general description of the case, its objectives, success criteria, etc. It probably won't change much over time.
(2) The intermediate part that follows the actions of the user and the response of the subsystems. It will be different for each case.
(3) The lower part, with the reactions of the subsystems in the case of odd terminations.
Different for other cases and probably undergoing numerous additions over time from later findings on testing and operational use.
That is why I propose to divide the original table into three tables, each dedicated to its specific task.
[](https://i.stack.imgur.com/ncV1S.jpg)
[](https://i.stack.imgur.com/IMfyX.jpg)
[](https://i.stack.imgur.com/GP1bj.jpg)
In this way it will be easy to add new lines or modify the content without accidentally altering the other parts.
I chose to use the `nicematrix` package because by itself provides all the facilities needed for this task.
For starters it provides the command `\Block` that replaces the `\multicolumn` and `\multirow` and allow the use of `\\` inside.
It also allows general directives like `hvlines`. That takes care of the `\hlines` and `\cline {2-4}` within the code.
Overall the code is much cleaner and easier to maintain when revisited some time in the future.
Notes:
(1) All cells are vertically centered. Notice, for example, the numbers in the Steps column. This happens automatically, even in multiple rows cells.
(2) Using `\\` inside the `\Block` you can cut the sentence following the pauses of the natural way of speaking, facilitating reading.
(3) No change of the font size is needed.
```
\documentclass[12pt,a4paper]{article}
\usepackage[left=2.00cm, right=2.00cm, top=2.00cm, bottom=2.00cm]{geometry}
\usepackage{nicematrix} % everything needed
\usepackage{float} % provides[H]
\usepackage{kantlipsum} % dummy text
\begin{document}
\section{Utente effettua registrazione con terze parti}
1. \kant[1]
\begin{table}[H]
\centering
\caption{Conditions of Use Case \#1}
\medskip
\begin{NiceTabular}{ll}[hvlines,
code-before = \rectanglecolor{gray!15}{1-1}{1-2},
cell-space-top-limit = 7pt,
cell-space-bottom-limit = 7pt]
\textbf{Use Case \#1} & \textbf{Effettua registrazione con terze parti} \\
Goal in context & \Block[l]{1-1}{L'utente vuole effettuare la registrazione alla piattaforma \\con la propria email}\\
Precondition & L'utente non è autenticato \\
Success End Condition & L'utente riesce a registrarsi alla piattaforma \\
Failed End Condition & L'utente non si registra alla formatting \\
Primary Actor & Ospite \\
Trigger & \Block[l]{1-1}{L'utente preme il pulsante "profilo" della bottom bar\\ dell' APP\_HOME} \\
\end{NiceTabular}%
\end{table}
9. \kant[9]
\begin{table}[H]
\centering
\caption{Use Case \#1: user actions and responses step by step}
\medskip
\begin{NiceTabular}{c wc{4ex} wc{4ex} wc{3ex} wl{11.5cm}}[hvlines,
first-row,
code-for-first-row = \bfseries,
cell-space-top-limit = 7pt,
cell-space-bottom-limit = 7pt]
Step & \rotate{Ospite} & \rotate{API} & \rotate{Sistema} & \Block[c]{}{Description}\\
1 & X & & & \Block[l]{}{L'utente preme il pulsante "profile" della \\bottom bar della APP\_HOME} \\
2 & & & X & \Block[l]{}{Il sistema mostra dialog Iscription Request che avvisa l'utente \\ che per usufruire di tutte le funzionalità presenti \\ deve essere iscritto} \\
3 & X & & & \Block[l]{}{L'utente preme il pulsante "iscriviti" \\ della dialog Iscription Request} \\
4 & & & X & \Block[l]{}{Mostra la schermata di autenticazione\\ APPM\_AUTHENTICATION}\\
5 & X & & & Preme il pulsante "Accedi con email" \\
6 & & X & & Mostra la schermata per l'accesso \\
7 & & & X & Preme il pulsante "Registrati" \\
\end{NiceTabular}%
\end{table}
12. \kant[12]
\begin{table}[H]
\centering
\caption{Extensions of Use Case \#1}
\medskip
\begin{NiceTabular}{wl{5.5cm} c wc{4ex} wc{4ex} wc{3ex} wl{5.5cm}}[hvlines,
first-row,
code-for-first-row = \bfseries,
cell-space-top-limit = 6pt,
cell-space-bottom-limit = 6pt]
\Block[c]{}{Extension} & Step & \rotate{Ospite} & \rotate{API} & \rotate{Sistema} & \Block[c]{}{Description}\\
\Block{2-1}{EXTENSION \#1 \\ L'utente preme il pulsante \\ "Più tardi" annullando \\ l'operazione.}
& 3.1 & X & & & \Block[l]{}{Preme il pulsante "Più tardi".} \\
& 4.1 & & & X & \Block[l]{}{Torna alla schermata iniziale \\APP\_HOME e termina \\il caso d'uso.}\\
\Block{1-1}{EXTENSION \#2\\ L'utente inserisce un email\\ già presente nel sistema.}
& 5.2 & & & X & \Block[l]{}{Preme il pulsante "back".} \\
\Block{2-1}{EXTENSION \#3\\ L'utente decide di non voler \\effettuare l'autenticazione.}
& 3.5 & X & & & \Block[l]{}{Torna alla schermata \\ APPM\_AUTHENTICATION} \\
& 3.6 & & & X & \Block[l]{}{Torna alla schermata iniziale \\APP\_HOME e termina \\il caso d'uso.}\\
\end{NiceTabular}%
\end{table}
\end{document}
``` |
4,139,824 | I want to add a slide up affect with jQuery to a DIV when a link inside of the DIV is clicked, but the problem i am running into is the class of the DIV's are defined by a loop. So, i can't define the DIV class in the jQuery line, because each DIV class is different and i cannot determine ahead of time what they are. I am trying to use .parent and .child but I am not sure how to go about this. Is this making any sense? | 2010/11/09 | [
"https://Stackoverflow.com/questions/4139824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/476412/"
] | Apparently you cannot remove DOM nodes that are not in the DOM at the moment.
You could use:
```
nodes = nodes.not('#b');
```
Keep in mind that even after (and during) manipulation, ids should be unique. | **EDIT** - Updated to support not inserting the div's into the DOM, and simply removing them pre-insertion.
```
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script>
$(function() {
var data = '<div class="1">aa</div> <div class="2">bb</div> <div class="3">cc</div>';
$("#container_1").append(data);
var nodes = jQuery(data).not('.2');
// In this example it's '.2',
// though you changed your id's in the original to something else
$("#container_2").append(nodes);
});
</script>
</head>
<body>
<div id="container_1"> </div>
<div id="container_2"> </div>
</body>
</html>
``` |
387,411 | [](https://i.stack.imgur.com/ox5p4.jpg) This is on a control board from a crane...not sure of crane mfg or country of origin. Anyway, owner lost 12Vdc to the board and tried to jumper it in...ooops. This is where the smoke came out...can't seem to find anything on this part. Another part next door is also designated V but unfortunately it's not the same and I can't find that either. Letters appear to read GP447. Thanks all! | 2018/07/24 | [
"https://electronics.stackexchange.com/questions/387411",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/194349/"
] | That's some kind of diode, possibly in a SMA package. Note the cathode band on the left end (as oriented in your picture).
The designation "V" hints that it might be used as a voltage reference, which would mean a Zener diode. However, without seeing the rest of the circuit or a repair manual, there is no way to know.
If there is another diode on the board with the same markings, you can unsolder it and find its voltage.
However, it is quite possible that other parts on this board are damaged too, just not showing it in a obvious way. | From the looks of it it is a ST part. Problem is, the actual product marking is right where the case blew up. So there is no way to determine the correct part based on the code.
Here is the typical marking of a ST diode in a SMx case:
[](https://i.stack.imgur.com/Xnlgp.png)
You can guesstimate the ST logo, the e3 marking is there and there is a three digit code in the bottom right corner. Not sure if the manufacturing location was upped to a two letter code at some point or for other products.
There are a lot of ST diodes and I'm not going through every datasheet to find out.
My guess could be way off of course. |
1,767,899 | Let $a,b,c,a',b',c'\in \mathbb{Z}\_{\geq 1}$ be such that
$$
\frac{1}{a}+\frac{1}{b}+\frac{1}{c}<1,\quad \frac{1}{a'}+\frac{1}{b'}+\frac{1}{c'}<1.
$$
Suppose
$$
\frac{1}{a}+\frac{1}{b}+\frac{1}{c}=\frac{1}{a'}+\frac{1}{b'}+\frac{1}{c'}.
$$
Is it true that $\{a,b,c\}=\{a',b',c'\}$? If it is not, it should be easy to give a counterexample, but I am not able to find one. | 2016/05/02 | [
"https://math.stackexchange.com/questions/1767899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/336294/"
] | COUNTEREXAMPLE.
Take $\left\{a,b,c \right\}=\left\{4k,6k,12k\right\}$ and $\left\{a',b',c' \right\}=\left\{6k,6k,6k\right\}$. Then both sums add up to $\frac{1}{2k}$.
Since @HRSE asks, here is another counterexample, in the case $\left\{a,b,c \right\}=\left\{40k,20k,120k\right\}$$\left\{a',b',c' \right\}=\left\{21k,42k,84k\right\}$ both sums add up to $\frac{1}{12k}$. | It is not true. Take a=2,b=3,c=-2,a'= 3, b'=3, c'=-3. |
1,767,899 | Let $a,b,c,a',b',c'\in \mathbb{Z}\_{\geq 1}$ be such that
$$
\frac{1}{a}+\frac{1}{b}+\frac{1}{c}<1,\quad \frac{1}{a'}+\frac{1}{b'}+\frac{1}{c'}<1.
$$
Suppose
$$
\frac{1}{a}+\frac{1}{b}+\frac{1}{c}=\frac{1}{a'}+\frac{1}{b'}+\frac{1}{c'}.
$$
Is it true that $\{a,b,c\}=\{a',b',c'\}$? If it is not, it should be easy to give a counterexample, but I am not able to find one. | 2016/05/02 | [
"https://math.stackexchange.com/questions/1767899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/336294/"
] | Since you did not specify that $a\neq b\neq c$ and $a'\neq b'\neq c'$ an obvious counterexample is:
$1/4 + 1/4 +1/3= 5/6$
$1/6+1/3+1/3= 5/6$
I think the interesting question is what if you assume that $a\neq b\neq c$. Does there then exist $a',b',c'$ such that $1/a+1/b+1/c=1/a'+1/b'+1/c'$, $a'\neq b'\neq c'$ and $\{a,b,c\}\neq \{a',b',c'\}$? | It is not true. Take a=2,b=3,c=-2,a'= 3, b'=3, c'=-3. |
1,767,899 | Let $a,b,c,a',b',c'\in \mathbb{Z}\_{\geq 1}$ be such that
$$
\frac{1}{a}+\frac{1}{b}+\frac{1}{c}<1,\quad \frac{1}{a'}+\frac{1}{b'}+\frac{1}{c'}<1.
$$
Suppose
$$
\frac{1}{a}+\frac{1}{b}+\frac{1}{c}=\frac{1}{a'}+\frac{1}{b'}+\frac{1}{c'}.
$$
Is it true that $\{a,b,c\}=\{a',b',c'\}$? If it is not, it should be easy to give a counterexample, but I am not able to find one. | 2016/05/02 | [
"https://math.stackexchange.com/questions/1767899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/336294/"
] | COUNTEREXAMPLE.
Take $\left\{a,b,c \right\}=\left\{4k,6k,12k\right\}$ and $\left\{a',b',c' \right\}=\left\{6k,6k,6k\right\}$. Then both sums add up to $\frac{1}{2k}$.
Since @HRSE asks, here is another counterexample, in the case $\left\{a,b,c \right\}=\left\{40k,20k,120k\right\}$$\left\{a',b',c' \right\}=\left\{21k,42k,84k\right\}$ both sums add up to $\frac{1}{12k}$. | Since you did not specify that $a\neq b\neq c$ and $a'\neq b'\neq c'$ an obvious counterexample is:
$1/4 + 1/4 +1/3= 5/6$
$1/6+1/3+1/3= 5/6$
I think the interesting question is what if you assume that $a\neq b\neq c$. Does there then exist $a',b',c'$ such that $1/a+1/b+1/c=1/a'+1/b'+1/c'$, $a'\neq b'\neq c'$ and $\{a,b,c\}\neq \{a',b',c'\}$? |
1,767,899 | Let $a,b,c,a',b',c'\in \mathbb{Z}\_{\geq 1}$ be such that
$$
\frac{1}{a}+\frac{1}{b}+\frac{1}{c}<1,\quad \frac{1}{a'}+\frac{1}{b'}+\frac{1}{c'}<1.
$$
Suppose
$$
\frac{1}{a}+\frac{1}{b}+\frac{1}{c}=\frac{1}{a'}+\frac{1}{b'}+\frac{1}{c'}.
$$
Is it true that $\{a,b,c\}=\{a',b',c'\}$? If it is not, it should be easy to give a counterexample, but I am not able to find one. | 2016/05/02 | [
"https://math.stackexchange.com/questions/1767899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/336294/"
] | COUNTEREXAMPLE.
Take $\left\{a,b,c \right\}=\left\{4k,6k,12k\right\}$ and $\left\{a',b',c' \right\}=\left\{6k,6k,6k\right\}$. Then both sums add up to $\frac{1}{2k}$.
Since @HRSE asks, here is another counterexample, in the case $\left\{a,b,c \right\}=\left\{40k,20k,120k\right\}$$\left\{a',b',c' \right\}=\left\{21k,42k,84k\right\}$ both sums add up to $\frac{1}{12k}$. | For the more general case when $a\neq b\neq c$ and $a'\neq b'\neq c'$, the answer is also no.
In particular, let $\frac1a +\frac1b = \frac{1}{a'}$, and $\frac{1}{c} = \frac{1}{b'} +\frac{1}{c'}$. Then $a' = \frac{ab}{a + b}$, and $c = \frac{b' c' }{b'+ c'}$. We'd want these to be integers.
A simple way of making $\frac{ab}{a + b}$ an integer is by setting one to $a = k+1$ and $b = k (k + 1)$. In this way, for $k = 2$, we can have $\frac{1}{3} + \frac{1}{6} = \frac{1}{2}$; and for $k = 4$, $\frac{1}{5} + \frac{1}{20} = \frac{1}{4}$. We have a counter-example:
$$\frac{1}{3} + \frac{1}{6} + \frac{1}{4} = \frac{1}{5} + \frac{1}{20} + \frac{1}{2} = \frac{3}{4}$$ |
1,767,899 | Let $a,b,c,a',b',c'\in \mathbb{Z}\_{\geq 1}$ be such that
$$
\frac{1}{a}+\frac{1}{b}+\frac{1}{c}<1,\quad \frac{1}{a'}+\frac{1}{b'}+\frac{1}{c'}<1.
$$
Suppose
$$
\frac{1}{a}+\frac{1}{b}+\frac{1}{c}=\frac{1}{a'}+\frac{1}{b'}+\frac{1}{c'}.
$$
Is it true that $\{a,b,c\}=\{a',b',c'\}$? If it is not, it should be easy to give a counterexample, but I am not able to find one. | 2016/05/02 | [
"https://math.stackexchange.com/questions/1767899",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/336294/"
] | Since you did not specify that $a\neq b\neq c$ and $a'\neq b'\neq c'$ an obvious counterexample is:
$1/4 + 1/4 +1/3= 5/6$
$1/6+1/3+1/3= 5/6$
I think the interesting question is what if you assume that $a\neq b\neq c$. Does there then exist $a',b',c'$ such that $1/a+1/b+1/c=1/a'+1/b'+1/c'$, $a'\neq b'\neq c'$ and $\{a,b,c\}\neq \{a',b',c'\}$? | For the more general case when $a\neq b\neq c$ and $a'\neq b'\neq c'$, the answer is also no.
In particular, let $\frac1a +\frac1b = \frac{1}{a'}$, and $\frac{1}{c} = \frac{1}{b'} +\frac{1}{c'}$. Then $a' = \frac{ab}{a + b}$, and $c = \frac{b' c' }{b'+ c'}$. We'd want these to be integers.
A simple way of making $\frac{ab}{a + b}$ an integer is by setting one to $a = k+1$ and $b = k (k + 1)$. In this way, for $k = 2$, we can have $\frac{1}{3} + \frac{1}{6} = \frac{1}{2}$; and for $k = 4$, $\frac{1}{5} + \frac{1}{20} = \frac{1}{4}$. We have a counter-example:
$$\frac{1}{3} + \frac{1}{6} + \frac{1}{4} = \frac{1}{5} + \frac{1}{20} + \frac{1}{2} = \frac{3}{4}$$ |
36,956,375 | I wrote this code to compare two `CSV files (f1 and f2)` which both have 3 columns and many rows, then each time an `item at cell 1 of f1 matches that of f2` and `item at cell 2 of f1 matches that of f2, it should write the values`cell1 of f1, cell2 of f1, cell 3 of f2, for each respective column to a file named `network_python.csv`
**The code:**
```
t = {}
with open('file1.csv') as ff:
for f1 in csv.DictReader(ff):
with open('file2.csv') as ff:
for f2 in csv.DictReader(ff):
if int(f1['From'].strip()) == int(f2['From'].strip()) and int(f1['To'].strip()) == int(f2['To'].strip()):
print (f1['From'], f1['To'], f2['Mode'])
t.update({'From': f1['From'], 'To': f1['To'], 'Mode': f2['Mode']})
with open('network_python.csv', 'w') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for k,v in t.iteritems():
writer.writerow(t)
```
**Sample data in file1.csv**
```
From To Mode
1 2 cw
2 1 cw
3 4 cwt
7 2 cbt
8 9 ct
```
**Sample data in file2.csv**
```
From To Mode
8 9 c
3 4 cw
1 2 cwt
7 2 ct
2 1 cb
```
The code works fine (ie gets the right output) but when writing to file it writes to one single row thereby overwriting the previous result. Also is there a way I can improve the code's efficiency? as it is quite slow with large files. I have searched some questions here but they don't exactly answer my question Thank you for your time | 2016/04/30 | [
"https://Stackoverflow.com/questions/36956375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3449019/"
] | I am thinking load all files to memory than compare them.
```
import csv
with open(file1Path,'rb') as f:
r = csv.reader(f)
res1 = [line for line in f]
with open(file2Path,'rb') as f:
r = csv.reader(f)
res2 = [line for line in f]
final = [ [file1col[0],file1col[1],file2col[2]]for file1col,file2col in zip(res1,res2) if file1col[0] == file2cole[0] and file1col[1] == file2col[1] ]
with open(finalPath,'wb') as f:
w = csv.writer(f)
w.writerow(['From','To','Mode'])
w.writerows(final)
``` | Try to not modify the "t" `dict` each time you get a new row and use generators instead of it
```
def get_row():
with open('file1.csv') as ff:
for f1 in csv.DictReader(ff):
with open('file2.csv') as ff:
for f2 in csv.DictReader(ff):
if int(f1['From'].strip()) == int(f2['From'].strip()) and int(f1['To'].strip()) == int(f2['To'].strip()):
print (f1['From'], f1['To'], f2['Mode'])
yield {'From': f1['From'], 'To': f1['To'], 'Mode': f2['Mode']}
with open('network_python.csv', 'w') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for k,v in t.iteritems():
writer.writerow(get_row())
``` |
36,956,375 | I wrote this code to compare two `CSV files (f1 and f2)` which both have 3 columns and many rows, then each time an `item at cell 1 of f1 matches that of f2` and `item at cell 2 of f1 matches that of f2, it should write the values`cell1 of f1, cell2 of f1, cell 3 of f2, for each respective column to a file named `network_python.csv`
**The code:**
```
t = {}
with open('file1.csv') as ff:
for f1 in csv.DictReader(ff):
with open('file2.csv') as ff:
for f2 in csv.DictReader(ff):
if int(f1['From'].strip()) == int(f2['From'].strip()) and int(f1['To'].strip()) == int(f2['To'].strip()):
print (f1['From'], f1['To'], f2['Mode'])
t.update({'From': f1['From'], 'To': f1['To'], 'Mode': f2['Mode']})
with open('network_python.csv', 'w') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for k,v in t.iteritems():
writer.writerow(t)
```
**Sample data in file1.csv**
```
From To Mode
1 2 cw
2 1 cw
3 4 cwt
7 2 cbt
8 9 ct
```
**Sample data in file2.csv**
```
From To Mode
8 9 c
3 4 cw
1 2 cwt
7 2 ct
2 1 cb
```
The code works fine (ie gets the right output) but when writing to file it writes to one single row thereby overwriting the previous result. Also is there a way I can improve the code's efficiency? as it is quite slow with large files. I have searched some questions here but they don't exactly answer my question Thank you for your time | 2016/04/30 | [
"https://Stackoverflow.com/questions/36956375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3449019/"
] | Not 100% sure but lists should be slightly more efficient in your case (iteration, memory and no look up). However, dictionnaries are extremely efficient to look up values. Also, you don't need to convert to integer and use strip when comparing. This code should work fine.
```
import csv
output = []
with open('file1.csv') as file1, open('file2.csv') as file2:
for f1 in csv.DictReader(file1, delimiter='\t'):
for f2 in csv.DictReader(file2, delimiter='\t'):
if f1['From'] == f2['From'] and f1['To'] == f2['To']:
new_item = [f1['From'], f1['To'], f2['Mode']]
print new_item
output.append(new_item)
with open('network_python.csv', 'w') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.writer(csvfile, delimiter=',')
writer.writerow(fieldnames)
for row in output:
writer.writerow(row)
``` | Try to not modify the "t" `dict` each time you get a new row and use generators instead of it
```
def get_row():
with open('file1.csv') as ff:
for f1 in csv.DictReader(ff):
with open('file2.csv') as ff:
for f2 in csv.DictReader(ff):
if int(f1['From'].strip()) == int(f2['From'].strip()) and int(f1['To'].strip()) == int(f2['To'].strip()):
print (f1['From'], f1['To'], f2['Mode'])
yield {'From': f1['From'], 'To': f1['To'], 'Mode': f2['Mode']}
with open('network_python.csv', 'w') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for k,v in t.iteritems():
writer.writerow(get_row())
``` |
36,956,375 | I wrote this code to compare two `CSV files (f1 and f2)` which both have 3 columns and many rows, then each time an `item at cell 1 of f1 matches that of f2` and `item at cell 2 of f1 matches that of f2, it should write the values`cell1 of f1, cell2 of f1, cell 3 of f2, for each respective column to a file named `network_python.csv`
**The code:**
```
t = {}
with open('file1.csv') as ff:
for f1 in csv.DictReader(ff):
with open('file2.csv') as ff:
for f2 in csv.DictReader(ff):
if int(f1['From'].strip()) == int(f2['From'].strip()) and int(f1['To'].strip()) == int(f2['To'].strip()):
print (f1['From'], f1['To'], f2['Mode'])
t.update({'From': f1['From'], 'To': f1['To'], 'Mode': f2['Mode']})
with open('network_python.csv', 'w') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for k,v in t.iteritems():
writer.writerow(t)
```
**Sample data in file1.csv**
```
From To Mode
1 2 cw
2 1 cw
3 4 cwt
7 2 cbt
8 9 ct
```
**Sample data in file2.csv**
```
From To Mode
8 9 c
3 4 cw
1 2 cwt
7 2 ct
2 1 cb
```
The code works fine (ie gets the right output) but when writing to file it writes to one single row thereby overwriting the previous result. Also is there a way I can improve the code's efficiency? as it is quite slow with large files. I have searched some questions here but they don't exactly answer my question Thank you for your time | 2016/04/30 | [
"https://Stackoverflow.com/questions/36956375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3449019/"
] | You could create a `dict` where key is `(from, to)` from both csv files and combine them for the result:
```
import csv
from collections import OrderedDict
with open('file1.csv') as f:
reader = csv.reader(f)
reader.next()
rows = OrderedDict((tuple(row[:2]), None) for row in reader)
with open('file2.csv') as f:
reader = csv.reader(f)
reader.next()
# Skip row if matching row wasn't present in file1.csv
rows.update({tuple(row[:2]): row[2] for row in reader if tuple(row[:2]) in rows})
with open('network_python.csv', 'wb') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.writer(csvfile)
writer.writerow(fieldnames)
# Skip row if it wasn't present in file2.csv
writer.writerows((k[0], k[1], v) for k, v in rows.iteritems() if v is not None)
``` | Try to not modify the "t" `dict` each time you get a new row and use generators instead of it
```
def get_row():
with open('file1.csv') as ff:
for f1 in csv.DictReader(ff):
with open('file2.csv') as ff:
for f2 in csv.DictReader(ff):
if int(f1['From'].strip()) == int(f2['From'].strip()) and int(f1['To'].strip()) == int(f2['To'].strip()):
print (f1['From'], f1['To'], f2['Mode'])
yield {'From': f1['From'], 'To': f1['To'], 'Mode': f2['Mode']}
with open('network_python.csv', 'w') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for k,v in t.iteritems():
writer.writerow(get_row())
``` |
36,956,375 | I wrote this code to compare two `CSV files (f1 and f2)` which both have 3 columns and many rows, then each time an `item at cell 1 of f1 matches that of f2` and `item at cell 2 of f1 matches that of f2, it should write the values`cell1 of f1, cell2 of f1, cell 3 of f2, for each respective column to a file named `network_python.csv`
**The code:**
```
t = {}
with open('file1.csv') as ff:
for f1 in csv.DictReader(ff):
with open('file2.csv') as ff:
for f2 in csv.DictReader(ff):
if int(f1['From'].strip()) == int(f2['From'].strip()) and int(f1['To'].strip()) == int(f2['To'].strip()):
print (f1['From'], f1['To'], f2['Mode'])
t.update({'From': f1['From'], 'To': f1['To'], 'Mode': f2['Mode']})
with open('network_python.csv', 'w') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for k,v in t.iteritems():
writer.writerow(t)
```
**Sample data in file1.csv**
```
From To Mode
1 2 cw
2 1 cw
3 4 cwt
7 2 cbt
8 9 ct
```
**Sample data in file2.csv**
```
From To Mode
8 9 c
3 4 cw
1 2 cwt
7 2 ct
2 1 cb
```
The code works fine (ie gets the right output) but when writing to file it writes to one single row thereby overwriting the previous result. Also is there a way I can improve the code's efficiency? as it is quite slow with large files. I have searched some questions here but they don't exactly answer my question Thank you for your time | 2016/04/30 | [
"https://Stackoverflow.com/questions/36956375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3449019/"
] | Not 100% sure but lists should be slightly more efficient in your case (iteration, memory and no look up). However, dictionnaries are extremely efficient to look up values. Also, you don't need to convert to integer and use strip when comparing. This code should work fine.
```
import csv
output = []
with open('file1.csv') as file1, open('file2.csv') as file2:
for f1 in csv.DictReader(file1, delimiter='\t'):
for f2 in csv.DictReader(file2, delimiter='\t'):
if f1['From'] == f2['From'] and f1['To'] == f2['To']:
new_item = [f1['From'], f1['To'], f2['Mode']]
print new_item
output.append(new_item)
with open('network_python.csv', 'w') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.writer(csvfile, delimiter=',')
writer.writerow(fieldnames)
for row in output:
writer.writerow(row)
``` | I am thinking load all files to memory than compare them.
```
import csv
with open(file1Path,'rb') as f:
r = csv.reader(f)
res1 = [line for line in f]
with open(file2Path,'rb') as f:
r = csv.reader(f)
res2 = [line for line in f]
final = [ [file1col[0],file1col[1],file2col[2]]for file1col,file2col in zip(res1,res2) if file1col[0] == file2cole[0] and file1col[1] == file2col[1] ]
with open(finalPath,'wb') as f:
w = csv.writer(f)
w.writerow(['From','To','Mode'])
w.writerows(final)
``` |
36,956,375 | I wrote this code to compare two `CSV files (f1 and f2)` which both have 3 columns and many rows, then each time an `item at cell 1 of f1 matches that of f2` and `item at cell 2 of f1 matches that of f2, it should write the values`cell1 of f1, cell2 of f1, cell 3 of f2, for each respective column to a file named `network_python.csv`
**The code:**
```
t = {}
with open('file1.csv') as ff:
for f1 in csv.DictReader(ff):
with open('file2.csv') as ff:
for f2 in csv.DictReader(ff):
if int(f1['From'].strip()) == int(f2['From'].strip()) and int(f1['To'].strip()) == int(f2['To'].strip()):
print (f1['From'], f1['To'], f2['Mode'])
t.update({'From': f1['From'], 'To': f1['To'], 'Mode': f2['Mode']})
with open('network_python.csv', 'w') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for k,v in t.iteritems():
writer.writerow(t)
```
**Sample data in file1.csv**
```
From To Mode
1 2 cw
2 1 cw
3 4 cwt
7 2 cbt
8 9 ct
```
**Sample data in file2.csv**
```
From To Mode
8 9 c
3 4 cw
1 2 cwt
7 2 ct
2 1 cb
```
The code works fine (ie gets the right output) but when writing to file it writes to one single row thereby overwriting the previous result. Also is there a way I can improve the code's efficiency? as it is quite slow with large files. I have searched some questions here but they don't exactly answer my question Thank you for your time | 2016/04/30 | [
"https://Stackoverflow.com/questions/36956375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3449019/"
] | You could create a `dict` where key is `(from, to)` from both csv files and combine them for the result:
```
import csv
from collections import OrderedDict
with open('file1.csv') as f:
reader = csv.reader(f)
reader.next()
rows = OrderedDict((tuple(row[:2]), None) for row in reader)
with open('file2.csv') as f:
reader = csv.reader(f)
reader.next()
# Skip row if matching row wasn't present in file1.csv
rows.update({tuple(row[:2]): row[2] for row in reader if tuple(row[:2]) in rows})
with open('network_python.csv', 'wb') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.writer(csvfile)
writer.writerow(fieldnames)
# Skip row if it wasn't present in file2.csv
writer.writerows((k[0], k[1], v) for k, v in rows.iteritems() if v is not None)
``` | I am thinking load all files to memory than compare them.
```
import csv
with open(file1Path,'rb') as f:
r = csv.reader(f)
res1 = [line for line in f]
with open(file2Path,'rb') as f:
r = csv.reader(f)
res2 = [line for line in f]
final = [ [file1col[0],file1col[1],file2col[2]]for file1col,file2col in zip(res1,res2) if file1col[0] == file2cole[0] and file1col[1] == file2col[1] ]
with open(finalPath,'wb') as f:
w = csv.writer(f)
w.writerow(['From','To','Mode'])
w.writerows(final)
``` |
36,956,375 | I wrote this code to compare two `CSV files (f1 and f2)` which both have 3 columns and many rows, then each time an `item at cell 1 of f1 matches that of f2` and `item at cell 2 of f1 matches that of f2, it should write the values`cell1 of f1, cell2 of f1, cell 3 of f2, for each respective column to a file named `network_python.csv`
**The code:**
```
t = {}
with open('file1.csv') as ff:
for f1 in csv.DictReader(ff):
with open('file2.csv') as ff:
for f2 in csv.DictReader(ff):
if int(f1['From'].strip()) == int(f2['From'].strip()) and int(f1['To'].strip()) == int(f2['To'].strip()):
print (f1['From'], f1['To'], f2['Mode'])
t.update({'From': f1['From'], 'To': f1['To'], 'Mode': f2['Mode']})
with open('network_python.csv', 'w') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for k,v in t.iteritems():
writer.writerow(t)
```
**Sample data in file1.csv**
```
From To Mode
1 2 cw
2 1 cw
3 4 cwt
7 2 cbt
8 9 ct
```
**Sample data in file2.csv**
```
From To Mode
8 9 c
3 4 cw
1 2 cwt
7 2 ct
2 1 cb
```
The code works fine (ie gets the right output) but when writing to file it writes to one single row thereby overwriting the previous result. Also is there a way I can improve the code's efficiency? as it is quite slow with large files. I have searched some questions here but they don't exactly answer my question Thank you for your time | 2016/04/30 | [
"https://Stackoverflow.com/questions/36956375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3449019/"
] | You could create a `dict` where key is `(from, to)` from both csv files and combine them for the result:
```
import csv
from collections import OrderedDict
with open('file1.csv') as f:
reader = csv.reader(f)
reader.next()
rows = OrderedDict((tuple(row[:2]), None) for row in reader)
with open('file2.csv') as f:
reader = csv.reader(f)
reader.next()
# Skip row if matching row wasn't present in file1.csv
rows.update({tuple(row[:2]): row[2] for row in reader if tuple(row[:2]) in rows})
with open('network_python.csv', 'wb') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.writer(csvfile)
writer.writerow(fieldnames)
# Skip row if it wasn't present in file2.csv
writer.writerows((k[0], k[1], v) for k, v in rows.iteritems() if v is not None)
``` | Not 100% sure but lists should be slightly more efficient in your case (iteration, memory and no look up). However, dictionnaries are extremely efficient to look up values. Also, you don't need to convert to integer and use strip when comparing. This code should work fine.
```
import csv
output = []
with open('file1.csv') as file1, open('file2.csv') as file2:
for f1 in csv.DictReader(file1, delimiter='\t'):
for f2 in csv.DictReader(file2, delimiter='\t'):
if f1['From'] == f2['From'] and f1['To'] == f2['To']:
new_item = [f1['From'], f1['To'], f2['Mode']]
print new_item
output.append(new_item)
with open('network_python.csv', 'w') as csvfile:
fieldnames = ['From', 'To', 'Mode']
writer = csv.writer(csvfile, delimiter=',')
writer.writerow(fieldnames)
for row in output:
writer.writerow(row)
``` |
28,908,080 | I'm trying to select a random element in a 2D list in python.
I'm creating a blackjack game.
>
> I'm aware of how long and non-optimized this code is, but I'm new to programming and I want to make mistakes to learn.
>
>
> Here's the initial code that I have set up. I create the suits (spades, clubs, hearts, diamonds). I append it to the list called list\_of\_cards which was initialized as an empty array.
>
>
> Then I have another list called player\_card for the player to view. Here it is in reference.
>
>
>
```
list_of_suits= [] #Creating list of cards
player_card = []
king_of_spades = 10 #Creating face cards for the spades deck.
queen_of_spades = 10
jack_of_spades = 10
king_of_clubs = 10
queen_of_clubs = 10
jack_of_clubs = 10
king_of_hearts = 10
queen_of_hearts = 10
jack_of_hearts = 10
king_of_diamonds = 10
queen_of_diamonds = 10
jack_of_diamonds = 10
ace_of_spades = [1,11] # Aces are either 1 or 11
ace_of_clubs = [1,11]
ace_of_hearts = [1,11]
ace_of_diamonds = [1,11]
spades = [ace_of_spades,2,3,4,5,6,7,8,9,10, jack_of_spades, queen_of_spades, king_of_spades]
clubs = [ace_of_clubs,2,3,4,5,6,7,8,9,10, jack_of_clubs, queen_of_clubs, king_of_clubs]
hearts = [ace_of_hearts,2,3,4,5,6,7,8,9,10, jack_of_hearts, queen_of_hearts, king_of_hearts]
diamonds = [ace_of_diamonds,2,3,4,5,6,7,8,9,10, jack_of_diamonds, queen_of_diamonds, king_of_diamonds]
list_of_suits.append(spades)
list_of_suits.append(clubs)
list_of_suits.append(hearts)
list_of_suits.append(diamonds)
```
>
> This is the selector for a random card. It will iterate through the array to select one of the four cards randomly. Next, it will go into that array and choose a random card.
>
>
>
```
random_list_of_suits = random.choice(list_of_suits)
random_card_number = random.choice(random_list_of_suits)
random_list_of_suits.remove(random_card_number)
player_card.append(random_card_number)
print player_card
print list_of_suits
```
>
> Here's what I'm trying to figure out: How do I create a new random number each time?
>
>
> I'm kind of stuck and I tried putting it through a for loop, but if I put the random\_card\_number in a loop, it will select the same random card that it did initially four times.
>
>
> | 2015/03/06 | [
"https://Stackoverflow.com/questions/28908080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4598380/"
] | ```
import random
list2d = [range(0, 5), range(5, 10), range(10, 15), range(15, 20)]
for i in range(0, 10):
random_suite = random.choice(list2d)
random_card = random.choice(random_suite)
print random_suite, random_card
```
output:
```
[5, 6, 7, 8, 9] 7
[5, 6, 7, 8, 9] 5
[5, 6, 7, 8, 9] 5
[10, 11, 12, 13, 14] 11
[10, 11, 12, 13, 14] 13
[10, 11, 12, 13, 14] 12
[10, 11, 12, 13, 14] 14
[10, 11, 12, 13, 14] 10
[10, 11, 12, 13, 14] 10
[0, 1, 2, 3, 4] 2
``` | ```
#include <stdafx.h>
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
using namespace std;
int main()
{
srand(time(0)); // set initial seed value to system clock
for (int nCount=0; nCount < 100; ++nCount)
{
cout << rand() << "\t";
if ((nCount+1) % 5 == 0)
cout << endl;
}
```
The srand uses time as the first intial seed to create your random numbers therefore each time you run the program you will get a different random number because the intail seed will be changing with the time. |
28,908,080 | I'm trying to select a random element in a 2D list in python.
I'm creating a blackjack game.
>
> I'm aware of how long and non-optimized this code is, but I'm new to programming and I want to make mistakes to learn.
>
>
> Here's the initial code that I have set up. I create the suits (spades, clubs, hearts, diamonds). I append it to the list called list\_of\_cards which was initialized as an empty array.
>
>
> Then I have another list called player\_card for the player to view. Here it is in reference.
>
>
>
```
list_of_suits= [] #Creating list of cards
player_card = []
king_of_spades = 10 #Creating face cards for the spades deck.
queen_of_spades = 10
jack_of_spades = 10
king_of_clubs = 10
queen_of_clubs = 10
jack_of_clubs = 10
king_of_hearts = 10
queen_of_hearts = 10
jack_of_hearts = 10
king_of_diamonds = 10
queen_of_diamonds = 10
jack_of_diamonds = 10
ace_of_spades = [1,11] # Aces are either 1 or 11
ace_of_clubs = [1,11]
ace_of_hearts = [1,11]
ace_of_diamonds = [1,11]
spades = [ace_of_spades,2,3,4,5,6,7,8,9,10, jack_of_spades, queen_of_spades, king_of_spades]
clubs = [ace_of_clubs,2,3,4,5,6,7,8,9,10, jack_of_clubs, queen_of_clubs, king_of_clubs]
hearts = [ace_of_hearts,2,3,4,5,6,7,8,9,10, jack_of_hearts, queen_of_hearts, king_of_hearts]
diamonds = [ace_of_diamonds,2,3,4,5,6,7,8,9,10, jack_of_diamonds, queen_of_diamonds, king_of_diamonds]
list_of_suits.append(spades)
list_of_suits.append(clubs)
list_of_suits.append(hearts)
list_of_suits.append(diamonds)
```
>
> This is the selector for a random card. It will iterate through the array to select one of the four cards randomly. Next, it will go into that array and choose a random card.
>
>
>
```
random_list_of_suits = random.choice(list_of_suits)
random_card_number = random.choice(random_list_of_suits)
random_list_of_suits.remove(random_card_number)
player_card.append(random_card_number)
print player_card
print list_of_suits
```
>
> Here's what I'm trying to figure out: How do I create a new random number each time?
>
>
> I'm kind of stuck and I tried putting it through a for loop, but if I put the random\_card\_number in a loop, it will select the same random card that it did initially four times.
>
>
> | 2015/03/06 | [
"https://Stackoverflow.com/questions/28908080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4598380/"
] | The list you enter in random.choice() must be a 1D array.
So you can do this,
```
random_list_of_suits = np.random.choice(list_of_suits) # you can get spades/clubs/hearts/diamonds
index_of_random_card_number = random.choice(len(random_list_of_suits))
random_card = random_list_of_suits[index_of_random_card_number] # You get a random card
``` | ```
#include <stdafx.h>
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
using namespace std;
int main()
{
srand(time(0)); // set initial seed value to system clock
for (int nCount=0; nCount < 100; ++nCount)
{
cout << rand() << "\t";
if ((nCount+1) % 5 == 0)
cout << endl;
}
```
The srand uses time as the first intial seed to create your random numbers therefore each time you run the program you will get a different random number because the intail seed will be changing with the time. |
28,908,080 | I'm trying to select a random element in a 2D list in python.
I'm creating a blackjack game.
>
> I'm aware of how long and non-optimized this code is, but I'm new to programming and I want to make mistakes to learn.
>
>
> Here's the initial code that I have set up. I create the suits (spades, clubs, hearts, diamonds). I append it to the list called list\_of\_cards which was initialized as an empty array.
>
>
> Then I have another list called player\_card for the player to view. Here it is in reference.
>
>
>
```
list_of_suits= [] #Creating list of cards
player_card = []
king_of_spades = 10 #Creating face cards for the spades deck.
queen_of_spades = 10
jack_of_spades = 10
king_of_clubs = 10
queen_of_clubs = 10
jack_of_clubs = 10
king_of_hearts = 10
queen_of_hearts = 10
jack_of_hearts = 10
king_of_diamonds = 10
queen_of_diamonds = 10
jack_of_diamonds = 10
ace_of_spades = [1,11] # Aces are either 1 or 11
ace_of_clubs = [1,11]
ace_of_hearts = [1,11]
ace_of_diamonds = [1,11]
spades = [ace_of_spades,2,3,4,5,6,7,8,9,10, jack_of_spades, queen_of_spades, king_of_spades]
clubs = [ace_of_clubs,2,3,4,5,6,7,8,9,10, jack_of_clubs, queen_of_clubs, king_of_clubs]
hearts = [ace_of_hearts,2,3,4,5,6,7,8,9,10, jack_of_hearts, queen_of_hearts, king_of_hearts]
diamonds = [ace_of_diamonds,2,3,4,5,6,7,8,9,10, jack_of_diamonds, queen_of_diamonds, king_of_diamonds]
list_of_suits.append(spades)
list_of_suits.append(clubs)
list_of_suits.append(hearts)
list_of_suits.append(diamonds)
```
>
> This is the selector for a random card. It will iterate through the array to select one of the four cards randomly. Next, it will go into that array and choose a random card.
>
>
>
```
random_list_of_suits = random.choice(list_of_suits)
random_card_number = random.choice(random_list_of_suits)
random_list_of_suits.remove(random_card_number)
player_card.append(random_card_number)
print player_card
print list_of_suits
```
>
> Here's what I'm trying to figure out: How do I create a new random number each time?
>
>
> I'm kind of stuck and I tried putting it through a for loop, but if I put the random\_card\_number in a loop, it will select the same random card that it did initially four times.
>
>
> | 2015/03/06 | [
"https://Stackoverflow.com/questions/28908080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4598380/"
] | ```
import random
list2d = [range(0, 5), range(5, 10), range(10, 15), range(15, 20)]
for i in range(0, 10):
random_suite = random.choice(list2d)
random_card = random.choice(random_suite)
print random_suite, random_card
```
output:
```
[5, 6, 7, 8, 9] 7
[5, 6, 7, 8, 9] 5
[5, 6, 7, 8, 9] 5
[10, 11, 12, 13, 14] 11
[10, 11, 12, 13, 14] 13
[10, 11, 12, 13, 14] 12
[10, 11, 12, 13, 14] 14
[10, 11, 12, 13, 14] 10
[10, 11, 12, 13, 14] 10
[0, 1, 2, 3, 4] 2
``` | The list you enter in random.choice() must be a 1D array.
So you can do this,
```
random_list_of_suits = np.random.choice(list_of_suits) # you can get spades/clubs/hearts/diamonds
index_of_random_card_number = random.choice(len(random_list_of_suits))
random_card = random_list_of_suits[index_of_random_card_number] # You get a random card
``` |
382,875 | I have two of the exact same 2TB external HDDs. I copied a bunch of information to one of them and then copied everything from the first to the second HDD and now their sitting at different amounts of free space. The copy job completed without error and there are no obvious large hidden files lying around.
First question is: how can this happen? I used robocopy so I know I brought over all hidden files and everything
Second question is: is there anything I can use to make sure both HDDs have exactly the same information on them? | 2012/01/27 | [
"https://superuser.com/questions/382875",
"https://superuser.com",
"https://superuser.com/users/38871/"
] | Several possible causes
* System restore or volume shadow copy using the extra space
* chkdsk found some file fragments and left them in some folder
* MFT size difference
* Cluster size difference (more obvious if you're had a lot of small files)
* Robocopy did not handle sparse files/compressed files/junctions correctly | You could use SyncToy from Microsoft, or ROBOCOPY with the /MIR command under Windows XP or higher. What OS are you using? |
55,926,830 | I'm filtering some data where say table.x has the following structure
```
column1 | c.2 |column3
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.0 | 10 | 2019-04-29 14:45:52
0.0.0.0 | 50 | 2019-04-29 14:35:52
0.0.0.0 | 50 | 2019-04-29 14:25:52
0.0.0.0 | 90 | 2019-04-29 14:15:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.1 | 40 | 2019-04-29 13:45:52
0.0.0.1 | 70 | 2019-04-29 13:30:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
```
I would like the result set to return as
```
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
``` | 2019/04/30 | [
"https://Stackoverflow.com/questions/55926830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5450427/"
] | You need to get the max `column3` for each `column1` by grouping and then join to the table:
```
select t.*
from tablename t inner join (
select column1, max(column3) column3
from tablename
group by column1
) g on g.column1 = t.column1 and g.column3 = t.column3
``` | You could usea inner join on max col3 group by column1
```
select * from my_table m
inner join (
select column1, max(column3) col3
from my_table
group by column1
) t on t. column1 = m.column1 and t.col3 = m.column3
``` |
55,926,830 | I'm filtering some data where say table.x has the following structure
```
column1 | c.2 |column3
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.0 | 10 | 2019-04-29 14:45:52
0.0.0.0 | 50 | 2019-04-29 14:35:52
0.0.0.0 | 50 | 2019-04-29 14:25:52
0.0.0.0 | 90 | 2019-04-29 14:15:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.1 | 40 | 2019-04-29 13:45:52
0.0.0.1 | 70 | 2019-04-29 13:30:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
```
I would like the result set to return as
```
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
``` | 2019/04/30 | [
"https://Stackoverflow.com/questions/55926830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5450427/"
] | You need to get the max `column3` for each `column1` by grouping and then join to the table:
```
select t.*
from tablename t inner join (
select column1, max(column3) column3
from tablename
group by column1
) g on g.column1 = t.column1 and g.column3 = t.column3
``` | Try the following SQL code:
```
SELECT max(column1), column2, max(column3) --maximum of IP address and time
FROM yourTable
GROUP BY column1 --grouped by IP address
```
The result is:
```
max(column1) | column2 | max(column3)
------------------------------------------------
0.0.0.0 20 2019-04-29T14:55:52Z
0.0.0.1 40 2019-04-29T14:05:52Z
0.0.0.4 20 2019-04-29T13:25:52Z
``` |
55,926,830 | I'm filtering some data where say table.x has the following structure
```
column1 | c.2 |column3
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.0 | 10 | 2019-04-29 14:45:52
0.0.0.0 | 50 | 2019-04-29 14:35:52
0.0.0.0 | 50 | 2019-04-29 14:25:52
0.0.0.0 | 90 | 2019-04-29 14:15:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.1 | 40 | 2019-04-29 13:45:52
0.0.0.1 | 70 | 2019-04-29 13:30:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
```
I would like the result set to return as
```
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
``` | 2019/04/30 | [
"https://Stackoverflow.com/questions/55926830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5450427/"
] | You need to get the max `column3` for each `column1` by grouping and then join to the table:
```
select t.*
from tablename t inner join (
select column1, max(column3) column3
from tablename
group by column1
) g on g.column1 = t.column1 and g.column3 = t.column3
``` | Try to use window function
```
select
column1, column2, column3
from (
SELECT
column1, column2, column3,
row_number() over ( partition by column1 ) pbg
FROM tablename
) aaaa
where aaaa.pbg = 1
``` |
55,926,830 | I'm filtering some data where say table.x has the following structure
```
column1 | c.2 |column3
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.0 | 10 | 2019-04-29 14:45:52
0.0.0.0 | 50 | 2019-04-29 14:35:52
0.0.0.0 | 50 | 2019-04-29 14:25:52
0.0.0.0 | 90 | 2019-04-29 14:15:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.1 | 40 | 2019-04-29 13:45:52
0.0.0.1 | 70 | 2019-04-29 13:30:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
```
I would like the result set to return as
```
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
``` | 2019/04/30 | [
"https://Stackoverflow.com/questions/55926830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5450427/"
] | What about using `DISTINCT` with one column like so :
```
SELECT DISTINCT ON (column1) column1, column2, column3 FROM table_name
```
---
**Note** `c.2` is not a valid column name.
---
Here is a demo online <https://rextester.com/FBIS74019> | You could usea inner join on max col3 group by column1
```
select * from my_table m
inner join (
select column1, max(column3) col3
from my_table
group by column1
) t on t. column1 = m.column1 and t.col3 = m.column3
``` |
55,926,830 | I'm filtering some data where say table.x has the following structure
```
column1 | c.2 |column3
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.0 | 10 | 2019-04-29 14:45:52
0.0.0.0 | 50 | 2019-04-29 14:35:52
0.0.0.0 | 50 | 2019-04-29 14:25:52
0.0.0.0 | 90 | 2019-04-29 14:15:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.1 | 40 | 2019-04-29 13:45:52
0.0.0.1 | 70 | 2019-04-29 13:30:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
```
I would like the result set to return as
```
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
``` | 2019/04/30 | [
"https://Stackoverflow.com/questions/55926830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5450427/"
] | What about using `DISTINCT` with one column like so :
```
SELECT DISTINCT ON (column1) column1, column2, column3 FROM table_name
```
---
**Note** `c.2` is not a valid column name.
---
Here is a demo online <https://rextester.com/FBIS74019> | Try the following SQL code:
```
SELECT max(column1), column2, max(column3) --maximum of IP address and time
FROM yourTable
GROUP BY column1 --grouped by IP address
```
The result is:
```
max(column1) | column2 | max(column3)
------------------------------------------------
0.0.0.0 20 2019-04-29T14:55:52Z
0.0.0.1 40 2019-04-29T14:05:52Z
0.0.0.4 20 2019-04-29T13:25:52Z
``` |
55,926,830 | I'm filtering some data where say table.x has the following structure
```
column1 | c.2 |column3
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.0 | 10 | 2019-04-29 14:45:52
0.0.0.0 | 50 | 2019-04-29 14:35:52
0.0.0.0 | 50 | 2019-04-29 14:25:52
0.0.0.0 | 90 | 2019-04-29 14:15:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.1 | 40 | 2019-04-29 13:45:52
0.0.0.1 | 70 | 2019-04-29 13:30:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
```
I would like the result set to return as
```
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
``` | 2019/04/30 | [
"https://Stackoverflow.com/questions/55926830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5450427/"
] | What about using `DISTINCT` with one column like so :
```
SELECT DISTINCT ON (column1) column1, column2, column3 FROM table_name
```
---
**Note** `c.2` is not a valid column name.
---
Here is a demo online <https://rextester.com/FBIS74019> | Try to use window function
```
select
column1, column2, column3
from (
SELECT
column1, column2, column3,
row_number() over ( partition by column1 ) pbg
FROM tablename
) aaaa
where aaaa.pbg = 1
``` |
55,926,830 | I'm filtering some data where say table.x has the following structure
```
column1 | c.2 |column3
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.0 | 10 | 2019-04-29 14:45:52
0.0.0.0 | 50 | 2019-04-29 14:35:52
0.0.0.0 | 50 | 2019-04-29 14:25:52
0.0.0.0 | 90 | 2019-04-29 14:15:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.1 | 40 | 2019-04-29 13:45:52
0.0.0.1 | 70 | 2019-04-29 13:30:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
```
I would like the result set to return as
```
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
``` | 2019/04/30 | [
"https://Stackoverflow.com/questions/55926830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5450427/"
] | You could usea inner join on max col3 group by column1
```
select * from my_table m
inner join (
select column1, max(column3) col3
from my_table
group by column1
) t on t. column1 = m.column1 and t.col3 = m.column3
``` | Try to use window function
```
select
column1, column2, column3
from (
SELECT
column1, column2, column3,
row_number() over ( partition by column1 ) pbg
FROM tablename
) aaaa
where aaaa.pbg = 1
``` |
55,926,830 | I'm filtering some data where say table.x has the following structure
```
column1 | c.2 |column3
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.0 | 10 | 2019-04-29 14:45:52
0.0.0.0 | 50 | 2019-04-29 14:35:52
0.0.0.0 | 50 | 2019-04-29 14:25:52
0.0.0.0 | 90 | 2019-04-29 14:15:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.1 | 40 | 2019-04-29 13:45:52
0.0.0.1 | 70 | 2019-04-29 13:30:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
```
I would like the result set to return as
```
0.0.0.0 | 20 | 2019-04-29 14:55:52
0.0.0.1 | 40 | 2019-04-29 14:05:52
0.0.0.4 | 20 | 2019-04-29 13:25:52
``` | 2019/04/30 | [
"https://Stackoverflow.com/questions/55926830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5450427/"
] | Try the following SQL code:
```
SELECT max(column1), column2, max(column3) --maximum of IP address and time
FROM yourTable
GROUP BY column1 --grouped by IP address
```
The result is:
```
max(column1) | column2 | max(column3)
------------------------------------------------
0.0.0.0 20 2019-04-29T14:55:52Z
0.0.0.1 40 2019-04-29T14:05:52Z
0.0.0.4 20 2019-04-29T13:25:52Z
``` | Try to use window function
```
select
column1, column2, column3
from (
SELECT
column1, column2, column3,
row_number() over ( partition by column1 ) pbg
FROM tablename
) aaaa
where aaaa.pbg = 1
``` |
282,381 | I want to return the previous row based on the current id number.
All id numbers are UNIQUE, but are NOT (necessarily) SEQUENTIAL.
```
SELECT LAG(id) FROM cb_cat WHERE id=450;
```
I thought this query should work.
If possible, I would like to return \* from the previous row before the current id.
I do not know which id number that is, but it is smaller than the current id number, e.g. 450. It could be 449 or even 1.
How can I achieve this? | 2020/12/31 | [
"https://dba.stackexchange.com/questions/282381",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/221179/"
] | Window functions work on the result after the `WHERE` clause is applied. Since `id` is unique and you ask for exactly one `id`, that result has a maximum of one row. There just isn't any previous row whatsoever.
Further more relational tables represent relations which are a special form of (multi) sets. And (multi) sets aren't ordered. Unless there's an explicit `ORDER BY`, the order the tuples of a result are returned in is to be considered random. Window functions depending on an order therefore also need an `ORDER BY` specified in the `OVER` clause, unless they just should pick some random row. You didn't specify what defines your order, I assume it's the `id` in the following.
Using `lag()` you'd have to select all rows in a derived table where you apply the `lag()` and then go for the row with the `id` of `450` in the outer `SELECT`.
```
SELECT l
FROM (SELECT id,
lag(id) OVER (ORDER BY id) l
FROM cb_cat) x
WHERE id = 450;
```
This can be optimized a little. Since `id` defines the order, we actually only need to look at the records with an `id` lower than or equal to `450` in the inner `SELECT`. (I have doubts the optimizer would figure this out by itself. But maybe I'm underestimating its capabilities.)
```
SELECT l
FROM (SELECT id,
lag(id) OVER (ORDER BY id) l
FROM cb_cat
WHERE id <= 450) x
WHERE id = 450;
```
But if we think of it, what we actually want is the the largest `id` that is less than `450`. `lag()` isn't the best tool to get this, `LIMIT` is. We get all `id`s less than `450`, order them in descending order and pick the first one of that ordered result.
```
SELECT id
FROM cb_cat
WHERE id < 450
ORDER BY id DESC
LIMIT 1;
``` | You just need to add an `OVER` and `ORDER BY` clause to your lag function so it knows how to order the records to select the previous one. Also you can specify how many rows back to look (in this case one row back).
For example: `SELECT LAG(id, 1) OVER (ORDER BY id) FROM cb_cat WHERE id=450`
Using this you can either apply the `LAG()` function to every column you want to get the previous value of, or you can use a CTE or subquery to get just the ID of the previous row and then filter on it like so:
```
WITH PreviousRowId AS
(
SELECT LAG(id, 1) OVER (ORDER BY id) AS PreviousRowId, id AS CurrentRowId
FROM cb_cat
)
SELECT C.*
FROM cb_cat AS C
INNER JOIN PreviousRowId AS P
ON C.id = P.PreviousRowId
WHERE P.CurrentRowId = 450
```
There's good examples and more information on the `LAG()` function [here](https://www.postgresqltutorial.com/postgresql-lag-function/). |
63,599,077 | I am trying to differentiate the linetype and/or color in stacked `geom_area` by group. How can I do that? Simply `geom_area(linetype = type)` or `color = type` does not work. Only think that works changes the values for both groups: `geom_area(color = "white")`. How can I modify the color and linetype by group?
My dummy example:
```
dat <- data.frame(x = c(1:5,1:5),
y = c(9:5, 10,7,5,3,1),
type = rep(c("a", "b"), each = 5))
```
[](https://i.stack.imgur.com/qTBrg.png)
My `geom_area`:
```
library(dplyr)
dat %>%
ggplot(aes(fill = type,
x = x,
y = y)) +
geom_area(position="stack",
stat="identity",
alpha = 0.5,
color = "white")
``` | 2020/08/26 | [
"https://Stackoverflow.com/questions/63599077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2742140/"
] | C++ treats `const` very strictly. Copying such a struct will be painful if possible at all (without UB). Perhaps what you are really looking for is "readonly" instead? In that case you can make fields private with public getters/setters:
```cpp
struct Foo {
public:
Foo(): id(-1), value(-1) {}
Foo(int id): id(id), value(0) {}
int getId() const {
return id;
}
int getValue() const {
return value;
}
void setValue(int newValue) {
value = newValue;
}
private:
int id;
int value;
};
``` | In C++, an object can be initialized only once. Your constant member is initialized via the default constructor when you declare the array. Then, you attempt to change that value via assignment
```
foos[0] = Foo(1234);
```
This fails, and righly so. One thing you could do is to have a container of not Foos, but some sort of pointers to foo. Thus, you will have allocated the memory for the pointers but will create the actual objects only when you can. For example:
```
Foo* foos[10]; //here you have only the pointers
foos[0] = new Foo(1234); //OK, the object is inialized here
```
You may consider using smart pointers such as `std::unique_ptr` instead of raw pointers here. |
Subsets and Splits