问:
How exactly CSS works?
Currently, I am stack with CSS. I can't understand how exactly CSS works.
If I want to apply "border: 1px solid red" to a CSS parent element then it is only applied to parent element but not other elements (children) that inside this parent. But If I apply "color: red" then the color property is applied to every single child inside the parent (Including parent itself).

Example-1:

```<code><div class="parent">
    Inside parent class
    <div class="child">Inside child class 1</div>
    <div class="child">Inside child class 2</div>
</div>
</code>```

```<code>.parent {
  border: 1px solid red;
}
</code>```

Example-2:

```<code><div class="parent">
    Inside parent class
    <div class="child">Inside child class 1</div>
    <div class="child">Inside child class 2</div>
</div>
</code>```

```<code>.parent {
  color: red;
}
</code>```

why example-1 works for the parent element, not for children.
Example-2 works fine what I expected.

答:
Some CSS properties do not inherit the computed value of the element’s parent.
You could use the inherit keyword on the child div elements’ border to let them inherit the same border as their parent

Try this:

```<code><html>
<head>
    <title>test</title>
    <style>
        .parent {
          border: 1px solid red;
        }

        .child{
            border: inherit;
        }
    </style>
</head>
<body>
    <div class="parent">
        Inside parent class
        <div class="child">Inside child class 1</div>
        <div class="child">Inside child class 2</div>
    </div>
</body>
</code>```

Title: How exactly CSS works?

Body:
Currently, I am stack with CSS. I can't understand how exactly CSS works.
If I want to apply "border: 1px solid red" to a CSS parent element then it is only applied to parent element but not other elements (children) that inside this parent. But If I apply "color: red" then the color property is applied to every single child inside the parent (Including parent itself).

Example-1:

    Inside parent class

Inside child class 1

Inside child class 2

.parent {
  border: 1px solid red;
}

Example-2:

    Inside parent class

Inside child class 1

Inside child class 2

.parent {
  color: red;
}

why example-1 works for the parent element, not for children.
Example-2 works fine what I expected.

Body:
Some CSS properties do not inherit the computed value of the element’s parent.
You could use the inherit keyword on the child div elements’ border to let them inherit the same border as their parent

Try this:

<html>
<head>
    <title>test</title>
    <style>
        .parent {
          border: 1px solid red;
        }

        .child{
            border: inherit;
        }
    </style>
</head>
<body>
    <div class="parent">
        Inside parent class
        <div class="child">Inside child class 1</div>
        <div class="child">Inside child class 2</div>
    </div>
</body>


来源: stackexchange

问:
I cannot initialize Flask SocketIO with app.from_object parameter
I have an app.py file where I initialize my app. I have another file (run.py) where I run Flask server from. Everything works with a standard flask app. However I am trying to integrate flask-socketio and it keeps failing with different errors depending on how I try to initialize the app.

I have tried the following ways to initialize flask-socketio:

```<code>socketio = SocketIO(app.config.from_object(app_config[env_name]))
socketio = SocketIO(app, **app.config[env_name])
socketio = SocketIO(**app.config[env_name])
</code>```

Here is the relevant code from my app.py file.

```<code>def create_app(env_name):
  """
  Create app
  """

  # app initiliazation
  app = Flask(__name__)

  app.config.from_object(app_config[env_name])
  async_mode = None

  # initializing bcrypt and db
  bcrypt.init_app(app)
  db.init_app(app)
  socketio = SocketIO(app.config.from_object(app_config[env_name]))
  return socketio
</code>```

My run.py file looks like this:

```<code>rom src.app import create_app

load_dotenv(find_dotenv())

env_name = os.getenv('FLASK_ENV')
app = create_app(env_name)

if __name__ == '__main__':
  port = os.getenv('PORT')
  # run app
  app.run(app, host='0.0.0.0', port=port)
</code>```

You will notice I am importing from a config.py file. That is where my environment variables are being for (dev, test, prod). Each environment is it's own class. For example:

```<code>class Development(object):
    """
    Development environment configuration
    """
    DEBUG = True
    TESTING = False
    SQLALCHEMY_TRACK_MODIFICATIONS=False
    JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY')
    SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
    ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
    UPLOADED_FILES_DEST = os.getenv('UPLOADED_FILES_DEST')
</code>```

As you can see, most of those values are set in an environment variable since it is bad practice to put such sensitive information into a repo.

I would like to be able to initialize flask-socketio so I can setup rooms where users can share location based information.

Thanks in advance.

答:
The Flask-SocketIO extensions takes the application instance as an argument. You should configure the application and then initialize it. For example:

app.config.from_object(app_config[env_name])
socketio = SocketIO(app)
```

ContentLicense: CC BY-SA 4.0

Body:
I have an app.py file where I initialize my app. I have another file (run.py) where I run Flask server from. Everything works with a standard flask app. However I am trying to integrate flask-socketio and it keeps failing with different errors depending on how I try to initialize the app.

I have tried the following ways to initialize flask-socketio:

socketio = SocketIO(app.config.from_object(app_config[env_name]))
socketio = SocketIO(app, **app.config[env_name])
socketio = SocketIO(**app.config[env_name])

Here is the relevant code from my app.py file.

def create_app(env_name):
  """
  Create app
  """

  # app initiliazation
  app = Flask(__name__)

  app.config.from_object(app_config[env_name])
  async_mode = None

  # initializing bcrypt and db
  bcrypt.init_app(app)
  db.init_app(app)
  socketio = SocketIO(app.config.from_object(app_config[env_name]))
  return socketio

My run.py file looks like this:

rom src.app import create_app

load_dotenv(find_dotenv())

env_name = os.getenv('FLASK_ENV')
app = create_app(env_name)

if __name__ == '__main__':
  port = os.getenv('PORT')
  # run app
  app.run(app, host='0.0.0.0', port=port)

You will notice I am importing from a config.py file. That is where my environment variables are being for (dev, test, prod). Each environment is it's own class. For example:

class Development(object):
    """
    Development environment configuration
    """
    DEBUG = True
    TESTING = False
    SQLALCHEMY_TRACK_MODIFICATIONS=False
    JWT_SECRET_KEY = os.getenv('JWT_SECRET_KEY')
    SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
    ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
    UPLOADED_FILES_DEST = os.getenv('UPLOADED_FILES_DEST')

As you can see, most of those values are set in an environment variable since it is bad practice to put such sensitive information into a repo.

I would like to be able to initialize flask-socketio so I can setup rooms where users can share location based information.

Thanks in advance.


问:
Scenarios from cucumber .feature file not running
I have hundreds of feature files, all under same folder structure,Most run fine (using Junit) but some of them just do not run. All I get in console output is:-

```<code>     Feature: Verify  Customer Registration/ Sign Up

    @Web @Regression @P-High
  Scenario: Verify the available fields on the Sign Up page

    Given user launches the browser and navigates to "HOME" page

    When user clicks on SignIn link from global header

    And clicks on SignUp link from SignIn page

    Then Verify below Sub/Main Module of My Account

0 Scenarios ()
4 Steps (5 skipped)
0m0.000s
</code>```

I'v made sure that all the steps have stepdefinitions glued to it.

```<code>package com.aso.qe.test.runner;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class) @CucumberOptions(

    features="src/test/resources/features/web",
    glue="com.aso.qe.test.stepdefinition.web",
    tags = "@P-High",
)
 public class WebTestRunner{     }
</code>```

Every feature file with tag @P-High has same issue
while every other feature file without this tag runs just fine.

答:
It turned out Not to be a tag or code issue. Each one of those files not running had scenario details on next line instead of right in front of keyword scenario (see example).

Scenario:
Check Flight Status

Once I fixed above everything was smooth.

Body:
I have hundreds of feature files, all under same folder structure,Most run fine (using Junit) but some of them just do not run. All I get in console output is:-

     Feature: Verify  Customer Registration/ Sign Up

    @Web @Regression @P-High
  Scenario: Verify the available fields on the Sign Up page

    Given user launches the browser and navigates to "HOME" page

    When user clicks on SignIn link from global header

    And clicks on SignUp link from SignIn page

    Then Verify below Sub/Main Module of My Account

0 Scenarios ()
4 Steps (5 skipped)
0m0.000s

I'v made sure that all the steps have stepdefinitions glued to it.

package com.aso.qe.test.runner;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class) @CucumberOptions(

    features="src/test/resources/features/web",
    glue="com.aso.qe.test.stepdefinition.web",
    tags = "@P-High",
)
 public class WebTestRunner{     }

Every feature file with tag @P-High has same issue
while every other feature file without this tag runs just fine.


问:
Calling an Object by an Integer
I'm trying to edit some objects texts with this:

```<code>' Textbox1
' Textbox2
' Textbox3

Sub Change_Text()

    Dim i As Integer

    For i = 1 To 3

        UserForm1.Textbox & i = "Hi"

    Next i

End Sub
</code>```

I think the code explain my problem, of course it's returning an error, I don't have idea what to do...

答:
You could do it like that</p>

```<code>For i = 1 To 3
    Controls("Textbox" & i) = "Hi"
