prompt
stringlengths 48
2.37k
| chosen
stringlengths 7
4.28k
| rejected
stringlengths 11
4.44k
|
---|---|---|
Question: Trying to work out where I have screwed up with trying to create a count down timer which displays seconds and milliseconds. The idea is the timer displays the count down time to an NSString which updates a UILable.
The code I currently have is
```
-(void)timerRun {
if (self.timerPageView.startCountdown) {
NSLog(@"%i",self.timerPageView.xtime);
self.timerPageView.sec = self.timerPageView.sec - 1;
seconds = (self.timerPageView.sec % 60) % 60 ;
milliseconds = (self.timerPageView.sec % 60) % 1000;
NSString *timerOutput = [NSString stringWithFormat:@"%i:%i", seconds, milliseconds];
self.timerPageView.timerText.text = timerOutput;
if (self.timerPageView.resetTimer == YES) {
[self setTimer];
}
}
else {
}
}
-(void)setTimer{
if (self.timerPageView.xtime == 0) {
self.timerPageView.xtime = 60000;
}
self.timerPageView.sec = self.timerPageView.xtime;
self.timerPageView.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerRun) userInfo:Nil repeats:YES];
self.timerPageView.resetTimer = NO;
}
int seconds;
int milliseconds;
int minutes;
}
```
Anyone got any ideas what I am doing wrong?
Answer: | You have a timer that will execute roughly 100 times per second (interval of 0.01).
You decrement a value by `1` each time. Therefore, your `self.timerPageView.sec` variable appears to be hundredths of a second.
To get the number of seconds, you need to divide this value by 100. To get the number of milliseconds, you need to multiply by 10 then modulo by 1000.
```
seconds = self.timerPageView.sec / 100;
milliseconds = (self.timerPageView.sec * 10) % 1000;
```
Update:
Also note that your timer is highly inaccurate. The timer will not repeat EXACTLY every hundredth of a second. It may only run 80 times per second or some other inexact rate.
A better approach would be to get the current time at the start. Then inside your `timerRun` method you get the current time again. Subtract the two numbers. This will give the actual elapsed time. Use this instead of decrementing a value each loop. | You set a time interval of 0.01, which is every 10 milliseconds, 0.001 is every millisecond.
Even so, NSTimer is not that accurate, you probably won't get it to work every 1 ms. It is fired from the run loop so there is latency and jitter. |
Question: I am quite a noob when it comes to deploying a Django project. I'd like to know what are the various methods to deploy Django project and which one is the most preferred.
Answer: | Use the Nginx/Apache/mod-wsgi and you can't go wrong.
If you prefer a simple alternative, just use Apache.
There is a very good deployment document: <http://lethain.com/entry/2009/feb/13/the-django-and-ubuntu-intrepid-almanac/> | I myself have faced a lot of problems in deploying Django Projects and automating the deployment process. Apache and mod\_wsgi were like curse for Django Deployment. There are several tools like [Nginx](http://wiki.nginx.org/Main), [Gunicorn](http://gunicorn.org/), [SupervisorD](http://supervisord.org/) and Fabric which are trending for Django deployment. At first I used/configured them individually without Deployment automation which took a lot of time(I had to maintain testing as well as production servers for my client and had to update them as soon as a new feature was tested and approved.) but then I stumbled upon django-fagungis, which totally automates my Django Deployment from cloning my project from bitbucket to deploying on my remote server (it uses Nginx, Gunicorn, SupervisorD, Fabtic and virtualenv and also installs all the dependencies on the fly), all with just three commands :) You can find more about it in my blog post [**here**](http://alirazabhayani.blogspot.com/2013/02/easy-django-deployment-tools-tutorial-fabric-gunicorn-nginx-supervisor.html). Now I even don't have to get involved in this process(which used to take a lot of my time) and one of my junior developers runs those three commands of django-fagungis [mentioned here](http://alirazabhayani.blogspot.com/2013/02/easy-django-deployment-tools-tutorial-fabric-gunicorn-nginx-supervisor.html) on his local machine and we get a crisp new copy of our project deployed in minutes without any hassle:) |
Question: I am quite a noob when it comes to deploying a Django project. I'd like to know what are the various methods to deploy Django project and which one is the most preferred.
Answer: | The Django documentation lists Apache/mod\_wsgi, Apache/mod\_python and FastCGI etc.
**mod\_python** is deprecated now, one should use mod\_wsgi instead.
Django with **mod\_wsgi** is easy to setup, but:
* you can only use one python version at a time [edit: you even can only use the python version mod\_wsgi was compiled for]
* [edit: seems if I'm wrong on mod\_wsgi not supporting virtualenv: it does]
So for multiple sites (targeting different django/python versions) on a server mod\_wsgi is not
the best solution.
**FastCGI** can be used with virtualenv, also with different python versions, as you run it with
```
./manage.py runfcgi …
```
and then configure your webserver to use this fcgi interface.
The new, hot stuff about django deployment seems to be **gunicorn**. It's a webserver that implements wsgi and is typically used as backend with a "big" webserver as proxy.
Deployment with **gunicorn** feels a lot like fcgi: you run a process doing the django processing stuff with manage.py, and a webserver as frontend to the world.
But gunicorn deployment has some advantages over fcgi:
* speed - I didn't find the sources, but benchmarks say fcgi is not as fast as the f suggests
* config files, for fcgi you must do all configuration on the commandline when executing the manage.py command. This comes unhandy when running multiple django instances via an init.d (unix-like OS' system service startup). It's always the same cmdline, with just different configuration files
* gunicorn can drop privileges: no need to do this in your init.d script, and it's easy to switch to one user per django instance
* gunicorn behaves more like a daemon: writing pidfile and logfile, forking to the background etc. makes again using it in an init.d script easier.
Thus, I would suggest to use the gunicorn solution, unless you have a single site on a single server with low traffic, than you could use the wsgi solution. But I think in the long run you're more happy with gunicorn.
If you have a django only webserver, I would suggest to use nginx as frontendproxy, as it's the best performing (again this is based on benchmarks I read in some blogposts - don't have the url anymore).
Personally I use apache as frontendproxy, as I need it for other sites hosted on the server.
A simple setup instruction for django deployment could be found here:
<http://ericholscher.com/blog/2010/aug/16/lessons-learned-dash-easy-django-deployment/>
My init.d script for gunicorn is located at github:
<https://gist.github.com/753053>
Unfortunately I did not yet blog about it, but an experienced sysadmin should be able to do the required setup. | I myself have faced a lot of problems in deploying Django Projects and automating the deployment process. Apache and mod\_wsgi were like curse for Django Deployment. There are several tools like [Nginx](http://wiki.nginx.org/Main), [Gunicorn](http://gunicorn.org/), [SupervisorD](http://supervisord.org/) and Fabric which are trending for Django deployment. At first I used/configured them individually without Deployment automation which took a lot of time(I had to maintain testing as well as production servers for my client and had to update them as soon as a new feature was tested and approved.) but then I stumbled upon django-fagungis, which totally automates my Django Deployment from cloning my project from bitbucket to deploying on my remote server (it uses Nginx, Gunicorn, SupervisorD, Fabtic and virtualenv and also installs all the dependencies on the fly), all with just three commands :) You can find more about it in my blog post [**here**](http://alirazabhayani.blogspot.com/2013/02/easy-django-deployment-tools-tutorial-fabric-gunicorn-nginx-supervisor.html). Now I even don't have to get involved in this process(which used to take a lot of my time) and one of my junior developers runs those three commands of django-fagungis [mentioned here](http://alirazabhayani.blogspot.com/2013/02/easy-django-deployment-tools-tutorial-fabric-gunicorn-nginx-supervisor.html) on his local machine and we get a crisp new copy of our project deployed in minutes without any hassle:) |
Question: I have this source of a single file that is successfully compiled in C:
```
#include <stdio.h>
int a;
unsigned char b = 'A';
extern int alpha;
int main() {
extern unsigned char b;
double a = 3.4;
{
extern a;
printf("%d %d\n", b, a+1);
}
return 0;
}
```
After running it, the output is
>
> 65 1
>
>
>
Could anybody please tell me why the extern a statement will capture the global value instead of the **double** local one and why the **printf** statement print the global value instead of the local one?
Also, I have noticed that if I change the statement on line 3 from
```
int a;
```
to
```
int a2;
```
I will get an error from the **extern a;** statement. Why does not a just use the assignment **double a=3.4;** ? It's not like it is bound to be int.
Answer: | The problem is here:
```
System.out.println("Average of column 1:" + (myTable [0][0] + myTable [0][1] + myTable [0][2] + myTable [0][3] + myTable [0][4]) / 4 );
```
You're accessing to `myTable[0][4]`, when `myTable` is defined as `int[5][4]`. Fix this and your code will work.
```
System.out.println("Average of column 1:" + (myTable [0][0] + myTable [0][1] + myTable [0][2] + myTable [0][3]) / 4 );
```
---
A biggest problem here is your design. You should use a `for` loop to set the values in your `myTable` instead of using 20 variables (!). Here's an example:
```
int[][] myTable = new int[5][4];
for (int i = 0; i < myTable.length; i++) {
for (int j = 0; j < myTable[i].length; j++) {
System.out.println("Type a number:");
myTable[i][j] = Integer.parseInt(mVHS.readLine());
}
}
``` | Essentially, `myTable` is defined for values up to `[4][3]` which is fine, but in your output statements, you get the mixed, as if they went up to `[3][4]`. You need 5 not 4 lines and you need to remove `+ myTable [?][4]` in each of them. |
Question: I am currently investigating the specific square number $a^n+1$ and whether it can become a square. I know that $a^n+1$ cannot be a square if n is even because then I can write n=2x, and so $(a^n)^2$+1 is always smaller than $(a^n+1)^2$.
But what about odd powers of n? Can they allow $a^n+1$ to become a square? Or a more general case, can $a^n+1$ ever be a square number?
Answer: | To answer the question in the title:
The next square after $n^2$ is $(n+1)^2=n^2+2n+1 > n^2+1$ if $n>0$.
Therefore, $n^2+1$ is never a square, unless $n=0$. | Can $a^n+1$ ever be a square? PARTIAL ANSWER
If $a^n+1=m^2$ then $a^n=(m^2-1)=(m+1)(m-1)$. If $a$ is odd, then both $(m+1)$ and $(m-1)$ are odd, and moreover, two sequential odd numbers have no factors in common. Thus $(m+1)=r^n$ and $(m-1)=s^n$, $\gcd{r,s}=1$, because the product of $(m+1)$ and $(m-1)$ must be an $n^{th}$ power. $r^n-s^n=2$ has no integer solutions for $n>1$, so $a^n+1\neq m^2$ if $a$ is odd. |
Question: The MySQL Stored Procedure was:
```
BEGIN
set @sql=_sql;
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
set _ires=LAST_INSERT_ID();
END$$
```
I tried to convert it to:
```
BEGIN
EXECUTE _sql;
SELECT INTO _ires CURRVAL('table_seq');
RETURN;
END;
```
I get the error:
```
SQL error:
ERROR: relation "table_seq" does not exist
LINE 1: SELECT CURRVAL('table_seq')
^
QUERY: SELECT CURRVAL('table_seq')
CONTEXT: PL/pgSQL function "myexecins" line 4 at SQL statement
In statement:
SELECT myexecins('SELECT * FROM tblbilldate WHERE billid = 2')
```
The query used is for testing purposes only. I believe this function is used to get the row id of the inserted or created row from the query. Any Suggestions?
Answer: | You can add an option 'expression' to the configuration. Normally it gets a "$user" as argument. So you can do something like:
```
array('allow',
'actions'=>array('index','update', 'create', 'delete'),
'expression'=> '$user->isAdmin',
),
```
Note that I haven't tested this but I think it will work.
Take a look [here](http://www.yiiframework.com/doc/api/1.1/CAccessControlFilter) for the rest. | Well it won't work because it knows Yii::app()->user as a CWebUser Instance and you developed the UserIdentity class so it would say 'CWebUser and its behaviors do not have a method or closure named "isAdmin"'! To use expressions like $user->isAdmin your should set isAdmin property throw the setState command which would use session to save that usually in authentication method so it would be something like this:
```
class UserIdentity extends CUserIdentity
{
public function authenticate()
{
//your authentication code
//using your functions like $level=$this->isTeacher();
//or $level=$this->isAdmin();
$this->setState('isAdmin',$level);
}
}
```
and now in the user controller in accessRules method you can have expressions
```
public function accessRules()
{
return array(
array('allow',
'actions'=>array('action1','action2',...),
'expression'=>'$user->isAdmin',
//or Yii::app()->user->getState('isAdmin'),
),
//...
);
}
``` |
Question: This should be straight foreward, but I simply can't figure it out(!)
I have a UIView 'filled with' a UIScrollView. Inside the scrollView I wan't to have a UITableView.
I have hooked up both the scrollView and the tableView with IBOutlet's in IB and set the ViewController to be the delegate and datasource of the tableView.
What else do I need to do ? Or what shouldn't I have done?
Answer: | Personally, I would define the key-states as disjoint states and write a simple state-machine, thus:
```
enum keystate
{
inactive,
firstPress,
active
};
keystate keystates[256];
Class::CalculateKeyStates()
{
for (int i = 0; i < 256; ++i)
{
keystate &k = keystates[i];
switch (k)
{
inactive:
k = (isDown(i)) ? firstPress : inactive;
break;
firstPress:
k = (isDown(i)) ? active : inactive;
break;
active:
k = (isDown(i)) ? active : inactive;
break;
}
}
}
```
This is easier to extend, and easier to read if it gets any more complex. | You are always setting `IsFirstPress` if the key is down, which might not be what you want. |
Question: This should be straight foreward, but I simply can't figure it out(!)
I have a UIView 'filled with' a UIScrollView. Inside the scrollView I wan't to have a UITableView.
I have hooked up both the scrollView and the tableView with IBOutlet's in IB and set the ViewController to be the delegate and datasource of the tableView.
What else do I need to do ? Or what shouldn't I have done?
Answer: | Personally, I would define the key-states as disjoint states and write a simple state-machine, thus:
```
enum keystate
{
inactive,
firstPress,
active
};
keystate keystates[256];
Class::CalculateKeyStates()
{
for (int i = 0; i < 256; ++i)
{
keystate &k = keystates[i];
switch (k)
{
inactive:
k = (isDown(i)) ? firstPress : inactive;
break;
firstPress:
k = (isDown(i)) ? active : inactive;
break;
active:
k = (isDown(i)) ? active : inactive;
break;
}
}
}
```
This is easier to extend, and easier to read if it gets any more complex. | I'm not sure what you want to achieve with `IsFirstPress`, as the keystate cannot remember any previous presses anyways. If you want to mark with this bit, that it's the first time you recognized the key being down, then your logic is wrong in the corresponding `if` statement.
`keystates[i] & WasHeldDown` evaluates to true if you already set the bit `WasHeldDown` earlier for this keystate.
In that case, what you may want to do is actually remove the `IsFirstPress` bit by xor-ing it: `keystates[i] ^= IsFirstPress` |
Question: AFAIK GHC is the most common compiler today, but I also see, that some other ompilers are available too. Is GHC really the best choice for all purposes or may I use something else instead? For instance, I read that some compiler (forgot the name) does better on optimizations, but doesn't implements all extensions.
Answer: | GHC is by far the most widely used Haskell compiler, and it offers the most features. There are other options, though, which sometimes have some benefits over GHC. These are some of the more popular alternatives:
[Hugs](http://www.haskell.org/hugs/) - Hugs is an interpreter (I don't think it includes a compiler) which is fast and efficient. It's also known for producing more easily understood error messages than GHC.
[JHC](http://repetae.net/computer/jhc/) - A whole-program compiler. JHC can produce very efficient code, but it's not feature-complete yet (this is probably what you're thinking of). Note that it's not always faster than GHC, only sometimes. I haven't used JHC much because it doesn't implement multi-parameter type classes, which I use heavily. I've heard that the source code is extremely clear and readable, making this a good compiler to hack on. JHC is also more convenient for cross-compiling and usually produces smaller binaries.
[UHC](http://www.cs.uu.nl/wiki/UHC) - The Utrecht Haskell Compiler is near feature-complete (I think the only thing missing is n+k patterns) for Haskell98. It implements many of GHC's most popular extensions and some original extensions as well. According to the documentation code isn't necessarily well-optimized yet. This is also a good compiler to hack on.
In short, if you want efficient code and cutting-edge features, GHC is your best bet. JHC is worth trying if you don't need MPTC's or some other features. UHC's extensions may be compelling in some cases, but I wouldn't count on it for fast code yet. | ghc is a solid compiler. saying it is the best choice for all purposes is a very strong one. and looking for such a tool is futile.
Use it, and if you really require something else then by that point you'll probably know what it is. |
Question: AFAIK GHC is the most common compiler today, but I also see, that some other ompilers are available too. Is GHC really the best choice for all purposes or may I use something else instead? For instance, I read that some compiler (forgot the name) does better on optimizations, but doesn't implements all extensions.
Answer: | GHC is by far the most widely used Haskell compiler, and it offers the most features. There are other options, though, which sometimes have some benefits over GHC. These are some of the more popular alternatives:
[Hugs](http://www.haskell.org/hugs/) - Hugs is an interpreter (I don't think it includes a compiler) which is fast and efficient. It's also known for producing more easily understood error messages than GHC.
[JHC](http://repetae.net/computer/jhc/) - A whole-program compiler. JHC can produce very efficient code, but it's not feature-complete yet (this is probably what you're thinking of). Note that it's not always faster than GHC, only sometimes. I haven't used JHC much because it doesn't implement multi-parameter type classes, which I use heavily. I've heard that the source code is extremely clear and readable, making this a good compiler to hack on. JHC is also more convenient for cross-compiling and usually produces smaller binaries.
[UHC](http://www.cs.uu.nl/wiki/UHC) - The Utrecht Haskell Compiler is near feature-complete (I think the only thing missing is n+k patterns) for Haskell98. It implements many of GHC's most popular extensions and some original extensions as well. According to the documentation code isn't necessarily well-optimized yet. This is also a good compiler to hack on.
In short, if you want efficient code and cutting-edge features, GHC is your best bet. JHC is worth trying if you don't need MPTC's or some other features. UHC's extensions may be compelling in some cases, but I wouldn't count on it for fast code yet. | I think it's also worth mentioning [nhc98](http://www.haskell.org/nhc98/). From the blurb on the homepage:
>
> nhc98 is a small, easy to install,
> standards-compliant compiler for
> Haskell 98, the lazy functional
> programming language. It is very
> portable, and aims to produce small
> executables that run in small amounts
> of memory. It produces medium-fast
> code, and compilation is itself quite
> fast. It also comes with extensive
> tool support for automatic
> compilation, foreign language
> interfacing, heap and time profiling,
> tracing, and debugging.
>
>
> |
Question: AFAIK GHC is the most common compiler today, but I also see, that some other ompilers are available too. Is GHC really the best choice for all purposes or may I use something else instead? For instance, I read that some compiler (forgot the name) does better on optimizations, but doesn't implements all extensions.
Answer: | GHC is by far the most widely used Haskell compiler, and it offers the most features. There are other options, though, which sometimes have some benefits over GHC. These are some of the more popular alternatives:
[Hugs](http://www.haskell.org/hugs/) - Hugs is an interpreter (I don't think it includes a compiler) which is fast and efficient. It's also known for producing more easily understood error messages than GHC.
[JHC](http://repetae.net/computer/jhc/) - A whole-program compiler. JHC can produce very efficient code, but it's not feature-complete yet (this is probably what you're thinking of). Note that it's not always faster than GHC, only sometimes. I haven't used JHC much because it doesn't implement multi-parameter type classes, which I use heavily. I've heard that the source code is extremely clear and readable, making this a good compiler to hack on. JHC is also more convenient for cross-compiling and usually produces smaller binaries.
[UHC](http://www.cs.uu.nl/wiki/UHC) - The Utrecht Haskell Compiler is near feature-complete (I think the only thing missing is n+k patterns) for Haskell98. It implements many of GHC's most popular extensions and some original extensions as well. According to the documentation code isn't necessarily well-optimized yet. This is also a good compiler to hack on.
In short, if you want efficient code and cutting-edge features, GHC is your best bet. JHC is worth trying if you don't need MPTC's or some other features. UHC's extensions may be compelling in some cases, but I wouldn't count on it for fast code yet. | 1. Haskell is informally defined as the language handled by GHC.
2. GHC is the compiler of the *Haskell platform*.
3. Trying to optimize your code with GHC may pay off more than switching to another compiler as you'll learn some optimization skills.
4. There are many *very* useful extensions in GHC. I just can't see how to live without them.
So, for anything serious (e.g. non-academic, non-experimental, non-volatile or using many packages), the pragmatic choice is to go with GHC. |
Question: AFAIK GHC is the most common compiler today, but I also see, that some other ompilers are available too. Is GHC really the best choice for all purposes or may I use something else instead? For instance, I read that some compiler (forgot the name) does better on optimizations, but doesn't implements all extensions.
Answer: | GHC is by far the most widely used Haskell compiler, and it offers the most features. There are other options, though, which sometimes have some benefits over GHC. These are some of the more popular alternatives:
[Hugs](http://www.haskell.org/hugs/) - Hugs is an interpreter (I don't think it includes a compiler) which is fast and efficient. It's also known for producing more easily understood error messages than GHC.
[JHC](http://repetae.net/computer/jhc/) - A whole-program compiler. JHC can produce very efficient code, but it's not feature-complete yet (this is probably what you're thinking of). Note that it's not always faster than GHC, only sometimes. I haven't used JHC much because it doesn't implement multi-parameter type classes, which I use heavily. I've heard that the source code is extremely clear and readable, making this a good compiler to hack on. JHC is also more convenient for cross-compiling and usually produces smaller binaries.
[UHC](http://www.cs.uu.nl/wiki/UHC) - The Utrecht Haskell Compiler is near feature-complete (I think the only thing missing is n+k patterns) for Haskell98. It implements many of GHC's most popular extensions and some original extensions as well. According to the documentation code isn't necessarily well-optimized yet. This is also a good compiler to hack on.
In short, if you want efficient code and cutting-edge features, GHC is your best bet. JHC is worth trying if you don't need MPTC's or some other features. UHC's extensions may be compelling in some cases, but I wouldn't count on it for fast code yet. | As of 2011, there's really no other choice than GHC for everyday programming. The HP team strongly encourages the use of GHC by all Haskell programmers.
---
If you're a researcher, you might use be using UHC, if you're on a very strange system, you might have only Hugs or nhc98 available. If you're a retro-fan like me, you still have gofer, hbc and hbi installed:
```
$ hbi
Welcome to interactive Haskell98 version 0.9999.5c Pentium 2004 Jun 29!
Loading prelude... 1 values, 4 libraries, 200 types found.
Type "help;" to get help.
> help;
HBI -- Interactive Haskell B 1.3
```
hbi is cool because a) it implements Haskell B, and b) it supports the full language at the command line:
```
> data L a = I | X a (L a) deriving Show;
data L b = I | X b (L b) deriving (Show)
> X 4 (X 3 I);
X 4 (X 3 I)
```
and the compiler produces pretty good code, even 15 years later. |
Question: I have a chunk of text I need to paste into Illustrator. No matter what I do, I can't resize the text area without scaling the text. I want to resize the area and have the text wrap (font size to remain the same).
How can I do this? I'm using CS5.1
Answer: | Select your `Type` tool. Instead of clicking on your canvas, click and drag to draw a box. Put whatever copy you want inside the type box and when you resize the box it will reflow the text instead of changing the font.
You can also link multiple type boxes together to flow text across multiple points on your artboard. Create type objects wherever you want text to be. Add all your copy to the first box. Assuming it overflows, there will be a ![+](https://i.stack.imgur.com/FpE3v.png) symbol in the bottom-right corner of the type box. Click this ![+](https://i.stack.imgur.com/FpE3v.png) symbol and then click the next type box where you want text to flow. Illustrator will flow text through as many type boxes as you link together. | Here's a great article, **["Make Illustrator behave!"](http://www.creativepro.com/article/make-illustrator-behave-)** that explains it all in in full.
Figuring out under what circumstances Illustrator scales the many types of text object and when it scales the bounding box, wrapping the text, is a common frustration.
The differences between the different types of text object in Illustrator are brilliant once you've mastered and made sense of them, but massively frustrating until you do so...
I really recommend taking some time out to go through that article in full. |
Question: I have a chunk of text I need to paste into Illustrator. No matter what I do, I can't resize the text area without scaling the text. I want to resize the area and have the text wrap (font size to remain the same).
How can I do this? I'm using CS5.1
Answer: | Select your `Type` tool. Instead of clicking on your canvas, click and drag to draw a box. Put whatever copy you want inside the type box and when you resize the box it will reflow the text instead of changing the font.
You can also link multiple type boxes together to flow text across multiple points on your artboard. Create type objects wherever you want text to be. Add all your copy to the first box. Assuming it overflows, there will be a ![+](https://i.stack.imgur.com/FpE3v.png) symbol in the bottom-right corner of the type box. Click this ![+](https://i.stack.imgur.com/FpE3v.png) symbol and then click the next type box where you want text to flow. Illustrator will flow text through as many type boxes as you link together. | OK, here goes.
If you have already type some text using the type tool and selected this text using `Selection Tool`(the black arrow), you will see something like this
![enter image description here](https://i.stack.imgur.com/TM0x3.png)
have you notice the rightmost circle?
![enter image description here](https://i.stack.imgur.com/3l66t.png)
just move the cursor on to this circle, double click it, and you'll see this
![enter image description here](https://i.stack.imgur.com/cj6Pk.png)
OK, now you can adjust the border of this text box without shrinking the characters, but it takes two steps, first
![enter image description here](https://i.stack.imgur.com/WBx1T.png)
to notice there is a ![enter image description here](https://i.stack.imgur.com/j5nxs.png) which means there are some text hidden. Then, second step increase the height of the box, the word "here" automatically wrapped to the second line.
![enter image description here](https://i.stack.imgur.com/y3Edr.png) |
Question: I have a chunk of text I need to paste into Illustrator. No matter what I do, I can't resize the text area without scaling the text. I want to resize the area and have the text wrap (font size to remain the same).
How can I do this? I'm using CS5.1
Answer: | OK, here goes.
If you have already type some text using the type tool and selected this text using `Selection Tool`(the black arrow), you will see something like this
![enter image description here](https://i.stack.imgur.com/TM0x3.png)
have you notice the rightmost circle?
![enter image description here](https://i.stack.imgur.com/3l66t.png)
just move the cursor on to this circle, double click it, and you'll see this
![enter image description here](https://i.stack.imgur.com/cj6Pk.png)
OK, now you can adjust the border of this text box without shrinking the characters, but it takes two steps, first
![enter image description here](https://i.stack.imgur.com/WBx1T.png)
to notice there is a ![enter image description here](https://i.stack.imgur.com/j5nxs.png) which means there are some text hidden. Then, second step increase the height of the box, the word "here" automatically wrapped to the second line.
![enter image description here](https://i.stack.imgur.com/y3Edr.png) | Here's a great article, **["Make Illustrator behave!"](http://www.creativepro.com/article/make-illustrator-behave-)** that explains it all in in full.
Figuring out under what circumstances Illustrator scales the many types of text object and when it scales the bounding box, wrapping the text, is a common frustration.
The differences between the different types of text object in Illustrator are brilliant once you've mastered and made sense of them, but massively frustrating until you do so...
I really recommend taking some time out to go through that article in full. |
Question: I have a question about if a animation ends that it will like `gotoAndStop()` to another frame
```
if (bird.hitTestObject(pipe1)) {
bird.gotoAndStop(3); //frame 3 = animation
}
```
after it ends it will need to go the Game Over frame (frame 3) and I use the `Flash Timeline` not `.as` thanks!
Answer: | Java does not provide a convenient way to list the "files" in a "directory", when that directory is backed by a JAR file on the classpath (see [How do I list the files inside a JAR file?](https://stackoverflow.com/questions/1429172/how-do-i-list-the-files-inside-a-jar-file) for some work-arounds). I believe this is because the general case where a "directory" exists in multiple .jar files and classpath directories is really complicated (the system would have to present a union of entries across multiple sources and deal with overlaps).
Because Java/Android do not have clean support this, neither does Libgdx (searching the classpath is what "internal" Libgdx files map to).
I think the easiest way to work-around this is to build a list of levels into a text file, then open that and use it as a list of file names. So, something like:
```
// XXX More pseudo code in Java than actual code ... (this is untested)
fileList = Gdx.files.internal("levels.txt");
String files[] = fileList.readString().split("\\n");
for (String filename: files) {
FileHandle fh = Gdx.files.internal("levels/" + filename);
...
}
```
Ideally you'd set something up that builds this text file when the JAR file is built. (That's a separate SO question I don't know the answer to ...)
As an aside, your work-around that uses `ApplicationType.Desktop` is leveraging the fact that in addition to the .jar file, there is a real directory on the classpath that you can open. That directory doesn't exist on the Android device (it actually only exists on the desktop when running under your build environment). | If you are still looking for an actual answer here is [mine](https://pastebin.com/R0jMh4ui) (it is kinda hacky but its work).
To use it you simply have to call one of the 2 options below :
```
FileHandle[] fileList = JarUtils.listFromJarIfNecessary("Path/to/your/folder");
FileHandle[] fileList = JarUtils.listFromJarIfNecessary(yourJarFileFilter);
```
A JarFileFilter is a simple class that overload the Java default FileFilter to fits the jar filter needs.
This will work both: when running from the IDE and from within a jar file. It also check that the game is running on desktop otherwise it use the default libGDX way of loadding the resources so it is safe to use for cross-platform project (Android, Ios, etc.).
Feel free to update the code if necessary to fit your needs. The code is documented and is ~150 lines so hopefully you will understand it.
Warning: Beware that this might not be very efficient since it has to look for all the entries within your jar so you do not want to call it too often. |
Question: I have a question about if a animation ends that it will like `gotoAndStop()` to another frame
```
if (bird.hitTestObject(pipe1)) {
bird.gotoAndStop(3); //frame 3 = animation
}
```
after it ends it will need to go the Game Over frame (frame 3) and I use the `Flash Timeline` not `.as` thanks!
Answer: | Java does not provide a convenient way to list the "files" in a "directory", when that directory is backed by a JAR file on the classpath (see [How do I list the files inside a JAR file?](https://stackoverflow.com/questions/1429172/how-do-i-list-the-files-inside-a-jar-file) for some work-arounds). I believe this is because the general case where a "directory" exists in multiple .jar files and classpath directories is really complicated (the system would have to present a union of entries across multiple sources and deal with overlaps).
Because Java/Android do not have clean support this, neither does Libgdx (searching the classpath is what "internal" Libgdx files map to).
I think the easiest way to work-around this is to build a list of levels into a text file, then open that and use it as a list of file names. So, something like:
```
// XXX More pseudo code in Java than actual code ... (this is untested)
fileList = Gdx.files.internal("levels.txt");
String files[] = fileList.readString().split("\\n");
for (String filename: files) {
FileHandle fh = Gdx.files.internal("levels/" + filename);
...
}
```
Ideally you'd set something up that builds this text file when the JAR file is built. (That's a separate SO question I don't know the answer to ...)
As an aside, your work-around that uses `ApplicationType.Desktop` is leveraging the fact that in addition to the .jar file, there is a real directory on the classpath that you can open. That directory doesn't exist on the Android device (it actually only exists on the desktop when running under your build environment). | What i do sometimes is to loop the "sounds" folder with a prefixed filename and a numbered suffix like this:
```
for(String snd_name : new String[]{"flesh_", "sword_", "shield_", "death_", "skating_", "fall_", "block_"}) {
int idx = 0;
FileHandle fh;
while((fh = Gdx.files.internal("snd/" + (snd_name + idx++) + ".ogg")).exists()) {
String name = fh.nameWithoutExtension();
Sound s = Gdx.audio.newSound(fh);
if(name.startsWith("flesh")) {
sounds_flesh.addLast(s);
}
else if(name.startsWith("sword")) {
sounds_sword.addLast(s);
}
else if(name.startsWith("shield")) {
sounds_shield.addLast(s);
}
else if(name.startsWith("death")) {
sounds_death.addLast(s);
}
else if(name.startsWith("skating")) {
sounds_skating.addLast(s);
}
else if(name.startsWith("fall")) {
sounds_fall.addLast(s);
}
else if(name.startsWith("block")) {
sounds_block.addLast(s);
}
}
}
``` |
Question: I have a question about if a animation ends that it will like `gotoAndStop()` to another frame
```
if (bird.hitTestObject(pipe1)) {
bird.gotoAndStop(3); //frame 3 = animation
}
```
after it ends it will need to go the Game Over frame (frame 3) and I use the `Flash Timeline` not `.as` thanks!
Answer: | If you are still looking for an actual answer here is [mine](https://pastebin.com/R0jMh4ui) (it is kinda hacky but its work).
To use it you simply have to call one of the 2 options below :
```
FileHandle[] fileList = JarUtils.listFromJarIfNecessary("Path/to/your/folder");
FileHandle[] fileList = JarUtils.listFromJarIfNecessary(yourJarFileFilter);
```
A JarFileFilter is a simple class that overload the Java default FileFilter to fits the jar filter needs.
This will work both: when running from the IDE and from within a jar file. It also check that the game is running on desktop otherwise it use the default libGDX way of loadding the resources so it is safe to use for cross-platform project (Android, Ios, etc.).
Feel free to update the code if necessary to fit your needs. The code is documented and is ~150 lines so hopefully you will understand it.
Warning: Beware that this might not be very efficient since it has to look for all the entries within your jar so you do not want to call it too often. | What i do sometimes is to loop the "sounds" folder with a prefixed filename and a numbered suffix like this:
```
for(String snd_name : new String[]{"flesh_", "sword_", "shield_", "death_", "skating_", "fall_", "block_"}) {
int idx = 0;
FileHandle fh;
while((fh = Gdx.files.internal("snd/" + (snd_name + idx++) + ".ogg")).exists()) {
String name = fh.nameWithoutExtension();
Sound s = Gdx.audio.newSound(fh);
if(name.startsWith("flesh")) {
sounds_flesh.addLast(s);
}
else if(name.startsWith("sword")) {
sounds_sword.addLast(s);
}
else if(name.startsWith("shield")) {
sounds_shield.addLast(s);
}
else if(name.startsWith("death")) {
sounds_death.addLast(s);
}
else if(name.startsWith("skating")) {
sounds_skating.addLast(s);
}
else if(name.startsWith("fall")) {
sounds_fall.addLast(s);
}
else if(name.startsWith("block")) {
sounds_block.addLast(s);
}
}
}
``` |
Question: I am using jQuery mobile 1.4.2. I need to shift the search icon from left to right and how can I avoid the clear button appearing.
```
<div data-role=page">
<form method="post">
<input name="search" id="search" value="" placeholder="Buscar" type="search" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Buscar'">
</form>
</div>
```
Answer: | The constructor is `new Rect(left,top,width,height)`
Any fewer arguments will result in those many fields not being set. eg. `new Rect(1,2,3)` will return a Rect object with no height
Screenshot here : <http://puu.sh/81KSa/e225064bec.png> | The `Rect` in your jsfiddle is **NOT** the Mozilla `Rect` object.
[What is Rect function in Chrome/Firefox for?](https://stackoverflow.com/questions/18814683/what-is-rect-function-for-in-javascript)
The Mozilla `Rect` is provided by <https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Geometry.jsm>
You can only use it in a Firefox extension after `Components.utils.import("resource://gre/modules/Geometry.jsm", your_scope_obj);`
I don't think you can test it in jsfiddle env. |
Question: I have some code which captures a key.
Now i have in event.code the real key-name and in event.key i get the key-char.
To make an example: I press SHIFT and J, so i get:
*event.code: SHIFT KEYJ*
*event.key: J*
So, i get in event.key the "interpreted key" from shift J. But now i need to convert the native key to a char. So i am looking for a solution to get from "KEYJ" to a char, that means "j". How can this be done? I have not found anything about this.
Answer: | Solution was the H2 version.
We upgraded also H2 to 2.0 but that version is not compatible with Spring Batch 4.3.4.
Downgrade to H2 version 1.4.200 solved the issue. | `MODE=LEGACY` will solve the issue on H2 2.x with Spring boot 2.6.x.
(`nextval` support will be re-enabled)
See the details: <https://github.com/spring-projects/spring-boot/issues/29034#issuecomment-1002641782> |
Question: I want to run a .exe file (or) any application from pen drive on insert in to pc. I dont want to use Autorun.inf file, as all anti virus software's blocks it. I have used portable application launcher also, that also using autorun only. so once again anti virus software blocks it. Is there any alternative option, such that .exe file from pen drive should start automatically on pen drive insert?
Answer: | Anti-virus programs block autorun.inf on the solely purpose not to allow some .exe-s to start automatically on pen drive insert. So, basically, what you're asking is impossible. | I havent used Windows in a long time, but I am fairly sure there is a setting in Windows to enable/disable autorunning executeables on mounted drives. That and changing such setting in your antivirus application (or get a new, saner one) would be my best guess.
Good luck! |
Question: Here is what I have so far:
Let $\varepsilon > 0$ be given
We want for all $n >N$, $|1/n! - 0|< \varepsilon$
We know $1/n <ε$ and $1/n! ≤ 1/n < ε$.
I don't know how to solve for $n$, given $1/n!$. And this is where I get stuck in my proof, I cannot solve for $n$, and therefore cannot pick $N > \cdots$.
Answer: | Since $0 < \frac{1}{n!} < \frac{1}{n}$, by the squeeze theorem...
Without squeeze theorem: Let $\epsilon > 0$. Define $N = \epsilon^{-1}$. Then if $n > N$, $$\left|\frac{1}{n!}\right| = \frac{1}{n!} < \frac{1}{n} < \frac{1}{N} = \epsilon$$ | You don't need to *solve for* $n$, just to find *some* $n$ that is large enough that $1/n!$ is smaller than $\varepsilon$. It doesn't matter if you find an $N$ that is much larger than it *needs to be*, as long as it is finite.
By the hint that $1/n! \le 1/n$, therefore, it is enough to find an $N$ that is large enough that $1/n < \varepsilon$. And this is clearly the case if only $n > 1/\varepsilon$ ... |
Question: Here is what I have so far:
Let $\varepsilon > 0$ be given
We want for all $n >N$, $|1/n! - 0|< \varepsilon$
We know $1/n <ε$ and $1/n! ≤ 1/n < ε$.
I don't know how to solve for $n$, given $1/n!$. And this is where I get stuck in my proof, I cannot solve for $n$, and therefore cannot pick $N > \cdots$.
Answer: | Since $0 < \frac{1}{n!} < \frac{1}{n}$, by the squeeze theorem...
Without squeeze theorem: Let $\epsilon > 0$. Define $N = \epsilon^{-1}$. Then if $n > N$, $$\left|\frac{1}{n!}\right| = \frac{1}{n!} < \frac{1}{n} < \frac{1}{N} = \epsilon$$ | How about this one: $$\sum\_{n=0}^{\infty}\frac{1}{n!}=e^1=e.$$ Thus the series converges and therefore $$\lim\_{n\to \infty}\frac{1}{n!}=0.$$ |
Question: I got my first android phone since two week
And I'm starting my first real App.
My phone is a LG Optimus 2X and one of the missing thing is a
notification led for when there is a missed call, sms, email ect ...
So I'm wondering what's the best way to do this.
For know I've a broatcastreceiver for incoming sms, and the I call a
service that will light the phone buttons (don't bother about this
part, it's working).
But seems that this method will workin only for sms, phone calls, not
emails.
So know I'm thinking to used Listeners instead for everything, but
this mean having a service running nonstop. Not sure it's the best
way ...
I hope I'm clear, and that my ennglish is not too bad.
Thx in advance
Answer: | ```
UIBarButtonItem *addButton =
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(myCallback:)];
self.navigationItem.rightBarButtonItem = addButton;
[addButton release];
``` | Yes, that `[+]` button is a default button, provided by Apple. It is the `UIBarButtonSystemItemAdd` identifier.
Here's some code to get it working:
```
// Create the Add button
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(someMethod)];
// Display it
self.navigationItem.rightBarButtonItem = addButton;
// Release the button
[addButton release];
```
You will need to define `someMethod`, so your program has code to run when the button is tapped. |
Question: Recently, I read a lot of good articles about how to do good encapsulation. And when I say "good encapsulation", I am not talking about hiding private fields with public properties; I am talking about preventing users of your API from doing wrong things.
Here are two good articles about this subject:
<http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx>
<http://lostechies.com/derickbailey/2011/03/28/encapsulation-youre-doing-it-wrong/>
At my job, the majority of our applications are not destined for other programmers but rather for the customers.
About 80% of the application code is at the top of the structure (Not used by other code). For this reason, there is probably no chance ever that this code will be used by other application.
An example of encapsulation that prevents users from doing wrong things with your API is returning an IEnumerable instead of IList when you don't want to give the ability to the user to add or remove items in the list.
My question is: When can encapsulation be considered simply OOP purism, keeping in mind that each hour of programming is charged to the customer?
I want to create code that is maintainable and easy to read and use, but when I am not building a public API (to be used by other programmers), where can we draw the line between perfect code and not so perfect code?
Answer: | Answer: When you have your interface complete, then automatically you are done with encapsulation. It does not matter if implemenation or consumption part is incomplete, you are done since interface is accepted as final.
**Proper development tools should reduce cost more than tools cost themself.**
You suggest that if encapsulation or whatever property is not relevant to market offer, if customer does not care then the property has no value. Correct. And customer cares nearly about no internal property of code.
So why this and other measurable properties of code exist ? Why deveoper should care ? I think the reason is money as well: any labor intensive and costly work in software development will call for a cure. Encapsulation is targeted not at the customer but at user of library. You saying you do not have external users, but for your own code you yourself are the user number 1.
* If you introduce risk of errors into daily use, then you **increase the cost of development**.
* If you spend on reducing the risk, you will **increase the cost of development**.
Market and evolution keep forcing this choice. Choose the least increase.
This is all understood well. But you are asking about this particular feature. It is not the hardest one to maintain. It is definitely cost effective. But be aware about laws of human nature and economy. Tools have their own market. The labeled cost for some can be $0, but there is always hidden cost in terms of time spent on adoption. And this market is flooded with methodologies and practices with negative value. | Encapsulation exists to protect your class invariants. This is the primary measure for 'how much is enough'. Any way to break invariants breaks class semantics and is bad (tm).
A secondary concern is limiting visibility and as such the number of places that can/will access data and thus increase coupling and/or number of dependencies. This needs to be done with care though. As requirements change, often times that decision to limit what the class exposes leads to awkward hacks to deal with the new requirement.
This though is one of those design concerns that comes with experience. In doubt, favor encapsulation. The concerns are regardless of 'public' API or not. Even for internal code, new or forgetful or sleepy programmers *will* write bad code. If your class needs to be resistant to bad code, then do so. |
Question: Recently, I read a lot of good articles about how to do good encapsulation. And when I say "good encapsulation", I am not talking about hiding private fields with public properties; I am talking about preventing users of your API from doing wrong things.
Here are two good articles about this subject:
<http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx>
<http://lostechies.com/derickbailey/2011/03/28/encapsulation-youre-doing-it-wrong/>
At my job, the majority of our applications are not destined for other programmers but rather for the customers.
About 80% of the application code is at the top of the structure (Not used by other code). For this reason, there is probably no chance ever that this code will be used by other application.
An example of encapsulation that prevents users from doing wrong things with your API is returning an IEnumerable instead of IList when you don't want to give the ability to the user to add or remove items in the list.
My question is: When can encapsulation be considered simply OOP purism, keeping in mind that each hour of programming is charged to the customer?
I want to create code that is maintainable and easy to read and use, but when I am not building a public API (to be used by other programmers), where can we draw the line between perfect code and not so perfect code?
Answer: | The fact that your code is not being written as a public API is not really the point--the maintainability you mention is.
Yes, application development is a cost center, and the customer does not want to pay for unnecessary work. However, a badly designed or implemented application is going to cost the customer a lot more money when they decide that it needs another feature, or (as will certainly happen) the business rules change. Good OO principles are there because they help make it safer to modify and append the code base.
So, the customer may not directly care what your code looks like, but the next guy who has to modify it certainly will. If the encapsulation (as you're defining it) is not there, it's going to take him a lot longer and be much riskier for him to do what he needs to do to serve the customer's needs. | Encapsulation exists to protect your class invariants. This is the primary measure for 'how much is enough'. Any way to break invariants breaks class semantics and is bad (tm).
A secondary concern is limiting visibility and as such the number of places that can/will access data and thus increase coupling and/or number of dependencies. This needs to be done with care though. As requirements change, often times that decision to limit what the class exposes leads to awkward hacks to deal with the new requirement.
This though is one of those design concerns that comes with experience. In doubt, favor encapsulation. The concerns are regardless of 'public' API or not. Even for internal code, new or forgetful or sleepy programmers *will* write bad code. If your class needs to be resistant to bad code, then do so. |
Question: I am trying to insert a new column into a CSV file after existing data. For example, my CSV file currently contains:
```
Heading 1 Heading 2
1
1
0
2
1
0
```
I have a list of integers in format:
```
[1,0,1,2,1,2,1,1]
```
**How can i insert this list into the CSV file under 'Header 2'?**
So far all i have been able to achieve is adding the new list of integers underneath the current data, for example:
```
Heading 1 Heading 2
1
1
0
2
1
0
1
0
1
2
1
2
1
1
```
Using the code:
```
#Open CSV file
with open('C:\Data.csv','wb') as g:
#New writer
gw = csv.writer(g)
#Add headings
gw.writerow(["Heading 1","Heading 2"])
#Write First list of data to heading 1 (orgList)
gw.writerows([orgList[item]] for item in column)
#For each value in new integer list, add row to CSV
for val in newList:
gw.writerow([val])
```
Answer: | I guess this question is already kind of old but I came across the same problem.
Its not any "best practice" solution but here is what I do.
In `twig` you can use this `{{ path('yourRouteName') }}` thing in a perfect way. So in my `twig` file I have a structure like that:
```
...
<a href="{{ path('myRoute') }}"> //results in e.g http://localhost/app_dev.php/myRoute
<div id="clickMe">Click</div>
</a>
```
Now if someone clicks the div, I do the following in my `.js file`:
```
$('#clickMe').on('click', function(event) {
event.preventDefault(); //prevents the default a href behaviour
var url = $(this).closest('a').attr('href');
$.ajax({
url: url,
method: 'POST',
success: function(data) {
console.log('GENIUS!');
}
});
});
```
I know that this is not a solution for every situation where you want to trigger an Ajax request but I just leave this here and perhaps somebody thinks it's useful :) | Since this jQuery ajax function is placed on twig side and the url points to your application you can insert routing path
```
$.ajax({
url: '{{ path("your_ajax_routing") }}',
data: "url="+urlinput,
dataType: 'html',
timeout: 5000,
success: function(data, status){
// DO Stuff here
}
});
``` |
Question: I am trying to insert a new column into a CSV file after existing data. For example, my CSV file currently contains:
```
Heading 1 Heading 2
1
1
0
2
1
0
```
I have a list of integers in format:
```
[1,0,1,2,1,2,1,1]
```
**How can i insert this list into the CSV file under 'Header 2'?**
So far all i have been able to achieve is adding the new list of integers underneath the current data, for example:
```
Heading 1 Heading 2
1
1
0
2
1
0
1
0
1
2
1
2
1
1
```
Using the code:
```
#Open CSV file
with open('C:\Data.csv','wb') as g:
#New writer
gw = csv.writer(g)
#Add headings
gw.writerow(["Heading 1","Heading 2"])
#Write First list of data to heading 1 (orgList)
gw.writerows([orgList[item]] for item in column)
#For each value in new integer list, add row to CSV
for val in newList:
gw.writerow([val])
```
Answer: | I ended up using the jsrouting-bundle
Once installed I could simply do the following:
```
$.ajax({
url: Routing.generate('urlgetter'),
data: "url="+urlinput,
dataType: 'html',
timeout: 5000,
success: function(data, status){
// DO Stuff here
}
});
```
where urlgetter is a route defined in routing.yml like:
```
urlgetter:
pattern: /ajax/urlgetter
defaults: { _controller: MyAjaxBundle:SomeController:urlgetter }
options:
expose: true
```
notice the expose: true option has to be set for the route to work with jsrouting-bundle | Since this jQuery ajax function is placed on twig side and the url points to your application you can insert routing path
```
$.ajax({
url: '{{ path("your_ajax_routing") }}',
data: "url="+urlinput,
dataType: 'html',
timeout: 5000,
success: function(data, status){
// DO Stuff here
}
});
``` |
Question: I am attempting to use Tkinter for the first time on my computer, and I am getting the error in the title, "NameError: name 'Tk' is not defined", citing the "line root = Tk()". I have not been able to get Tkinter to work in any form. I am currently on a macbook pro using python 2.7.5. I have tried re-downloading python multiple times but it is still not working.
Anyone have any ideas as to why it isn't working? Any more information needed from me?
Thanks in advance
```
#!/usr/bin/python
from Tkinter import *
root = Tk()
canvas = Canvas(root, width=300, height=200)
canvas.pack()
canvas.create_rectangle( 0, 0, 150, 150, fill="yellow")
canvas.create_rectangle(100, 50, 250, 100, fill="orange", width=5)
canvas.create_rectangle( 50, 100, 150, 200, fill="green", outline="red", width=3)
canvas.create_rectangle(125, 25, 175, 190, fill="purple", width=0)
root.mainloop()
```
Answer: | You have some other module that is taking the name "Tkinter", shadowing the one you actually want. Rename or remove it.
```
import Tkinter
print Tkinter.__file__
``` | your code is right but the indent is wrong in the import code, instead of using one space use two spaces and try to not type this command:
```
import tkinter
```
use this code:
```
from tkinter import *
root = Tk()
canvas = Canvas(root, width=300, height=200)
canvas.pack()
canvas.create_rectangle( 0, 0, 150, 150, fill="yellow")
canvas.create_rectangle(100, 50, 250, 100, fill="orange", width=5)
canvas.create_rectangle( 50, 100, 150, 200, fill="green", outline="red", width=3)
canvas.create_rectangle(125, 25, 175, 190, fill="purple", width=0)
root.mainloop()
```
the problem also could be typing "Tkinter", so type "tkinter" as python in case sensitive, I think this should work, it does for me |
Question: I am attempting to use Tkinter for the first time on my computer, and I am getting the error in the title, "NameError: name 'Tk' is not defined", citing the "line root = Tk()". I have not been able to get Tkinter to work in any form. I am currently on a macbook pro using python 2.7.5. I have tried re-downloading python multiple times but it is still not working.
Anyone have any ideas as to why it isn't working? Any more information needed from me?
Thanks in advance
```
#!/usr/bin/python
from Tkinter import *
root = Tk()
canvas = Canvas(root, width=300, height=200)
canvas.pack()
canvas.create_rectangle( 0, 0, 150, 150, fill="yellow")
canvas.create_rectangle(100, 50, 250, 100, fill="orange", width=5)
canvas.create_rectangle( 50, 100, 150, 200, fill="green", outline="red", width=3)
canvas.create_rectangle(125, 25, 175, 190, fill="purple", width=0)
root.mainloop()
```
Answer: | You have some other module that is taking the name "Tkinter", shadowing the one you actually want. Rename or remove it.
```
import Tkinter
print Tkinter.__file__
``` | Please make sure your Python file name is not "tkinter.py", or it will show this error. |
Question: I am attempting to use Tkinter for the first time on my computer, and I am getting the error in the title, "NameError: name 'Tk' is not defined", citing the "line root = Tk()". I have not been able to get Tkinter to work in any form. I am currently on a macbook pro using python 2.7.5. I have tried re-downloading python multiple times but it is still not working.
Anyone have any ideas as to why it isn't working? Any more information needed from me?
Thanks in advance
```
#!/usr/bin/python
from Tkinter import *
root = Tk()
canvas = Canvas(root, width=300, height=200)
canvas.pack()
canvas.create_rectangle( 0, 0, 150, 150, fill="yellow")
canvas.create_rectangle(100, 50, 250, 100, fill="orange", width=5)
canvas.create_rectangle( 50, 100, 150, 200, fill="green", outline="red", width=3)
canvas.create_rectangle(125, 25, 175, 190, fill="purple", width=0)
root.mainloop()
```
Answer: | Please make sure your Python file name is not "tkinter.py", or it will show this error. | your code is right but the indent is wrong in the import code, instead of using one space use two spaces and try to not type this command:
```
import tkinter
```
use this code:
```
from tkinter import *
root = Tk()
canvas = Canvas(root, width=300, height=200)
canvas.pack()
canvas.create_rectangle( 0, 0, 150, 150, fill="yellow")
canvas.create_rectangle(100, 50, 250, 100, fill="orange", width=5)
canvas.create_rectangle( 50, 100, 150, 200, fill="green", outline="red", width=3)
canvas.create_rectangle(125, 25, 175, 190, fill="purple", width=0)
root.mainloop()
```
the problem also could be typing "Tkinter", so type "tkinter" as python in case sensitive, I think this should work, it does for me |
Question: I have a list:
```
\begin{enumerate}[label={[\Roman*]},ref={[\Roman*]}]
\item\label{item1} The first item.
\end{enumerate}
```
What I want to achieve is this:
In the most instances, I want to refer to the items of the list by the format specified above (that is: `\ref{item1}` should in general produce "[I]"). However, in a few particular instances, I want to refer to the items by a custom reference formatting (more specifically, without the square brackets, by "1" instead of "[1]"), but I want still that the numbering is automatic (otherwise, I could use, for example `\hyperref[item1]{1}` to refer). Therefore, I would like to, for example, define a new command `\nobracketsref` such that `\nobracketsref{item1}` should produces "1".
How this could be achieved? I would appreciate any help.
PS. In the situation there is one twist that may affect the solution: I have two `.tex` files so that the list is in one file (the list document) and I am referring to its items from the other file (the main document).
This is done in a usual way by involving in the preamble of the main document:
```
\usepackage{xr-hyper}
\usepackage{hyperref}
\externaldocument{the_list_document.tex}
```
Answer: | Define `ref=` to use a macro, instead of the explicit brackets; such a macro can be redefined to do nothing when the brackets are not wanted.
```
\documentclass{article}
\usepackage{enumitem,xparse}
\usepackage[colorlinks]{hyperref}
\makeatletter
\NewDocumentCommand{\nobracketref}{sm}{%
\begingroup\let\bracketref\@firstofone
\IfBooleanTF{#1}{\ref*{#2}}{\ref{#2}}%
\endgroup
}
\makeatother
\NewDocumentCommand{\bracketref}{m}{[#1]}
\begin{document}
\begin{enumerate}[label={[\Roman*]},ref={\bracketref{\Roman*}}]
\item\label{item1} The first item.
\end{enumerate}
With brackets: \ref{item1} (link)
With brackets: \ref*{item1} (no link)
Without brackets: \nobracketref{item1} (link)
Without brackets: \nobracketref*{item1} (no link)
\end{document}
```
I don't think `xr-hyper` is much of a concern here.
[![enter image description here](https://i.stack.imgur.com/W0rtE.png)](https://i.stack.imgur.com/W0rtE.png) | Here's a LuaLaTeX-based solution. It sets up a LaTeX macro called `\nobracketref` which, in turn, invokes a Lua function called `nobrackets` which removes the outermost brackets in the function's argument.
Observe that the Lua function tests whether the cross-reference is valid. If it is not valid, i.e., if `\ref` returns `??` instead of something like `[I]`, `\nobracketref` prints an empty string. Once the cross-reference is resolved correctly, `\nobracketref` will print `I`.
[![enter image description here](https://i.stack.imgur.com/zpd1b.png)](https://i.stack.imgur.com/zpd1b.png)
```
\documentclass{article}
\usepackage{enumitem,luacode}
%% Lua-side code
\begin{luacode}
function nobrackets ( s )
if string.find ( s , "%?" ) then
return ""
else
s = string.gsub ( s , "%[(.*)%]", "%1" )
return tex.sprint ( s )
end
end
\end{luacode}
%% TeX-side code
\newcommand\nobracketref[1]{%
\directlua{ nobrackets ( \luastring{\ref{#1}} ) }}
\begin{document}
\begin{enumerate}[label={[\Roman*]},ref={[\Roman*]}]
\item\label{item:1} The first item.
\end{enumerate}
Using \texttt{\textbackslash ref}: item \ref{item:1}.
Using \texttt{\textbackslash nobracketref}: item \nobracketref{item:1}.
\end{document}
```
A caveat: This solution is (for now) not compatible with the `hyperref` package. Do let me know if `hyperref` compatibility is a requirement for you. |
Question: I have a list:
```
\begin{enumerate}[label={[\Roman*]},ref={[\Roman*]}]
\item\label{item1} The first item.
\end{enumerate}
```
What I want to achieve is this:
In the most instances, I want to refer to the items of the list by the format specified above (that is: `\ref{item1}` should in general produce "[I]"). However, in a few particular instances, I want to refer to the items by a custom reference formatting (more specifically, without the square brackets, by "1" instead of "[1]"), but I want still that the numbering is automatic (otherwise, I could use, for example `\hyperref[item1]{1}` to refer). Therefore, I would like to, for example, define a new command `\nobracketsref` such that `\nobracketsref{item1}` should produces "1".
How this could be achieved? I would appreciate any help.
PS. In the situation there is one twist that may affect the solution: I have two `.tex` files so that the list is in one file (the list document) and I am referring to its items from the other file (the main document).
This is done in a usual way by involving in the preamble of the main document:
```
\usepackage{xr-hyper}
\usepackage{hyperref}
\externaldocument{the_list_document.tex}
```
Answer: | Define `ref=` to use a macro, instead of the explicit brackets; such a macro can be redefined to do nothing when the brackets are not wanted.
```
\documentclass{article}
\usepackage{enumitem,xparse}
\usepackage[colorlinks]{hyperref}
\makeatletter
\NewDocumentCommand{\nobracketref}{sm}{%
\begingroup\let\bracketref\@firstofone
\IfBooleanTF{#1}{\ref*{#2}}{\ref{#2}}%
\endgroup
}
\makeatother
\NewDocumentCommand{\bracketref}{m}{[#1]}
\begin{document}
\begin{enumerate}[label={[\Roman*]},ref={\bracketref{\Roman*}}]
\item\label{item1} The first item.
\end{enumerate}
With brackets: \ref{item1} (link)
With brackets: \ref*{item1} (no link)
Without brackets: \nobracketref{item1} (link)
Without brackets: \nobracketref*{item1} (no link)
\end{document}
```
I don't think `xr-hyper` is much of a concern here.
[![enter image description here](https://i.stack.imgur.com/W0rtE.png)](https://i.stack.imgur.com/W0rtE.png) | You have a couple of options:
1. Remove the brackets using a delimited argument.
2. Create a new `\label` that uses `\Roman` instead of `[\Roman]`.
The first option is implemented by means of your `\nobracketsref{<label>}` choice. The second option is implemented by means of a `\speciallabel{<what>}{<label>}`. `<what>` here is set to `\Roman{enumi}`, since `enumi` is the first-level counter within an `enumerate`.
[![enter image description here](https://i.stack.imgur.com/vg5fI.png)](https://i.stack.imgur.com/vg5fI.png)
```
\documentclass{article}
\usepackage{enumitem,hyperref,refcount}
\makeatletter
\newcommand*{\speciallabel}[2]{{%
\protected@edef\@currentlabel{#1}% Update the current label
\label{#2}% \label item
}}
\def\@removebrackets[#1]{#1}
\newcommand*{\nobracketsref}[1]{{%
\edef\@nobracketsref{\getrefnumber{#1}}% Retrieve reference
\expandafter\edef\expandafter\@nobracketsref\@nobracketsref% Strip outer group
\expandafter\edef\expandafter\@nobracketsref\expandafter{\expandafter\@removebrackets\@nobracketsref}% Strip [.]
\hyperref[#1]{\@nobracketsref}% Reference
}}
\makeatother
\begin{document}
\begin{enumerate}[label={[\Roman*]},ref={[\Roman*]}]
\item\label{item1}\speciallabel{\Roman{enumi}}{item2} The first item.
\end{enumerate}
\ref{item1} \quad \nobracketsref{item1} \quad \ref{item2}
\end{document}
``` |
Question: there is a page ($9\times 9$) how many different rectangles can you draw with odd area?
rectangles are different if they are different on size and place.
for example if a rectangle is $15$ squares, its area is odd.
if a rectangle is $12$ squares, its area is even.
I have no idea how to approach this question so I can't give my answer.
Thanks!
Answer: | If the area has to be odd, the length and breadth both have to be odd. Hence, we count the number of rectangles by first choosing a row and a column ($10 \cdot 10$ ways to do this), and then choosing another row and column which are at an odd distance from the chosen one ($5 \cdot 5$ ways to do this). But we have counted each rectangle four times -- by the first row/column and then again by the second row/column -- so we divide by 4 to get our final answer: $1/4 \cdot 10 \cdot 10 \cdot 5 \cdot 5 = 625$. | the number of squares with equal dimensions is $81$. so if number of squares is odd then the rectangle has an odd area. the total rectangles are given by ${10 \choose 2}.{10 \choose 2}=2025$ . you have rectangles now you just need to select two lines which are odd distances apart from each other . and its done. hope its clear. |
Question: What is the best way of removing element from a list by either a comparison to the second list or a list of indices.
```
val myList = List(Dog, Dog, Cat, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat, Cat)
val toDropFromMylist = List(Cat, Cat, Dog)
```
Which the indices accordance with myList are:
```
val indices = List(2, 7, 0)
```
The end result expected to be as below:
```
newList = List(Dog, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat)
```
Any idea?
Answer: | Something like this should do the trick:
```
myList
.indices
.filter(!indices.contains(_))
.map(myList)
``` | This works:
```
myList
.zipWithIndex
.collect{case (x, n) if !indices.contains(n) => x}
```
Here's a complete, self-contained REPL transcript showing it working:
```
scala> case object Dog; case object Cat; case object Monkey; case object Mouse; case object Donkey
defined object Dog
defined object Cat
defined object Monkey
defined object Mouse
defined object Donkey
scala> val myList = List(Dog, Dog, Cat, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat, Cat)
myList: List[Product with Serializable] = List(Dog, Dog, Cat, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat, Cat)
scala> val indices = List(2, 7, 0)
indices: List[Int] = List(2, 7, 0)
scala> myList.zipWithIndex.collect{case (x, n) if !indices.contains(n) => x}
res1: List[Product with Serializable] = List(Dog, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat)
```
Note that I didn't use `toDropFromMylist`; that may mean I have misunderstood your question. |
Question: What is the best way of removing element from a list by either a comparison to the second list or a list of indices.
```
val myList = List(Dog, Dog, Cat, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat, Cat)
val toDropFromMylist = List(Cat, Cat, Dog)
```
Which the indices accordance with myList are:
```
val indices = List(2, 7, 0)
```
The end result expected to be as below:
```
newList = List(Dog, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat)
```
Any idea?
Answer: | Using `toDropFromMylist` is actually the simplest.
```
scala> myList diff toDropFromMylist
res0: List[String] = List(Dog, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat)
``` | This works:
```
myList
.zipWithIndex
.collect{case (x, n) if !indices.contains(n) => x}
```
Here's a complete, self-contained REPL transcript showing it working:
```
scala> case object Dog; case object Cat; case object Monkey; case object Mouse; case object Donkey
defined object Dog
defined object Cat
defined object Monkey
defined object Mouse
defined object Donkey
scala> val myList = List(Dog, Dog, Cat, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat, Cat)
myList: List[Product with Serializable] = List(Dog, Dog, Cat, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat, Cat)
scala> val indices = List(2, 7, 0)
indices: List[Int] = List(2, 7, 0)
scala> myList.zipWithIndex.collect{case (x, n) if !indices.contains(n) => x}
res1: List[Product with Serializable] = List(Dog, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat)
```
Note that I didn't use `toDropFromMylist`; that may mean I have misunderstood your question. |
Question: What is the best way of removing element from a list by either a comparison to the second list or a list of indices.
```
val myList = List(Dog, Dog, Cat, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat, Cat)
val toDropFromMylist = List(Cat, Cat, Dog)
```
Which the indices accordance with myList are:
```
val indices = List(2, 7, 0)
```
The end result expected to be as below:
```
newList = List(Dog, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat)
```
Any idea?
Answer: | Using `toDropFromMylist` is actually the simplest.
```
scala> myList diff toDropFromMylist
res0: List[String] = List(Dog, Donkey, Dog, Donkey, Mouse, Cat, Cat, Cat)
``` | Something like this should do the trick:
```
myList
.indices
.filter(!indices.contains(_))
.map(myList)
``` |
Question: I am working on a web api and I am curios about the `HTTP SEARCH` verb and how you should use it.
My first approach was, well you could use it surely for a search. But asp.net WebApi doesn't support the `SEARCH` verb.
My question is basically, should I use `SEARCH` or is it not important?
PS: I found the `SEARCH` verb in fiddler2 from telerik.
Answer: | The HTTP protocol is defined by RFC documents. RFC2616 defines HTTP/1.1 the current release.
SEARCH is not documented as a verb in this document. | AFAIK the `SEARCH` method is only a proposal and should not be used. Use `GET` instead. |
Question: I recreated a Select box and its dropdown function using this:
```
$(".selectBox").click(function(e) {
if (!$("#dropDown").css("display") || $("#dropDown").css("display") == "none")
$("#dropDown").slideDown();
else
$("#dropDown").slideUp();
e.preventDefault();
});
```
The only problem is that if you click away from the box, the dropdown stays. I'd like it to mimic a regular dropdown and close when you click away, so I thought I could do a 'body' click:
```
$('body').click(function(){
if ($("#dropdown").css("display") || $("#dropdown").css("display") != "none")
$("#dropdown").slideUp();
});
```
But now, when you click the Select box, the dropdown slides down and right back up. Any ideas what I'm doing wrong? Thanks very much in advance...
Answer: | You also need to stop a click from *inside* the `#dropdown` from bubbling back up to `body`, like this:
```
$(".selectBox, #dropdown").click(function(e) {
e.stopPropagation();
});
```
We're using [`event.stopPropagation()`](http://api.jquery.com/event.stopPropagation/) it stops the click from bubbling up, causing the [`.slideUp()`](http://api.jquery.com/slideUp/). Also your other 2 event handlers can be simplified with [`:visible`](http://api.jquery.com/visible-selector/) or [`.slideToggle()`](http://api.jquery.com/slideToggle/), like this overall:
```
$(".selectBox").click(function(e) {
$("#dropDown").slideToggle();
return false; //also prevents bubbling
});
$("#dropdown").click(function(e) {
e.stopPropagation();
});
$(document).click(function(){
$("#dropdown:visible").slideUp();
});
``` | Since you are setting an event handler that catches every click, you don't need another one on a child.
```
$(document).click(function(e) {
if ($(e.target).closest('.selectBox').length) {
$('#dropdown').slideToggle();
return false;
} else {
$('#dropdown:visible').slideUp();
}
});
``` |
Question: Here is a program about the Fibonacci sequence. Each time the code branches off again you are calling the fibonacci function from within itself two times.
```
def fibonacci(number)
if number < 2
number
else
fibonacci(number - 1) + fibonacci(number - 2)
end
end
puts fibonacci(6)
```
The only thing I understand is that it adds the number from the previous number. This program was taken from my assignment. It says, "If you take all of those ones and zeros and add them together, you'll get the same answer you get when you run the code."
[![enter image description here](https://i.stack.imgur.com/JoZlf.jpg)](https://i.stack.imgur.com/JoZlf.jpg)
I really tried my best to understand how this code works but I failed. Can anyone out there who is so kind and explain to me in layman's term or in a way a dummy would understand what's happening on this code?
Answer: | This is just the direct 1:1 translation (with a simple twist) of the standard mathematical definition of the Fibonacci Function:
```
Fib(0) = 0
Fib(1) = 1
Fib(n) = Fib(n-2) + Fib(n-1)
```
Translated to Ruby, this becomes:
```
def fib(n)
return 0 if n.zero?
return 1 if n == 1
fib(n-2) + fib(n-1)
end
```
It's easy to see that the first two cases can be combined: if n is 0, the result is 0, if n is 1, the result is 1. That's the same as saying if n is 0 or 1, the result is the same as n. And "n is 0 or 1" is the same as "n is less than 2":
```
def fib(n)
return n if n < 2
fib(n-2) + fib(n-1)
end
```
There's nothing special about this, it's the exact translation of the recursive definition of the mathematical Fibonacci function. | I don't really know which part baffles you but let me try.
In the graph, a function f() denotes your fibonacci() and f(1) and f(0) are pre-defined as 1 and 0.
As f(number) comes from f(number - 1) + f(number - 2) in your number = 2,
f(2) = f(2 - 1) + f(2 - 2) = 1 + 0 = 1.
Likewise, you can get f(3) = f(3 - 1) + f(3 - 2) = f(2) + f(1) = 1 + 1. You can proceed to number 6 in your graph with the code then you get the answer.
And do not care about people who already forget when they were the babe. It's just like convention here :) |
Question: How can I retrieve all keys in a Hash in Ruby, also the nested ones. Duplicates should be ignored, e.g.
```
{ a: 3, b: { b: 2, b: { c: 5 } } }.soberize
=> [:a, :b, :c]
```
What would be the fastest implementation?
Answer: | Simple recursive solution:
```
def recursive_keys(data)
data.keys + data.values.map{|value| recursive_keys(value) if value.is_a?(Hash) }
end
def all_keys(data)
recursive_keys(data).flatten.compact.uniq
end
```
Usage:
```
all_keys({ a: 3, b: { b: 2, b: { c: 5 } } })
=> [:a, :b, :c]
``` | What about a recursive method?
```
def nested_keys(hash, array)
if hash.is_a?(Hash)
array |= hash.keys
hash.keys.map do |key|
array = nested_keys(hash[key], array)
end
end
array
end
``` |
Question: I'm reading through K&R and the question is to: write a program to copy its input to its output, replacing each string of one or more blanks by a single blank. In my mind I think I know what I need to do, set up a boolean to know when I am in a space or not. I've attempted it and did not succeed. I've found this code and it works, I am struggling to figure out what stops the space from being written. I think I may have it but I need clarification.
```
#include <stdio.h>
int main(void)
{
int c;
int inspace;
inspace = 0;
while((c = getchar()) != EOF)
{
if(c == ' ')
{
if(inspace == 0)
{
inspace = 1;
putchar(c);
}
}
/* We haven't met 'else' yet, so we have to be a little clumsy */
if(c != ' ')
{
inspace = 0;
putchar(c);
}
}
return 0;
}
```
I have created a text file to work on, the text reads:
```
so this is where you have been
```
After the 's' on 'this' the state changes to 1 because we are in a space. The space gets written and it reads the next space. So now we enter:
```
while((c = getchar()) != EOF)
{
if(c == ' ')
{
if(inspace == 0)
{
inspace = 1;
putchar(c);
}
```
But inspace is not 0, it is 1. So what happens? Does the code skip to return 0;, not writing anything and just continues the while loop? return 0; is outside of the loop but this is the only way I can see that a value is not returned.
Answer: | At this point:
```
if(c == ' ')
{
if(inspace == 0) // <-- here
```
If inspace is equal to 1, it will not execute the if body, it will jump to:
```
if(c != ' ') {
```
And as long as c == ' ' above will be false, so it will skip the if body and jump to:
```
while((c = getchar()) != EOF) {
```
And this will continue until the end of the file or until `(c != ' ')` evaluates to true. When c is non-space:
```
if(c != ' ')
{
inspace = 0;
putchar(c);
```
inspace is zeroed, and character is printed. | Yeah in the case you mentioned, it does not write anything and continues in the while loop and fetches the next character. If the next character is again space then it will do the same thing i.e go to next iteration without printing. Whenever it will find first non-space it will set inspace to 0 and start printing.
While loop will terminate whenever getchar will fetch EOF. Then program will return 0. |
Question: I'm reading through K&R and the question is to: write a program to copy its input to its output, replacing each string of one or more blanks by a single blank. In my mind I think I know what I need to do, set up a boolean to know when I am in a space or not. I've attempted it and did not succeed. I've found this code and it works, I am struggling to figure out what stops the space from being written. I think I may have it but I need clarification.
```
#include <stdio.h>
int main(void)
{
int c;
int inspace;
inspace = 0;
while((c = getchar()) != EOF)
{
if(c == ' ')
{
if(inspace == 0)
{
inspace = 1;
putchar(c);
}
}
/* We haven't met 'else' yet, so we have to be a little clumsy */
if(c != ' ')
{
inspace = 0;
putchar(c);
}
}
return 0;
}
```
I have created a text file to work on, the text reads:
```
so this is where you have been
```
After the 's' on 'this' the state changes to 1 because we are in a space. The space gets written and it reads the next space. So now we enter:
```
while((c = getchar()) != EOF)
{
if(c == ' ')
{
if(inspace == 0)
{
inspace = 1;
putchar(c);
}
```
But inspace is not 0, it is 1. So what happens? Does the code skip to return 0;, not writing anything and just continues the while loop? return 0; is outside of the loop but this is the only way I can see that a value is not returned.
Answer: | At this point:
```
if(c == ' ')
{
if(inspace == 0) // <-- here
```
If inspace is equal to 1, it will not execute the if body, it will jump to:
```
if(c != ' ') {
```
And as long as c == ' ' above will be false, so it will skip the if body and jump to:
```
while((c = getchar()) != EOF) {
```
And this will continue until the end of the file or until `(c != ' ')` evaluates to true. When c is non-space:
```
if(c != ' ')
{
inspace = 0;
putchar(c);
```
inspace is zeroed, and character is printed. | If a condition in an if-statement is not true, the following expression is not executed. This means that everything inside the corresponding brackets is skipped and the execution resumes 'after' the closing bracket.
As the following if-statement is also false, nothing is done inside this iteration of the for-loop. |
Question: I'm reading through K&R and the question is to: write a program to copy its input to its output, replacing each string of one or more blanks by a single blank. In my mind I think I know what I need to do, set up a boolean to know when I am in a space or not. I've attempted it and did not succeed. I've found this code and it works, I am struggling to figure out what stops the space from being written. I think I may have it but I need clarification.
```
#include <stdio.h>
int main(void)
{
int c;
int inspace;
inspace = 0;
while((c = getchar()) != EOF)
{
if(c == ' ')
{
if(inspace == 0)
{
inspace = 1;
putchar(c);
}
}
/* We haven't met 'else' yet, so we have to be a little clumsy */
if(c != ' ')
{
inspace = 0;
putchar(c);
}
}
return 0;
}
```
I have created a text file to work on, the text reads:
```
so this is where you have been
```
After the 's' on 'this' the state changes to 1 because we are in a space. The space gets written and it reads the next space. So now we enter:
```
while((c = getchar()) != EOF)
{
if(c == ' ')
{
if(inspace == 0)
{
inspace = 1;
putchar(c);
}
```
But inspace is not 0, it is 1. So what happens? Does the code skip to return 0;, not writing anything and just continues the while loop? return 0; is outside of the loop but this is the only way I can see that a value is not returned.
Answer: | At this point:
```
if(c == ' ')
{
if(inspace == 0) // <-- here
```
If inspace is equal to 1, it will not execute the if body, it will jump to:
```
if(c != ' ') {
```
And as long as c == ' ' above will be false, so it will skip the if body and jump to:
```
while((c = getchar()) != EOF) {
```
And this will continue until the end of the file or until `(c != ' ')` evaluates to true. When c is non-space:
```
if(c != ' ')
{
inspace = 0;
putchar(c);
```
inspace is zeroed, and character is printed. | When inspace is 1 and c is ' ' the expression:
```
inspace == 0
```
evaluates to 0 and the code
```
inspace = 1;
putchar(c);
```
does not get executed.
The program will then go to the next iteration of the while loop if it can, but it won't return 0 until the while loop has ended.
You can simplify the while loop to this code:
```
while((c = getchar()) != EOF)
{
if(c == ' ')
{
if(inspace == 0)
{
inspace = 1;
putchar(c);
}
} else
{
inspace = 0;
putchar(c);
}
}
``` |
Question: I am going to move from Blogger to WordPress and I also don't want to set earlier Blogger Permalink structure in WordPress.
Now I want to know if there is any way to redirect URLs as mentioned below.
Current (In Blogger):
```
http://www.example.com/2017/10/seba-online-form-fill-up-2018.html
```
After (In WordPress):
```
http://www.example.com/seba-online-form-fill-up-2018.html
```
That means I want to remove my Blogger's year & month from URL from numbers of indexed URL and redirect them to WordPress generated new URLs.
Answer: | If `/seba-online-form-fill-up-2018.html` is an actual WordPress URL then this is relatively trivial to do in `.htaccess`. For example, the following one-liner using mod\_rewrite could be used. This should be placed *before* the existing WordPress directives in `.htaccess`:
```
RewriteRule ^\d{4}/\d{1,2}/(.+\.html)$ /$1 [R=302,L]
```
This redirects a URL of the form `/NNNN/NN/<anything>.html` to `/<anything>.html`. Where `N` is a digit 0-9 and the month (`NN`) can be either 1 or 2 digits. If your Blogger URLs always have a 2 digit month, then change `\d{1,2}` to `\d\d`.
The `$1` in the *substitution* is a backreference to the captured group in the `RewriteRule` *pattern*. ie. `(.+\.html)`.
Note that this is a 302 (temporary) redirect. You should change this to 301 (permanent) only when you have confirmed this is working OK. (301s are cached hard by the browser so can make testing problematic.) | Well, there are some Data base migrator plugins for that porpuse like [Migrate DB](https://wordpress.org/plugins/wp-migrate-db/), obviuosly this is for changes inside a SQL data base used for wordpress and basically this plugin will look for the old URL to change it for the new URLS. So you can search and replace like:
Search: <http://yoursite.in/2017/10/>
replace: <http://yoursite.in/>
you will have <http://yoursite.in/xxxxxx.html>
Also you can do the same with a text editor like NOTEPAD++ in your backup file. Both method works |
Question: Here is my code at the moment
```
percentagesOff = [5,10,15.....]
for percentage in percentagesOff:
print("Percent off: ",percentage, end= " ")
```
and the output looks like this
```
Percent off: 5
Percent off: 10
Percent off: 15
```
and so on.
This is an example of what I want my code to look like. (have to use nested for loops as part of homework)
```
$10 $100 $1000
Percent off: 5% x x x
10% x x x
15% x x x
20% x x x
```
My question is focusing on this part
```
Percent off: 5%
10%
15%
20%
```
I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
Answer: | Here
```
percentagesOff = [5, 10, 15, 20]
print("Percent off:\t", percentagesOff[0], '%')
for percentage in percentagesOff[1:]:
print("\t\t", percentage, "%")
```
Output
```
Percent off: 5 %
10 %
15 %
20 %
``` | The fact is that python print add line break after your string to be printed. So,
Import `import sys` and, before your loop, use that:
```
sys.stdout.write(' $10 $100 $1000\n')
sys.stdout.write('Percent off:')
```
And now, you can start using print to write your table entries.
You can simply add a if statement with a boolean too. |
Question: Here is my code at the moment
```
percentagesOff = [5,10,15.....]
for percentage in percentagesOff:
print("Percent off: ",percentage, end= " ")
```
and the output looks like this
```
Percent off: 5
Percent off: 10
Percent off: 15
```
and so on.
This is an example of what I want my code to look like. (have to use nested for loops as part of homework)
```
$10 $100 $1000
Percent off: 5% x x x
10% x x x
15% x x x
20% x x x
```
My question is focusing on this part
```
Percent off: 5%
10%
15%
20%
```
I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
Answer: | I really dislike teachers who tell students to accomplish something without having shown them the *right* tool for the job. I'm guessing you haven't yet been introduced to the `string.format()` method? Without which, lining up your columns will be an utter pain. You're trying to use a hammer when you need a screwdriver.
Anyway, regardless of that, I'd say that the right approach is to print a string of spaces the same length as 'Percent off:' when you don't want that string. So:
```
poff = 'Percent off: '
pad = ' '*len(poff)
p = poff
for percentage in percentagesOff:
print(p ,percentage, end= " ")
p = pad # for all subsequent trips around the loop
```
Better style would be to allow for the possibility that you might want `poff` output again (say) at the top of each page of output. So a better way to do the second code block is
```
for lineno, percentage in enumerate(percentagesOff):
if lineno==0: # can replace later with are-we-at-the-top-of-a-page test?
p = poff
else
p = pad
# p = poff if lineno==0 else pad # alternative shorter form
print(p ,percentage, end= " ")
``` | It is interesting excercise......
You can do something like this.
```
first = True
for p in pe:
if first == True:
print("percent off: ")
first = False
print(p)
else:
....
....
```
But you would not normally do it this way. |
Question: Here is my code at the moment
```
percentagesOff = [5,10,15.....]
for percentage in percentagesOff:
print("Percent off: ",percentage, end= " ")
```
and the output looks like this
```
Percent off: 5
Percent off: 10
Percent off: 15
```
and so on.
This is an example of what I want my code to look like. (have to use nested for loops as part of homework)
```
$10 $100 $1000
Percent off: 5% x x x
10% x x x
15% x x x
20% x x x
```
My question is focusing on this part
```
Percent off: 5%
10%
15%
20%
```
I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
Answer: | It is interesting excercise......
You can do something like this.
```
first = True
for p in pe:
if first == True:
print("percent off: ")
first = False
print(p)
else:
....
....
```
But you would not normally do it this way. | The fact is that python print add line break after your string to be printed. So,
Import `import sys` and, before your loop, use that:
```
sys.stdout.write(' $10 $100 $1000\n')
sys.stdout.write('Percent off:')
```
And now, you can start using print to write your table entries.
You can simply add a if statement with a boolean too. |
Question: Here is my code at the moment
```
percentagesOff = [5,10,15.....]
for percentage in percentagesOff:
print("Percent off: ",percentage, end= " ")
```
and the output looks like this
```
Percent off: 5
Percent off: 10
Percent off: 15
```
and so on.
This is an example of what I want my code to look like. (have to use nested for loops as part of homework)
```
$10 $100 $1000
Percent off: 5% x x x
10% x x x
15% x x x
20% x x x
```
My question is focusing on this part
```
Percent off: 5%
10%
15%
20%
```
I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
Answer: | Here
```
percentagesOff = [5, 10, 15, 20]
print("Percent off:\t", percentagesOff[0], '%')
for percentage in percentagesOff[1:]:
print("\t\t", percentage, "%")
```
Output
```
Percent off: 5 %
10 %
15 %
20 %
``` | It is interesting excercise......
You can do something like this.
```
first = True
for p in pe:
if first == True:
print("percent off: ")
first = False
print(p)
else:
....
....
```
But you would not normally do it this way. |
Question: Here is my code at the moment
```
percentagesOff = [5,10,15.....]
for percentage in percentagesOff:
print("Percent off: ",percentage, end= " ")
```
and the output looks like this
```
Percent off: 5
Percent off: 10
Percent off: 15
```
and so on.
This is an example of what I want my code to look like. (have to use nested for loops as part of homework)
```
$10 $100 $1000
Percent off: 5% x x x
10% x x x
15% x x x
20% x x x
```
My question is focusing on this part
```
Percent off: 5%
10%
15%
20%
```
I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
Answer: | Here is one alternate solution:
```
percentagesOff = [1,2,3,4,5,6,7,8,9,10]
print 'Percent off: ', percentagesOff[0] #use blanks instead of '\t'
for percentage in percentagesOff[1:]:
print ' '*len('Percent off: '), percentage
```
The last line, leaves one blank space for every character of the string ''Percent off: '' and then start printing elements of array.
Basically, "len('something')" returns how many character does the string 'something' include. Then we muliply ' ' (which is one space) by that number. | The fact is that python print add line break after your string to be printed. So,
Import `import sys` and, before your loop, use that:
```
sys.stdout.write(' $10 $100 $1000\n')
sys.stdout.write('Percent off:')
```
And now, you can start using print to write your table entries.
You can simply add a if statement with a boolean too. |
Question: Here is my code at the moment
```
percentagesOff = [5,10,15.....]
for percentage in percentagesOff:
print("Percent off: ",percentage, end= " ")
```
and the output looks like this
```
Percent off: 5
Percent off: 10
Percent off: 15
```
and so on.
This is an example of what I want my code to look like. (have to use nested for loops as part of homework)
```
$10 $100 $1000
Percent off: 5% x x x
10% x x x
15% x x x
20% x x x
```
My question is focusing on this part
```
Percent off: 5%
10%
15%
20%
```
I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
Answer: | I really dislike teachers who tell students to accomplish something without having shown them the *right* tool for the job. I'm guessing you haven't yet been introduced to the `string.format()` method? Without which, lining up your columns will be an utter pain. You're trying to use a hammer when you need a screwdriver.
Anyway, regardless of that, I'd say that the right approach is to print a string of spaces the same length as 'Percent off:' when you don't want that string. So:
```
poff = 'Percent off: '
pad = ' '*len(poff)
p = poff
for percentage in percentagesOff:
print(p ,percentage, end= " ")
p = pad # for all subsequent trips around the loop
```
Better style would be to allow for the possibility that you might want `poff` output again (say) at the top of each page of output. So a better way to do the second code block is
```
for lineno, percentage in enumerate(percentagesOff):
if lineno==0: # can replace later with are-we-at-the-top-of-a-page test?
p = poff
else
p = pad
# p = poff if lineno==0 else pad # alternative shorter form
print(p ,percentage, end= " ")
``` | Here is one alternate solution:
```
percentagesOff = [1,2,3,4,5,6,7,8,9,10]
print 'Percent off: ', percentagesOff[0] #use blanks instead of '\t'
for percentage in percentagesOff[1:]:
print ' '*len('Percent off: '), percentage
```
The last line, leaves one blank space for every character of the string ''Percent off: '' and then start printing elements of array.
Basically, "len('something')" returns how many character does the string 'something' include. Then we muliply ' ' (which is one space) by that number. |
Question: Here is my code at the moment
```
percentagesOff = [5,10,15.....]
for percentage in percentagesOff:
print("Percent off: ",percentage, end= " ")
```
and the output looks like this
```
Percent off: 5
Percent off: 10
Percent off: 15
```
and so on.
This is an example of what I want my code to look like. (have to use nested for loops as part of homework)
```
$10 $100 $1000
Percent off: 5% x x x
10% x x x
15% x x x
20% x x x
```
My question is focusing on this part
```
Percent off: 5%
10%
15%
20%
```
I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
Answer: | I really dislike teachers who tell students to accomplish something without having shown them the *right* tool for the job. I'm guessing you haven't yet been introduced to the `string.format()` method? Without which, lining up your columns will be an utter pain. You're trying to use a hammer when you need a screwdriver.
Anyway, regardless of that, I'd say that the right approach is to print a string of spaces the same length as 'Percent off:' when you don't want that string. So:
```
poff = 'Percent off: '
pad = ' '*len(poff)
p = poff
for percentage in percentagesOff:
print(p ,percentage, end= " ")
p = pad # for all subsequent trips around the loop
```
Better style would be to allow for the possibility that you might want `poff` output again (say) at the top of each page of output. So a better way to do the second code block is
```
for lineno, percentage in enumerate(percentagesOff):
if lineno==0: # can replace later with are-we-at-the-top-of-a-page test?
p = poff
else
p = pad
# p = poff if lineno==0 else pad # alternative shorter form
print(p ,percentage, end= " ")
``` | You can just pull it out of the for loop, then it gets printed only once, or you could "remember" that you already printed it by setting some boolean variable to `True`(initialized at `False`) and then checking whether that variable is `True` or `False` before printing that part of the string. |
Question: Here is my code at the moment
```
percentagesOff = [5,10,15.....]
for percentage in percentagesOff:
print("Percent off: ",percentage, end= " ")
```
and the output looks like this
```
Percent off: 5
Percent off: 10
Percent off: 15
```
and so on.
This is an example of what I want my code to look like. (have to use nested for loops as part of homework)
```
$10 $100 $1000
Percent off: 5% x x x
10% x x x
15% x x x
20% x x x
```
My question is focusing on this part
```
Percent off: 5%
10%
15%
20%
```
I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
Answer: | I really dislike teachers who tell students to accomplish something without having shown them the *right* tool for the job. I'm guessing you haven't yet been introduced to the `string.format()` method? Without which, lining up your columns will be an utter pain. You're trying to use a hammer when you need a screwdriver.
Anyway, regardless of that, I'd say that the right approach is to print a string of spaces the same length as 'Percent off:' when you don't want that string. So:
```
poff = 'Percent off: '
pad = ' '*len(poff)
p = poff
for percentage in percentagesOff:
print(p ,percentage, end= " ")
p = pad # for all subsequent trips around the loop
```
Better style would be to allow for the possibility that you might want `poff` output again (say) at the top of each page of output. So a better way to do the second code block is
```
for lineno, percentage in enumerate(percentagesOff):
if lineno==0: # can replace later with are-we-at-the-top-of-a-page test?
p = poff
else
p = pad
# p = poff if lineno==0 else pad # alternative shorter form
print(p ,percentage, end= " ")
``` | The fact is that python print add line break after your string to be printed. So,
Import `import sys` and, before your loop, use that:
```
sys.stdout.write(' $10 $100 $1000\n')
sys.stdout.write('Percent off:')
```
And now, you can start using print to write your table entries.
You can simply add a if statement with a boolean too. |
Question: Here is my code at the moment
```
percentagesOff = [5,10,15.....]
for percentage in percentagesOff:
print("Percent off: ",percentage, end= " ")
```
and the output looks like this
```
Percent off: 5
Percent off: 10
Percent off: 15
```
and so on.
This is an example of what I want my code to look like. (have to use nested for loops as part of homework)
```
$10 $100 $1000
Percent off: 5% x x x
10% x x x
15% x x x
20% x x x
```
My question is focusing on this part
```
Percent off: 5%
10%
15%
20%
```
I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
Answer: | Here is one alternate solution:
```
percentagesOff = [1,2,3,4,5,6,7,8,9,10]
print 'Percent off: ', percentagesOff[0] #use blanks instead of '\t'
for percentage in percentagesOff[1:]:
print ' '*len('Percent off: '), percentage
```
The last line, leaves one blank space for every character of the string ''Percent off: '' and then start printing elements of array.
Basically, "len('something')" returns how many character does the string 'something' include. Then we muliply ' ' (which is one space) by that number. | It is interesting excercise......
You can do something like this.
```
first = True
for p in pe:
if first == True:
print("percent off: ")
first = False
print(p)
else:
....
....
```
But you would not normally do it this way. |
Question: Here is my code at the moment
```
percentagesOff = [5,10,15.....]
for percentage in percentagesOff:
print("Percent off: ",percentage, end= " ")
```
and the output looks like this
```
Percent off: 5
Percent off: 10
Percent off: 15
```
and so on.
This is an example of what I want my code to look like. (have to use nested for loops as part of homework)
```
$10 $100 $1000
Percent off: 5% x x x
10% x x x
15% x x x
20% x x x
```
My question is focusing on this part
```
Percent off: 5%
10%
15%
20%
```
I'm struggling to figure out how to only print the `Percent off:` part once in my for loop.
Answer: | You can just pull it out of the for loop, then it gets printed only once, or you could "remember" that you already printed it by setting some boolean variable to `True`(initialized at `False`) and then checking whether that variable is `True` or `False` before printing that part of the string. | The fact is that python print add line break after your string to be printed. So,
Import `import sys` and, before your loop, use that:
```
sys.stdout.write(' $10 $100 $1000\n')
sys.stdout.write('Percent off:')
```
And now, you can start using print to write your table entries.
You can simply add a if statement with a boolean too. |
Question: So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing?
<http://jsfiddle.net/8TVn5/>
```
window.onload = function () {
var currentPercent = 0;
var showPercent = window.setInterval(function() {
$('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) {
currentPercent= 0;});
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');}
document.getElementById('result').innerHTML = currentPercent;
}, 200);
};
```
Answer: | You can't append a `list` to a `tuple` because tuples are ["immutable"](http://docs.python.org/2/library/functions.html#tuple) (they can't be changed). It is however easy to append a *tuple* to a *list*:
```
vertices = [(0, 0), (0, 0), (0, 0)]
for x in range(10):
vertices.append((x, y))
```
You can add tuples together to create a *new*, longer tuple, but that strongly goes against the purpose of tuples, and will slow down as the number of elements gets larger. Using a list in this case is preferred. | You can't modify a tuple. You'll either need to replace the tuple with a new one containing the additional vertex, or change it to a list. A list is simply a modifiable tuple.
```
vertices = [[0,0],[0,0],[0,0]]
for ...:
vertices.append([x, y])
``` |
Question: So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing?
<http://jsfiddle.net/8TVn5/>
```
window.onload = function () {
var currentPercent = 0;
var showPercent = window.setInterval(function() {
$('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) {
currentPercent= 0;});
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');}
document.getElementById('result').innerHTML = currentPercent;
}, 200);
};
```
Answer: | You can't modify a tuple. You'll either need to replace the tuple with a new one containing the additional vertex, or change it to a list. A list is simply a modifiable tuple.
```
vertices = [[0,0],[0,0],[0,0]]
for ...:
vertices.append([x, y])
``` | Not sure I understand you, but if you want to append x,y to each vertex you can do something like :
```
vertices = ([0,0],[0,0],[0,0])
for v in vertices:
v[0] += x
v[1] += y
``` |
Question: So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing?
<http://jsfiddle.net/8TVn5/>
```
window.onload = function () {
var currentPercent = 0;
var showPercent = window.setInterval(function() {
$('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) {
currentPercent= 0;});
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');}
document.getElementById('result').innerHTML = currentPercent;
}, 200);
};
```
Answer: | You can't append a `list` to a `tuple` because tuples are ["immutable"](http://docs.python.org/2/library/functions.html#tuple) (they can't be changed). It is however easy to append a *tuple* to a *list*:
```
vertices = [(0, 0), (0, 0), (0, 0)]
for x in range(10):
vertices.append((x, y))
```
You can add tuples together to create a *new*, longer tuple, but that strongly goes against the purpose of tuples, and will slow down as the number of elements gets larger. Using a list in this case is preferred. | You can concatenate two tuples:
```
>>> vertices = ([0,0],[0,0],[0,0])
>>> lst = [10, 20]
>>> vertices = vertices + tuple([lst])
>>> vertices
([0, 0], [0, 0], [0, 0], [10, 20])
``` |
Question: So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing?
<http://jsfiddle.net/8TVn5/>
```
window.onload = function () {
var currentPercent = 0;
var showPercent = window.setInterval(function() {
$('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) {
currentPercent= 0;});
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');}
document.getElementById('result').innerHTML = currentPercent;
}, 200);
};
```
Answer: | You can't append a `list` to a `tuple` because tuples are ["immutable"](http://docs.python.org/2/library/functions.html#tuple) (they can't be changed). It is however easy to append a *tuple* to a *list*:
```
vertices = [(0, 0), (0, 0), (0, 0)]
for x in range(10):
vertices.append((x, y))
```
You can add tuples together to create a *new*, longer tuple, but that strongly goes against the purpose of tuples, and will slow down as the number of elements gets larger. Using a list in this case is preferred. | You probably want a list, as mentioned above. But if you really need a tuple, you can create a new tuple by concatenating tuples:
```
vertices = ([0,0],[0,0],[0,0])
for x in (1, 2):
for y in (3, 4):
vertices += ([x,y],)
```
Alternatively, and for more efficiency, use a list while you're building the tuple and convert it at the end:
```
vertices = ([0,0],[0,0],[0,0])
#...
vlist = list(vertices)
for x in (1, 2):
for y in (3, 4):
vlist.append([x, y])
vertices = tuple(vlist)
```
At the end of either one, `vertices` is:
```
([0, 0], [0, 0], [0, 0], [1, 3], [1, 4], [2, 3], [2, 4])
``` |
Question: So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing?
<http://jsfiddle.net/8TVn5/>
```
window.onload = function () {
var currentPercent = 0;
var showPercent = window.setInterval(function() {
$('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) {
currentPercent= 0;});
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');}
document.getElementById('result').innerHTML = currentPercent;
}, 200);
};
```
Answer: | You can't append a `list` to a `tuple` because tuples are ["immutable"](http://docs.python.org/2/library/functions.html#tuple) (they can't be changed). It is however easy to append a *tuple* to a *list*:
```
vertices = [(0, 0), (0, 0), (0, 0)]
for x in range(10):
vertices.append((x, y))
```
You can add tuples together to create a *new*, longer tuple, but that strongly goes against the purpose of tuples, and will slow down as the number of elements gets larger. Using a list in this case is preferred. | Not sure I understand you, but if you want to append x,y to each vertex you can do something like :
```
vertices = ([0,0],[0,0],[0,0])
for v in vertices:
v[0] += x
v[1] += y
``` |
Question: So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing?
<http://jsfiddle.net/8TVn5/>
```
window.onload = function () {
var currentPercent = 0;
var showPercent = window.setInterval(function() {
$('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) {
currentPercent= 0;});
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');}
document.getElementById('result').innerHTML = currentPercent;
}, 200);
};
```
Answer: | You can concatenate two tuples:
```
>>> vertices = ([0,0],[0,0],[0,0])
>>> lst = [10, 20]
>>> vertices = vertices + tuple([lst])
>>> vertices
([0, 0], [0, 0], [0, 0], [10, 20])
``` | Not sure I understand you, but if you want to append x,y to each vertex you can do something like :
```
vertices = ([0,0],[0,0],[0,0])
for v in vertices:
v[0] += x
v[1] += y
``` |
Question: So I have this script that is a counter that follows an infinite animation. The counter resets to 0 everytime an interation finishes. On the line fourth from the bottom I am trying to invoke a x.classList.toggle() to change css when the counter hits 20. When I replace the classList.toggle with an alert() function it works, but as is no class 'doton' is added to 'dot1'. What am I missing?
<http://jsfiddle.net/8TVn5/>
```
window.onload = function () {
var currentPercent = 0;
var showPercent = window.setInterval(function() {
$('#dot1').on('animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration', function (e) {
currentPercent= 0;});
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
if (currentPercent == 20){document.getElementByID('dot1').classList.toggle('doton');}
document.getElementById('result').innerHTML = currentPercent;
}, 200);
};
```
Answer: | You probably want a list, as mentioned above. But if you really need a tuple, you can create a new tuple by concatenating tuples:
```
vertices = ([0,0],[0,0],[0,0])
for x in (1, 2):
for y in (3, 4):
vertices += ([x,y],)
```
Alternatively, and for more efficiency, use a list while you're building the tuple and convert it at the end:
```
vertices = ([0,0],[0,0],[0,0])
#...
vlist = list(vertices)
for x in (1, 2):
for y in (3, 4):
vlist.append([x, y])
vertices = tuple(vlist)
```
At the end of either one, `vertices` is:
```
([0, 0], [0, 0], [0, 0], [1, 3], [1, 4], [2, 3], [2, 4])
``` | Not sure I understand you, but if you want to append x,y to each vertex you can do something like :
```
vertices = ([0,0],[0,0],[0,0])
for v in vertices:
v[0] += x
v[1] += y
``` |
Question: Is there any way I can authenticate a Facebook user without requiring them to connect in the front end? I'm trying to report the number of "likes" for an alcohol-gated page and will need to access the information with an over-21 access token, but do not want to have to log in every time I access the data.
Or is there a way to generate an access token that doesn't expire?
I'm really not that much of an expert with facebook, so any alternatives to these ideas would be greatly appreciated.
Answer: | When you're requesting the access token you're going to use to check the Page, request the `offline_access` extended permission and the token won't expire when you/the user logs out. | If you're using the [Graph API](https://developers.facebook.com/docs/reference/api/), when you initially get the `access_token`, add `offline_access` to the list of permissions you're requesting via the `scope` parameter. From the [permissions](https://developers.facebook.com/docs/reference/api/permissions/) documentation:
>
> The set of permissions below basically explain what types of permissions you can ask a u ser in the scope parameter of your auth dialog to get the permissions you need for your app.
>
>
>
So add `offline_access` to the permissions you're requesting in the `scope` parameter:
```
$config = array(
...
"scope" => "offline_access,...",
...
);
...
``` |
Question: I have an object that is apparently double deleted despite being kept track of by smart pointers. I am new to using smart pointers so I made a simple function to test whether I am using the object correctly.
```
int *a = new int(2);
std::shared_ptr<int> b(a);
std::shared_ptr<int> c(a);
```
This set of lines in the main function causes a runtime error as the pointers go out of scope, why? Aren't smart pointers supposed to be able to handle the deletion of a by themselves?
Answer: | A `shared_ptr` expects to *own* the pointed-at object.
What you've done is to create *two* separate smart pointers, each of which thinks it has exclusive ownership of the underlying `int`. They don't know about each other's existence, they don't talk to each other. Therefore, when they go out of scope, both pointers delete the underlying resource, with the obvious result.
When you create a `shared_ptr`, it creates a sort of "management object" which is responsible for the resource's lifetime. When you *copy* a `shared_ptr`, both copies reference the same management object. The management object keeps track of how many `shared_ptr` instances are pointing at this resource. An `int*` by itself has no such "management object", so copying it does not keep track of references.
Here's a minimal rewrite of your code:
```
// incidentally, "make_shared" is the best way to do this, but I'll leave your
// original code intact for now.
int *a = new int(2);
std::shared_ptr<int> b(a);
std::shared_ptr<int> c = b;
```
Now, they both reference the same underlying management object. As each `shared_ptr` is destroyed, the number of references on the `int*` is reduced and when the last reference goes ther object is deleted. | Correct usage is:
```
std::shared_ptr<int> b = std::make_shared<int>(2);
std::shared_ptr<int> c = b;
``` |
Question: I have an object that is apparently double deleted despite being kept track of by smart pointers. I am new to using smart pointers so I made a simple function to test whether I am using the object correctly.
```
int *a = new int(2);
std::shared_ptr<int> b(a);
std::shared_ptr<int> c(a);
```
This set of lines in the main function causes a runtime error as the pointers go out of scope, why? Aren't smart pointers supposed to be able to handle the deletion of a by themselves?
Answer: | You are only allowd to make a smartpointer once from a raw pointer. All other shared pointers have to be copies of the first one in order for them to work correctly. Even better: use make shared:
```
std::shared_ptr<int> sp1 = std::make_shared<int>(2);
std::shared_ptr<int> sp2 = sp1;
```
EDIT: forgot to add the second pointer | Correct usage is:
```
std::shared_ptr<int> b = std::make_shared<int>(2);
std::shared_ptr<int> c = b;
``` |
Question: I have an object that is apparently double deleted despite being kept track of by smart pointers. I am new to using smart pointers so I made a simple function to test whether I am using the object correctly.
```
int *a = new int(2);
std::shared_ptr<int> b(a);
std::shared_ptr<int> c(a);
```
This set of lines in the main function causes a runtime error as the pointers go out of scope, why? Aren't smart pointers supposed to be able to handle the deletion of a by themselves?
Answer: | A `shared_ptr` expects to *own* the pointed-at object.
What you've done is to create *two* separate smart pointers, each of which thinks it has exclusive ownership of the underlying `int`. They don't know about each other's existence, they don't talk to each other. Therefore, when they go out of scope, both pointers delete the underlying resource, with the obvious result.
When you create a `shared_ptr`, it creates a sort of "management object" which is responsible for the resource's lifetime. When you *copy* a `shared_ptr`, both copies reference the same management object. The management object keeps track of how many `shared_ptr` instances are pointing at this resource. An `int*` by itself has no such "management object", so copying it does not keep track of references.
Here's a minimal rewrite of your code:
```
// incidentally, "make_shared" is the best way to do this, but I'll leave your
// original code intact for now.
int *a = new int(2);
std::shared_ptr<int> b(a);
std::shared_ptr<int> c = b;
```
Now, they both reference the same underlying management object. As each `shared_ptr` is destroyed, the number of references on the `int*` is reduced and when the last reference goes ther object is deleted. | You are only allowd to make a smartpointer once from a raw pointer. All other shared pointers have to be copies of the first one in order for them to work correctly. Even better: use make shared:
```
std::shared_ptr<int> sp1 = std::make_shared<int>(2);
std::shared_ptr<int> sp2 = sp1;
```
EDIT: forgot to add the second pointer |
Question: I was reading about CMS and ERP. And got confused at this point that whether a system can both be an ERP and a CMS? is it possible?
Answer: | Sure - you can program whatever you like. Whether it makes any sense is a different question.
As for whether having an ERP/CMS hybrid makes sense or already exists - I don't think so. There are some vague similarities and overlaps in that both will typically allow you to define your own entities with fields ("document types" in a CMS, "business objects" in an ERP) and present a web interface for data entry and publishing, but at heart they have completely different purposes. | An example, though maybe a contrived one but one I encounterd in the wild a long time ago:
An application was built that would store incoming documents pertaining to required reports sent in by customers of a financial services company.
The same application also served to automatically send out reminder letters to customers who were late sending in those documents, and as an entry point for the telephone support people in the company to look up customer information if customer called (or had to be called).
In that case both functionalities were closely intertwined. In other systems both functionalities might exist but not be as tightly linked (think something like SAP or Lotus Notes). |
Question: I was reading about CMS and ERP. And got confused at this point that whether a system can both be an ERP and a CMS? is it possible?
Answer: | In a very theoretical sense yes. But in most cases this would not make very much sense. The basic functionality of an ERP system is business management. The data produced here may become part of the data displayed on a web site. But normally the data here is pure text and numbers, like definitions of products, orders, invoices and some statistical information.
An CMS main task is to provide information in a way that not only the content as such can be edited but often enough the representation and styling too. Its functionality is much more limited and the amount of data normally far less than in an ERP system.
In our company for example all our product and customer data is kept in an ERP system. Customers can login and search products, order them and see shipment and invoice data. All this they get directly from the ERP system. Some information in the ERP is specifically there for the web site (for example our product categories for the web site are slightly different from those used internally for statistical purposes). But this data is purely information. In theory this ERP system would have a lot of options to store even more information, even combined with some styling information. We don't use this.
Information that we do not actually need for business purposes is edited in a small CMS system for the web site. This includes things like a news section, some pages with company information and similar more text/style oriented data. We could store this in the ERP too, there are tables for such things, but it is more effort to code in the ERP area and then we would have more effort to display on the web. | An example, though maybe a contrived one but one I encounterd in the wild a long time ago:
An application was built that would store incoming documents pertaining to required reports sent in by customers of a financial services company.
The same application also served to automatically send out reminder letters to customers who were late sending in those documents, and as an entry point for the telephone support people in the company to look up customer information if customer called (or had to be called).
In that case both functionalities were closely intertwined. In other systems both functionalities might exist but not be as tightly linked (think something like SAP or Lotus Notes). |
Question: I was reading about CMS and ERP. And got confused at this point that whether a system can both be an ERP and a CMS? is it possible?
Answer: | In a very theoretical sense yes. But in most cases this would not make very much sense. The basic functionality of an ERP system is business management. The data produced here may become part of the data displayed on a web site. But normally the data here is pure text and numbers, like definitions of products, orders, invoices and some statistical information.
An CMS main task is to provide information in a way that not only the content as such can be edited but often enough the representation and styling too. Its functionality is much more limited and the amount of data normally far less than in an ERP system.
In our company for example all our product and customer data is kept in an ERP system. Customers can login and search products, order them and see shipment and invoice data. All this they get directly from the ERP system. Some information in the ERP is specifically there for the web site (for example our product categories for the web site are slightly different from those used internally for statistical purposes). But this data is purely information. In theory this ERP system would have a lot of options to store even more information, even combined with some styling information. We don't use this.
Information that we do not actually need for business purposes is edited in a small CMS system for the web site. This includes things like a news section, some pages with company information and similar more text/style oriented data. We could store this in the ERP too, there are tables for such things, but it is more effort to code in the ERP area and then we would have more effort to display on the web. | Sure - you can program whatever you like. Whether it makes any sense is a different question.
As for whether having an ERP/CMS hybrid makes sense or already exists - I don't think so. There are some vague similarities and overlaps in that both will typically allow you to define your own entities with fields ("document types" in a CMS, "business objects" in an ERP) and present a web interface for data entry and publishing, but at heart they have completely different purposes. |
Question: I was reading about CMS and ERP. And got confused at this point that whether a system can both be an ERP and a CMS? is it possible?
Answer: | Sure - you can program whatever you like. Whether it makes any sense is a different question.
As for whether having an ERP/CMS hybrid makes sense or already exists - I don't think so. There are some vague similarities and overlaps in that both will typically allow you to define your own entities with fields ("document types" in a CMS, "business objects" in an ERP) and present a web interface for data entry and publishing, but at heart they have completely different purposes. | In most cases this would not make very much sense,ERP system generally use in business management.An CMS able to edit not only content but the entire design can be edited.Information that is not important for business prospective are edited by CMS. |
Question: I was reading about CMS and ERP. And got confused at this point that whether a system can both be an ERP and a CMS? is it possible?
Answer: | In a very theoretical sense yes. But in most cases this would not make very much sense. The basic functionality of an ERP system is business management. The data produced here may become part of the data displayed on a web site. But normally the data here is pure text and numbers, like definitions of products, orders, invoices and some statistical information.
An CMS main task is to provide information in a way that not only the content as such can be edited but often enough the representation and styling too. Its functionality is much more limited and the amount of data normally far less than in an ERP system.
In our company for example all our product and customer data is kept in an ERP system. Customers can login and search products, order them and see shipment and invoice data. All this they get directly from the ERP system. Some information in the ERP is specifically there for the web site (for example our product categories for the web site are slightly different from those used internally for statistical purposes). But this data is purely information. In theory this ERP system would have a lot of options to store even more information, even combined with some styling information. We don't use this.
Information that we do not actually need for business purposes is edited in a small CMS system for the web site. This includes things like a news section, some pages with company information and similar more text/style oriented data. We could store this in the ERP too, there are tables for such things, but it is more effort to code in the ERP area and then we would have more effort to display on the web. | In most cases this would not make very much sense,ERP system generally use in business management.An CMS able to edit not only content but the entire design can be edited.Information that is not important for business prospective are edited by CMS. |
Question: In the application there is a dialog where only numeric string entries are valid. Therefore I would like to set the numeric keyboard layout.
Does anyone know how to simulate key press on the keyboard or any other method to change the keyboard layout?
Thanks!
Answer: | You don't need to.
Just like full windows, you can set the edit control to be numeric input only. You can either do it [manually](http://msdn.microsoft.com/en-us/library/bb761655(VS.85).aspx) or in the dialog editor in the properites for the edit control.
The SIP should automatically display the numeric keyboard when the numeric only edit control goes into focus. | You can use the InputModeEditor:
```
InputModeEditor.SetInputMode(textBox1,InputMode.Numeric);
``` |
Question: In the application there is a dialog where only numeric string entries are valid. Therefore I would like to set the numeric keyboard layout.
Does anyone know how to simulate key press on the keyboard or any other method to change the keyboard layout?
Thanks!
Answer: | You don't need to.
Just like full windows, you can set the edit control to be numeric input only. You can either do it [manually](http://msdn.microsoft.com/en-us/library/bb761655(VS.85).aspx) or in the dialog editor in the properites for the edit control.
The SIP should automatically display the numeric keyboard when the numeric only edit control goes into focus. | There is only one way to do this (edit: this is referring to the SIP in non-smartphone Windows Mobile, so I'm not sure it's relevant to your question), and it does involve simulating a mouse click on the 123 button. This is only half the problem, however, since you also need to know whether the keyboard is already in numeric mode or not. The way to do this is to peek a pixel near the upper left corner of the keypad - if you look at how the 123 button works, you'll see that it's system text on windows background, and then inverted in numeric mode (so the pixel will be the system text color only when in numeric mode). There's one more bit of weirdness you have to do to guarantee it will work on all devices (you have to draw a pixel on the keyboard, too).
Lucky for you, I have an easy-to-use code sample that does all this. Unlucky for you, it's in C#, but I think it should at least point you in the right direction. |
Question: ```
try:
folderSizeInMB= int(subprocess.check_output('du -csh --block-size=1M', shell=True).decode().split()[0])
print('\t\tTotal download progress (MB):\t' + str(folderSizeInMB), end = '\r')
except Exception as e:
print('\t\tDownloading' + '.'*(loopCount - gv.parallelDownloads + 3), end = '\r')
```
I have this code in my script because for some reason my unix decided to not find 'du' command. It throws an error `/bin/sh: du: command not found`.
My hope with this code was that even though my program runs into this error, it will just display the message in the `except` block and move-along. However, it prints the error before displaying the message in the `except` block. Why is it doing so? Is there a way for me to suppress the error message displayed by the `try` block?
Thanks.
EDIT:
I rewrote the code after receiving the answer like shown below and it works. I had to rewrite only one line:
```
folderSizeInMB= int(subprocess.check_output('du -csh --block-size=1M', shell=True, stederr=subprocess.DEVNULL).decode().split()[0])
```
Answer: | The error is being shown by the shell, printing to stderr. Because you’re not redirecting its stderr, it just goes straight through to your own program’s stderr, which goes to your terminal.
If you don’t want this—or any other shell features—then the simplest solution is to just not use the shell. Pass a list of arguments instead of a command line, and get rid of that `shell=True`, and the error will become a normal Python exception that you can handle with the code you already have.
If you just use the shell for some reason, you will need to redirect its stderr. You can pass `stderr=subprocess.STDOUT` to make it merge in with the stdout that you’re already capturing, or `subprocess.DEVNULL` to ignore it. The `subprocess` module docs explain all of the options nicely, so read them, decide which behavior you want, and do that. | You can try redirecting the stderr to null to prevent the error from displaying.
```
import sys
class DevNull:
def write(self, msg):
pass
sys.stderr = DevNull()
``` |
Question: I work with reconstructing fossil skeletons of human ancestors. Bones are usually incomplete and I need to assemble whole virtual bones from laser scans of different fossil parts of the bone I have scanned. How can I efficiently delete parts I don't need so that I can assemble whole virtual bones? I know it's easy to delete by bisecting, but that's not enough for what I need [![enter image description here](https://i.stack.imgur.com/zYOwO.jpg)](https://i.stack.imgur.com/zYOwO.jpg)Does this image help explain what I wantto do?
Answer: | Hope this helps:
You can try centering the mesh in an axis (X or Y most commonly) and then use `numpad 1` or `numpad 3` to get an isometric view of the mesh along that axis. (Depending on your blender config, you might need to also press `numpad 5`)
Then you can press `z` and `tab` to go into wireframe mode and edit mode respectively.
Once there, you can select whatever vertices are not needed (To select vertices you can use the hotkey `ctrl`+`shift`+`tab` and select vertices in the popup menu) and delete them. Then press `tab` again to go back to object mode and add a mirror modifier to mirror the whole "correct" side of the mesh along the axis you need. Fiddle around with the merge and clipping options to get whatever desired effect you were looking for. | You can use `Shift`+`Ctrl`+`Alt`+`M` to select non manifold vertices, essentially finding all holes and floating vertices in a mesh. |
Question: In Objective C I want to create a simple application that posts a string to a php file using ASIHTTPRequest.
I have no need for an interface and am finding it hard to find any example code. Does anyone know where I can find code, or can anyone give me an example of such code?
Answer: | The ASIHTTPRequest documentation covers this. Specifically, [Sending a form POST with ASIFormDataRequest](http://allseeing-i.com/ASIHTTPRequest/How-to-use#sending_a_form_post_with_ASIFormDataRequest). | [This site](http://www.webdesignideas.org/2011/08/18/simple-login-app-for-iphone-tutorial/comment-page-1/#comment-34811) has a really great walkthrough on how to use ASIHTTPREQUEST to authenticate data against a database. the walkthrough breaks the entire process down file by file for you. |
Question: I have this metric:
$$ds^2=-dt^2+e^tdx^2$$
and I want to find the equation of motion (of x). for that i thought I have two options:
1. using E.L. with the Lagrangian: $L=-\dot t ^2+e^t\dot x ^2 $.
2. using the fact that for a photon $ds^2=0$ to get: $0=-dt^2+e^tdx^2$ and then:
$dt=\pm e^{t/2} dx$.
The problem is that (1) gives me $x=ae^{-t}+b$ and (2) gives me $x=ae^{-t/2} +b$.
Answer: | If your solution is not a null geodesic then it is wrong for a massless particle.
The reason you go astray is that Lagrangian you give in (1) is incorrect for massless particles. The general action for a particle (massive or massless) is:
$$ S = -\frac{1}{2} \int \mathrm{d}\xi\ \left( \sigma(\xi) \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2 + \frac{m^2}{\sigma(\xi)}\right), $$
where $\xi$ is an arbitrary worldline parameter and $\sigma(\xi)$ an auxiliary variable that must be eliminated by its equation of motion. Also note the notation
$$ \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2\equiv \pm g\_{\mu\nu} \frac{\mathrm{d}X^\mu}{\mathrm{d}\xi}\frac{\mathrm{d}X^\nu}{\mathrm{d}\xi}, $$
modulo your metric sign convention (I haven't checked which one is right for your convention). Check that for $m\neq 0$ this action reduces to the usual action for a massive particle. For the massless case however, you get
$$ S = -\frac{1}{2} \int \mathrm{d}\xi\ \sigma(\xi) \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2. $$
The equation of motion for $\sigma$ gives the constraint
$$ \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2 = 0, $$
for a null geodesic. This is necessary and consistent for massless particles, as you know.
The equation of motion for $X^\mu$ is (**EDIT**: Oops, I forgot a term here. Note that $g\_{\mu\nu}$ depends on $X$ so a term involving $\partial\_\rho g\_{\mu\nu}$ comes into the variation. Try working it out for yourself. I'll fix the following equations up later):
$$ \frac{\mathrm{d}}{\mathrm{d}\xi}\left(\sigma g\_{\mu\nu}\frac{\mathrm{d}X^{\mu}}{\mathrm{d}\xi}\right)=0, $$
but you can change the parameter $\xi\to\lambda$ so that $\sigma \frac{\mathrm{d}}{\mathrm{d}\xi} = \frac{\mathrm{d}}{\mathrm{d}\lambda}$, so the equation of motion simplifies to
$$ \frac{\mathrm{d}}{\mathrm{d}\lambda}\left(g\_{\mu\nu}\frac{\mathrm{d}X^{\mu}}{\mathrm{d}\lambda}\right)=0, $$
which you should be able to solve to get something satisfying the null constraint. | There is an elegant way of doing this using symmetries.
Notice that this metric is space translation invariant, so it has a killing vector $\partial\_x$. There is a corresponding conserved quantity $c\_x$ along geodesics $x^\mu(\lambda)$ given by
\begin{align}
c\_x = g\_{\mu\nu}\dot x^\mu(\partial\_x)^\nu = e^t\dot x
\end{align}
Where an overdot denotes differentiation with respect to affine parameter. On the other hand, the fact that the desired geodesic is a (null) photon geodesic along which $ds^2 = 0$ gives
\begin{align}
0=-\dot t^2 + e^t\dot x^2
\end{align}
This forms a set of coupled differential equations that is not actually that hard to solve. Hint: Try solving the first equation for $\dot x$, and then plugging it into the second equation. |
Question: I have this metric:
$$ds^2=-dt^2+e^tdx^2$$
and I want to find the equation of motion (of x). for that i thought I have two options:
1. using E.L. with the Lagrangian: $L=-\dot t ^2+e^t\dot x ^2 $.
2. using the fact that for a photon $ds^2=0$ to get: $0=-dt^2+e^tdx^2$ and then:
$dt=\pm e^{t/2} dx$.
The problem is that (1) gives me $x=ae^{-t}+b$ and (2) gives me $x=ae^{-t/2} +b$.
Answer: | If your solution is not a null geodesic then it is wrong for a massless particle.
The reason you go astray is that Lagrangian you give in (1) is incorrect for massless particles. The general action for a particle (massive or massless) is:
$$ S = -\frac{1}{2} \int \mathrm{d}\xi\ \left( \sigma(\xi) \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2 + \frac{m^2}{\sigma(\xi)}\right), $$
where $\xi$ is an arbitrary worldline parameter and $\sigma(\xi)$ an auxiliary variable that must be eliminated by its equation of motion. Also note the notation
$$ \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2\equiv \pm g\_{\mu\nu} \frac{\mathrm{d}X^\mu}{\mathrm{d}\xi}\frac{\mathrm{d}X^\nu}{\mathrm{d}\xi}, $$
modulo your metric sign convention (I haven't checked which one is right for your convention). Check that for $m\neq 0$ this action reduces to the usual action for a massive particle. For the massless case however, you get
$$ S = -\frac{1}{2} \int \mathrm{d}\xi\ \sigma(\xi) \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2. $$
The equation of motion for $\sigma$ gives the constraint
$$ \left(\frac{\mathrm{d}X}{\mathrm{d}\xi}\right)^2 = 0, $$
for a null geodesic. This is necessary and consistent for massless particles, as you know.
The equation of motion for $X^\mu$ is (**EDIT**: Oops, I forgot a term here. Note that $g\_{\mu\nu}$ depends on $X$ so a term involving $\partial\_\rho g\_{\mu\nu}$ comes into the variation. Try working it out for yourself. I'll fix the following equations up later):
$$ \frac{\mathrm{d}}{\mathrm{d}\xi}\left(\sigma g\_{\mu\nu}\frac{\mathrm{d}X^{\mu}}{\mathrm{d}\xi}\right)=0, $$
but you can change the parameter $\xi\to\lambda$ so that $\sigma \frac{\mathrm{d}}{\mathrm{d}\xi} = \frac{\mathrm{d}}{\mathrm{d}\lambda}$, so the equation of motion simplifies to
$$ \frac{\mathrm{d}}{\mathrm{d}\lambda}\left(g\_{\mu\nu}\frac{\mathrm{d}X^{\mu}}{\mathrm{d}\lambda}\right)=0, $$
which you should be able to solve to get something satisfying the null constraint. | I) Well, in 1+1 dimensions the light-cone (based at some point) is just two intersecting curves, which are precisely determined by the condition
$$\tag{1} g\_{\mu\nu}\dot{x}^{\mu}\dot{x}^{\nu}~=~0,$$
and an initial condition cf. OP's second method. However, this eq. (1) will not determine light-like geodesics in higher dimensions.
II) OP's first method, namely to vary the Lagrangian
$$\tag{2} L~:=~ g\_{\mu\nu}(x)\dot{x}^{\mu}\dot{x}^{\nu} $$
is in principle also correct. It is a nice exercise to show that Euler-Lagrange equations are the [geodesic](http://en.wikipedia.org/wiki/Geodesic) equation. However, it seems that OP mistakenly identifies the parameter $\lambda$ of the geodesic with the $x^0$-coordinate. These are two different things! In 1+1 dimensions, we have two coordinates $x^0$ and $x^1$. There are two Euler-Lagrange equations. The complete solution for $\lambda\mapsto x^0(\lambda)$ and $\lambda\mapsto x^1(\lambda)$ will be *all* geodesics: time-like, light-like and space-like.
Since we are only interested in *light-like* geodesics, we would also have to impose eq. (1) in the Euler-Lagrange method.
III) If one makes a coordinate transformation
$$\tag{3} u~=~\exp(-\frac{x^0}{2})\quad\text{and}\quad v~=~\frac{x^1}{2}, $$
then OP's metric becomes
$$\tag{4} \frac{4}{u^2}(-du^2+dv^2)$$
which is e.g. also considered in [this](https://physics.stackexchange.com/q/64468/2451) Phys.SE post (up to an overall constant factor). Obviously, the light-like geodesics are of the form
$$\tag{5} v-v\_0~=~ \pm (u-u\_0). $$ |
Question: I've been trying for a long time to write the results to my file, but since it's a multithreaded task, the files are written in a mixed way
The task that adds the file is in the get\_url function
And this fonction is launched via pool.submit(get\_url,line)
```
import requests
from concurrent.futures import ThreadPoolExecutor
import fileinput
from bs4 import BeautifulSoup
import traceback
import threading
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import warnings
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
warnings.filterwarnings("ignore", category=UserWarning, module='bs4')
count_requests = 0
host_error = 0
def get_url(url):
try:
global count_requests
result_request = requests.get(url, verify=False)
soup = BeautifulSoup(result_request.text, 'html.parser')
with open('outfile.txt', 'a', encoding="utf-8") as f:
f.write(soup.title.get_text())
count_requests = count_requests + 1
except:
global host_error
host_error = host_error + 1
with ThreadPoolExecutor(max_workers=100) as pool:
for line in fileinput.input(['urls.txt']):
pool.submit(get_url,line)
print(str("requests success : ") + str(count_requests) + str(" | requests error ") + str(host_error), end='\r')
```
This is what the output looks like :
google.com - Google
w3schools.com - W3Schools Online Web Tutorials
Answer: | You can use [`multiprocessing.Pool`](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool) and `pool.imap_unordered` to receive processed results and write it to the file. That way the results are written only inside main thread and won't be interleaved. For example:
```py
import requests
import multiprocessing
from bs4 import BeautifulSoup
def get_url(url):
# do your processing here:
soup = BeautifulSoup(requests.get(url).content, "html.parser")
return soup.title.text
if __name__ == "__main__":
# read urls from file or other source:
urls = ["http://google.com", "http://yahoo.com"]
with multiprocessing.Pool() as p, open("result.txt", "a") as f_out:
for result in p.imap_unordered(get_url, urls):
print(result, file=f_out)
``` | I agree with Andrej Kesely that we should not write to file within `get_url`. Here is my approach:
```py
from concurrent.futures import ThreadPoolExecutor, as_completed
def get_url(url):
# Processing...
title = ...
return url, title
if __name__ == "__main__":
with open("urls.txt") as stream:
urls = [line.strip() for line in stream]
with ThreadPoolExecutor() as executor:
urls_and_titles = executor.map(get_url, urls)
# Exiting the with block: all tasks are done
with open("outfile.txt", "w", encoding="utf-8") as stream:
for url, title in urls_and_titles:
stream.write(f"{url},{title}\n")
```
This approach waits until all tasks completed before writing out the result. If we want to write out the tasks as soon as possible:
```py
from concurrent.futures import ThreadPoolExecutor, as_completed
...
if __name__ == "__main__":
with open("urls.txt") as stream:
urls = [line.strip() for line in stream]
with ThreadPoolExecutor() as executor, open("outfile.txt", "w", encoding="utf-8") as stream:
futures = [
executor.submit(get_url, url)
for url in urls
]
for future in as_completed(futures):
url, title = future.result()
stream.write(f"{url},{title}\n")
```
The `as_completed()` function will take care to order the `Futures` object so the ones completed first is at the beginning of the queue.
In conclusion, the key here is for the worker function `get_url` to return some value and do not write to file. That task will be done in the main thread. |
Question: I have the following code that is trying to remove some JSESSIONID cookies from my browser.
```
String[] cookieList = "/App1/,/App2/,/App3/".split(",");
for (int i = 0; i < cookieList.length; i++) {
String cookiePathString = cookieList[i];
response.setContentType("text/html");
Cookie cookieToKill = new Cookie("JSESSIONID", "No Data");
cookieToKill.setDomain(getCookieDomainName("myDomain.com"));
cookieToKill.setMaxAge(0);
cookieToKill.setPath(cookiePathString);
cookieToKill.setComment("EXPIRING COOKIE at " + System.currentTimeMillis());
response.addCookie(cookieToKill);
}
```
The code works fine in Firefox, and deletes the JSESSIONID. In Chrome and IE it does not. What do you have to do to expire these session cookies from IE and Chrome?
This is running in an Spring MVC Application on Tomcat running Java 7
Answer: | Cookie is completely messed up.
The best practices for a server:
1. use Set-Cookie, not Set-Cookie2.
2. if there are multiple cookies, use a separate Set-Cookie header for each cookie.
3. use Expires, not Max-Age.
4. use the date format: `Sun, 06 Nov 1994 08:49:37 GMT`
For example:
```
Set-Cookie: JSESSIONID=NO_DATA; Path=/App1/; Domain=myDomain.com; Expires=Thu, 01 Jan 1970 00:00:00 GMT
```
What I can recommend you to do:
1. Don't have spaces in cookie values.
2. Call `cookie.setVersion(0);`
If still no luck, forget the `Cookie` class, try set the http header manually
```
response.addHeader("Set-Cookie",
"JSESSIONID=NO_DATA; Path=/App1/; Domain=myDomain.com; Expires=Thu, 01 Jan 1970 00:00:00 GMT");
``` | [This SO question](https://stackoverflow.com/questions/1716555/setting-persistent-cookie-from-java-doesnt-work-in-ie) indicates that the solution may be to call `setHttpOnly(true)`. |
Question: Also, if there is truth behind Republican support to make voting more restrictive for people in general, how long ago might this party have started advocating legislation with more restrictions?
Why
---
Listening to the video on [this post](https://www.cnn.com/2021/03/02/politics/supreme-court-brnovich-v-dnc-case-analysis-john-roberts/index.html), there are different Republican and Democrat views on voting access.
It seems to be portrayed that...
1. Democrats want more people to have access to their voting rights by fewer disqualifying restrictions.
2. Republicans want fewer people to have access to their voting rights by more disqualifying restrictions.
I found the end of the audio most interesting where [Amy Coney Barrett](https://en.wikipedia.org/wiki/Amy_Coney_Barrett) asked the RNC attorney about the interest to the RNC in keeping the out-of-precinct voter ballot disqualification rule in place in Arizona.
The RNC attorney's response was "*Because it puts us at a competitive disadvantage relative to Democrats. Politics is a zero-sum game*".
Answer: | Speaking nationally, Democrats currently have a 6%-7% advantage over Republicans in terms of voter representation. In fact, Democrats have a lead among every demographic group except *white males without a college education*. However, Democratic voters tend to be clustered in urban and suburban areas, which attenuates their voting power somewhat and leaves them vulnerable to manipulations like gerrymandering. Further, they have lower SES (socio-economic status) as a group, meaning they are more affected by restrictions on registration and voting. And that's not mentioning the Electoral College, which gives a significant advantage to parties that control smaller states (which currently — for the most part — lean Republican).
So yes: making voting more restrictive mainly impacts low income voters in urban areas, those who have the least free time and fewest material and financial resources to jump through bureaucratic hoops.
At least some Republicans and conservatives explicitly advocate for this kind of implicit disenfranchisement in order to maintain power. I cannot speak to the intentions of the GOP as a whole, except to note that anyone in the political universe with any minimal competence is aware of the fact that there are material conditions to voting which can present obstacles. This has been well-known and thoroughly argued since the Jim Crow days, back when the Supreme Court struck down poll taxes, so anyone who talks about voting restrictions without also considering the issue of structural disenfranchisement is either deeply ignorant or purely Machiavellian. Granting that some conservatives do argue that there should be a 'civic commitment' standard applied to voting — akin to the ancient Greek practice of restricting the democratic participation to established property owners and native sons, on the grounds that such people have a firm commitment to the welfare of the community — the GOP itself has never raised that *explicitly* as a platform, for the obvious 'optics' reasons.
And note that the situation is more complex than it appears on the surface. The GOP could (for instance) work to increase its voter base, thus obviating the need for voting restrictions. But that would involve creating a forward-thinking platform meant to appeal to a broader coalition, which risks insulting certain die-hard, single-issue voting blocks that the GOP has catered to since the 70s. Those voting blocks are not exactly unified, but they represent some of the most readily mobilized elements of the GOP base, so the GOP prefers a fragmented, decentered, 'talking point' style of politics, one which allows them to play both ends against the middle without committing themselves to anything. Squeezing out unwanted voters is simpler and safer. | Not necessarily.
If any once dominant political party wishes to win more elections without imposing "voting restrictions", they might also consider changing with the times to better represent the wider preferences of the general public. |
Question: I'm using ant to package a JavaFX-based application. No problem with doing the actual JavaFX stuff, except that `fx:jar` doesn't support the `if` or `condition` tags. I want to dynamically include some platform-specific libraries, depending on a variable i set. Currently I have this:
```
<fx:fileset dir="/my/classes/folder">
<include name="**/*lib1.dylib" if="??"/>
<include name="**/*lib2.dll" if="??" />
<include name="**/*lib3.dll" if="??" />
</fx:fileset>
```
I want to run this target multiple times, with a different variable value depending on the platform. It seems you can not do something like:
```
<include name="**/*lib3.dll" if="platform=mac" />
```
So I'm stuck. Please help!
Answer: | Many readers of this forum expect to see *some* code that you tried....
```
program flow
version 8 // will work on almost all Stata in current use
gettoken what garbage : 0
if "`what'" == "" | "`garbage'" != "" | !inlist("`what'", "e", "i") {
di as err "syntax is flow e or flow i"
exit 198
}
if "`what'" == "e" {
<code for e>
}
else if "`what'" == "i" {
<code for i>
}
end
```
The last `if` condition is redundant as we've already established that the user typed `e` or `i`. Edit it out according to taste. | Given your comment on the answer by @NickCox, I assume you tried something like this:
```
program flow
version 8
syntax [, i e]
if "`i'`e'" == "" {
di as err "either the i or the e option needs to be specified"
exit 198
}
if "`i'" != "" & "`e'" != "" {
di as err "the i and e options cannot be specified together"
exit 198
}
if "`e'" != "" {
<code for e>
}
if "`i'" != "" {
<code for i>
}
end
```
After that you call `flow` like this: `flow, i` or `flow, e`. Notice the comma, this is now necessary (but not in the command by @NickCox) because you made them options. |
Question: I'm using ant to package a JavaFX-based application. No problem with doing the actual JavaFX stuff, except that `fx:jar` doesn't support the `if` or `condition` tags. I want to dynamically include some platform-specific libraries, depending on a variable i set. Currently I have this:
```
<fx:fileset dir="/my/classes/folder">
<include name="**/*lib1.dylib" if="??"/>
<include name="**/*lib2.dll" if="??" />
<include name="**/*lib3.dll" if="??" />
</fx:fileset>
```
I want to run this target multiple times, with a different variable value depending on the platform. It seems you can not do something like:
```
<include name="**/*lib3.dll" if="platform=mac" />
```
So I'm stuck. Please help!
Answer: | Many readers of this forum expect to see *some* code that you tried....
```
program flow
version 8 // will work on almost all Stata in current use
gettoken what garbage : 0
if "`what'" == "" | "`garbage'" != "" | !inlist("`what'", "e", "i") {
di as err "syntax is flow e or flow i"
exit 198
}
if "`what'" == "e" {
<code for e>
}
else if "`what'" == "i" {
<code for i>
}
end
```
The last `if` condition is redundant as we've already established that the user typed `e` or `i`. Edit it out according to taste. | If you want `i` and `e` to be mutually exclusive options, then this is yet another alternative:
```
program flow
version 8
capture syntax , e
if _rc == 0 { // syntax matched what was typed
<code for e>
}
else {
syntax , i // error message and program exit if syntax is incorrect
<code for i>
}
end
```
If the code in each branch is at all long, many would prefer subprograms for each case as a matter of good style, but that would be consistent with the sketch here. Note that in each `syntax` statement the option is declared compulsory.
The effect of `capture` is this: errors are not fatal, but are "eaten" by `capture`. So you need to look at the return code, accessible in `_rc`. 0 for `_rc` always means that the command was successful. Non-zero always means that the command was unsuccessful. Here, and often elsewhere, there are only two ways for the command to be right, so we don't need to know what `_rc` was; we just need to check for the other legal syntax.
Note that even my two answers here differ in style on whether a user typing an illegal command gets an informative error message or just "invalid syntax". The context to this is an expectation that every Stata command comes with a help file. Some programmers write on the assumption that the help file explains the syntax; others want their error messages to be as helpful as possible. |
Question: I'm using ant to package a JavaFX-based application. No problem with doing the actual JavaFX stuff, except that `fx:jar` doesn't support the `if` or `condition` tags. I want to dynamically include some platform-specific libraries, depending on a variable i set. Currently I have this:
```
<fx:fileset dir="/my/classes/folder">
<include name="**/*lib1.dylib" if="??"/>
<include name="**/*lib2.dll" if="??" />
<include name="**/*lib3.dll" if="??" />
</fx:fileset>
```
I want to run this target multiple times, with a different variable value depending on the platform. It seems you can not do something like:
```
<include name="**/*lib3.dll" if="platform=mac" />
```
So I'm stuck. Please help!
Answer: | Given your comment on the answer by @NickCox, I assume you tried something like this:
```
program flow
version 8
syntax [, i e]
if "`i'`e'" == "" {
di as err "either the i or the e option needs to be specified"
exit 198
}
if "`i'" != "" & "`e'" != "" {
di as err "the i and e options cannot be specified together"
exit 198
}
if "`e'" != "" {
<code for e>
}
if "`i'" != "" {
<code for i>
}
end
```
After that you call `flow` like this: `flow, i` or `flow, e`. Notice the comma, this is now necessary (but not in the command by @NickCox) because you made them options. | If you want `i` and `e` to be mutually exclusive options, then this is yet another alternative:
```
program flow
version 8
capture syntax , e
if _rc == 0 { // syntax matched what was typed
<code for e>
}
else {
syntax , i // error message and program exit if syntax is incorrect
<code for i>
}
end
```
If the code in each branch is at all long, many would prefer subprograms for each case as a matter of good style, but that would be consistent with the sketch here. Note that in each `syntax` statement the option is declared compulsory.
The effect of `capture` is this: errors are not fatal, but are "eaten" by `capture`. So you need to look at the return code, accessible in `_rc`. 0 for `_rc` always means that the command was successful. Non-zero always means that the command was unsuccessful. Here, and often elsewhere, there are only two ways for the command to be right, so we don't need to know what `_rc` was; we just need to check for the other legal syntax.
Note that even my two answers here differ in style on whether a user typing an illegal command gets an informative error message or just "invalid syntax". The context to this is an expectation that every Stata command comes with a help file. Some programmers write on the assumption that the help file explains the syntax; others want their error messages to be as helpful as possible. |
Question: Let $\sum a\_n=a$ with terms non-negative. Let $ s\_n$ the n-nth partial sum.
Prove $\sum na\_n$ converge if $\sum (a-s\_n)$ converge
Answer: | $$
\begin{align}
\sum\_{k=1}^nka\_k
&=\sum\_{k=1}^n\sum\_{j=1}^ka\_k\\
&=\sum\_{j=1}^n\sum\_{k=j}^na\_k\\
&=\sum\_{j=1}^n(s\_n-s\_{j-1})
\end{align}
$$
Taking limits, we get by [Monotone Convergence](https://en.wikipedia.org/wiki/Monotone_convergence_theorem) that
$$
\begin{align}
\sum\_{k=1}^\infty ka\_k
&=\sum\_{j=1}^\infty(a-s\_{j-1})\\
&=a+\sum\_{j=1}^\infty(a-s\_j)\\
\end{align}
$$ | It is easy to prove the following fact:
If $(a\_n) $ is decreasing sequence and $\sum\_{j=1}^{\infty } a\_j $ converges then $\lim\_{j\to \infty } ja\_j =0.$
Now let $r\_n =\sum\_{k=n+1}^{\infty } a\_n $ and assume that $\sum\_{i=1}^{\infty} r\_n <\infty .$ Observe that $(r\_n )$ is an decreasing sequence, hence by the fact $\lim\_{n\to\infty} nr\_n =0.$ Take any $\varepsilon >0$ and let $n\_0 $ by such a big that $nr\_n <\varepsilon $ and $\sum\_{k=n}^{\infty} r\_k <\varepsilon $ for $n\geqslant n\_0 -1$ then we have $$\sum\_{j=n\_0}^{\infty} ja\_j = n\_0 r\_{n\_0 -1} + \sum\_{k=n\_0}^{\infty } r\_k\leqslant \varepsilon +\varepsilon =2\varepsilon .$$ Thus the series $$\sum\_{j=1}^{\infty} ja\_j $$ converges. |
Question: Let $\sum a\_n=a$ with terms non-negative. Let $ s\_n$ the n-nth partial sum.
Prove $\sum na\_n$ converge if $\sum (a-s\_n)$ converge
Answer: | $$
\begin{align}
\sum\_{k=1}^nka\_k
&=\sum\_{k=1}^n\sum\_{j=1}^ka\_k\\
&=\sum\_{j=1}^n\sum\_{k=j}^na\_k\\
&=\sum\_{j=1}^n(s\_n-s\_{j-1})
\end{align}
$$
Taking limits, we get by [Monotone Convergence](https://en.wikipedia.org/wiki/Monotone_convergence_theorem) that
$$
\begin{align}
\sum\_{k=1}^\infty ka\_k
&=\sum\_{j=1}^\infty(a-s\_{j-1})\\
&=a+\sum\_{j=1}^\infty(a-s\_j)\\
\end{align}
$$ | This is less rigorous than the other answer but more intuitive to me (and tells us a neat thing).
$\displaystyle \sum\_1^{N} (a-s\_n)=Na-\sum\_1^N(N+1-n)a\_n$.
As $N \to \infty$, $\displaystyle Na-\sum\_1^N(N+1-n)a\_n \to -\sum\_1^{\infty}(1-n)a\_n = \sum\_1^{\infty} na\_n-a$.
Hence $\displaystyle \sum\_1^{\infty} (a-s\_n)$ converges $\displaystyle \iff \sum\_1^{\infty} na\_n$ converges.
The neat thing is that assuming convergence, $\displaystyle \sum\_1^{\infty} (a-s\_n) = \sum\_1^{\infty} na\_n-a$ |
Question: Let $\sum a\_n=a$ with terms non-negative. Let $ s\_n$ the n-nth partial sum.
Prove $\sum na\_n$ converge if $\sum (a-s\_n)$ converge
Answer: | $$
\begin{align}
\sum\_{k=1}^nka\_k
&=\sum\_{k=1}^n\sum\_{j=1}^ka\_k\\
&=\sum\_{j=1}^n\sum\_{k=j}^na\_k\\
&=\sum\_{j=1}^n(s\_n-s\_{j-1})
\end{align}
$$
Taking limits, we get by [Monotone Convergence](https://en.wikipedia.org/wiki/Monotone_convergence_theorem) that
$$
\begin{align}
\sum\_{k=1}^\infty ka\_k
&=\sum\_{j=1}^\infty(a-s\_{j-1})\\
&=a+\sum\_{j=1}^\infty(a-s\_j)\\
\end{align}
$$ | Simply note
$$
\sum\_n (a-s\_n)=\sum\_n \sum\_{k=n+1}^\infty a\_k = \sum\_{k=2}^\infty \sum\_{n=1}^{k-1} a\_k =\sum\_{k=2}^\infty (k-1)a\_k.
$$
Here, we can interchange the same since all commands are nonnegative.
Using the assumption that $\sum\_n a\_n$ converges, this easily implies the claim (even with if and only if). |
Question: I am using jQuery and jQuery UI and i am trying to read a checkbox state through the addition of the "aria-pressed" property that jQuery UI Button toggle between false and true.
```
$('.slideButton').live('click', function() {
alert($(this).attr('aria-pressed'));
});
```
This code however seems to read the aria-pressed before jQuery UI has updated aria-pressed. So i unreliable values. Can i schedule it to execute after the UI has updated or can i make it wait?
[Live example here!](http://jonasbengtson.se/projects/dh/admin/)
Answer: | Can't you add a listener to the actual checkbox behind the label or span?
```
$("#days_list li div div div input[type='checkbox']").change(function(){
alert("Someone just clicked checkbox with id"+$(this).attr("id"));
});
```
This should work since, once you click the label, you change the value in the checkbox.
---
Alright, I've composed a [live example](http://jsfiddle.net/S5NEf/4/) for you that demonstrates the general idea of how it works, and how you retrieve the status of the checkbox.
```
$("#checkbox_container input").change(function(){
if($(this).is(":checked")) alert("Checked!");
else alert("Unchecked!");
});
```
In your case, since the checkbox is added dynamically by JQuery you have to use the live event, but it is basically the same thing
```
$("#checkbox_container input").live("changed"....
```
[Here's an example](http://jsfiddle.net/S5NEf/8/) with some additional scripting and checking, mostly for demonstrative purposes. | You can use a callback to execute the `alert($(this).attr('aria-pressed'));` after the toggle has completed.
```
$('.slidebutton').toggle(1000, function(){
alert($(this).attr('aria-pressed'));
});
```
I'm not too sure if your using `.toggle()` or not but you would need to use a callback either way to ensure sequential execution. |
Question: I have a vbscript that runs on the command line in xp. It accepts one argument for the path to a directory. Is there a simple way to prompt the user in the command line box for this?
If not, I can just echo what was passed in to show the user what they actually typed in case of typos.
Thanks,
James
Aftermath:
Here is the code I ended up with:
On Error Resume Next
strDirectory = InputBox(Message, Title, "For example - P:\Windows\")
```
If strDirectory = "" Then
'Wscript.Echo cancelledText
Else
'Wscript.Echo enteredText & strDirectory
etc...
```
I found some snippets and it turned out to be really simple to work with the inputBox.
HTH.
James
Answer: | You can use the [`WScript.StdIn`](http://msdn.microsoft.com/en-us/library/1y8934a7%28v=VS.85%29.aspx) property to read from the the standard input. If you want to supply the path when invoking the script, you can pass the path as a parameter. You'll find it in the [`WScript.Arguments`](http://msdn.microsoft.com/en-us/library/z2b05k8s%28v=VS.85%29.aspx) property. | you can use the choice command, [choice](http://www.robvanderwoude.com/choice.php)
it sets errorlevel to the value selected. I think it comes with DOS, Windows 95,98, then MS dropped it and then came back again in Windows 7 and probably Vista
P.D. oh never mind, I read again and you're in XP. There are other options, like `set /p name= What is your name?` would create a variable %name% you can use |
Question: I recently discovered this script: [JS fiddle text swapper](http://jsfiddle.net/PMKDG/) - but I'd like to add a nice fade in and fade out.
I guess this is a 2 part question.
1. Can I add fadeIn the way this is structured?
2. I'm guessing I'll also need a FadeOut?
Help would be greatly appreciated!
Thanks
```
$(function() {
$("#all-iso, #date-iso, #actor-iso, #film-iso").on("click", function(e) {
var txt = "";
switch ($(this).prop("id")) {
case "all-iso":
txt = "ALLE NEWS";
break;
case "date-iso":
txt = "DATUM";
break;
case "actor-iso":
txt = "SCHAUSPIELER";
break;
case "film-iso":
txt = "FILM";
break;
}
$("#news-h3-change").text(txt);
})
})
```
Answer: | Try
```
$("#news-h3-change").fadeOut(function(){
$(this).text(txt)
}).fadeIn();
```
Demo: [Fiddle](http://jsfiddle.net/arunpjohny/93WG6/)
I might suggest to use `data-*` to make it little more nice, like
```
<ul id="iso">
<li data-txt="ALLE NEWS">all-iso</li>
<li data-txt="DATUM">date-iso</li>
<li data-txt="SCHAUSPIELER">actor-iso</li>
<li data-txt="FILM">film-iso</li>
</ul>
<h3 id="news-h3-change"></h3>
```
then
```
$(function () {
$("#iso > li").on("click", function (e) {
var txt = $(this).data('txt');
$("#news-h3-change").stop(true, true).fadeOut(function () {
$(this).text(txt)
}).fadeIn('slow');
})
})
```
Demo: [Fiddle](http://jsfiddle.net/arunpjohny/dmZ5W/) | Here is another way to do it [JSFiddle](http://jsfiddle.net/PMKDG/29/)
```
$(function() {
$("#all-iso, #date-iso, #actor-iso, #film-iso").on("click", function(e) {
var txt = "", id = $(this).prop("id");
$('#news-h3-change').fadeOut('slow', function() {
switch (id) {
case "all-iso":
txt = "ALLE NEWS";
break;
case "date-iso":
txt = "DATUM";
break;
case "actor-iso":
txt = "SCHAUSPIELER";
break;
case "film-iso":
txt = "FILM";
break;
}
$(this).text(txt);
$("#news-h3-change").fadeIn('slow');
});
})
})
``` |
Question: I'm trying to edit this code to be dynamic as I'm going to schedule it to run.
Normally I would input the date in the where statement as 'YYYY-MM-DD' and so to make it dynamic I changed it to DATE(). I'm not erroring out, but I'm also not pulling data. I just need help with format and my google searching isn't helping.
```
PROC SQL;
CONNECT TO Hadoop (server=disregard this top part);
CREATE TABLE raw_daily_fcast AS SELECT * FROM connection to Hadoop(
SELECT DISTINCT
a.RUN_DATE,
a.SCHEDSHIPDATE,
a.SOURCE,
a.DEST ,
a.ITEM,
b.U_OPSTUDY,
a.QTY,
c.case_pack_qty
FROM CSO.RECSHIP a
LEFT JOIN CSO.UDT_ITEMPARAM b
ON a.ITEM = b.ITEM
LEFT JOIN SCM.DIM_PROD_PLN c
ON a.ITEM = c.PLN_NBR
WHERE a.RUN_DATE = DATE()
AND a.SOURCE IN ('88001', '88003', '88004', '88006', '88008', '88010', '88011', '88012',
'88017', '88018', '88024', '88035', '88040', '88041', '88042', '88047')
);
DISCONNECT FROM Hadoop;
QUIT;
```
Answer: | Try command
```
ionic cordova build android --prod --release
``` | Any one still having this issue, a big cause of this problem is PLUGINS
run `ionic cordova plugin`
And have a look at your list of plugins, and uninstall All the dodgy ones, and those you arent SURE are working by running `ionic cordova plugin rm your-plugin-name`
This is the problem 98% of the time. |
Question: I was once asked the following question by a student I was tutoring; and I was stumped by it:
When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground?
* One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case.
* One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere.
* It's because of the nature of the force. It's independent of the motion of the stone.
I prefer the last explanation - but is it true? And is this the best explanation?
Answer: | >
> When one throws a stone....
>
>
>
Your arm is capable of propelling an object at up to around 150km/h (and that's with some practice). At that speed the many factors like air resistance are negligible.
Let’s load a 16-inch shell into a gun (you will find several on the USS Iowa), aim it 45 degrees up and press the button. The shell is going to go up at an initial rate of Mach 1.7 (vertical vector), decreasing to zero at apogee, and it will come down accelerating at *g* until it reaches its terminal velocity. Things tend not to fall at supersonic speeds so it should be clear that the up time will not equal the down time. | **Assuming that the only forces acting on the stone are the initial force exerted by the hand on the stone AND the force of gravity**, we have the following situation:
Immediately after throwing, the stone has a kinetic energy in the x-direction that never changes (**conservation of energy**) and the stone has a kinetic energy in the y-direction that is constantly being depleted by gravity as it rises to its apex. Once the stone is at its apex (vertical kinetic energy = 0), gravity **works** to restore all of the stone's original vertical kinetic energy as it falls back to its original height.
So, the x-direction **kinetic energy** remained constant throughout the flight and the y-direction **total energy (kinetic + potential)** remained constant throughout the flight, independent of each other. This combination causes the symmetry of the situation.
If air resistance and terminal velocity are introduced into the problem, the character of the problem is completely changed. Even a very simple situation as the one you described can become very complex and confusing to most people. Most people would be stymied by the complexity of the math involved even in this simple situation, let alone the complexity of putting a probe into orbit about Earth. |
Question: I was once asked the following question by a student I was tutoring; and I was stumped by it:
When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground?
* One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case.
* One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere.
* It's because of the nature of the force. It's independent of the motion of the stone.
I prefer the last explanation - but is it true? And is this the best explanation?
Answer: | I would consider that since acceleration is a constant vector pointing downward, that the time the projectiles downward component takes to accelerate from V(initial) to 0 would be the same as the time it takes to accelerate the object from 0 to V(final) | Asking "Why" in physics often leads out of physics and into philosophy. Why is there light? Because God said so. Physics only answers questions about how the universe behaves and how to describe that behavior. If a why question can be answered with physics, the answer is "because it follows from a law of physics." A law is just a mathematical description of behavior that has been verified with experiments.
In this case, the answer follows from $F = ma$. If $a$ is constant, this leads to $x = 1/2at^2 + v\_0t + x\_0$. Since you are a physics tutor, you can set up the initial and final conditions and solve for t.
This may well lead to more questions. Why is $F = ma$? Why is there gravity? You could fall back on philosophy, or you could say "I don't know. But experiments show that it works this way."
Why questions are usually about things that are unfamiliar. A young child will ask "Why is there gravity?" A high school student is more likely to ask "Why is $F = ma$?" He may not know the answer to the first question, but he has become used to it.
So the way to answer $F = ma$ questions is to show how it applies to familiar situations. This is why high school physics is full of pictures of springs and ropes and pulleys. |
Question: I was once asked the following question by a student I was tutoring; and I was stumped by it:
When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground?
* One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case.
* One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere.
* It's because of the nature of the force. It's independent of the motion of the stone.
I prefer the last explanation - but is it true? And is this the best explanation?
Answer: | I think its because both halves of a projectile's trajectory are symmetric in every aspect. The projectile going from its apex position to the ground is just the time reversed version of the projectile going from its initial position to the apex position. | A lot of things have to hold to get that symmetry. You have to neglect air resistance. You either have to throw it straight up, or the ground over there has to be at the the same altitude as the ground over here. You have to through it slowly enough that it comes back down (watch out for escape velocity)
But if you have that, then the simplest explanation in the simplest case is that the acceleration is constant. So you keep going up until you have zero (vertical) velocity, which takes time $v\_0/g$, during which you travel up a certain distance. On the way down, the acceleration is still constant, so now the velocity becomes more down over time, but that just makes it the time reverse (when looking at the vertical component alone) so it takes an equal amount of time.
If you want to throw it high enough that the acceleration starts to vary, an energy argument is quicker, though you can study the kinematics on the way back down as the time reverse (gaining just as much as you lost before, in just as much time, going just as far, etc.). |
Question: I was once asked the following question by a student I was tutoring; and I was stumped by it:
When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground?
* One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case.
* One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere.
* It's because of the nature of the force. It's independent of the motion of the stone.
I prefer the last explanation - but is it true? And is this the best explanation?
Answer: | >
> One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case.
>
>
>
This is not hypothetical once you take air resistance into account.
>
> One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent.
>
>
>
Assuming constant horizontal velocity, the height vs time diagram will essentially look the same as the height vs horizontal distance diagram. Under that assumption, it is valid to argue about time-of-flight from the symmetry of the trajectory; in general, it's not.
>
> It's because of the nature of the force. It's independent of the motion of the stone.
>
>
>
The motion of the stone depends on the force, so it's hardly independent.
Under constant vertical acceleration, the change in vertical velocity is linear in time. This means that it takes the same amount of time to go from initial velocity $+v$ to 0 as it takes going from 0 to $-v$. In fact, the velocity profiles will be mirror images, and the same distance will have been covered. | Asking "Why" in physics often leads out of physics and into philosophy. Why is there light? Because God said so. Physics only answers questions about how the universe behaves and how to describe that behavior. If a why question can be answered with physics, the answer is "because it follows from a law of physics." A law is just a mathematical description of behavior that has been verified with experiments.
In this case, the answer follows from $F = ma$. If $a$ is constant, this leads to $x = 1/2at^2 + v\_0t + x\_0$. Since you are a physics tutor, you can set up the initial and final conditions and solve for t.
This may well lead to more questions. Why is $F = ma$? Why is there gravity? You could fall back on philosophy, or you could say "I don't know. But experiments show that it works this way."
Why questions are usually about things that are unfamiliar. A young child will ask "Why is there gravity?" A high school student is more likely to ask "Why is $F = ma$?" He may not know the answer to the first question, but he has become used to it.
So the way to answer $F = ma$ questions is to show how it applies to familiar situations. This is why high school physics is full of pictures of springs and ropes and pulleys. |
Question: I was once asked the following question by a student I was tutoring; and I was stumped by it:
When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground?
* One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case.
* One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere.
* It's because of the nature of the force. It's independent of the motion of the stone.
I prefer the last explanation - but is it true? And is this the best explanation?
Answer: | I would say that it is a result of time reversal symmetry. If you consider the projectile at the apex of its trajectory then all that changes under time reversal is the direction of the horizontal component of motion. This means that the trajectory of the particle to get to that point and its trajectory after that point should be identical apart from a mirror inversion. | Conservation of momentum!
=========================
### Force × Time = Impulse = Δ Momentum
Since the average force is the same going up and down, and since the momentum change is the same going up and down as well, the time during which the force is applied must also be the same. |
Question: I was once asked the following question by a student I was tutoring; and I was stumped by it:
When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground?
* One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case.
* One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere.
* It's because of the nature of the force. It's independent of the motion of the stone.
I prefer the last explanation - but is it true? And is this the best explanation?
Answer: | (Non-kinematics math attempt but just some principles)
It is a partial observation in that
* It hits the ground with same speed.
* Angle by which it hits the ground is the same (maybe a direction change)
* It takes equal time to reach to the peak and then hit the ground
They are equally strange coincidences. Which are more fundamental? Consider the following setup: There are two smooth surfaces of a mountain with different angles. You kick a ball from the ground along a surface towards the hill top so that it just reaches the peak. Now if it rolls back from the same surface, all the above entities will be preserved (including the angle as the ball rolls down on the same surface). But if the ball just goes over the peak (with almost zero speed) and rolls down via the other surface, it will reach the ground at in shorter or longer time and with a different angle. But the speed will be the same (conservation of energy!).
So, once an entity is conserved, there we can find a symmetry. The opposite is also true. If there are symmetries, then some thing must be preserved. I heard this is proved mathematically long ago.
In your setup you have all the symmetries and it is no wonder you have conserved entities in the process. | **Assuming that the only forces acting on the stone are the initial force exerted by the hand on the stone AND the force of gravity**, we have the following situation:
Immediately after throwing, the stone has a kinetic energy in the x-direction that never changes (**conservation of energy**) and the stone has a kinetic energy in the y-direction that is constantly being depleted by gravity as it rises to its apex. Once the stone is at its apex (vertical kinetic energy = 0), gravity **works** to restore all of the stone's original vertical kinetic energy as it falls back to its original height.
So, the x-direction **kinetic energy** remained constant throughout the flight and the y-direction **total energy (kinetic + potential)** remained constant throughout the flight, independent of each other. This combination causes the symmetry of the situation.
If air resistance and terminal velocity are introduced into the problem, the character of the problem is completely changed. Even a very simple situation as the one you described can become very complex and confusing to most people. Most people would be stymied by the complexity of the math involved even in this simple situation, let alone the complexity of putting a probe into orbit about Earth. |
Question: I was once asked the following question by a student I was tutoring; and I was stumped by it:
When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground?
* One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case.
* One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere.
* It's because of the nature of the force. It's independent of the motion of the stone.
I prefer the last explanation - but is it true? And is this the best explanation?
Answer: | I would consider that since acceleration is a constant vector pointing downward, that the time the projectiles downward component takes to accelerate from V(initial) to 0 would be the same as the time it takes to accelerate the object from 0 to V(final) | **Assuming that the only forces acting on the stone are the initial force exerted by the hand on the stone AND the force of gravity**, we have the following situation:
Immediately after throwing, the stone has a kinetic energy in the x-direction that never changes (**conservation of energy**) and the stone has a kinetic energy in the y-direction that is constantly being depleted by gravity as it rises to its apex. Once the stone is at its apex (vertical kinetic energy = 0), gravity **works** to restore all of the stone's original vertical kinetic energy as it falls back to its original height.
So, the x-direction **kinetic energy** remained constant throughout the flight and the y-direction **total energy (kinetic + potential)** remained constant throughout the flight, independent of each other. This combination causes the symmetry of the situation.
If air resistance and terminal velocity are introduced into the problem, the character of the problem is completely changed. Even a very simple situation as the one you described can become very complex and confusing to most people. Most people would be stymied by the complexity of the math involved even in this simple situation, let alone the complexity of putting a probe into orbit about Earth. |
Question: I was once asked the following question by a student I was tutoring; and I was stumped by it:
When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground?
* One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case.
* One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere.
* It's because of the nature of the force. It's independent of the motion of the stone.
I prefer the last explanation - but is it true? And is this the best explanation?
Answer: | I think its because both halves of a projectile's trajectory are symmetric in every aspect. The projectile going from its apex position to the ground is just the time reversed version of the projectile going from its initial position to the apex position. | Conservation of momentum!
=========================
### Force × Time = Impulse = Δ Momentum
Since the average force is the same going up and down, and since the momentum change is the same going up and down as well, the time during which the force is applied must also be the same. |
Question: I was once asked the following question by a student I was tutoring; and I was stumped by it:
When one throws a stone why does it take the same amount of time for a stone to rise to its peak and then down to the ground?
* One could say that this is an experimental observation; after one could envisage, hypothetically, where this is not the case.
* One could say that the curve that the stone describes is a parabola; and the two halves are symmetric around the perpendicular line through its apex. But surely the description of the motion of a projectile as a parabola was the outcome of observation; and even if it moves along a parabola, it may (putting observation aside) move along it with its descent speed different from its ascent; or varying; and this, in part, leads to the observation or is justified by the Newtons description of time - it flows equably everywhere.
* It's because of the nature of the force. It's independent of the motion of the stone.
I prefer the last explanation - but is it true? And is this the best explanation?
Answer: | Asking "Why" in physics often leads out of physics and into philosophy. Why is there light? Because God said so. Physics only answers questions about how the universe behaves and how to describe that behavior. If a why question can be answered with physics, the answer is "because it follows from a law of physics." A law is just a mathematical description of behavior that has been verified with experiments.
In this case, the answer follows from $F = ma$. If $a$ is constant, this leads to $x = 1/2at^2 + v\_0t + x\_0$. Since you are a physics tutor, you can set up the initial and final conditions and solve for t.
This may well lead to more questions. Why is $F = ma$? Why is there gravity? You could fall back on philosophy, or you could say "I don't know. But experiments show that it works this way."
Why questions are usually about things that are unfamiliar. A young child will ask "Why is there gravity?" A high school student is more likely to ask "Why is $F = ma$?" He may not know the answer to the first question, but he has become used to it.
So the way to answer $F = ma$ questions is to show how it applies to familiar situations. This is why high school physics is full of pictures of springs and ropes and pulleys. | **Assuming that the only forces acting on the stone are the initial force exerted by the hand on the stone AND the force of gravity**, we have the following situation:
Immediately after throwing, the stone has a kinetic energy in the x-direction that never changes (**conservation of energy**) and the stone has a kinetic energy in the y-direction that is constantly being depleted by gravity as it rises to its apex. Once the stone is at its apex (vertical kinetic energy = 0), gravity **works** to restore all of the stone's original vertical kinetic energy as it falls back to its original height.
So, the x-direction **kinetic energy** remained constant throughout the flight and the y-direction **total energy (kinetic + potential)** remained constant throughout the flight, independent of each other. This combination causes the symmetry of the situation.
If air resistance and terminal velocity are introduced into the problem, the character of the problem is completely changed. Even a very simple situation as the one you described can become very complex and confusing to most people. Most people would be stymied by the complexity of the math involved even in this simple situation, let alone the complexity of putting a probe into orbit about Earth. |