Next i
</code>```

Title: Calling an Object by an Integer

Body:
I'm trying to edit some objects texts with this:

' Textbox1
' Textbox2
' Textbox3

Sub Change_Text()

    Dim i As Integer

    For i = 1 To 3

        UserForm1.Textbox & i = "Hi"

    Next i

End Sub

I think the code explain my problem, of course it's returning an error, I don't have idea what to do...

Body:
You could do it like that

For i = 1 To 3
    Controls("Textbox" & i) = "Hi"
Next i


问:
Accessing Beyond the malloc()'d Memory
My question is when I allocate memory for go variable as in the following code I can reach the area which I didn't allocate ( in this case after the first one). So what is the limit of this top reaching point because when I try to print or access thousandth place I get an segmentation error. How does OS(Ubuntu 18.04) limiting this area ?</p>

```<code>#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(){
    int *go=NULL;
    go = malloc(sizeof(int)*1);
    *go = 190;
    *(go+1)=20;
    *(go+2)=-13;
    *(go+3)=450;
    *(go+4)=140;
    *(go+5)=190;
    printf("%d\n",*(go));
    printf("%d\n",*(go+1));
    printf("%d\n",*(go+2));
    printf("%d\n",*(go+3));
    printf("%d\n",*(go+4));
    printf(">>>%d\n",*(go+5));
    return 0;
}
</code>```

答:
Address space is allocated by the application from the OS.   These allocations have a granularity which is a function of the hardware, the operating system and the parameters to the malloc library.   Few architectures have bytewise granularity.

Malloc is not typically an operating system intereface, rather it is a highly usable library built upon less sophisticated mechanisms.  Malloc determines what granularity it wants to grow and shrink the address space by, and constructs data structures to track the memory at a size that is convenient to it.   For example, it might never return less than a 64byte object.   You might be able to determine this using realloc:  allocate a set of small objects (say 1 byte), and find the two addresses that are closest together, and call grow() below with the lower pointer and this difference.   It may be possible you have an unconventional malloc, and this won't work....

```<code>int grow(void *p, int maxdiff) {
    int i;

    for (i = 2; i < maxdiff; i++) {
        void *t = realloc(p, i);
        if (t != p) {
            return i;
        }
    }
    return -1;
}
</code>```

For a good tutorial on malloc(), read and understand the implementation of it in K&R's "The C Programming Language".

Title: Accessing Beyond the malloc()'d Memory

Body:
My question is when I allocate memory for go variable as in the following code I can reach the area which I didn't allocate ( in this case after the first one). So what is the limit of this top reaching point because when I try to print or access thousandth place I get an segmentation error. How does OS(Ubuntu 18.04) limiting this area ?

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(){
    int *go=NULL;
    go = malloc(sizeof(int)*1);
    *go = 190;
    *(go+1)=20;
    *(go+2)=-13;
    *(go+3)=450;
    *(go+4)=140;
    *(go+5)=190;
    printf("%d\n",*(go));
    printf("%d\n",*(go+1));
    printf("%d\n",*(go+2));
    printf("%d\n",*(go+3));
    printf("%d\n",*(go+4));
    printf(">>>%d\n",*(go+5));
    return 0;
}

Body:
Address space is allocated by the application from the OS.   These allocations have a granularity which is a function of the hardware, the operating system and the parameters to the malloc library.   Few architectures have bytewise granularity.

Malloc is not typically an operating system intereface, rather it is a highly usable library built upon less sophisticated mechanisms.  Malloc determines what granularity it wants to grow and shrink the address space by, and constructs data structures to track the memory at a size that is convenient to it.   For example, it might never return less than a 64byte object.   You might be able to determine this using realloc:  allocate a set of small objects (say 1 byte), and find the two addresses that are closest together, and call grow() below with the lower pointer and this difference.   It may be possible you have an unconventional malloc, and this won't work....

int grow(void *p, int maxdiff) {
    int i;

    for (i = 2; i < maxdiff; i++) {
        void *t = realloc(p, i);
        if (t != p) {
            return i;
        }
    }
    return -1;
}

For a good tutorial on malloc(), read and understand the implementation of it in K&R's "The C Programming Language".


问:
Nested list comprehension with generators
I have some strange behavior on python 3.7 with a nested list comprehension that involves a generator.

This works:

```<code>i = range(20)
n = [1, 2, 3]
result = [min(x + y for x in i) for y in n]
</code>```

It does not work if i is a generator:

```<code>i = (p for p in range(20))
n = [1, 2, 3]
result = [min(x + y for x in i) for y in n]
</code>```

This raises a ValueError: min() arg is an empty sequence

Now even if the generator i is wrapped with list it still creates the same error:

```<code>i = (p for p in range(20))
n = [1, 2, 3]
result = [min(x + y for x in list(i)) for y in n]
</code>```

Is this a python bug or is it expected behavior? If it is expected behavior, can you explain why this does not work?

答:
The generator is emptied after the first for loop for both for x in i or for x in list(i), instead you need to convert the generator to a list, (which essentially iterates over the generator and empties it) beforehand and use that list

Note that this essentially defeats the purpose of a generator, since now this becomes the same as the first approach

```<code>In [14]: list(range(20)) ==  list(p for p in range(20))
Out[14]: True
</code>```

Hence the updated code will be

```<code>#Create generator and convert to list
i = list(p for p in range(20))

n = [1, 2, 3]
#Use that list in the list comprehension
result = [min(x + y for x in i) for y in n]
print(result)
</code>```

The output will be

```<code>[1, 2, 3]
</code>```

Hence the better approach hence is to stick with the first approach itself, or you can have the generator inline, which, again is the same as the first approach with range

```<code>n = [1, 2, 3]
result = [min(x + y for x in (p for p in range(20))) for y in n]
print(result)
#[1, 2, 3]
</code>```

Body:
I have some strange behavior on python 3.7 with a nested list comprehension that involves a generator.

This works:

i = range(20)
n = [1, 2, 3]
result = [min(x + y for x in i) for y in n]

It does not work if i is a generator:

i = (p for p in range(20))
n = [1, 2, 3]
result = [min(x + y for x in i) for y in n]

This raises a ValueError: min() arg is an empty sequence

Now even if the generator i is wrapped with list it still creates the same error:

i = (p for p in range(20))
n = [1, 2, 3]
result = [min(x + y for x in list(i)) for y in n]

Is this a python bug or is it expected behavior? If it is expected behavior, can you explain why this does not work?

Body:
The generator is emptied after the first for loop for both for x in i or for x in list(i), instead you need to convert the generator to a list, (which essentially iterates over the generator and empties it) beforehand and use that list

Note that this essentially defeats the purpose of a generator, since now this becomes the same as the first approach

In [14]: list(range(20)) ==  list(p for p in range(20))
Out[14]: True

Hence the updated code will be

#Create generator and convert to list
i = list(p for p in range(20))

n = [1, 2, 3]
#Use that list in the list comprehension
result = [min(x + y for x in i) for y in n]
print(result)

The output will be

[1, 2, 3]

Hence the better approach hence is to stick with the first approach itself, or you can have the generator inline, which, again is the same as the first approach with range

n = [1, 2, 3]
result = [min(x + y for x in (p for p in range(20))) for y in n]
print(result)
#[1, 2, 3]


问:
What is the time-complexity of this function?
What is the Time complexity of this algorithm?

I understand that array.map have O(n) where n is the length of the array. I have also read that string.slice() also have a time complexity of O(n). However, since slice is dependent on the length of the word, is it right for me to say that the Time Complexity is 0(n + m), where m is the length of the words.

```<code>function sentenceCaps(str) {
  if (!str) {
    return new Error('empty string');
  }

  let arr = str.toLowerCase().split(' ');
  let results = arr.map(word => {return word[0].toUpperCase()+ word.slice(1)});
  return results.join(' ');
}
</code>```

答:
What is the time-complexity of this function?

O(n).

is it right for me to say that the Time Complexity is 0(n + m), where m is the length of the words.

No, because m is roughly equal to n. Even if we assume that String.slice() is O(n) in the length of the result, the total number of letters sliced is a fraction of n, so it is already factored into the complexity. In practice, this is probably a constant-time operation.

(Analyzing the time complexity of any Javascript code is a little fuzzy, as the language makes no guarantees about the time complexity of any operations, and the runtime is capable of making some extremely powerful optimizations.)

Body:
What is the Time complexity of this algorithm?

I understand that array.map have O(n) where n is the length of the array. I have also read that string.slice() also have a time complexity of O(n). However, since slice is dependent on the length of the word, is it right for me to say that the Time Complexity is 0(n + m), where m is the length of the words.

function sentenceCaps(str) {
  if (!str) {
    return new Error('empty string');
  }

  let arr = str.toLowerCase().split(' ');
  let results = arr.map(word => {return word[0].toUpperCase()+ word.slice(1)});
  return results.join(' ');
}


问:
Different behavior due to different "looping styles"
I have a simple problem. Navigate to a certain line in a fine, and delete everything after that. I use the suitable file.truncate() call. However, the two snippets of code below behave differently.

1)

```<code>with open(file, "a+b", 1) as f:
  #Navigate to the MARKER
  while True:
    line = f.readline()
    if MARKER in line:
      f.truncate()
      f.write(stuff)
      break
</code>```

2)

```<code>with open(file, "a+b", 1) as f:
  #Navigate to the MARKER
  for line in f:
    if MARKER in line:
      f.truncate()
      f.write(stuff)
      break
</code>```

(1) behaves as expected. However in case of (2), the file in truncated several lines after the MARKER is found. I speculate that there is some buffering going on, but as you can see, I explicitly define the buffering behavior as "line buffered" to the open() call.

Any thoughts? I would like to use the more intuitive "for line in file" syntax...

答:
That's because of the 'a' mode:

a

Open for appending (writing at end
  of file). The file is created if it
  does not exist. The stream is
  positioned at the end of the file.

a+

Open for reading and appending
  (writing at end of file). The file is
  created if it does not exist. The
  initial file position for reading is
  at the beginning of the file, but
  output is always appended to the end of the file.

http://linux.die.net/man/3/fopen

.

EDIT

My above answer is wrong.

I already knew that looping over the lines of a file uses a read-ahead of buffer, but I believed that truncate() would trigger the file's pointer to be moved to the end of the file, since, as far as I know, truncating a file consists in writing a little sequence of bytes called EOF meaning end-of-file, and 'a' mode always provoke writing at the end of a file  whatever is the position of the file's pointer just before the moment of writing.

Well, it's not like that, I should have verified by executing a code. So my answer deserves a downvote.

But downvoting without any explanation is shabby and frustrating in such a case in which the error in this answer isn't evident.

.

The following code shows that the file's pointer isn't moved to the end of the file before the action of truncate().

To clear things, the file 'fileA' is composed of lines having each a length of 100 characters ( '\r\n comprised), ending like that ('\r\n' are not visible here):

```<code>....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000100
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000200
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000300
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000400
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000500
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000600
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000700
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000800
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000900
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00001000
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00001100
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00001200
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00001300
............................
</code>```

The code:

```<code>print '\n===================== 1 ==================\n'

from os.path import getsize

# length of ecr is 90 :
ecr = 10*'a' + 10*'b' + 10*'c' + 10*'d' + 10*'e' +\
      10*'f' + 10*'g' + 10*'h' + 10*'i'

# creation of a file whose length exceeds the reading buffer's size
with open('fileA.txt','wb') as f:
    for i in xrange(100,53001,100): # 530 turns of iteration
        f.write(ecr + str(i).zfill(8) + '\r\n')
        # Length of each written line is 100 :
        # 90 (ecr) + 8 (str(i).zfill(8)) + 2 ('\r\n')
        # File's length will be 53000

print 'size of fileA before truncating : ',getsize('fileA.txt')
# truncating file at uncontroled position
with open('fileA.txt','a+b') as g:
    for line in g:
        if '00000800' in line:
            print repr(line[78:]),'  g.tell()==',g.tell()
            # at this point, 800 characters should have been read
            # in the file if there wasn't a reading buffer
            g.truncate()
print 'size of fileA after truncating : ',getsize('fileA.txt')
</code>```

result

```<code>===================== 1 ==================

size of fileA before truncating :  53000
'hhiiiiiiiiii00000800\r\n'   g.tell()== 8192
size of fileA after truncating :  8192
</code>```

.

So, AKX and Fenisko are right when evoking the buffer (however they didn't test this hypothesis more than me) because the opening of the file in 'a' mode have no influence on the action of truncate(). I think it is what the upper cased sentence in the following extract of the doc says:

file.truncate([size]) Truncate the
  file’s size. If the optional size
  argument is present, the file is
  truncated to (at most) that size. The
  size defaults to the current position.
  THE CURRENT FILE POSITION IS NOT
  CHANGED

http://docs.python.org/library/stdtypes.html#file.truncate

Until now, I had never understood this sentence.

.

As pointed out by AKX, the size of the buffer is 8192 .... for the first reading.

But for the next readings, the buffer is manifestly 10240 characters long:

```<code>print '\n=================== 2 ====================\n'

from os.path import getsize

# length of ecr is 90 :
ecr = 10*'a' + 10*'b' + 10*'c' + 10*'d' + 10*'e' +\
      10*'f' + 10*'g' + 10*'h' + 10*'i'

# creation of a file whose length exceeds the reading buffer's size
with open('fileA.txt','wb') as f:
    for i in xrange(100,53001,100): # 530 turns of iteration
        f.write(ecr + str(i).zfill(8) + '\r\n')
        # length of each written line is 100
        # file's length will be 53000

print 'size of fileA before truncating : ',getsize('fileA.txt')
# truncating file at uncontroled position
with open('fileA.txt','a+b') as g:
    for line in g:
        if '00008100' in line:
            print repr(line[78:]),'  g.tell()==',g.tell()
            # at this point, 800 characters should have been read
            # in the file if there wasn't a reading buffer
            g.truncate()
print 'size of fileA after truncating : ',getsize('fileA.txt')

# -----------

print
# creation of a file whose length exceeds the reading buffer's size
with open('fileA.txt','wb') as f:
    for i in xrange(100,53001,100): # 530 turns of iteration
        f.write(ecr + str(i).zfill(8) + '\r\n')
        # length of each written line is 100
        # file's length will be 53000

print 'size of fileA before truncating : ',getsize('fileA.txt')
# truncating file at uncontroled position
with open('fileA.txt','a+b') as g:
    for line in g:
        if '00008200' in line:
            print repr(line[78:]),'  g.tell()==',g.tell()
            # at this point, 800 characters should have been read
            # in the file if there wasn't a reading buffer
            g.truncate()
print 'size of fileA after truncating : ',getsize('fileA.txt')

# -----------

print
# creation of a file whose length exceeds the reading buffer's size
with open('fileA.txt','wb') as f:
    for i in xrange(100,53001,100): # 530 turns of iteration
        f.write(ecr + str(i).zfill(8) + '\r\n')
        # length of each written line is 100
        # file's length will be 53000

print 'size of fileA before truncating : ',getsize('fileA.txt')
# truncating file at uncontroled position
with open('fileA.txt','a+b') as g:
    for line in g:
        if '00018400' in line:
            print repr(line[78:]),'  g.tell()==',g.tell()
            # at this point, 800 characters should have been read
            # in the file if there wasn't a reading buffer
            g.truncate()
print 'size of fileA after truncating : ',getsize('fileA.txt')

# -----------

print
# creation of a file whose length exceeds the reading buffer's size
with open('fileA.txt','wb') as f:
    for i in xrange(100,53001,100): # 530 turns of iteration
        f.write(ecr + str(i).zfill(8) + '\r\n')
        # length of each written line is 100
        # file's length will be 53000

print 'size of fileA before truncating : ',getsize('fileA.txt')
# truncating file at uncontroled position
with open('fileA.txt','a+b') as g:
    for line in g:
        if '00018500' in line:
            print repr(line[78:]),'  g.tell()==',g.tell()
            # at this point, 800 characters should have been read
            # in the file if there wasn't a reading buffer
            g.truncate()
print 'size of fileA after truncating : ',getsize('fileA.txt')
</code>```

result

```<code>=================== 2 ====================

size of fileA before truncating :  53000
'hhiiiiiiiiii00008100\r\n'   g.tell()== 8192
size of fileA after truncating :  8192

size of fileA before truncating :  53000
'hhiiiiiiiiii00008200\r\n'   g.tell()== 18432
size of fileA after truncating :  18432

size of fileA before truncating :  53000
'hhiiiiiiiiii00018400\r\n'   g.tell()== 18432
size of fileA after truncating :  18432

size of fileA before truncating :  53000
'hhiiiiiiiiii00018500\r\n'   g.tell()== 28672
size of fileA after truncating :  28672
</code>```

.

By the way, truncate() doesn't close the file:

```<code>print '\n=================== 3 ====================\n'

from os.path import getsize

# length of ecr is 90 :
ecr = 10*'a' + 10*'b' + 10*'c' + 10*'d' + 10*'e' +\
      10*'f' + 10*'g' + 10*'h' + 10*'i'

# creation of a file whose length exceeds the reading buffer's size
with open('fileA.txt','wb') as f:
    for i in xrange(100,53001,100): # 530 turns of iteration
        f.write(ecr + str(i).zfill(8) + '\r\n')
        # length of each written line is 100
        # file's length will be 53000

print 'size of fileA before truncating : ',getsize('fileA.txt')
with open('fileA.txt','a+b') as g:
    for line in g:
        if '00000200' in line:
            print repr(line[78:]),'  g.tell()==',g.tell()
            # at this point, 800 characters should have been read
            # if there wasn't a buffer
            g.truncate()
    g.seek(6000,0)
    k = 0
    for li in g:
        k+=1
        print 'k==',k,'   ',repr(li[-32:])
        if k==7:
            break
print 'size of fileA after truncating : ',getsize('fileA.txt')
</code>```

result

```<code>=================== 3 ====================

size of fileA before truncating :  53000
'hhiiiiiiiiii00000200\r\n'   g.tell()== 8192
k== 1     'gghhhhhhhhhhiiiiiiiiii00006100\r\n'
k== 2     'gghhhhhhhhhhiiiiiiiiii00006200\r\n'
k== 3     'gghhhhhhhhhhiiiiiiiiii00006300\r\n'
k== 4     'gghhhhhhhhhhiiiiiiiiii00006400\r\n'
k== 5     'gghhhhhhhhhhiiiiiiiiii00006500\r\n'
k== 6     'gghhhhhhhhhhiiiiiiiiii00006600\r\n'
k== 7     'gghhhhhhhhhhiiiiiiiiii00006700\r\n'
size of fileA after truncating :  8192
</code>```

But if a writing instruction is placed just after truncate(), the behavior of the program becomes incoherent. Try it.

ContentLicense: CC BY-SA 3.0

Body:
I have a simple problem. Navigate to a certain line in a fine, and delete everything after that. I use the suitable file.truncate() call. However, the two snippets of code below behave differently.

1)

with open(file, "a+b", 1) as f:
  #Navigate to the MARKER
  while True:
    line = f.readline()
    if MARKER in line:
      f.truncate()
      f.write(stuff)
      break

2)

with open(file, "a+b", 1) as f:
  #Navigate to the MARKER
  for line in f:
    if MARKER in line:
      f.truncate()
      f.write(stuff)
      break

(1) behaves as expected. However in case of (2), the file in truncated several lines after the MARKER is found. I speculate that there is some buffering going on, but as you can see, I explicitly define the buffering behavior as "line buffered" to the open() call.

Any thoughts? I would like to use the more intuitive "for line in file" syntax...

Body:
That's because of the 'a' mode:

a

Open for appending (writing at end
  of file). The file is created if it
  does not exist. The stream is
  positioned at the end of the file.

a+

Open for reading and appending
  (writing at end of file). The file is
  created if it does not exist. The
  initial file position for reading is
  at the beginning of the file, but
  output is always appended to the end of the file.

http://linux.die.net/man/3/fopen

.

EDIT

My above answer is wrong.

I already knew that looping over the lines of a file uses a read-ahead of buffer, but I believed that truncate() would trigger the file's pointer to be moved to the end of the file, since, as far as I know, truncating a file consists in writing a little sequence of bytes called EOF meaning end-of-file, and 'a' mode always provoke writing at the end of a file  whatever is the position of the file's pointer just before the moment of writing.

Well, it's not like that, I should have verified by executing a code. So my answer deserves a downvote.

But downvoting without any explanation is shabby and frustrating in such a case in which the error in this answer isn't evident.

.

The following code shows that the file's pointer isn't moved to the end of the file before the action of truncate().

To clear things, the file 'fileA' is composed of lines having each a length of 100 characters ( '\r\n comprised), ending like that ('\r\n' are not visible here):

....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000100
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000200
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000300
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000400
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000500
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000600
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000700
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000800
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00000900
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00001000
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00001100
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00001200
....ffffffgggggggggghhhhhhhhhhiiiiiiiiii00001300
............................

The code:

print '\n===================== 1 ==================\n'

from os.path import getsize

# length of ecr is 90 :
ecr = 10*'a' + 10*'b' + 10*'c' + 10*'d' + 10*'e' +\
      10*'f' + 10*'g' + 10*'h' + 10*'i'

# creation of a file whose length exceeds the reading buffer's size
with open('fileA.txt','wb') as f:
    for i in xrange(100,53001,100): # 530 turns of iteration
        f.write(ecr + str(i).zfill(8) + '\r\n')
        # Length of each written line is 100 :
        # 90 (ecr) + 8 (str(i).zfill(8)) + 2 ('\r\n')
        # File's length will be 53000

print 'size of fileA before truncating : ',getsize('fileA.txt')
# truncating file at uncontroled position
with open('fileA.txt','a+b') as g:
    for line in g:
        if '00000800' in line:
            print repr(line[78:]),'  g.tell()==',g.tell()
            # at this point, 800 characters should have been read
            # in the file if there wasn't a reading buffer
            g.truncate()
print 'size of fileA after truncating : ',getsize('fileA.txt')

result

===================== 1 ==================

size of fileA before truncating :  53000
'hhiiiiiiiiii00000800\r\n'   g.tell()== 8192
size of fileA after truncating :  8192

.

So, AKX and Fenisko are right when evoking the buffer (however they didn't test this hypothesis more than me) because the opening of the file in 'a' mode have no influence on the action of truncate(). I think it is what the upper cased sentence in the following extract of the doc says:

file.truncate([size]) Truncate the
  file’s size. If the optional size
  argument is present, the file is
  truncated to (at most) that size. The
  size defaults to the current position.
  THE CURRENT FILE POSITION IS NOT
  CHANGED

http://docs.python.org/library/stdtypes.html#file.truncate

Until now, I had never understood this sentence.

.

As pointed out by AKX, the size of the buffer is 8192 .... for the first reading.

But for the next readings, the buffer is manifestly 10240 characters long:

print '\n=================== 2 ====================\n'

from os.path import getsize

# length of ecr is 90 :
ecr = 10*'a' + 10*'b' + 10*'c' + 10*'d' + 10*'e' +\
      10*'f' + 10*'g' + 10*'h' + 10*'i'

# creation of a file whose length exceeds the reading buffer's size
with open('fileA.txt','wb') as f:
    for i in xrange(100,53001,100): # 530 turns of iteration
        f.write(ecr + str(i).zfill(8) + '\r\n')
        # length of each written line is 100
        # file's length will be 53000

print 'size of fileA before truncating : ',getsize('fileA.txt')
# truncating file at uncontroled position
with open('fileA.txt','a+b') as g:
    for line in g:
        if '00008100' in line:
            print repr(line[78:]),'  g.tell()==',g.tell()
            # at this point, 800 characters should have been read
            # in the file if there wasn't a reading buffer
            g.truncate()
print 'size of fileA after truncating : ',getsize('fileA.txt')

# -----------

print
# creation of a file whose length exceeds the reading buffer's size
with open('fileA.txt','wb') as f:
    for i in xrange(100,53001,100): # 530 turns of iteration
        f.write(ecr + str(i).zfill(8) + '\r\n')
        # length of each written line is 100
        # file's length will be 53000

print 'size of fileA before truncating : ',getsize('fileA.txt')
# truncating file at uncontroled position
with open('fileA.txt','a+b') as g:
    for line in g:
        if '00008200' in line:
            print repr(line[78:]),'  g.tell()==',g.tell()
            # at this point, 800 characters should have been read
            # in the file if there wasn't a reading buffer
            g.truncate()
print 'size of fileA after truncating : ',getsize('fileA.txt')

# -----------

print
# creation of a file whose length exceeds the reading buffer's size
with open('fileA.txt','wb') as f:
    for i in xrange(100,53001,100): # 530 turns of iteration
        f.write(ecr + str(i).zfill(8) + '\r\n')
        # length of each written line is 100
        # file's length will be 53000

print 'size of fileA before truncating : ',getsize('fileA.txt')
# truncating file at uncontroled position
with open('fileA.txt','a+b') as g:
    for line in g:
        if '00018400' in line:
            print repr(line[78:]),'  g.tell()==',g.tell()
            # at this point, 800 characters should have been read
            # in the file if there wasn't a reading buffer
            g.truncate()
print 'size of fileA after truncating : ',getsize('fileA.txt')

# -----------

print
# creation of a file whose length exceeds the reading buffer's size
with open('fileA.txt','wb') as f:
    for i in xrange(100,53001,100): # 530 turns of iteration
        f.write(ecr + str(i).zfill(8) + '\r\n')
        # length of each written line is 100
        # file's length will be 53000

print 'size of fileA before truncating : ',getsize('fileA.txt')
# truncating file at uncontroled position
with open('fileA.txt','a+b') as g:
    for line in g:
        if '00018500' in line:
            print repr(line[78:]),'  g.tell()==',g.tell()
            # at this point, 800 characters should have been read
            # in the file if there wasn't a reading buffer
            g.truncate()
print 'size of fileA after truncating : ',getsize('fileA.txt')

result

=================== 2 ====================

size of fileA before truncating :  53000
'hhiiiiiiiiii00008100\r\n'   g.tell()== 8192
size of fileA after truncating :  8192

size of fileA before truncating :  53000
'hhiiiiiiiiii00008200\r\n'   g.tell()== 18432
size of fileA after truncating :  18432

size of fileA before truncating :  53000
'hhiiiiiiiiii00018400\r\n'   g.tell()== 18432
size of fileA after truncating :  18432

size of fileA before truncating :  53000
'hhiiiiiiiiii00018500\r\n'   g.tell()== 28672
size of fileA after truncating :  28672

.

By the way, truncate() doesn't close the file:

print '\n=================== 3 ====================\n'

from os.path import getsize

# length of ecr is 90 :
ecr = 10*'a' + 10*'b' + 10*'c' + 10*'d' + 10*'e' +\
      10*'f' + 10*'g' + 10*'h' + 10*'i'

# creation of a file whose length exceeds the reading buffer's size
with open('fileA.txt','wb') as f:
    for i in xrange(100,53001,100): # 530 turns of iteration
        f.write(ecr + str(i).zfill(8) + '\r\n')
        # length of each written line is 100
        # file's length will be 53000

print 'size of fileA before truncating : ',getsize('fileA.txt')
with open('fileA.txt','a+b') as g:
    for line in g:
        if '00000200' in line:
            print repr(line[78:]),'  g.tell()==',g.tell()
            # at this point, 800 characters should have been read
            # if there wasn't a buffer
            g.truncate()
    g.seek(6000,0)
    k = 0
    for li in g:
        k+=1
        print 'k==',k,'   ',repr(li[-32:])
        if k==7:
            break
print 'size of fileA after truncating : ',getsize('fileA.txt')

result

=================== 3 ====================

size of fileA before truncating :  53000
'hhiiiiiiiiii00000200\r\n'   g.tell()== 8192
k== 1     'gghhhhhhhhhhiiiiiiiiii00006100\r\n'
k== 2     'gghhhhhhhhhhiiiiiiiiii00006200\r\n'
k== 3     'gghhhhhhhhhhiiiiiiiiii00006300\r\n'
k== 4     'gghhhhhhhhhhiiiiiiiiii00006400\r\n'
k== 5     'gghhhhhhhhhhiiiiiiiiii00006500\r\n'
k== 6     'gghhhhhhhhhhiiiiiiiiii00006600\r\n'
k== 7     'gghhhhhhhhhhiiiiiiiiii00006700\r\n'
size of fileA after truncating :  8192

But if a writing instruction is placed just after truncate(), the behavior of the program becomes incoherent. Try it.


答:
In both of your last examples, you try to iterate on the generator again after it got exhausted.

In your last example, list(i) is evaluated again for each value of y, so i will be exhausted after the first run.

You have to make a list of the values it yields once before, as in:

```<code>i = (p for p in range(20))
n = [1, 2, 3]
list_i = list(i)
result = [min(x + y for x in list_i) for y in n]
</code>```

Title: Nested list comprehension with generators

Body:
In both of your last examples, you try to iterate on the generator again after it got exhausted.

In your last example, list(i) is evaluated again for each value of y, so i will be exhausted after the first run.

You have to make a list of the values it yields once before, as in:

i = (p for p in range(20))
n = [1, 2, 3]
list_i = list(i)
result = [min(x + y for x in list_i) for y in n]


问:
HTTP 500 error when trying to produce JSON using REST
Trying to produce JSON code from database entries using rest but I am getting a HTTP 500 error code

```<code>
@Path("product")
public class ProductResource {
    @GET
    @Produces({ MediaType.APPLICATION_XML })
    public List<Product> getProductInformation() {
        return ProductDAO.instance.getProductInformation();
}
    }

</code>```

^^ This is the class I have mapped to the resource I am trying to access

It then accesses the ProductDAO class which gets the info from the database and adds it to a HashMap (This part seems to work fine)

```<code>public enum ProductDAO {
    instance;

    private Map<Integer, Product> productMap = new HashMap<Integer, Product>();

    private ProductDAO() {
        loadFromDb();
    }

    public Map<Integer, Product> loadFromDb() {
        productMap.clear();
        try {
            Connection conn = Utils.getConnection();
            PreparedStatement psmt = conn.prepareStatement("SELECT * FROM products");
            ResultSet rs = psmt.executeQuery();
            while (rs.next()) {
                Product p = new Product(rs.getInt("id"), rs.getString("description"), rs.getInt("CategoryId"),
                        rs.getDouble("price"), rs.getInt("QuantitySold"), rs.getString("image"));
                productMap.put(productMap.size() + 1, p);
                System.out.println(productMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return productMap;
    }

    public List<Product> getProductInformation() {
        List<Product> product = new ArrayList<Product>();
        product.addAll(productMap.values());
        return product;
    }
</code>```

I have 4 test entries in the database currently.
When I add a system.out.println() for the HashMap I get the following output to the console:

```<code>Database connection established
{1=myApp.Product@20c427e5}
{1=myApp.Product@20c427e5, 2=myApp.Product@610e026a}
{1=myApp.Product@20c427e5, 2=myApp.Product@610e026a, 3=myApp.Product@2e0456eb}
{1=myApp.Product@20c427e5, 2=myApp.Product@610e026a, 3=myApp.Product@2e0456eb, 4=myApp.Product@5241c547}`
</code>```

My pom.xml is as follows:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.framesinmind</groupId>
    <artifactId>FramesIM</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>FramesIM</name>

    <build>
        <finalName>FramesIM</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
            <!-- artifactId>jersey-container-servlet</artifactId -->
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.3</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.3</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <properties>
        <jersey.version>2.16</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>
</code>```

Web.xml as follows:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
     see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>myApp</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

The Java classes are all part of the 'myApp' package
When trying to access the url 'http://localhost:8080/FramesIM/rest/product' I get the HTTP 500 error. Any ideas?

答:
The internal server error is because you need to code the Product class with the annotations and cannot directly pass the list as response. Please follow the code below.

```<code>import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;
@XmlRootElement(name = "product")
@XmlAccessorType (XmlAccessType.FIELD)
public class Product {
    String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "products")
@XmlAccessorType (XmlAccessType.FIELD)
public class Products
{
    @XmlElement(name="product")
    private List<Product> products;

    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }
}

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("product")
public class ProductResource {
    @GET
    @Produces(MediaType.APPLICATION_XML)
    public Products getProductInformation() {
        List<Product> product = ProductDAO.instance.getProductInformation();
        Products products = new Products();
        products.setProducts(product);
        return products;
    }
}
</code>```

The response below is the sample output

```<code><products>
<product>
<id>12</id>
</product>
</products>
</code>```

Body:
Trying to produce JSON code from database entries using rest but I am getting a HTTP 500 error code

@Path("product")
public class ProductResource {
    @GET
    @Produces({ MediaType.APPLICATION_XML })
    public List<Product> getProductInformation() {
        return ProductDAO.instance.getProductInformation();
}
    }

^^ This is the class I have mapped to the resource I am trying to access

It then accesses the ProductDAO class which gets the info from the database and adds it to a HashMap (This part seems to work fine)

public enum ProductDAO {
    instance;

    private Map<Integer, Product> productMap = new HashMap<Integer, Product>();

    private ProductDAO() {
        loadFromDb();
    }

    public Map<Integer, Product> loadFromDb() {
        productMap.clear();
        try {
            Connection conn = Utils.getConnection();
            PreparedStatement psmt = conn.prepareStatement("SELECT * FROM products");
            ResultSet rs = psmt.executeQuery();
            while (rs.next()) {
                Product p = new Product(rs.getInt("id"), rs.getString("description"), rs.getInt("CategoryId"),
                        rs.getDouble("price"), rs.getInt("QuantitySold"), rs.getString("image"));
                productMap.put(productMap.size() + 1, p);
                System.out.println(productMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return productMap;
    }

    public List<Product> getProductInformation() {
        List<Product> product = new ArrayList<Product>();
        product.addAll(productMap.values());
        return product;
    }

I have 4 test entries in the database currently.
When I add a system.out.println() for the HashMap I get the following output to the console:

Database connection established
{1=myApp.Product@20c427e5}
{1=myApp.Product@20c427e5, 2=myApp.Product@610e026a}
{1=myApp.Product@20c427e5, 2=myApp.Product@610e026a, 3=myApp.Product@2e0456eb}
{1=myApp.Product@20c427e5, 2=myApp.Product@610e026a, 3=myApp.Product@2e0456eb, 4=myApp.Product@5241c547}`

My pom.xml is as follows:

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.framesinmind</groupId>
    <artifactId>FramesIM</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>FramesIM</name>

    <build>
        <finalName>FramesIM</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>

        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-moxy</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.3</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.3</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <properties>
        <jersey.version>2.16</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

Web.xml as follows:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>myApp</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

The Java classes are all part of the 'myApp' package
When trying to access the url 'http://localhost:8080/FramesIM/rest/product' I get the HTTP 500 error. Any ideas?

Body:
The internal server error is because you need to code the Product class with the annotations and cannot directly pass the list as response. Please follow the code below.

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;
@XmlRootElement(name = "product")
@XmlAccessorType (XmlAccessType.FIELD)
public class Product {
    String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "products")
@XmlAccessorType (XmlAccessType.FIELD)
public class Products
{
    @XmlElement(name="product")
    private List<Product> products;

    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    }
}

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("product")
public class ProductResource {
    @GET
    @Produces(MediaType.APPLICATION_XML)
    public Products getProductInformation() {
        List<Product> product = ProductDAO.instance.getProductInformation();
        Products products = new Products();
        products.setProducts(product);
        return products;
    }
}

The response below is the sample output

<products>
<product>
<id>12</id>
</product>
</products>


问:
Problems with grouped bar chart
I am new to d3 and trying to make a grouped bar chart following this and this websites.

The following is my code for the scales

```<code>x0 = d3.scaleTime()
               .domain([
                 d3.min(dataset, function(d) {return d.date;}),
                 d3.max(dataset, function(d) {return d.date;})
               ])
               .range([0,w]);

    x1 = d3.scaleOrdinal()
            .domain([dataset.WorldPopulation, dataset.InternetUser]);
    //        .rangeRound([0, x0.bandwidth()]);

   y = d3.scaleLinear()
          .domain([0, d3.max(dataset, function(d) {return d.WorldPopulation})])
          .range([h,0]);
</code>```

In the website above they use scaleOrdinal but I used scaleTime as x0. Therefore I'm not too sure if that works.

This is my code for the append(rect) for the bar chart

```<code>var date = svg.selectAll(".date")
                .data(dataset)
                .enter()
                .append("g")
                .attr("class", "g")
                .attr("transform", function(d) {return "translate(" + x0(d.date) + ",0)";});

              /* Add field1 bars */
            date.selectAll(".bar.field1")
              .data(d => [d])
              .enter()
              .append("rect")
              .attr("class", "bar field1")
            .style("fill","blue")
              .attr("x", d => x0(d.WorldPopulation))
              .attr("y", d => y(d.WorldPopulation))
              .attr("width", x1.bandwidth())
              .attr("height", d => {
                return height - margin.top - margin.bottom - y(d.WorldPopulation)
              });

            /* Add field2 bars */
            date.selectAll(".bar.field2")
              .data(d => [d])
              .enter()
              .append("rect")
              .attr("class", "bar field2")
            .style("fill","red")
              .attr("x", d => x0(d.InternetUser))
              .attr("y", d => y(d.InternetUser))
              .attr("width", x1.bandwidth())
              .attr("height", d => {
                return height - margin.top - margin.bottom - y(d.InternetUser)
              });
</code>```

And this is my csv file. Not too sure how to upload excel so I took a screenshot.

Any help provided will be appreciated. Feel free to request for any extra snippets of my code for clarification.

edit: After tweaking the code, no errors are shown but the svg is not produced either.

答:
Using scaleBand for both x0 and x1, the following code works:

```<code><script src="js/d3.v4.js"></script>

<script>

    var margin = { top: 20, right: 20, bottom: 30, left: 40 },
        width = 960 - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;

    var x0 = d3.scaleBand()
        .rangeRound([0, width]).padding(.1);

    var x1 = d3.scaleBand();

    var y = d3.scaleLinear()
        .range([height, 0]);

    var xAxis = d3.axisBottom()
        .scale(x0)
        .tickSize(0);

    var yAxis = d3.axisLeft()
        .scale(y);

    var svg = d3.select('body').append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    d3.csv("InternetUserStats.csv", function (error, data) {

        var dates = data.map(function (d) { return d.date; });
        var ymax = d3.max(data, function (d) { return Math.max(d.WorldPopulation, d.InternetUser); });

        x0.domain(dates);
        x1.domain(['WorldPopulations', 'InternetUsers']).rangeRound([0, x0.bandwidth()]);
        y.domain([0, ymax]);

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis);

        var date = svg.selectAll(".g")
            .data(data)
            .enter().append("g")
            .attr("class", "g")
            .attr("transform", function (d) { return "translate(" + x0(d.date) + ",0)"; });

        /* Add field1 bars */
        date/*.selectAll(".bar.field1")
          .data(data)
          .enter()*/
          .append("rect")
          .attr("class", "bar field1")
        .style("fill", "blue")
          .attr("x", function (d) { return x1('WorldPopulations'); })
          .attr("y", function (d) { return y(+d.WorldPopulation); })
          .attr("width", x0.bandwidth() / 2)
          .attr("height", function (d) {
            return height /*- margin.top - margin.bottom*/ - y(d.WorldPopulation)
          });

        /* Add field2 bars */
        date/*.selectAll(".bar.field1")
          .data(data)
          .enter()*/
          .append("rect")
          .attr("class", "bar field2")
        .style("fill", "red")
          .attr("x", function (d) { return x1('InternetUsers'); })
          .attr("y", function (d) { return y(d.InternetUser); })
          .attr("width", x0.bandwidth() / 2)
          .attr("height", function (d) {
            return height /*- margin.top - margin.bottom*/ - y(d.InternetUser)
          });

    });

</script>
</code>```

EDIT: the following code adds a legend that is based on your comment and your second link:

```<code>        //This code goes after field2 bars are added.

        /* Legend */
        var legend = svg.selectAll(".legend")
            .data(['WorldPopulations', 'InternetUsers'])  //Bind an array of the legend entries
        .enter().append("g")
            .attr("class", "legend")
            .attr("font-family", "sans-serif")
            .attr("font-size", 13)
            .style("text-anchor", "end")
            .attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; });

        legend.append("rect")
            .attr("x", width - 18)
            .attr("width", 18)
            .attr("height", 18)
            .style("fill", function (d) {
                // Return "blue" for "WorldPopulations" and "red" for "InternetUsers":
                return ((d === "WorldPopulations") ? "blue" : "red");
            });

        legend.append("text")
            .attr("x", width - 24)
            .attr("y", 9)
            .attr("dy", ".35em")
            //.style("text-anchor", "end")  //Already applied to .legend
            .text(function (d) { return d; });
</code>```

Title: Problems with grouped bar chart

Body:
I am new to d3 and trying to make a grouped bar chart following this and this websites.

The following is my code for the scales

x0 = d3.scaleTime()
               .domain([
                 d3.min(dataset, function(d) {return d.date;}),
                 d3.max(dataset, function(d) {return d.date;})
               ])
               .range([0,w]);

    x1 = d3.scaleOrdinal()
            .domain([dataset.WorldPopulation, dataset.InternetUser]);
    //        .rangeRound([0, x0.bandwidth()]);

   y = d3.scaleLinear()
          .domain([0, d3.max(dataset, function(d) {return d.WorldPopulation})])
          .range([h,0]);

In the website above they use scaleOrdinal but I used scaleTime as x0. Therefore I'm not too sure if that works.

This is my code for the append(rect) for the bar chart

var date = svg.selectAll(".date")
                .data(dataset)
                .enter()
                .append("g")
                .attr("class", "g")
                .attr("transform", function(d) {return "translate(" + x0(d.date) + ",0)";});

              /* Add field1 bars */
            date.selectAll(".bar.field1")
              .data(d => [d])
              .enter()
              .append("rect")
              .attr("class", "bar field1")
            .style("fill","blue")
              .attr("x", d => x0(d.WorldPopulation))
              .attr("y", d => y(d.WorldPopulation))
              .attr("width", x1.bandwidth())
              .attr("height", d => {
                return height - margin.top - margin.bottom - y(d.WorldPopulation)
              });

            /* Add field2 bars */
            date.selectAll(".bar.field2")
              .data(d => [d])
              .enter()
              .append("rect")
              .attr("class", "bar field2")
            .style("fill","red")
              .attr("x", d => x0(d.InternetUser))
              .attr("y", d => y(d.InternetUser))
              .attr("width", x1.bandwidth())
              .attr("height", d => {
                return height - margin.top - margin.bottom - y(d.InternetUser)
              });

And this is my csv file. Not too sure how to upload excel so I took a screenshot.

Any help provided will be appreciated. Feel free to request for any extra snippets of my code for clarification.

edit: After tweaking the code, no errors are shown but the svg is not produced either.

Body:
Using scaleBand for both x0 and x1, the following code works:

<script src="js/d3.v4.js"></script>

<script>

    var margin = { top: 20, right: 20, bottom: 30, left: 40 },
        width = 960 - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;

    var x0 = d3.scaleBand()
        .rangeRound([0, width]).padding(.1);

    var x1 = d3.scaleBand();

    var y = d3.scaleLinear()
        .range([height, 0]);

    var xAxis = d3.axisBottom()
        .scale(x0)
        .tickSize(0);

    var yAxis = d3.axisLeft()
        .scale(y);

    var svg = d3.select('body').append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    d3.csv("InternetUserStats.csv", function (error, data) {

        var dates = data.map(function (d) { return d.date; });
        var ymax = d3.max(data, function (d) { return Math.max(d.WorldPopulation, d.InternetUser); });

        x0.domain(dates);
        x1.domain(['WorldPopulations', 'InternetUsers']).rangeRound([0, x0.bandwidth()]);
        y.domain([0, ymax]);

        svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis);

        svg.append("g")
            .attr("class", "y axis")
            .call(yAxis);

        var date = svg.selectAll(".g")
            .data(data)
            .enter().append("g")
            .attr("class", "g")
            .attr("transform", function (d) { return "translate(" + x0(d.date) + ",0)"; });

        /* Add field1 bars */
        date/*.selectAll(".bar.field1")
          .data(data)
          .enter()*/
          .append("rect")
          .attr("class", "bar field1")
        .style("fill", "blue")
          .attr("x", function (d) { return x1('WorldPopulations'); })
          .attr("y", function (d) { return y(+d.WorldPopulation); })
          .attr("width", x0.bandwidth() / 2)
          .attr("height", function (d) {
            return height /*- margin.top - margin.bottom*/ - y(d.WorldPopulation)
          });

        /* Add field2 bars */
        date/*.selectAll(".bar.field1")
          .data(data)
          .enter()*/
          .append("rect")
          .attr("class", "bar field2")
        .style("fill", "red")
          .attr("x", function (d) { return x1('InternetUsers'); })
          .attr("y", function (d) { return y(d.InternetUser); })
          .attr("width", x0.bandwidth() / 2)
          .attr("height", function (d) {
            return height /*- margin.top - margin.bottom*/ - y(d.InternetUser)
          });

    });

</script>

EDIT: the following code adds a legend that is based on your comment and your second link:

        //This code goes after field2 bars are added.

        /* Legend */
        var legend = svg.selectAll(".legend")
            .data(['WorldPopulations', 'InternetUsers'])  //Bind an array of the legend entries
        .enter().append("g")
            .attr("class", "legend")
            .attr("font-family", "sans-serif")
            .attr("font-size", 13)
            .style("text-anchor", "end")
            .attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; });

        legend.append("rect")
            .attr("x", width - 18)
            .attr("width", 18)
            .attr("height", 18)
            .style("fill", function (d) {
                // Return "blue" for "WorldPopulations" and "red" for "InternetUsers":
                return ((d === "WorldPopulations") ? "blue" : "red");
            });

        legend.append("text")
            .attr("x", width - 24)
            .attr("y", 9)
            .attr("dy", ".35em")
            //.style("text-anchor", "end")  //Already applied to .legend
            .text(function (d) { return d; });


问:
Downloading a compressed folder on client side not working in angular+node (MEAN)
I need to allow user to download compressed folders from server. I managed to make the compression however even if I try to read the tar file and send it to client side for download file is corrupted or is saving only one file from folder (1/7 for example).

I have tried to send json files and the same code worked but for large and tar files it's not sending entire file.
I have tried just to send tar file from backend to client side to download but it also doesn't work.

```<code>/* back controller. */
const getDataDownload = function(req,res) {
    if (req.params && req.params.dataId){
        DataModel
            .findById(req.params.dataId)
            .exec((err,data) => {
                if(data){
                    var file = '../data/filename.tar';
                    var stat = fs.statSync(file);
                    res.writeHead(200, {
                        'Content-Type' : 'application/tar',
                        'Content-Length' : stat.size
                    });
                    var tempTarFile = fs.createReadStream(file);
                    tempTarFile.pipe(res);
                }})}
    else {
            res
                .status(404)
                .json({"message":"No Id in request"});
        }
}
</code>```

```<code>/* front controller. */
public dataDownload(dataId: string){
        const url: string = `${this.apiBaseUrl}/dataDownload/${dataId}/`;
        const req = new HttpRequest('GET', url, {
                headers: new HttpHeaders({'Authorization': token}),
                responseType: 'text' as 'text',
                reportProgress: true});
        this.http.request(req).subscribe((event: HttpEvent<any>)=>{
            switch (event.type) {
                case HttpEventType.Response:
                    const filename = 'filename.tar'
                    var blob = new Blob([event.body], { type: "application/tar" });
                    saveAs(blob, 'filename.tar')
                    break;
                case HttpEventType.DownloadProgress:
                    console.log(' (',Math.round(event.loaded/event.total),')');
                    break;
            }}
        )

    }
</code>```

File doesn't open properly and it doesn't have a proper size.
Please help

答:
Back controller:

```<code>const getDataDownload = function (req, res) {
  if (req.params && req.params.dataId) {
    DataModel
      .findById(req.params.dataId)
      .exec((err, data) => {
        if (data) {
          let file = '/home/pierbjx/Documents/sorfML/test.tar';
          try {
            let stat = fs.statSync(file);
            res.writeHead(200, {
              'Content-Type': 'application/tar',
              'Content-Length': stat.size
            });
            let tempTarFile = fs.createReadStream(file);
            tempTarFile.pipe(res);
          } catch (err) {
            console.log('Error: ' + err);
          }
        }
      })
  }
  else {
    res
      .status(404)
      .json({ "message": "No Id in request" });
  }
}
</code>```

Front controller:

```<code>  public dataDownload(dataId: string): void {
    const url: string = `${this.apiBaseUrl}/dataDownload/${dataId}/`;
    const req = new HttpRequest('GET', url, {
      responseType: "blob",
      headers: new HttpHeaders().append("Content-Type", "application/json"),
      reportProgress: true
    });

    this.http.request(req)
      .subscribe(
        event => {
          if (event.type === HttpEventType.DownloadProgress) {
            console.log("Download progress event", event);
          }

          if (event.type === HttpEventType.Response) {
            console.log("response received...", event.body);
            const filename = 'filename.tar';
            saveAs(event.body, filename);
          }

        },
        err => {
          alert("Problem while downloading the file.");
          console.error(err);
        }
      );
  }
</code>```

Body:
I need to allow user to download compressed folders from server. I managed to make the compression however even if I try to read the tar file and send it to client side for download file is corrupted or is saving only one file from folder (1/7 for example).

I have tried to send json files and the same code worked but for large and tar files it's not sending entire file.
I have tried just to send tar file from backend to client side to download but it also doesn't work.

/* back controller. */
const getDataDownload = function(req,res) {
    if (req.params && req.params.dataId){
        DataModel
            .findById(req.params.dataId)
            .exec((err,data) => {
                if(data){
                    var file = '../data/filename.tar';
                    var stat = fs.statSync(file);
                    res.writeHead(200, {
                        'Content-Type' : 'application/tar',
                        'Content-Length' : stat.size
                    });
                    var tempTarFile = fs.createReadStream(file);
                    tempTarFile.pipe(res);
                }})}
    else {
            res
                .status(404)
                .json({"message":"No Id in request"});
        }
}

/* front controller. */
public dataDownload(dataId: string){
        const url: string = `${this.apiBaseUrl}/dataDownload/${dataId}/`;
        const req = new HttpRequest('GET', url, {
                headers: new HttpHeaders({'Authorization': token}),
                responseType: 'text' as 'text',
                reportProgress: true});
        this.http.request(req).subscribe((event: HttpEvent<any>)=>{
            switch (event.type) {
                case HttpEventType.Response:
                    const filename = 'filename.tar'
                    var blob = new Blob([event.body], { type: "application/tar" });
                    saveAs(blob, 'filename.tar')
                    break;
                case HttpEventType.DownloadProgress:
                    console.log(' (',Math.round(event.loaded/event.total),')');
                    break;
            }}
        )

    }

File doesn't open properly and it doesn't have a proper size.
Please help

Body:
Back controller:

const getDataDownload = function (req, res) {
  if (req.params && req.params.dataId) {
    DataModel
      .findById(req.params.dataId)
      .exec((err, data) => {
        if (data) {
          let file = '/home/pierbjx/Documents/sorfML/test.tar';
          try {
            let stat = fs.statSync(file);
            res.writeHead(200, {
              'Content-Type': 'application/tar',
              'Content-Length': stat.size
            });
            let tempTarFile = fs.createReadStream(file);
            tempTarFile.pipe(res);
          } catch (err) {
            console.log('Error: ' + err);
          }
        }
      })
  }
  else {
    res
      .status(404)
      .json({ "message": "No Id in request" });
  }
}

Front controller:

  public dataDownload(dataId: string): void {
    const url: string = `${this.apiBaseUrl}/dataDownload/${dataId}/`;
    const req = new HttpRequest('GET', url, {
      responseType: "blob",
      headers: new HttpHeaders().append("Content-Type", "application/json"),
      reportProgress: true
    });

    this.http.request(req)
      .subscribe(
        event => {
          if (event.type === HttpEventType.DownloadProgress) {
            console.log("Download progress event", event);
          }

          if (event.type === HttpEventType.Response) {
            console.log("response received...", event.body);
            const filename = 'filename.tar';
            saveAs(event.body, filename);
          }

        },
        err => {
          alert("Problem while downloading the file.");
          console.error(err);
        }
      );
  }


问:
Fastest running scripting language for use with Java
I would like to know the best (fastest) scripting language for use in Java. I don't much care if it takes long to load (as long as it is a one time load), as opposed to how fast it runs. I am currently using Jython (python) but I would like something faster.</p>

答:
Have you tried programming in Java?

You can write some of the performance critical functionality in Java, and leave most of the code in the scripting language of your choice.


问:
Print numbers 1,2,3 using thread1 and 4,5,6 using thread2, and 7,8,9 using thread3 and again 10,11,12 using thread1
I am trying a write a simple program with wait and notify in which I will create 3 threads.

The first thread should print 1, 2, 3.

The second thread should print 4, 5, 6.

The third thread should print 7, 8, 9.

After that, the first thread should print 10, 11, 12 and so on.

Below is a sample code for the same exercise, but I am unable to print the desired output.

```<code>public class MyThread2 extends Thread {

    public final static Object obj = new Object();

    int threadNo;
    static volatile int threadNoToRun;
    static volatile int counter = 1;

    public MyThread2(int threadNo){
        this.threadNo= threadNo;
    }

    @Override
    public void run() {
        synchronized (obj) {
                try {
                    if(threadNoToRun != threadNo)
                        obj.wait();
                    else{
                        for(int i = 1 ; i < 4 ; i++){
                            if(threadNoToRun == threadNo){
                                System.out.println(threadNo + " counter value is "+counter);
                                counter++;
                                System.out.println(threadNo + " counter value is "+counter);
                                counter++;
                                System.out.println(threadNo + " counter value is "+counter);
                                counter++;
                                if(threadNoToRun == 1){
                                    threadNoToRun = 2;
                                }
                                else if(threadNoToRun == 2){
                                    threadNoToRun = 3;
                                }
                                else if(threadNoToRun == 3){
                                    threadNoToRun = 1;
                                }
                            }
                        }

                        obj.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

        }
    }

    public static void main (String args[]) {

        /*
         * Creating as many threads as needed.
         */
        MyThread2 th1 = new MyThread2(1);
        MyThread2 th2 = new MyThread2(2);
        MyThread2 th3 = new MyThread2(3);
        MyThread2.threadNoToRun = 1;
        th1.start();
        th2.start();
        th3.start();
    }
}
</code>```

The output looks like:

```<code>1 counter value is 1
1 counter value is 2
1 counter value is 3
2 counter value is 4
2 counter value is 5
2 counter value is 6
</code>```

答:
Here, it was just a few changes.

Nonetheless, I have to point out that this kind of concurrency does NOT increase computation speed. Only one thread is alive at all times.

public class MyThread2 extends Thread {

    public final static Object obj = new Object();

    int threadNo;
    static volatile int threadNoToRun;
    static volatile int counter = 1;

    public MyThread2(int threadNo) {
        this.threadNo = threadNo;
    }

    @Override
    public void run() {
        synchronized (obj) {
            try {
                while (counter < 100) {
                    if (threadNoToRun != threadNo)
                        obj.wait();
                    else {
                        System.out.println(threadNo + " counter value is " + counter);
                        counter++;
                        System.out.println(threadNo + " counter value is " + counter);
                        counter++;
                        System.out.println(threadNo + " counter value is " + counter);
                        counter++;
                        if (threadNoToRun == 1) {
                            threadNoToRun = 2;
                        } else if (threadNoToRun == 2) {
                            threadNoToRun = 3;
                        } else if (threadNoToRun == 3) {
                            threadNoToRun = 1;
                        }

                        obj.notifyAll();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String args[]) {

        /*
         * Creating as many threads as needed.
         */
        MyThread2 th1 = new MyThread2(1);
        MyThread2 th2 = new MyThread2(2);
        MyThread2 th3 = new MyThread2(3);
        MyThread2.threadNoToRun = 1;
        th1.start();
        th2.start();
        th3.start();
    }
}
```

Body:
I am trying a write a simple program with wait and notify in which I will create 3 threads.

The first thread should print 1, 2, 3.

The second thread should print 4, 5, 6.

The third thread should print 7, 8, 9.

After that, the first thread should print 10, 11, 12 and so on.

Below is a sample code for the same exercise, but I am unable to print the desired output.

public class MyThread2 extends Thread {

    public final static Object obj = new Object();

    int threadNo;
    static volatile int threadNoToRun;
    static volatile int counter = 1;

    public MyThread2(int threadNo){
        this.threadNo= threadNo;
    }

    @Override
    public void run() {
        synchronized (obj) {
                try {
                    if(threadNoToRun != threadNo)
                        obj.wait();
                    else{
                        for(int i = 1 ; i < 4 ; i++){
                            if(threadNoToRun == threadNo){
                                System.out.println(threadNo + " counter value is "+counter);
                                counter++;
                                System.out.println(threadNo + " counter value is "+counter);
                                counter++;
                                System.out.println(threadNo + " counter value is "+counter);
                                counter++;
                                if(threadNoToRun == 1){
                                    threadNoToRun = 2;
                                }
                                else if(threadNoToRun == 2){
                                    threadNoToRun = 3;
                                }
                                else if(threadNoToRun == 3){
                                    threadNoToRun = 1;
                                }
                            }
                        }

                        obj.notifyAll();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

        }
    }

    public static void main (String args[]) {

        /*
         * Creating as many threads as needed.
         */
        MyThread2 th1 = new MyThread2(1);
        MyThread2 th2 = new MyThread2(2);
        MyThread2 th3 = new MyThread2(3);
        MyThread2.threadNoToRun = 1;
        th1.start();
        th2.start();
        th3.start();
    }
}

The output looks like:

1 counter value is 1
1 counter value is 2
1 counter value is 3
2 counter value is 4
2 counter value is 5
2 counter value is 6


问:
Why am I getting a NaN error when multiplying two numbers?
My getPercentage function works perfectly, but my getPayment function doesn't even though it's written exactly the same. When I click the "Get Payment" button it returns "NaN" on my HTML.

var taxes = {
  getPercentage: function(total, payment) {
   var percentage = (payment / total) * 100;
   return percentage;
   },
  getPayment: function(total, rate) {
    var payment = (total*rate);
    return payment;
    }
  };

var handlers = {
  getPercentage: function() {
    var totalInput = document.getElementById('totalInput');
    var paymentInput = document.getElementById('paymentInput');
    var answer = taxes.getPercentage(totalInput.value, paymentInput.value);
    getPercentageAnswer.innerHTML = answer;
  },
  getPayment: function() {
    var totalInputTwo = document.getElementById('totalInputTwo');
    var rateInput = document.getElementById("rateInput");
    var answer = taxes.getPayment(totalInputTwo.value, rateInput.value);
    getPaymentAnswer.innerHTML = answer;
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="getPayment">
  <div id="totalTwo">
        Total owed:
    <input id="totalInputTwo" type="text">
  </div>
<div id="rateInput">
      Your tax rate (as a decimal):
  <input id="rateInput" type="text">
  </div>
  <button onclick="handlers.getPayment()">Get payment</button>
  <p id="getPaymentAnswer"></p>
</div></code>```

答:
You have a div and an input with the same id rateInput. So, rateInput.value is trying to get the value from the div and it's returning undefined. Change the div's id to something else to get the correct input element in rateInput

var taxes = {
  getPayment: function(total, rate) {
    var payment = (total * rate);
    return payment;
  }
};

var handlers = {
  getPayment: function() {
    var totalInputTwo = document.getElementById('totalInputTwo');
    var rateInput = document.getElementById("rateInput");
    var answer = taxes.getPayment(+totalInputTwo.value, +rateInput.value);
    getPaymentAnswer.innerHTML = answer;
  }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="getPayment">
  <div id="totalTwo">
    Total owed:
    <input id="totalInputTwo" type="text">
  </div>
  <div id="rate">
    Your tax rate (as a decimal):
    <input id="rateInput" type="text">
  </div>
  <button onclick="handlers.getPayment()">Get payment</button>
  <p id="getPaymentAnswer"></p>
</div></code>```

Note:

The value of input is always in string format. So, you should always parse them to numbers before doing any mathematical operation. When you multiply, the are coerced into numbers. So, there's no problem here. But, if you were to do addition, the strings will be concatenated instead of their numerical values being added.

So, you can use the Unary plus operator to convert the strings to numbers:

```<code>var answer = taxes.getPayment(+totalInputTwo.value, +rateInput.value);
</code>```

Body:
My getPercentage function works perfectly, but my getPayment function doesn't even though it's written exactly the same. When I click the "Get Payment" button it returns "NaN" on my HTML.

var taxes = {
  getPercentage: function(total, payment) {
   var percentage = (payment / total) * 100;
   return percentage;
   },
  getPayment: function(total, rate) {
    var payment = (total*rate);
    return payment;
    }
  };

var handlers = {
  getPercentage: function() {
    var totalInput = document.getElementById('totalInput');
    var paymentInput = document.getElementById('paymentInput');
    var answer = taxes.getPercentage(totalInput.value, paymentInput.value);
    getPercentageAnswer.innerHTML = answer;
  },
  getPayment: function() {
    var totalInputTwo = document.getElementById('totalInputTwo');
    var rateInput = document.getElementById("rateInput");
    var answer = taxes.getPayment(totalInputTwo.value, rateInput.value);
    getPaymentAnswer.innerHTML = answer;
  }
};

        Total owed:
    <input id="totalInputTwo" type="text">

      Your tax rate (as a decimal):
  <input id="rateInput" type="text">

  <button onclick="handlers.getPayment()">Get payment</button>

Body:
You have a div and an input with the same id rateInput. So, rateInput.value is trying to get the value from the div and it's returning undefined. Change the div's id to something else to get the correct input element in rateInput

var taxes = {
  getPayment: function(total, rate) {
    var payment = (total * rate);
    return payment;
  }
};

var handlers = {
  getPayment: function() {
    var totalInputTwo = document.getElementById('totalInputTwo');
    var rateInput = document.getElementById("rateInput");
    var answer = taxes.getPayment(+totalInputTwo.value, +rateInput.value);
    getPaymentAnswer.innerHTML = answer;
  }
};

<div id="getPayment">
  <div id="totalTwo">
    Total owed:
    <input id="totalInputTwo" type="text">
  </div>
  <div id="rate">
    Your tax rate (as a decimal):
    <input id="rateInput" type="text">
  </div>
  <button onclick="handlers.getPayment()">Get payment</button>
  <p id="getPaymentAnswer"></p>
</div>

Note:

The value of input is always in string format. So, you should always parse them to numbers before doing any mathematical operation. When you multiply, the are coerced into numbers. So, there's no problem here. But, if you were to do addition, the strings will be concatenated instead of their numerical values being added.

So, you can use the Unary plus operator to convert the strings to numbers:

var answer = taxes.getPayment(+totalInputTwo.value, +rateInput.value);


问:
having a problem loading a tilemap into phaser 3
I've been having a problem loading a tilemap that I created with "tiled", I looked up the phaser 3 examples, I even copied pasted their file and png tile image into my project folder and it worked, so am pretty sure that the reason is me misusing the "tiled" software and not knowing how to properley handle a json file, I will add images of the errors am getting and the json file.
Note: I get a black screen.
https://i.stack.imgur.com/dF8ee.png /
https://i.stack.imgur.com/E04ng.png</p>

```<code>function preload ()
{
this.load.image('tilesplatform', 'ground_1x1.png'); this.load.tilemapTiledJSON('map', 'scene.json');
}

function create ()
{

var map = this.make.tilemap({ key: 'map' });
var Ground = map.addTilesetImage('ground_1x1', 'tilesplatform');
map.createStaticLayer(0, ground_1x1, 0, 0);
}
</code>```

答:
var config = {
    type: Phaser.WEBGL,
    width: 400,
    height: 288,
    parent: 'phaser-example',
    loader: {
      baseURL: 'https://raw.githubusercontent.com/nazimboudeffa/assets/master/maps/',
      crossOrigin: 'anonymous'
    },
    scene: {
        preload: preload,
        create: create
    }
};

var game = new Phaser.Game(config);
var map;
var cursors;
var player;
var groundLayer;

function preload ()
{
    this.load.image('tileset', 'sunny-land/tileset.png');
    this.load.tilemapTiledJSON('map', 'sunny-land/level0.json');
}

function create ()
{
  map = this.make.tilemap({ key: 'map' });
  var groundTiles = map.addTilesetImage('tileset');

  map.createStaticLayer('ground', groundTiles, 0, 0);
  //map.createStaticLayer('jumpThrough', groundTiles, 0, 0);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdn.jsdelivr.net/npm/phaser@3.17.0/dist/phaser.min.js"></script></code>```

Body:
I've been having a problem loading a tilemap that I created with "tiled", I looked up the phaser 3 examples, I even copied pasted their file and png tile image into my project folder and it worked, so am pretty sure that the reason is me misusing the "tiled" software and not knowing how to properley handle a json file, I will add images of the errors am getting and the json file.
Note: I get a black screen.
https://i.stack.imgur.com/dF8ee.png /
https://i.stack.imgur.com/E04ng.png

function preload ()
{
this.load.image('tilesplatform', 'ground_1x1.png'); this.load.tilemapTiledJSON('map', 'scene.json');
}

function create ()
{

var map = this.make.tilemap({ key: 'map' });
var Ground = map.addTilesetImage('ground_1x1', 'tilesplatform');
map.createStaticLayer(0, ground_1x1, 0, 0);
}

Body:
var config = {
    type: Phaser.WEBGL,
    width: 400,
    height: 288,
    parent: 'phaser-example',
    loader: {
      baseURL: 'https://raw.githubusercontent.com/nazimboudeffa/assets/master/maps/',
      crossOrigin: 'anonymous'
    },
    scene: {
        preload: preload,
        create: create
    }
};

var game = new Phaser.Game(config);
var map;
var cursors;
var player;
var groundLayer;

function preload ()
{
    this.load.image('tileset', 'sunny-land/tileset.png');
    this.load.tilemapTiledJSON('map', 'sunny-land/level0.json');
}

function create ()
{
  map = this.make.tilemap({ key: 'map' });
  var groundTiles = map.addTilesetImage('tileset');

  map.createStaticLayer('ground', groundTiles, 0, 0);
  //map.createStaticLayer('jumpThrough', groundTiles, 0, 0);

}

<script src="//cdn.jsdelivr.net/npm/phaser@3.17.0/dist/phaser.min.js"></script>


问:
Ecto: Dynamic order_by with count query on virtual field
I want to build a query with dynamic order by handling.
The basic sorting example id + name (see below) works fine. The sort variable is inserted in query.

```<code>favorites_count_query = from(f in Favorite,
  select: %{wallpaper_id: f.wallpaper_id, count: count(f.user_id)},
  group_by: f.wallpaper_id)

...

sort = [asc: :id, asc: :name] # comes from request

from(w in Wallpaper,
  left_join: f in subquery(favorites_count_query), on: f.wallpaper_id == w.id,
  left_join: d in subquery(downloads_count_query), on: d.wallpaper_id == w.id,
  select: w,
  select_merge: %{favorites_count: coalesce(f.count, 0)},
  select_merge: %{downloads_count: coalesce(d.count, 0)},
  order_by: ^sort,
  group_by: w.id)
</code>```

In addition I want to sort on count fields (favorites_count & downloads_count). Put this part static in query will work.

```<code>...
order_by: coalesce(d.count, 0),
</code>```

My question now is how to handle this like the first example with dynamic variable. I didn't find a way to handle this.

```<code>sort = [asc: :favorites_count, asc: :name] # comes from request
...
order_by: ^sort,
</code>```

Ends up with Unknown column 'w0.favorites_count' in 'order clause'

```<code>order_by: ^foo(sort),

def foo(sort), do: coalesce(:count, 0)
</code>```

Ends up with undefined function coalesce/2 (fragment/3)

Using dynamic/2 ends up with expected a field as an atom, a list or keyword list in 'order_by', got: 'dynamic(...)'

I understand the main problem, but didn't get a solution. Any ideas or in best case solutions? Thanks for help!

答:
I managed to do this much simpler so here's my solution:

```<code>from(p in Post,
  order_by: [desc_nulls_last: fragment("array_length(?, 1)", p.votes)]
)
|> Repo.all()
</code>```

The desc_nulls_last you can choose yourself, but the fragment works very well. array_length is a PostgreSQL specific thing so watch out for that!

Body:
I want to build a query with dynamic order by handling.
The basic sorting example id + name (see below) works fine. The sort variable is inserted in query.

favorites_count_query = from(f in Favorite,
  select: %{wallpaper_id: f.wallpaper_id, count: count(f.user_id)},
  group_by: f.wallpaper_id)

...

sort = [asc: :id, asc: :name] # comes from request

from(w in Wallpaper,
  left_join: f in subquery(favorites_count_query), on: f.wallpaper_id == w.id,
  left_join: d in subquery(downloads_count_query), on: d.wallpaper_id == w.id,
  select: w,
  select_merge: %{favorites_count: coalesce(f.count, 0)},
  select_merge: %{downloads_count: coalesce(d.count, 0)},
  order_by: ^sort,
  group_by: w.id)

In addition I want to sort on count fields (favorites_count & downloads_count). Put this part static in query will work.

...
order_by: coalesce(d.count, 0),

My question now is how to handle this like the first example with dynamic variable. I didn't find a way to handle this.

sort = [asc: :favorites_count, asc: :name] # comes from request
...
order_by: ^sort,

Ends up with Unknown column 'w0.favorites_count' in 'order clause'

order_by: ^foo(sort),

def foo(sort), do: coalesce(:count, 0)

Ends up with undefined function coalesce/2 (fragment/3)

Using dynamic/2 ends up with expected a field as an atom, a list or keyword list in 'order_by', got: 'dynamic(...)'

I understand the main problem, but didn't get a solution. Any ideas or in best case solutions? Thanks for help!

Body:
I managed to do this much simpler so here's my solution:

from(p in Post,
  order_by: [desc_nulls_last: fragment("array_length(?, 1)", p.votes)]
)
|> Repo.all()

The desc_nulls_last you can choose yourself, but the fragment works very well. array_length is a PostgreSQL specific thing so watch out for that!