问:
Plotting learning curve in keras gives KeyError: 'val_acc'
I was trying to plot train and test learning curve in keras, however, the following code produces KeyError: 'val_acc error.

The official document <https://keras.io/callbacks/> states that in order to use 'val_acc' I need to enable  validation and accuracy monitoring which I dont understand and dont know how to use in my code.

Any help would be much appreciated.
Thanks.

```<code>seed = 7
np.random.seed(seed)

dataframe = pandas.read_csv("iris.csv", header=None)
dataset = dataframe.values
X = dataset[:,0:4].astype(float)
Y = dataset[:,4]

encoder = LabelEncoder()
encoder.fit(Y)
encoded_Y = encoder.transform(Y)
dummy_y = np_utils.to_categorical(encoded_Y)

kfold = StratifiedKFold(y=Y, n_folds=10, shuffle=True, random_state=seed)
cvscores = []

for i, (train, test) in enumerate(kfold):

    model = Sequential()
    model.add(Dense(12, input_dim=4, init='uniform', activation='relu'))
    model.add(Dense(3, init='uniform', activation='sigmoid'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    history=model.fit(X[train], dummy_y[train], nb_epoch=200, batch_size=5, verbose=0)
    scores = model.evaluate(X[test], dummy_y[test], verbose=0)
    print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
    cvscores.append(scores[1] * 100)

print( "%.2f%% (+/- %.2f%%)" % (np.mean(cvscores), np.std(cvscores)))

print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
</code>```

答: If you upgrade keras older version (e.g. 2.2.5) to 2.3.0 (or newer) which is compatible with Tensorflow 2.0, you might have such error (e.g. KeyError: 'acc'). Both acc and val_acc has been renamed to accuracy and val_accuracy respectively. Renaming them in script will solve the issue.

OwnerDisplayName: Data Pagla

Body:
I was trying to plot train and test learning curve in keras, however, the following code produces KeyError: 'val_acc error.

The official document <https://keras.io/callbacks/> states that in order to use 'val_acc' I need to enable  validation and accuracy monitoring which I dont understand and dont know how to use in my code.

Any help would be much appreciated.
Thanks.

seed = 7
np.random.seed(seed)

dataframe = pandas.read_csv("iris.csv", header=None)
dataset = dataframe.values
X = dataset[:,0:4].astype(float)
Y = dataset[:,4]

encoder = LabelEncoder()
encoder.fit(Y)
encoded_Y = encoder.transform(Y)
dummy_y = np_utils.to_categorical(encoded_Y)

kfold = StratifiedKFold(y=Y, n_folds=10, shuffle=True, random_state=seed)
cvscores = []

for i, (train, test) in enumerate(kfold):

    model = Sequential()
    model.add(Dense(12, input_dim=4, init='uniform', activation='relu'))
    model.add(Dense(3, init='uniform', activation='sigmoid'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    history=model.fit(X[train], dummy_y[train], nb_epoch=200, batch_size=5, verbose=0)
    scores = model.evaluate(X[test], dummy_y[test], verbose=0)
    print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
    cvscores.append(scores[1] * 100)

print( "%.2f%% (+/- %.2f%%)" % (np.mean(cvscores), np.std(cvscores)))

print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()


来源: stackexchange

问:
How do i fix "npm does not support Node.js v12.14.1" when they came from the same LTS download?
Truthfully this has never happened with me on any development environment
My node version: 12.14.1
My npm version: 6.13.4

I was building a Gatsby Site using Sanity.io as a CRM and Im getting this error:

```<code>ahinds$ npm run dev

> sanity-gatsby-blog@1.0.7 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt
> lerna run dev --parallel

lerna notice cli v3.20.2
lerna info Executing command in 2 packages: "npm run dev"
sanity-gatsby-blog-web: npm WARN npm npm does not support Node.js v12.14.1
sanity-gatsby-blog-web: npm WARN npm You should probably upgrade to a newer version of node as we
sanity-gatsby-blog-web: npm WARN npm can't make any promises that npm will work with this version.
sanity-gatsby-blog-web: npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
sanity-gatsby-blog-web: npm WARN npm You can find the latest version at https://nodejs.org/
sanity-gatsby-blog-studio: npm WARN npm npm does not support Node.js v12.14.1
sanity-gatsby-blog-studio: npm WARN npm You should probably upgrade to a newer version of node as we
sanity-gatsby-blog-studio: npm WARN npm can't make any promises that npm will work with this version.
sanity-gatsby-blog-studio: npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
sanity-gatsby-blog-studio: npm WARN npm You can find the latest version at https://nodejs.org/
sanity-gatsby-blog-web: > sanity-gatsby-blog-web@1.0.1 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/web
sanity-gatsby-blog-web: > npm run clean-cache && gatsby develop
sanity-gatsby-blog-studio: > sanity-gatsby-blog-studio@1.0.5 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/studio
sanity-gatsby-blog-studio: > sanity start
sanity-gatsby-blog-web: npm WARN npm npm does not support Node.js v12.14.1
sanity-gatsby-blog-web: npm WARN npm You should probably upgrade to a newer version of node as we
sanity-gatsby-blog-web: npm WARN npm can't make any promises that npm will work with this version.
sanity-gatsby-blog-web: npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
sanity-gatsby-blog-web: npm WARN npm You can find the latest version at https://nodejs.org/
sanity-gatsby-blog-studio: Error occured trying to resolve project root:
sanity-gatsby-blog-studio: Unexpected token ] in JSON at position 425
sanity-gatsby-blog-studio: npm ERR! code ELIFECYCLE
sanity-gatsby-blog-studio: npm ERR! errno 1
sanity-gatsby-blog-studio: npm ERR! sanity-gatsby-blog-studio@1.0.5 dev: `sanity start`
sanity-gatsby-blog-studio: npm ERR! Exit status 1
sanity-gatsby-blog-studio: npm ERR!
sanity-gatsby-blog-studio: npm ERR! Failed at the sanity-gatsby-blog-studio@1.0.5 dev script.
sanity-gatsby-blog-studio: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
sanity-gatsby-blog-web: > sanity-gatsby-blog-web@1.0.1 clean-cache /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/web
sanity-gatsby-blog-web: > gatsby clean
sanity-gatsby-blog-studio: npm ERR! A complete log of this run can be found in:
sanity-gatsby-blog-studio: npm ERR!     /Users/ahinds/.npm/_logs/2020-02-14T21_27_42_015Z-debug.log
lerna ERR! npm run dev exited 1 in 'sanity-gatsby-blog-studio'
lerna ERR! npm run dev stdout:

> sanity-gatsby-blog-studio@1.0.5 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/studio
> sanity start

lerna ERR! npm run dev stderr:
npm WARN npm npm does not support Node.js v12.14.1
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
npm WARN npm You can find the latest version at https://nodejs.org/
Error occured trying to resolve project root:
Unexpected token ] in JSON at position 425
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sanity-gatsby-blog-studio@1.0.5 dev: `sanity start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sanity-gatsby-blog-studio@1.0.5 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/ahinds/.npm/_logs/2020-02-14T21_27_42_015Z-debug.log

lerna ERR! npm run dev exited 1 in 'sanity-gatsby-blog-studio'
lerna WARN complete Waiting for 1 child process to exit. CTRL-C to exit immediately.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sanity-gatsby-blog@1.0.7 dev: `lerna run dev --parallel`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sanity-gatsby-blog@1.0.7 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/ahinds/.npm/_logs/2020-02-14T21_27_42_097Z-debug.log
</code>```

Any idea why this version of node wouldn't work with this version of npm? I installed both from the NOde.js website so they were packaged together.

Here is my Repo

答:
So I am pretty much sure that here is your problem

```<code>sanity-gatsby-blog-studio: Error occured trying to resolve project root:
sanity-gatsby-blog-studio: Unexpected token ] in JSON at position 425
</code>```

Don't bother with WARNs that's alright

EDIT 1

Try to delete package-lock.json and node_modules, and do npm install, and try then

EDIT 2

After analyzing code error is in
studio -> sanity.json

I can make pull request if you want, but it's small change so go try :)

ContentLicense: CC BY-SA 4.0

Body:
Truthfully this has never happened with me on any development environment
My node version: 12.14.1
My npm version: 6.13.4

I was building a Gatsby Site using Sanity.io as a CRM and Im getting this error:

ahinds$ npm run dev

> sanity-gatsby-blog@1.0.7 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt
> lerna run dev --parallel

lerna notice cli v3.20.2
lerna info Executing command in 2 packages: "npm run dev"
sanity-gatsby-blog-web: npm WARN npm npm does not support Node.js v12.14.1
sanity-gatsby-blog-web: npm WARN npm You should probably upgrade to a newer version of node as we
sanity-gatsby-blog-web: npm WARN npm can't make any promises that npm will work with this version.
sanity-gatsby-blog-web: npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
sanity-gatsby-blog-web: npm WARN npm You can find the latest version at https://nodejs.org/
sanity-gatsby-blog-studio: npm WARN npm npm does not support Node.js v12.14.1
sanity-gatsby-blog-studio: npm WARN npm You should probably upgrade to a newer version of node as we
sanity-gatsby-blog-studio: npm WARN npm can't make any promises that npm will work with this version.
sanity-gatsby-blog-studio: npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
sanity-gatsby-blog-studio: npm WARN npm You can find the latest version at https://nodejs.org/
sanity-gatsby-blog-web: > sanity-gatsby-blog-web@1.0.1 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/web
sanity-gatsby-blog-web: > npm run clean-cache && gatsby develop
sanity-gatsby-blog-studio: > sanity-gatsby-blog-studio@1.0.5 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/studio
sanity-gatsby-blog-studio: > sanity start
sanity-gatsby-blog-web: npm WARN npm npm does not support Node.js v12.14.1
sanity-gatsby-blog-web: npm WARN npm You should probably upgrade to a newer version of node as we
sanity-gatsby-blog-web: npm WARN npm can't make any promises that npm will work with this version.
sanity-gatsby-blog-web: npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
sanity-gatsby-blog-web: npm WARN npm You can find the latest version at https://nodejs.org/
sanity-gatsby-blog-studio: Error occured trying to resolve project root:
sanity-gatsby-blog-studio: Unexpected token ] in JSON at position 425
sanity-gatsby-blog-studio: npm ERR! code ELIFECYCLE
sanity-gatsby-blog-studio: npm ERR! errno 1
sanity-gatsby-blog-studio: npm ERR! sanity-gatsby-blog-studio@1.0.5 dev: `sanity start`
sanity-gatsby-blog-studio: npm ERR! Exit status 1
sanity-gatsby-blog-studio: npm ERR!
sanity-gatsby-blog-studio: npm ERR! Failed at the sanity-gatsby-blog-studio@1.0.5 dev script.
sanity-gatsby-blog-studio: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
sanity-gatsby-blog-web: > sanity-gatsby-blog-web@1.0.1 clean-cache /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/web
sanity-gatsby-blog-web: > gatsby clean
sanity-gatsby-blog-studio: npm ERR! A complete log of this run can be found in:
sanity-gatsby-blog-studio: npm ERR!     /Users/ahinds/.npm/_logs/2020-02-14T21_27_42_015Z-debug.log
lerna ERR! npm run dev exited 1 in 'sanity-gatsby-blog-studio'
lerna ERR! npm run dev stdout:

> sanity-gatsby-blog-studio@1.0.5 dev /Users/ahinds/Desktop/AHinds/dev/LMPropertyMgmt/studio
> sanity start

lerna ERR! npm run dev stderr:
npm WARN npm npm does not support Node.js v12.14.1
npm WARN npm You should probably upgrade to a newer version of node as we
npm WARN npm can't make any promises that npm will work with this version.
npm WARN npm Supported releases of Node.js are the latest release of 4, 6, 7, 8, 9, 10.
npm WARN npm You can find the latest version at https://nodejs.org/
Error occured trying to resolve project root:
Unexpected token ] in JSON at position 425
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sanity-gatsby-blog-studio@1.0.5 dev: `sanity start`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sanity-gatsby-blog-studio@1.0.5 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/ahinds/.npm/_logs/2020-02-14T21_27_42_015Z-debug.log

lerna ERR! npm run dev exited 1 in 'sanity-gatsby-blog-studio'
lerna WARN complete Waiting for 1 child process to exit. CTRL-C to exit immediately.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! sanity-gatsby-blog@1.0.7 dev: `lerna run dev --parallel`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the sanity-gatsby-blog@1.0.7 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/ahinds/.npm/_logs/2020-02-14T21_27_42_097Z-debug.log

Any idea why this version of node wouldn't work with this version of npm? I installed both from the NOde.js website so they were packaged together.

Here is my Repo

Body:
So I am pretty much sure that here is your problem

sanity-gatsby-blog-studio: Error occured trying to resolve project root:
sanity-gatsby-blog-studio: Unexpected token ] in JSON at position 425

Don't bother with WARNs that's alright

EDIT 1

Try to delete package-lock.json and node_modules, and do npm install, and try then

EDIT 2

After analyzing code error is in
studio -> sanity.json

I can make pull request if you want, but it's small change so go try :)


问:
Zoom/scale at mouse position
I am struggling to figure out and determine how to zoom on my mouse position based on this example. (https://stackblitz.com/edit/js-fxnmkm?file=index.js)

```<code>let node,
    scale = 1,
    posX = 0,
    posY = 0,
    node = document.querySelector('.frame');

const render = () => {
  window.requestAnimationFrame(() => {
    let val = `translate3D(${posX}px, ${posY}px, 0px) scale(${scale})`
    node.style.transform = val
  })
}

window.addEventListener('wheel', (e) => {
  e.preventDefault();

  // Zooming happens here
  if (e.ctrlKey) {
    scale -= e.deltaY * 0.01;
  } else {
    posX -= e.deltaX * 2;
    posY -= e.deltaY * 2;
  }

  render();
});
</code>```

My desired effect is based on this example (https://codepen.io/techslides/pen/zowLd?editors=0010) when zooming in. Currently my example above only scales to the center of the "viewport" but I want it to be where my cursor currently is.

I have searched high and low for a solution that is not implemented via canvas. Any help would be appreciated!

Caveat The reason why I am using the wheel event is to mimic the interaction of Figma (the design tool) panning and zooming.

答:
This zoom in the 2nd link is a bit extreme so I tried to add some constraints. You can uncomment them and play more. For now looks and works exactly the same IMHO.

const container = document.querySelector('.container');
const image = document.querySelector('.image');
const speed = 0.5;
let size = {
  w: image.offsetWidth,
  h: image.offsetHeight
};
let pos = { x: 0, y: 0 };
let target = { x: 0, y: 0 };
let pointer = { x: 0, y: 0 };
let scale = 1;

window.addEventListener('wheel', event => {
  event.preventDefault();

  pointer.x = event.pageX - container.offsetLeft;
  pointer.y = event.pageY - container.offsetTop;
  target.x = (pointer.x - pos.x) / scale;
  target.y = (pointer.y - pos.y) / scale;

  scale += -1 * Math.max(-1, Math.min(1, event.deltaY)) * speed * scale;

  // Uncomment to constrain scale
  // const max_scale = 4;
  // const min_scale = 1;
  // scale = Math.max(min_scale, Math.min(max_scale, scale));

  pos.x = -target.x * scale + pointer.x;
  pos.y = -target.y * scale + pointer.y;

  // Uncomment for keeping the image within area (works with min scale = 1)
  // if (pos.x > 0) pos.x = 0;
  // if (pos.x + size.w * scale < size.w) pos.x = -size.w * (scale - 1);
  // if (pos.y > 0) pos.y = 0;
  // if (pos.y + size.h * scale < size.h) pos.y = -size.h * (scale - 1);

  image.style.transform = `translate(${pos.x}px,${pos.y}px) scale(${scale},${scale})`;
}, { passive: false });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  width: 400px;
  height: 400px;
  overflow: hidden;
  outline: 1px solid gray;
}

.image {
  width: 100%;
  height: 100%;
  transition: transform .3s;
  transform-origin: 0 0;
}

img {
  width: auto;
  height: auto;
  max-width: 100%;
}</code>```

```

Title: Zoom/scale at mouse position

Body:
I am struggling to figure out and determine how to zoom on my mouse position based on this example. (https://stackblitz.com/edit/js-fxnmkm?file=index.js)

let node,
    scale = 1,
    posX = 0,
    posY = 0,
    node = document.querySelector('.frame');

const render = () => {
  window.requestAnimationFrame(() => {
    let val = `translate3D(${posX}px, ${posY}px, 0px) scale(${scale})`
    node.style.transform = val
  })
}

window.addEventListener('wheel', (e) => {
  e.preventDefault();

  // Zooming happens here
  if (e.ctrlKey) {
    scale -= e.deltaY * 0.01;
  } else {
    posX -= e.deltaX * 2;
    posY -= e.deltaY * 2;
  }

  render();
});

My desired effect is based on this example (https://codepen.io/techslides/pen/zowLd?editors=0010) when zooming in. Currently my example above only scales to the center of the "viewport" but I want it to be where my cursor currently is.

I have searched high and low for a solution that is not implemented via canvas. Any help would be appreciated!

Caveat The reason why I am using the wheel event is to mimic the interaction of Figma (the design tool) panning and zooming.

Body:
This zoom in the 2nd link is a bit extreme so I tried to add some constraints. You can uncomment them and play more. For now looks and works exactly the same IMHO.

const container = document.querySelector('.container');
const image = document.querySelector('.image');
const speed = 0.5;
let size = {
  w: image.offsetWidth,
  h: image.offsetHeight
};
let pos = { x: 0, y: 0 };
let target = { x: 0, y: 0 };
let pointer = { x: 0, y: 0 };
let scale = 1;

window.addEventListener('wheel', event => {
  event.preventDefault();

  pointer.x = event.pageX - container.offsetLeft;
  pointer.y = event.pageY - container.offsetTop;
  target.x = (pointer.x - pos.x) / scale;
  target.y = (pointer.y - pos.y) / scale;

  scale += -1 * Math.max(-1, Math.min(1, event.deltaY)) * speed * scale;

  // Uncomment to constrain scale
  // const max_scale = 4;
  // const min_scale = 1;
  // scale = Math.max(min_scale, Math.min(max_scale, scale));

  pos.x = -target.x * scale + pointer.x;
  pos.y = -target.y * scale + pointer.y;

  // Uncomment for keeping the image within area (works with min scale = 1)
  // if (pos.x > 0) pos.x = 0;
  // if (pos.x + size.w * scale < size.w) pos.x = -size.w * (scale - 1);
  // if (pos.y > 0) pos.y = 0;
  // if (pos.y + size.h * scale < size.h) pos.y = -size.h * (scale - 1);

  image.style.transform = `translate(${pos.x}px,${pos.y}px) scale(${scale},${scale})`;
}, { passive: false });

.container {
  width: 400px;
  height: 400px;
  overflow: hidden;
  outline: 1px solid gray;
}

.image {
  width: 100%;
  height: 100%;
  transition: transform .3s;
  transform-origin: 0 0;
}

img {
  width: auto;
  height: auto;
  max-width: 100%;
}

<div class="container">
  <div class="image">
    <img src="https://picsum.photos/400/400" />
  </div>
</div>


问:
Sieve of Eratosthenes implementations and comparisons
Besides the simple implementation of Sieve of Eratosthenes with time complexity of O(N log log N), I also tried to implement a modification with time complexity O(N). Although, both produce the desired result, somehow the earlier one takes much lesser time compared to the next one and I'm unable to figure out why. I'd really appreciate some pointers on this.

Implementation 1:

```<code>def build_sieve_eratosthenes(num):
    ## Creates sieve of size (num+1) to correct for 0-indexing.
    primes_sieve = [1] * (num+1)
    primes_sieve[0] = primes_sieve[1] = 0
    for p in range(2, num):
        if primes_sieve[p] == 1:
            for mul in range(2*p, num+1, p):
                primes_sieve[mul] = 0
    return primes_sieve
</code>```

Implementation 2:

```<code>def build_sieve_eratosthenes_linear(num):
    ## Creates sieve of size (num+1) to correct for 0-indexing.
    primes_sieve = [1] * (num+1)
    primes_sieve[0] = primes_sieve[1] = 0

    ## Builds a list of size (num+1) recording the smallest prime factor of each number.
    SPF = [1] * (num+1)

    ## Builds a list of all primes seen so far with pos indicator of position where to insert the next prime.
    ## Uses a large fixed memory allocation scheme to avoid the usage of append list operation.
    primes = [0] * num
    pos = 0

    for p in range(2, num+1):
        if primes_sieve[p] == 1:
            primes[pos] = p
            pos = pos + 1
            ## Smallest prime factor of a prime is a prime itself.
            SPF[p] = p
        for i in range(0, pos):
            if p * primes[i] <= num and primes[i] <= SPF[p]:
                primes_sieve[p*primes[i]] = 0
                SPF[p * primes[i]] = primes[i]
            else:
                break
    return primes_sieve

test_num = 2000000
</code>```

Test method

```<code>def find_sum_of_primes_upto_num_with_sieve(sieve, num):
    primes_sieve = sieve(num)
    primes_sum = 0
    for n in range(len(primes_sieve)):
        if primes_sieve[n] == 1:
            primes_sum = primes_sum + n
    return primes_sum
</code>```

Results:

```<code>start2 = time.time()
sum_2 = find_sum_of_primes_upto_num_with_sieve(build_sieve_eratosthenes, test_num)
end2 = time.time()
print("Sum of primes obtained: ", sum_2)
print("Time taken by checking primality of each number is %f sec" % (end2 - start2))
</code>```

Sum of primes obtained:  142913828922

Time taken by checking primality of each number is 0.647822 sec

```<code>start3 = time.time()
sum_3 = find_sum_of_primes_upto_num_with_sieve(build_sieve_eratosthenes_linear, test_num)
end3 = time.time()
print("Sum of primes obtained: ", sum_3)
print("Time taken by checking primality of each number is %f sec" % (end3 - start3))
</code>```

Sum of primes obtained:  142913828922

Time taken by checking primality of each number is 1.561308 sec

答:
I dropped a simple iteration counter into each routine, and ran for powers of 10 from 10^3 through 10^7

build_sieve_eratosthenes:

```<code>    1000 has     1958 iterations in sieve
   10000 has    23071 iterations in sieve
  100000 has   256808 iterations in sieve
 1000000 has  2775210 iterations in sieve
10000000 has 29465738 iterations in sieve
</code>```

build_sieve_eratosthenes_linear:

```<code>    1000 has      831 iterations in sieve_linear
   10000 has     8770 iterations in sieve_linear
  100000 has    90407 iterations in sieve_linear
 1000000 has   921501 iterations in sieve_linear
10000000 has  9335420 iterations in sieve_linear
</code>```

Your linear function is not linear: note that inner loop, which runs pos times ... and pos is a count of the quantity of primes found, which is not a constant.

linear grows more slowly than the "normal" function, and has significantly fewer iterations overall.  However, it has a larger cost for each iteration, which is why you're seeing "inverted" times.  Each number found and each "cross-out" is more expensive in your linear function; the slower growth hasn't caught up by your limit of only 2*10^6, not by my limit of 10*7.  You could extrapolate this out for about a day to get a better feel of the appropriate timing, if that's worth it to you ... but the central "problem" is the slower processing for each number.

For the detail-curious, here's the full output:

```<code>1000 has 1958 iterations in sieve
Sum of primes obtained:  76127
Time taken by checking primality of each number is 0.000904 sec
10000 has 23071 iterations in sieve
Sum of primes obtained:  5736396
Time taken by checking primality of each number is 0.008270 sec
100000 has 256808 iterations in sieve
Sum of primes obtained:  454396537
Time taken by checking primality of each number is 0.067962 sec
1000000 has 2775210 iterations in sieve
Sum of primes obtained:  37550402023
Time taken by checking primality of each number is 0.428727 sec
10000000 has 29465738 iterations in sieve
Sum of primes obtained:  3203324994356
Time taken by checking primality of each number is 5.761439 sec
1000 has 831 iterations in sieve_linear
Sum of primes obtained:  76127
Time taken by checking primality of each number is 0.001069 sec
10000 has 8770 iterations in sieve_linear
Sum of primes obtained:  5736396
Time taken by checking primality of each number is 0.010398 sec
100000 has 90407 iterations in sieve_linear
Sum of primes obtained:  454396537
Time taken by checking primality of each number is 0.107276 sec
1000000 has 921501 iterations in sieve_linear
Sum of primes obtained:  37550402023
Time taken by checking primality of each number is 1.087080 sec
10000000 has 9335420 iterations in sieve_linear
Sum of primes obtained:  3203324994356
Time taken by checking primality of each number is 11.008726 sec
</code>```

Body:
Besides the simple implementation of Sieve of Eratosthenes with time complexity of O(N log log N), I also tried to implement a modification with time complexity O(N). Although, both produce the desired result, somehow the earlier one takes much lesser time compared to the next one and I'm unable to figure out why. I'd really appreciate some pointers on this.

Implementation 1:

def build_sieve_eratosthenes(num):
    ## Creates sieve of size (num+1) to correct for 0-indexing.
    primes_sieve = [1] * (num+1)
    primes_sieve[0] = primes_sieve[1] = 0
    for p in range(2, num):
        if primes_sieve[p] == 1:
            for mul in range(2*p, num+1, p):
                primes_sieve[mul] = 0
    return primes_sieve

Implementation 2:

def build_sieve_eratosthenes_linear(num):
    ## Creates sieve of size (num+1) to correct for 0-indexing.
    primes_sieve = [1] * (num+1)
    primes_sieve[0] = primes_sieve[1] = 0

    ## Builds a list of size (num+1) recording the smallest prime factor of each number.
    SPF = [1] * (num+1)

    ## Builds a list of all primes seen so far with pos indicator of position where to insert the next prime.
    ## Uses a large fixed memory allocation scheme to avoid the usage of append list operation.
    primes = [0] * num
    pos = 0

    for p in range(2, num+1):
        if primes_sieve[p] == 1:
            primes[pos] = p
            pos = pos + 1
            ## Smallest prime factor of a prime is a prime itself.
            SPF[p] = p
        for i in range(0, pos):
            if p * primes[i] <= num and primes[i] <= SPF[p]:
                primes_sieve[p*primes[i]] = 0
                SPF[p * primes[i]] = primes[i]
            else:
                break
    return primes_sieve

test_num = 2000000

Test method

def find_sum_of_primes_upto_num_with_sieve(sieve, num):
    primes_sieve = sieve(num)
    primes_sum = 0
    for n in range(len(primes_sieve)):
        if primes_sieve[n] == 1:
            primes_sum = primes_sum + n
    return primes_sum

Results:

start2 = time.time()
sum_2 = find_sum_of_primes_upto_num_with_sieve(build_sieve_eratosthenes, test_num)
end2 = time.time()
print("Sum of primes obtained: ", sum_2)
print("Time taken by checking primality of each number is %f sec" % (end2 - start2))

Sum of primes obtained:  142913828922

Time taken by checking primality of each number is 0.647822 sec

start3 = time.time()
sum_3 = find_sum_of_primes_upto_num_with_sieve(build_sieve_eratosthenes_linear, test_num)
end3 = time.time()
print("Sum of primes obtained: ", sum_3)
print("Time taken by checking primality of each number is %f sec" % (end3 - start3))

Sum of primes obtained:  142913828922

Time taken by checking primality of each number is 1.561308 sec

Body:
I dropped a simple iteration counter into each routine, and ran for powers of 10 from 10^3 through 10^7

build_sieve_eratosthenes:

    1000 has     1958 iterations in sieve
   10000 has    23071 iterations in sieve
  100000 has   256808 iterations in sieve
 1000000 has  2775210 iterations in sieve
10000000 has 29465738 iterations in sieve

build_sieve_eratosthenes_linear:

    1000 has      831 iterations in sieve_linear
   10000 has     8770 iterations in sieve_linear
  100000 has    90407 iterations in sieve_linear
 1000000 has   921501 iterations in sieve_linear
10000000 has  9335420 iterations in sieve_linear

Your linear function is not linear: note that inner loop, which runs pos times ... and pos is a count of the quantity of primes found, which is not a constant.

linear grows more slowly than the "normal" function, and has significantly fewer iterations overall.  However, it has a larger cost for each iteration, which is why you're seeing "inverted" times.  Each number found and each "cross-out" is more expensive in your linear function; the slower growth hasn't caught up by your limit of only 2*10^6, not by my limit of 10*7.  You could extrapolate this out for about a day to get a better feel of the appropriate timing, if that's worth it to you ... but the central "problem" is the slower processing for each number.

For the detail-curious, here's the full output:

1000 has 1958 iterations in sieve
Sum of primes obtained:  76127
Time taken by checking primality of each number is 0.000904 sec
10000 has 23071 iterations in sieve
Sum of primes obtained:  5736396
Time taken by checking primality of each number is 0.008270 sec
100000 has 256808 iterations in sieve
Sum of primes obtained:  454396537
Time taken by checking primality of each number is 0.067962 sec
1000000 has 2775210 iterations in sieve
Sum of primes obtained:  37550402023
Time taken by checking primality of each number is 0.428727 sec
10000000 has 29465738 iterations in sieve
Sum of primes obtained:  3203324994356
Time taken by checking primality of each number is 5.761439 sec
1000 has 831 iterations in sieve_linear
Sum of primes obtained:  76127
Time taken by checking primality of each number is 0.001069 sec
10000 has 8770 iterations in sieve_linear
Sum of primes obtained:  5736396
Time taken by checking primality of each number is 0.010398 sec
100000 has 90407 iterations in sieve_linear
Sum of primes obtained:  454396537
Time taken by checking primality of each number is 0.107276 sec
1000000 has 921501 iterations in sieve_linear
Sum of primes obtained:  37550402023
Time taken by checking primality of each number is 1.087080 sec
10000000 has 9335420 iterations in sieve_linear
Sum of primes obtained:  3203324994356
Time taken by checking primality of each number is 11.008726 sec


问:
High performance TCP server in C#
I am an experienced C# developer, but I have not developed a TCP server application so far. Now I have to develop a highly scalable and high performance server that can handle at least 5-10 thousand concurrent connections: getting -raw byte- data via GPRS from GPS devices.

A common communication process should look like this:

GPS device initiates a connection to my server

my server answers if I want to get data

device send GPS data

my server sends report to the device about getting it (sg like checksum)

getting new data from GPS, reportm and this happens again and again

later GPS DEVICE closes the connection

So, in my server I need

trace connected/active clients

to close any client from server side

catch the event, when a device closes the connection

get byte data

send data to clients

I started to read about this topic over the internet, but it seems to be a nightmare for me. There are a lot of ways, but I could not find out which is the best.

Async socket methods seems the best for me, but writing code in this async style is terrible and not easy to debug.

So my question is: which do you think the best way to implement a high performance TCP server in C#? Do you know any good open source component to do this? (I tried several ones, but I could not find a good one.)

答:
You can do this with the TcpClient class, although to tell the truth I don't know if you could have 10 thousand open sockets. That's quite a lot. But I regularly use TcpClient to handle dozens of concurrent sockets. And the asynchronous model is actually very nice to use.

Your biggest problem isn't going to be making TcpClient work. With 10 thousand concurrent connections, I'm thinking bandwidth and scalability are going to be problems. I don't even know if one machine can handle all that traffic. I suppose it depends on how large the packets are and how often they're coming in. But you'd better do some back-of-the-envelope estimation before you commit to implementing this all on a single computer.

ContentLicense: CC BY-SA 3.0

Title: High performance TCP server in C#


问:
Calendar List View in SharePoint Server 2019
In SharePoint 2019 I create a calendar by going to: Settings Wheel > Add an app > Calendar

How can I then create a list view for the calendar?  Can this be done by going to Calendar > Edit List, then creating a new view with the list view format?  If so, how?

Or do you need to create a seperate page and add the calendar to that page as a web part, then edit that web part (or something similar)?

By list view I mean a vertical list of calendar items that span from today's date to 12 months in advance.  However, I am less concerned with the specifics of the date range and more concerned with the basic how to.  Thanks.

答:
If you've been using Modern views and pages, the SharePoint calendar is likely very confusing because it still uses the "classic" view, even if the entire rest of your site is using the Modern UI.

Go open your calendar list to its default view.

In the upper left-hand corner, click on the small "Calendar" tab (see screenshot)

This will bring up the calendar "ribbon", and from there you have multiple View options to either edit the current view or create a new one (see screenshot)

For more details on List View creation, see https://support.office.com/en-us/article/create-change-or-delete-a-view-of-a-list-or-library-27ae65b8-bc5b-4949-b29b-4ee87144a9c9#OfficeVersion=2016,_2013,_2010 -- be sure to not actually look at the version of this page for SP2019, as it assumes you are editing a modern list.


问:
Move all files in subdirectories contained in one parent directory to N sub-subdirectories
So I have a directory with 44 subdirectories. Each of these subdirectories contain 15,000 files.

What I would like to do is: for each subdirectory, create a sub-subdirectory with max N files, i.e. 5,000.

From: Parent -> Subdirectory w/ 15,000 files

To: Parent -> Subdirectory -> N Sub-sub directories (with names starting at 1), each with max. N files.

Any advice on how to approach this is greatly appreciated!

答:
I would start by iterating through each of the directories.

```<code>$My44Subdirs = gci -directory "Path_to_my_Main_directory"
</code>```

For each of the directories, I would load all the files with an

```<code>[array]$AllFiles = gci "path_to_one_of_your_subdirectories"
</code>```

Finally, you could use array descriptors to loop through groups of files.

```<code>$ctr=0
$maxperfolder=5000
Do
{
    ForEach ($file in $AllFiles[$ctr..($ctr+$maxPerFolder-1)])
    {
        move the files here
    {
    $ctr += $maxPerFolder
} Until ($ctr -gt "total_#_of_Files_in_this_folder")
</code>```

I made this a bit generic so you could adapt it as you see fit.

Good luck.

Body:
I would start by iterating through each of the directories.

$My44Subdirs = gci -directory "Path_to_my_Main_directory"

For each of the directories, I would load all the files with an

[array]$AllFiles = gci "path_to_one_of_your_subdirectories"

Finally, you could use array descriptors to loop through groups of files.

$ctr=0
$maxperfolder=5000
Do
{
    ForEach ($file in $AllFiles[$ctr..($ctr+$maxPerFolder-1)])
    {
        move the files here
    {
    $ctr += $maxPerFolder
} Until ($ctr -gt "total_#_of_Files_in_this_folder")

I made this a bit generic so you could adapt it as you see fit.

Good luck.


问:
Best way to split data of varying length into columns
I have some data that includes 4 columns. First column is a place and last three columns are numbers or ranges of numbers.

What is the best way to split this data into four columns?

```<code>Red Coast Van 240-250 240-250 285-365
Beanbelt 310-400 310-400 450-540
North Star 310-400 310-400 450-540
Hamilton Fines, TA 380-390 380-390 505-530
Western Beanbelt 310-400 310-400 450-525
Main, PA 370-380 370-380 505-525
Dust Dodge, NY 380-390 380-390 520-525
Midwest Bean Belt (Des) m 400-475 400-475 572-615
</code>```

Desired Output

```<code>Red Coast Van; 240-250; 240-250; 285-365
Beanbelt; 310-400; 310-400; 450-540
North Star; 310-400; 310-400; 450-540
Hamilton Fines, TA; 380-390; 380-390; 505-530
Western Beanbelt; 310-400; 310-400; 450-525
Main, PA; 370-380; 370-380; 505-525
Dust Dodge, NY; 380-390; 380-390; 520-525
Midwest Bean Belt (Des) m; 400-475; 400-475; 572-615
</code>```

答:
It's completely simple to do this in Vim:

```<code>:%s/ \(\d\)/; \1/g
</code>```

You instantly get the result you want. ( 24 substitutions on 8 lines )

Body:
I have some data that includes 4 columns. First column is a place and last three columns are numbers or ranges of numbers.

What is the best way to split this data into four columns?

Red Coast Van 240-250 240-250 285-365
Beanbelt 310-400 310-400 450-540
North Star 310-400 310-400 450-540
Hamilton Fines, TA 380-390 380-390 505-530
Western Beanbelt 310-400 310-400 450-525
Main, PA 370-380 370-380 505-525
Dust Dodge, NY 380-390 380-390 520-525
Midwest Bean Belt (Des) m 400-475 400-475 572-615

Desired Output

Red Coast Van; 240-250; 240-250; 285-365
Beanbelt; 310-400; 310-400; 450-540
North Star; 310-400; 310-400; 450-540
Hamilton Fines, TA; 380-390; 380-390; 505-530
Western Beanbelt; 310-400; 310-400; 450-525
Main, PA; 370-380; 370-380; 505-525
Dust Dodge, NY; 380-390; 380-390; 520-525
Midwest Bean Belt (Des) m; 400-475; 400-475; 572-615

Body:
It's completely simple to do this in Vim:

:%s/ \(\d\)/; \1/g

You instantly get the result you want. ( 24 substitutions on 8 lines )


问:
Return large subgraphs from a list of Ids in Cypher (Neo4j)
I have a question regarding the use of the Neo4j client for Java. I have a graph with about 120.000.000 nodes and 1.000.000.000 edges. From this graph, I want to extract subgraphs (average size about 500 nodes). For this purpose, I have created an index on the Id fields of the nodes.
The queries look like this

```<code>MATCH (a:XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
RETURN a AS blablubb
</code>```

At the moment I am looking for the edges with a second query that looks like this

```<code>MATCH (a::XXX:YYYY)-[r:ZZZZ]-(b::XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
AND b.uid IN [9999, 5555, 7777, 99999, ...]
</code>```

This is very very slow especially when the subgraphs get bigger.
My question now is how can I connect the two queries to get both the edges and the nodes of the subgraph at once. I know that there is a faster solution because the Neo4j browser gives me a
a visualization for

```<code>MATCH (a:XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
RETURN a AS blablubb
</code>```

which contains all edges.

thank you very much for your help

答:
This is a simpler and more efficient version of your own answer:

```<code>WITH [9999, 5555, 7777, 99999, ...] AS wanted
MATCH (n:Uid)-[r]->(n2)
WHERE n.uid IN wanted AND n2 IN wanted
RETURN r AS relation
</code>```

If you pass in wanted as a parameter, the query would then be:

```<code>MATCH (n:Uid)-[r]->(n2)
WHERE n.uid IN $wanted AND n2 IN $wanted
RETURN r AS relation
</code>```

Body:
I have a question regarding the use of the Neo4j client for Java. I have a graph with about 120.000.000 nodes and 1.000.000.000 edges. From this graph, I want to extract subgraphs (average size about 500 nodes). For this purpose, I have created an index on the Id fields of the nodes.
The queries look like this

MATCH (a:XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
RETURN a AS blablubb

At the moment I am looking for the edges with a second query that looks like this

MATCH (a::XXX:YYYY)-[r:ZZZZ]-(b::XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
AND b.uid IN [9999, 5555, 7777, 99999, ...]

This is very very slow especially when the subgraphs get bigger.
My question now is how can I connect the two queries to get both the edges and the nodes of the subgraph at once. I know that there is a faster solution because the Neo4j browser gives me a
a visualization for

MATCH (a:XXX:YYYY)
WHERE a.uid IN [9999, 5555, 7777, 99999, ...]
RETURN a AS blablubb

which contains all edges.

thank you very much for your help

Body:
This is a simpler and more efficient version of your own answer:

WITH [9999, 5555, 7777, 99999, ...] AS wanted
MATCH (n:Uid)-[r]->(n2)
WHERE n.uid IN wanted AND n2 IN wanted
RETURN r AS relation

If you pass in wanted as a parameter, the query would then be:

MATCH (n:Uid)-[r]->(n2)
WHERE n.uid IN $wanted AND n2 IN $wanted
RETURN r AS relation


问:
Ceaser Cipher Using OOP Logic
Below is my code for a class based Ceaser's cipher, this is for MIT 6.001 Ps4b.py

Question:

In the test cases at the end of the code file (test case#02), the expected output is (24, 'hello').

While the actual output of the program is (2, 'hello')

And this makes sense because lines 330-332 :

```<code>plaintext = PlaintextMessage('hello', 2)
print('Expected Output: jgnnq')
print('Actual Output:', plaintext.get_message_text_encrypted())
</code>```

creates an instance of PlaintextMessage with the shift value set to 2.
where 'jgnnq' is the encryption of 'hello'.

And lines 335-337:

```<code>ciphertext = CiphertextMessage('jgnnq')
print('Expected Output:', (24, 'hello'))
print('Actual Output:', ciphertext.decrypt_message())

</code>```

here:
string = 'jgnnq'
decrypted string = 'hello'
best factor actual is 2, but expected is 24
should print a tuple containing the factor used to (de)crypt the string  and the decrypted string (which is 'hello').

So my question is why is the expected 'best factor' for test case#02 is 24 while the factor used to (de)crypt the string is 2.

The test cases are provided by MIT OCW and were not modified on my part.

Code:

```<code>def load_words(file_name):
    '''
    file_name (string): the name of the file containing
    the list of words to load

    Returns: a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    '''
    # print("Loading word list from file...")
    # inFile: file
    inFile = open(file_name, 'r')
    # wordlist: list of strings
    wordlist = []
    for line in inFile:
        wordlist.extend([word.lower() for word in line.split(' ')])
    # print("  ", len(wordlist), "words loaded.")
    return wordlist

def is_word(word_list, word):
    '''
    Determines if word is a valid word, ignoring
    capitalization and punctuation

    word_list (list): list of words in the dictionary.
    word (string): a possible word.

    Returns: True if word is in word_list, False otherwise

    Example:
    >>> is_word(word_list, 'bat') returns
    True
    >>> is_word(word_list, 'asdf') returns
    False
    '''
    word = word.lower()

    word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
    return word in word_list

def get_story_string():
    """
    Returns: a story in encrypted text.
    """
    f = open("story.txt", "r")
    story = str(f.read())
    f.close()
    return story

WORDLIST_FILENAME = 'words.txt'
words = load_words(WORDLIST_FILENAME)

class Message(object):
    def __init__(self, text):
        '''
        Initializes a Message object

        text (string): the message's text

        a Message object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''

        self.message_text = text
        self.valid_words = load_words(WORDLIST_FILENAME)
        #self.valid_words = [word for word in text.split() if is_word(words, word)]

    def get_message_text(self):
        '''
        Used to safely access self.message_text outside of the class

        Returns: self.message_text
        '''
        return self.message_text

    def get_valid_words(self):
        '''
        Used to safely access a copy of self.valid_words outside of the class.
        This helps you avoid accidentally mutating class attributes.

        Returns: a COPY of self.valid_words
        '''
        return self.valid_words.copy()

    def build_shift_dict(self, shift):
        '''
        Creates a dictionary that can be used to apply a cipher to a letter.
        The dictionary maps every uppercase and lowercase letter to a
        character shifted down the alphabet by the input shift. The dictionary
        should have 52 keys of all the uppercase letters and all the lowercase
        letters only.

        shift (integer): the amount by which to shift every letter of the
        alphabet. 0 <= shift < 26

        Returns: a dictionary mapping a letter (string) to
                 another letter (string).
        '''

        lowercase_letters = ascii_lowercase
        uppercase_letters = ascii_uppercase

        # alphabet = lowercase_letters + uppercase_letters

        # alphabet_shifted = alphabet[-shift:] + alphabet[:-shift]

        lowercase_shifted = lowercase_letters[shift:] + lowercase_letters[:shift]

        uppercase_shifted = uppercase_letters[-shift:] + uppercase_letters[:-shift]

        # shift_dict = {letter: shift for letter, shift in zip(alphabet, alphabet_shifted)}

        shift_dict_lowercase = {letter: shift for letter, shift in zip(lowercase_letters, lowercase_shifted)}

        shift_dict_uppercase = {letter: shift for letter, shift in zip(uppercase_letters, uppercase_shifted)}

        return [shift_dict_lowercase, shift_dict_uppercase]

    def apply_shift(self, shift):
        '''
        Applies the Caesar Cipher to self.message_text with the input shift.
        Creates a new string that is self.message_text shifted down the
        alphabet by some number of characters determined by the input shift

        shift (integer): the shift with which to encrypt the message.
        0 <= shift < 26

        Returns: the message text (string) in which every character is shifted
             down the alphabet by the input shift
        '''
        shift_dict_lowercase, shift_dict_uppercase = self.build_shift_dict(shift)

        plain_msg = self.message_text

        encrypted_msg = []

        for char in plain_msg:
            if char in ascii_lowercase:
                encrypted_msg.append(shift_dict_lowercase[char])
            elif char in ascii_uppercase:
                encrypted_msg.append(shift_dict_uppercase[char])
            else:
                encrypted_msg.append(char)

        # encrypted_msg = [shift_dict_lowercase.get(char, char) for char in plain_msg]

        return ''.join(encrypted_msg)

class PlaintextMessage(Message):
    def __init__(self, text, shift):
        '''
        Initializes a PlaintextMessage object

        text (string): the message's text
        shift (integer): the shift associated with this message

        A PlaintextMessage object inherits from Message and has five attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
            self.shift (integer, determined by input shift)
            self.encryption_dict (dictionary, built using shift)
            self.message_text_encrypted (string, created using shift)

        '''
        Message.__init__(self, text)
        self.shift = shift
        self.encryption_dict = self.build_shift_dict(shift)
        self.message_text_encrypted = self.apply_shift(shift)

    def get_shift(self):
        '''
        Used to safely access self.shift outside of the class

        Returns: self.shift
        '''
        return self.shift

    def get_encryption_dict(self):
        '''
        Used to safely access a copy self.encryption_dict outside of the class

        Returns: a COPY of self.encryption_dict
        '''
        return self.encryption_dict.copy()

    def get_message_text_encrypted(self):
        '''
        Used to safely access self.message_text_encrypted outside of the class

        Returns: self.message_text_encrypted
        '''
        return self.message_text_encrypted

    def change_shift(self, shift):
        '''
        Changes self.shift of the PlaintextMessage and updates other
        attributes determined by shift.

        shift (integer): the new shift that should be associated with this message.
        0 <= shift < 26

        Returns: nothing
        '''
        self.__init__(self.message_text, shift)

class CiphertextMessage(Message):
    def __init__(self, text):
        '''
        Initializes a CiphertextMessage object

        text (string): the message's text

        a CiphertextMessage object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''
        Message.__init__(self, text)

        # need to optimize this:

    def decrypt_message(self):
        '''
        Decrypt self.message_text by trying every possible shift value
        and find the "best" one. We will define "best" as the shift that
        creates the maximum number of real words when we use apply_shift(shift)
        on the message text. If s is the original shift value used to encrypt
        the message, then we would expect 26 - s to be the best shift value
        for decrypting it.

        Note: if multiple shifts are equally good such that they all create
        the maximum number of valid words, you may choose any of those shifts
        (and their corresponding decrypted messages) to return

        Returns: a tuple of the best shift value used to decrypt the message
        and the decrypted message text using that shift value
        '''
        # using a dictonary to get the max number of valid words in a string
        # have to figure out how to see if a word is valid after applying the
        # shift to it.
        results = {}
        words_found = {n: [] for n in range(26)}
        for n in range(26):
            for word in self.message_text.split():
                m = Message(word)
                word = m.apply_shift(-n)
                # print(word)
                if is_word(words, word):
                    results[n] = results.get(n, 0) + 1
                    words_found[n].append(word)
        # print(results)
        # print(words_found)
        # print(max(results))

        best_factor = max(results)

        return best_factor, PlaintextMessage(self.message_text, -best_factor).get_message_text_encrypted()

        # num_words_per_factor = {n:len(words_found[n]) for n in range(26)}
        # best_factor =
        # print(best_factor)

# plain_text_msg = PlaintextMessage('Hello, Cat, Dog, Kate', 0)

# print(plain_text_msg.get_message_text())

# encrypted_msg = plain_text_msg.apply_shift(3)

# print(encrypted_msg)

# cipher_msg = CiphertextMessage(encrypted_msg)

# decrypted_msg = cipher_msg.decrypt_message()

# print(decrypted_msg)

if __name__ == '__main__':

#    #Example test case (PlaintextMessage)
#    plaintext = PlaintextMessage('hello', 2)
#    print('Expected Output: jgnnq')
#    print('Actual Output:', plaintext.get_message_text_encrypted())
#
#    #Example test case (CiphertextMessage)
#    ciphertext = CiphertextMessage('jgnnq')
#    print('Expected Output:', (24, 'hello'))
#    print('Actual Output:', ciphertext.decrypt_message())

    #TODO: WRITE YOUR TEST CASES HERE

    #TODO: best shift value and unencrypted story

    #Example test case (PlaintextMessage)
    plaintext = PlaintextMessage('hello', 2)
    print('Expected Output: jgnnq')
    print('Actual Output:', plaintext.get_message_text_encrypted())

    #Example test case (CiphertextMessage)
    ciphertext = CiphertextMessage('jgnnq')
    print('Expected Output:', (24, 'hello'))
    print('Actual Output:', ciphertext.decrypt_message())

</code>```

答:
For decrypting with a certain factor you should shift in the opposite direction in respect to encrypt operation.

Note that 24 = -2 (mod 26).

The expected output apparently is looking for the shift value to apply with the encoding procedure.

Title: Ceaser Cipher Using OOP Logic

Body:
Below is my code for a class based Ceaser's cipher, this is for MIT 6.001 Ps4b.py

Question:

In the test cases at the end of the code file (test case#02), the expected output is (24, 'hello').

While the actual output of the program is (2, 'hello')

And this makes sense because lines 330-332 :

plaintext = PlaintextMessage('hello', 2)
print('Expected Output: jgnnq')
print('Actual Output:', plaintext.get_message_text_encrypted())

creates an instance of PlaintextMessage with the shift value set to 2.
where 'jgnnq' is the encryption of 'hello'.

And lines 335-337:

ciphertext = CiphertextMessage('jgnnq')
print('Expected Output:', (24, 'hello'))
print('Actual Output:', ciphertext.decrypt_message())

here:
string = 'jgnnq'
decrypted string = 'hello'
best factor actual is 2, but expected is 24
should print a tuple containing the factor used to (de)crypt the string  and the decrypted string (which is 'hello').

So my question is why is the expected 'best factor' for test case#02 is 24 while the factor used to (de)crypt the string is 2.

The test cases are provided by MIT OCW and were not modified on my part.

Code:

def load_words(file_name):
    '''
    file_name (string): the name of the file containing
    the list of words to load

    Returns: a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    '''
    # print("Loading word list from file...")
    # inFile: file
    inFile = open(file_name, 'r')
    # wordlist: list of strings
    wordlist = []
    for line in inFile:
        wordlist.extend([word.lower() for word in line.split(' ')])
    # print("  ", len(wordlist), "words loaded.")
    return wordlist

def is_word(word_list, word):
    '''
    Determines if word is a valid word, ignoring
    capitalization and punctuation

    word_list (list): list of words in the dictionary.
    word (string): a possible word.

    Returns: True if word is in word_list, False otherwise

    Example:
    >>> is_word(word_list, 'bat') returns
    True
    >>> is_word(word_list, 'asdf') returns
    False
    '''
    word = word.lower()

    word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
    return word in word_list

def get_story_string():
    """
    Returns: a story in encrypted text.
    """
    f = open("story.txt", "r")
    story = str(f.read())
    f.close()
    return story

WORDLIST_FILENAME = 'words.txt'
words = load_words(WORDLIST_FILENAME)

class Message(object):
    def __init__(self, text):
        '''
        Initializes a Message object

        text (string): the message's text

        a Message object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''

        self.message_text = text
        self.valid_words = load_words(WORDLIST_FILENAME)
        #self.valid_words = [word for word in text.split() if is_word(words, word)]

    def get_message_text(self):
        '''
        Used to safely access self.message_text outside of the class

        Returns: self.message_text
        '''
        return self.message_text

    def get_valid_words(self):
        '''
        Used to safely access a copy of self.valid_words outside of the class.
        This helps you avoid accidentally mutating class attributes.

        Returns: a COPY of self.valid_words
        '''
        return self.valid_words.copy()

    def build_shift_dict(self, shift):
        '''
        Creates a dictionary that can be used to apply a cipher to a letter.
        The dictionary maps every uppercase and lowercase letter to a
        character shifted down the alphabet by the input shift. The dictionary
        should have 52 keys of all the uppercase letters and all the lowercase
        letters only.

        shift (integer): the amount by which to shift every letter of the
        alphabet. 0 <= shift < 26

        Returns: a dictionary mapping a letter (string) to
                 another letter (string).
        '''

        lowercase_letters = ascii_lowercase
        uppercase_letters = ascii_uppercase

        # alphabet = lowercase_letters + uppercase_letters

        # alphabet_shifted = alphabet[-shift:] + alphabet[:-shift]

        lowercase_shifted = lowercase_letters[shift:] + lowercase_letters[:shift]

        uppercase_shifted = uppercase_letters[-shift:] + uppercase_letters[:-shift]

        # shift_dict = {letter: shift for letter, shift in zip(alphabet, alphabet_shifted)}

        shift_dict_lowercase = {letter: shift for letter, shift in zip(lowercase_letters, lowercase_shifted)}

        shift_dict_uppercase = {letter: shift for letter, shift in zip(uppercase_letters, uppercase_shifted)}

        return [shift_dict_lowercase, shift_dict_uppercase]

    def apply_shift(self, shift):
        '''
        Applies the Caesar Cipher to self.message_text with the input shift.
        Creates a new string that is self.message_text shifted down the
        alphabet by some number of characters determined by the input shift

        shift (integer): the shift with which to encrypt the message.
        0 <= shift < 26

        Returns: the message text (string) in which every character is shifted
             down the alphabet by the input shift
        '''
        shift_dict_lowercase, shift_dict_uppercase = self.build_shift_dict(shift)

        plain_msg = self.message_text

        encrypted_msg = []

        for char in plain_msg:
            if char in ascii_lowercase:
                encrypted_msg.append(shift_dict_lowercase[char])
            elif char in ascii_uppercase:
                encrypted_msg.append(shift_dict_uppercase[char])
            else:
                encrypted_msg.append(char)

        # encrypted_msg = [shift_dict_lowercase.get(char, char) for char in plain_msg]

        return ''.join(encrypted_msg)

class PlaintextMessage(Message):
    def __init__(self, text, shift):
        '''
        Initializes a PlaintextMessage object

        text (string): the message's text
        shift (integer): the shift associated with this message

        A PlaintextMessage object inherits from Message and has five attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
            self.shift (integer, determined by input shift)
            self.encryption_dict (dictionary, built using shift)
            self.message_text_encrypted (string, created using shift)

        '''
        Message.__init__(self, text)
        self.shift = shift
        self.encryption_dict = self.build_shift_dict(shift)
        self.message_text_encrypted = self.apply_shift(shift)

    def get_shift(self):
        '''
        Used to safely access self.shift outside of the class

        Returns: self.shift
        '''
        return self.shift

    def get_encryption_dict(self):
        '''
        Used to safely access a copy self.encryption_dict outside of the class

        Returns: a COPY of self.encryption_dict
        '''
        return self.encryption_dict.copy()

    def get_message_text_encrypted(self):
        '''
        Used to safely access self.message_text_encrypted outside of the class

        Returns: self.message_text_encrypted
        '''
        return self.message_text_encrypted

    def change_shift(self, shift):
        '''
        Changes self.shift of the PlaintextMessage and updates other
        attributes determined by shift.

        shift (integer): the new shift that should be associated with this message.
        0 <= shift < 26

        Returns: nothing
        '''
        self.__init__(self.message_text, shift)

class CiphertextMessage(Message):
    def __init__(self, text):
        '''
        Initializes a CiphertextMessage object

        text (string): the message's text

        a CiphertextMessage object has two attributes:
            self.message_text (string, determined by input text)
            self.valid_words (list, determined using helper function load_words)
        '''
        Message.__init__(self, text)

        # need to optimize this:

    def decrypt_message(self):
        '''
        Decrypt self.message_text by trying every possible shift value
        and find the "best" one. We will define "best" as the shift that
        creates the maximum number of real words when we use apply_shift(shift)
        on the message text. If s is the original shift value used to encrypt
        the message, then we would expect 26 - s to be the best shift value
        for decrypting it.

        Note: if multiple shifts are equally good such that they all create
        the maximum number of valid words, you may choose any of those shifts
        (and their corresponding decrypted messages) to return

        Returns: a tuple of the best shift value used to decrypt the message
        and the decrypted message text using that shift value
        '''
        # using a dictonary to get the max number of valid words in a string
        # have to figure out how to see if a word is valid after applying the
        # shift to it.
        results = {}
        words_found = {n: [] for n in range(26)}
        for n in range(26):
            for word in self.message_text.split():
                m = Message(word)
                word = m.apply_shift(-n)
                # print(word)
                if is_word(words, word):
                    results[n] = results.get(n, 0) + 1
                    words_found[n].append(word)
        # print(results)
        # print(words_found)
        # print(max(results))

        best_factor = max(results)

        return best_factor, PlaintextMessage(self.message_text, -best_factor).get_message_text_encrypted()

        # num_words_per_factor = {n:len(words_found[n]) for n in range(26)}
        # best_factor =
        # print(best_factor)

# plain_text_msg = PlaintextMessage('Hello, Cat, Dog, Kate', 0)

# print(plain_text_msg.get_message_text())

# encrypted_msg = plain_text_msg.apply_shift(3)

# print(encrypted_msg)

# cipher_msg = CiphertextMessage(encrypted_msg)

# decrypted_msg = cipher_msg.decrypt_message()

# print(decrypted_msg)

if __name__ == '__main__':

#    #Example test case (PlaintextMessage)
#    plaintext = PlaintextMessage('hello', 2)
#    print('Expected Output: jgnnq')
#    print('Actual Output:', plaintext.get_message_text_encrypted())
#
#    #Example test case (CiphertextMessage)
#    ciphertext = CiphertextMessage('jgnnq')
#    print('Expected Output:', (24, 'hello'))
#    print('Actual Output:', ciphertext.decrypt_message())

    #TODO: WRITE YOUR TEST CASES HERE

    #TODO: best shift value and unencrypted story

    #Example test case (PlaintextMessage)
    plaintext = PlaintextMessage('hello', 2)
    print('Expected Output: jgnnq')
    print('Actual Output:', plaintext.get_message_text_encrypted())

    #Example test case (CiphertextMessage)
    ciphertext = CiphertextMessage('jgnnq')
    print('Expected Output:', (24, 'hello'))
    print('Actual Output:', ciphertext.decrypt_message())


问:
Eclipse + Maven Plugin + EGit Plugin = Checkout from GitHub a specific Branche and Tag?
I know this is a relatively special question. Maybe some knows this nevertheless:

I want to compile Hector with Maven in Eclipse=> Branch: 0.7.0 and Tag: hector-0.7.0-29
(https://github.com/rantav/hector.git). (The mentionaed Branch/Tag are not(!) the Master Branch, so requires a dedicated Checkout.)

I have installed: Maven-Maven Plugin and the EGit Plugin for Eclipse

My Problem:

1.)Maven Plugin allows to checkout directoly from a SCM like GitHub (when installing the maven-git-plugin= this is not the same as egit plugin). I am now able to downlaod a Project directly from Github with the maven plugin. On Disk I find the Tag and Branch (as Git files in the .git Directory.)

But the Problem is, the Version that is checkout out is the MASTER Branch. And I do not find an option to checkout the specific Branch and Tag directly within Eclipse. When clicking on "Team-Context-Menu" I normally have all the EGit Options (to checkout a specific Branch/Tag). But due to the fact the Project got downladed via the Maven Plugin it seems it is not regarded from Eclipse as an Git Repository.) So klicking on "Team" where I normally have all my Git-Commoands is more or less empty. I need to find a way to tell Eclipse that this Project is a GIT/EGIT managable project, so that I have the menu options to manage it.

2.) Furthermore I want the downloaded Project to be completely "SCM-Managed" (via Git) so that I can "track" my local changes to the files. Therefore all "Egit Context Menu" Stuff should be working for this checked out project.

If someone knows how to do this, I would be very kind for any advice!

Thank you very much! Jens

答: Well, the simpler answer would just be to clone the repository with EGit, right click on the repository in the repositories view and select "Import Projects".</p>


问:
in nested for loop in JAVA, why is the faster big loop in small loop than small loop in big loop?
When the number of iterations is the same, I wonder if the smaller iterations of the outer 'for loop' are faster.

This is my java code.

total loops iterations is 100 billion.

```<code>public class Test {

    public static long run1() {
        final long start = System.nanoTime();
        long cnt = 0;
        for(int i = 0; i<1000000000; i++) {
            for(int j = 0 ; j<100 ; j++) {
                cnt++;
            }
        }
        final long end = System.nanoTime();

        System.out.println("run1 : "+(end-start)*1e-9+" sec");
        return start - end;
    }

    public static long run2() {
        final long start = System.nanoTime();
        long cnt = 0;
        for(int i = 0; i<100; i++) {
            for(int j = 0 ; j<1000000000 ; j++) {
                cnt++;
            }
        }
        final long end = System.nanoTime();

        System.out.println("run2 : "+(end-start)*1e-9+" sec");
        return start - end;
    }

    public static void main(String[] args) {

        for(int i = 0 ; i < 10 ; i++) {
            long test1 = run1();
            long test2 = run2();
            System.out.println("Time diff : "+(test1-test2)*1e-9+" sec\n");
        }
    }
}
</code>```

and this is result

```<code>run1 : 4.5772473950000006 sec
run2 : 1.7155700900000002 sec
Time diff : -2.861677305 sec

run1 : 4.4107229420000005 sec
run2 : 1.6532413140000002 sec
Time diff : -2.7574816280000003 sec

run1 : 3.815836296 sec
run2 : 1.761153921 sec
Time diff : -2.054682375 sec

run1 : 3.913543021 sec
run2 : 1.752971717 sec
Time diff : -2.1605713040000003 sec

run1 : 3.851766485 sec
run2 : 1.7262416440000001 sec
Time diff : -2.1255248410000003 sec

run1 : 3.95305219 sec
run2 : 1.7323067330000002 sec
Time diff : -2.220745457 sec

run1 : 3.924869236 sec
run2 : 1.6953032440000002 sec
Time diff : -2.229565992 sec

run1 : 3.839871705 sec
run2 : 1.692300162 sec
Time diff : -2.147571543 sec

run1 : 3.93864626 sec
run2 : 1.704322469 sec
Time diff : -2.234323791 sec

run1 : 3.863758493 sec
run2 : 1.700392962 sec
Time diff : -2.163365531 sec
</code>```

like this,

I wonder why these results are coming.

and, edited by Triple nested loops, Similar results are obtained.

答:
The performance difference you see is because of loop unrolling, JVM unrolls internal loop first, but cannot unroll outer loop.

Unrolling means that:

```<code>for (int i=0;i<MAX;i++) cnt++;
</code>```

is converted into something like:

```<code>int i=0;
for (;(i+16)<=MAX; i+=16) cnt+=16;
for (i<MAX; i++) cnt++; // handle case when MAX % 16 != 0
</code>```

so total number of operations is actually:

```<code>run1: 1000000000 * (100 / 16 + 4) = 10 000 000 000 operations
run2: 100 * (1000000000 / 16)     =  6 250 000 000 operations
</code>```

Body:
When the number of iterations is the same, I wonder if the smaller iterations of the outer 'for loop' are faster.

This is my java code.

total loops iterations is 100 billion.

public class Test {

    public static long run1() {
        final long start = System.nanoTime();
        long cnt = 0;
        for(int i = 0; i<1000000000; i++) {
            for(int j = 0 ; j<100 ; j++) {
                cnt++;
            }
        }
        final long end = System.nanoTime();

        System.out.println("run1 : "+(end-start)*1e-9+" sec");
        return start - end;
    }

    public static long run2() {
        final long start = System.nanoTime();
        long cnt = 0;
        for(int i = 0; i<100; i++) {
            for(int j = 0 ; j<1000000000 ; j++) {
                cnt++;
            }
        }
        final long end = System.nanoTime();

        System.out.println("run2 : "+(end-start)*1e-9+" sec");
        return start - end;
    }

    public static void main(String[] args) {

        for(int i = 0 ; i < 10 ; i++) {
            long test1 = run1();
            long test2 = run2();
            System.out.println("Time diff : "+(test1-test2)*1e-9+" sec\n");
        }
    }
}

and this is result

run1 : 4.5772473950000006 sec
run2 : 1.7155700900000002 sec
Time diff : -2.861677305 sec

run1 : 4.4107229420000005 sec
run2 : 1.6532413140000002 sec
Time diff : -2.7574816280000003 sec

run1 : 3.815836296 sec
run2 : 1.761153921 sec
Time diff : -2.054682375 sec

run1 : 3.913543021 sec
run2 : 1.752971717 sec
Time diff : -2.1605713040000003 sec

run1 : 3.851766485 sec
run2 : 1.7262416440000001 sec
Time diff : -2.1255248410000003 sec

run1 : 3.95305219 sec
run2 : 1.7323067330000002 sec
Time diff : -2.220745457 sec

run1 : 3.924869236 sec
run2 : 1.6953032440000002 sec
Time diff : -2.229565992 sec

run1 : 3.839871705 sec
run2 : 1.692300162 sec
Time diff : -2.147571543 sec

run1 : 3.93864626 sec
run2 : 1.704322469 sec
Time diff : -2.234323791 sec

run1 : 3.863758493 sec
run2 : 1.700392962 sec
Time diff : -2.163365531 sec

like this,

I wonder why these results are coming.

and, edited by Triple nested loops, Similar results are obtained.

Body:
The performance difference you see is because of loop unrolling, JVM unrolls internal loop first, but cannot unroll outer loop.

Unrolling means that:

for (int i=0;i<MAX;i++) cnt++;

is converted into something like:

int i=0;
for (;(i+16)<=MAX; i+=16) cnt+=16;
for (i<MAX; i++) cnt++; // handle case when MAX % 16 != 0

so total number of operations is actually:

run1: 1000000000 * (100 / 16 + 4) = 10 000 000 000 operations
run2: 100 * (1000000000 / 16)     =  6 250 000 000 operations


问:
Rendering several components in a grid
Imagen we have a little stock application. Here we make a list off all available stocks.We have a stocks.vue component, the code below, and a stock.vue component. We have 4 stocks here. We want to render them in a 2x2 grid. The code below renders them in a 1x4 grid.
A div.columns holds up to 12 div.column (Bulma), so for our 2x2 grid we'd need two div.columns each holding two div.column and each div.column would hold a stock.

```<code><template>
    <div>
        <p>Current stocks:</p>
        <div class="columns">
            <div class="column" v-for="stock in stocks">
                <app-stock :stock="stock"></app-stock>
            </div>
        </div>
    </div>
</template>

<script>
    import Stock from './stock.vue';

    export default {
        data() {
            return {
                stocks: [
                    { name: 'BMW', value: '23' },
                    { name: 'Apple', value: '223' },
                    { name: 'Sony', value: '43' },
                    { name: 'EDA', value: '235' }
                ]
            }
        },
        components: {
            appStock: Stock
        }
    }
</script>
</code>```

Now, what's a good way to rewrite the above code such that it renders our stocks in a 2x2 grid? Would it maybe be better to first rearrange our data in a computed such that it represents or view more appropriately i.e. in this case into a 2 dimensional array of objects?

答:
Rodurico's answer is definitely correct.

Adding the Bulma class "is-multiline" to the columns div, and "is-half" class to the stock column div is all you need to (and all you should) modify to achieve the desired grid layout.

As Rodurico provided:

```<code><div class="columns is-multiline">
  <div class="column is-half" v-for="stock in stocks">
    <app-stock :stock="stock"></app-stock>
  </div>
</div>
</code>```

Regarding the second part of your question, should you rearrange your data in a more appropriate way in a computed property to display it in a 2x2, the answer is no.

Your data is a list of individual and unrelated items.
Each stock item exists on its own, completely independent from the other items.

```<code>[item1, item2, item3, item4]
</code>```

Organizing the data into another structure (such as a 2D array) would imply some sort of shared relationship or commonality between the items that share a row with each other.

```<code>[ [item1, item2], [item3, item4] ]
</code>```

This format suggests item1 and item2 are somehow more closely related than item3 and item4, and that is not the case.

Though there are potentially some scenarios that might warrant reformatting your data for the purpose of displaying it, in the vast majority of scenarios, how it is displayed should be defined in the template/layout.

In fact, not only is having the data in a 2D array not required (or helpful) to display it in a 2x2 grid, doing so could actually present various new challenges.

Say for example you want to sort or search the data, it now needs to look inside arrays to compare the values, or say you want to add or remove an item, this now requires modifying considerably more arrays instead of just the one.

In this case, those changes wouldn't present such challenges, because if applied to the stocks object its computed properties would reflect those changes automatically. But I think the point is still relevant. Having to create and populate more complex datatypes whenever your array is modified isn't going to be faster. And if the result you're looking for can be achieved by adding minimal CSS classes or rules, that is hands down the approach that should be taken.

I hope that answers the other half of your question.

Title: Rendering several components in a grid

Body:
Imagen we have a little stock application. Here we make a list off all available stocks.We have a stocks.vue component, the code below, and a stock.vue component. We have 4 stocks here. We want to render them in a 2x2 grid. The code below renders them in a 1x4 grid.
A div.columns holds up to 12 div.column (Bulma), so for our 2x2 grid we'd need two div.columns each holding two div.column and each div.column would hold a stock.

<template>

Current stocks:

                <app-stock :stock="stock"></app-stock>

</template>

Now, what's a good way to rewrite the above code such that it renders our stocks in a 2x2 grid? Would it maybe be better to first rearrange our data in a computed such that it represents or view more appropriately i.e. in this case into a 2 dimensional array of objects?

Body:
Rodurico's answer is definitely correct.

Adding the Bulma class "is-multiline" to the columns div, and "is-half" class to the stock column div is all you need to (and all you should) modify to achieve the desired grid layout.

As Rodurico provided:

<div class="columns is-multiline">
  <div class="column is-half" v-for="stock in stocks">
    <app-stock :stock="stock"></app-stock>
  </div>
</div>

Regarding the second part of your question, should you rearrange your data in a more appropriate way in a computed property to display it in a 2x2, the answer is no.

Your data is a list of individual and unrelated items.
Each stock item exists on its own, completely independent from the other items.

[item1, item2, item3, item4]

Organizing the data into another structure (such as a 2D array) would imply some sort of shared relationship or commonality between the items that share a row with each other.

[ [item1, item2], [item3, item4] ]

This format suggests item1 and item2 are somehow more closely related than item3 and item4, and that is not the case.

Though there are potentially some scenarios that might warrant reformatting your data for the purpose of displaying it, in the vast majority of scenarios, how it is displayed should be defined in the template/layout.

In fact, not only is having the data in a 2D array not required (or helpful) to display it in a 2x2 grid, doing so could actually present various new challenges.

Say for example you want to sort or search the data, it now needs to look inside arrays to compare the values, or say you want to add or remove an item, this now requires modifying considerably more arrays instead of just the one.

In this case, those changes wouldn't present such challenges, because if applied to the stocks object its computed properties would reflect those changes automatically. But I think the point is still relevant. Having to create and populate more complex datatypes whenever your array is modified isn't going to be faster. And if the result you're looking for can be achieved by adding minimal CSS classes or rules, that is hands down the approach that should be taken.

I hope that answers the other half of your question.


问:
Display data in nice format in Python for elementary classroom project
I am working on a project to use in an elementary school where teachers and students will submit a list of adjectives and nouns that we will then use in a creative LEGO build challenge each week.

I am trying to learn python so please bear with me. I created a program asking people to submit 26 adjectives and 10 nouns. I want to take the screenshot and use as a the guide for the kids to build with.

I am not sure how to create a table or other structure to display the information all on one screen and more readable.

I would love any help! My code is below.

```<code>print("Thank you for helping with a creative LEGO project")
print("Please remember to keep words school safe and readable for elementary students")

adj1 = input("Give me a adjective ")
adj2 = input("Give me a adjective ")
adj3 = input("Give me a adjective ")
adj4 = input("Give me a adjective ")
adj5 = input("Give me a adjective ")
adj6 = input("Give me a adjective ")
adj7 = input("Give me a adjective ")
adj8 = input("Give me a adjective ")
adj9 = input("Give me a adjective ")
adj10 = input("Give me a adjective ")
adj11 = input("Give me a adjective ")
adj12 = input("Give me a adjective ")
adj13 = input("Give me a adjective ")
adj14 = input("Give me a adjective ")
adj15 = input("Give me a adjective ")
adj16 = input("Give me a adjective ")
adj17 = input("Give me a adjective ")
adj18 = input("Give me a adjective ")
adj19 = input("Give me a adjective ")
adj20 = input("Give me a adjective ")
adj21 = input("Give me a adjective ")
adj22 = input("Give me a adjective ")
adj23 = input("Give me a adjective ")
adj24 = input("Give me a adjective ")
adj25 = input("Give me a adjective ")
adj26 = input("Give me a adjective ")

print("Nice job coming up with all of those adjectives")
print("Now we are moving on to nouns")
print("Here we go!")

noun1 = input("Give me a noun ")
noun2 = input("Give me a noun ")
noun3 = input("Give me a noun ")
noun4 = input("Give me a noun ")
noun5 = input("Give me a noun ")
noun6 = input("Give me a noun ")
noun7 = input("Give me a noun ")
noun8 = input("Give me a noun ")
noun9 = input("Give me a noun ")
noun10 = input("Give me a noun ")

print("A = " + adj1)
print("B = " + adj2)
print("C = " + adj3)
print("D = " + adj4)
print("E = " + adj5)
print("F = " + adj6)
print("G = " + adj7)
print("H = " + adj8)
print("I = " + adj9)
print("J = " + adj10)
print("K = " + adj11)
print("L = " + adj12)
print("M = " + adj13)
print("N = " + adj14)
print("O = " + adj15)
print("P = " + adj16)
print("Q = " + adj17)
print("R = " + adj18)
print("S = " + adj19)
print("T = " + adj20)
print("U = " + adj21)
print("V = " + adj22)
print("W = " + adj23)
print("X = " + adj24)
print("Y = " + adj25)
print("Z = " + adj26)

print("1-3 = " + noun1)
print("4-6 = " + noun2)
print("7-9 = " + noun3)
print("10-12 = " + noun4)
print("13-15 = " + noun5)
print("16-18 = " + noun6)
print("19-21 = " + noun7)
print("22-25 = " + noun8)
print("26-28 = " + noun9)
print("29-31 = " + noun10)
</code>```

答:
Before my suggestions, I'd like to note that writing a Python program for this task may not be an ideal solution.

Given how you described your goal, it sounds to me like Google Forms or another survey service would easier to set up and easier for people to fill out. And with the results in a spreadsheet, you might find it easier to manipulate them to look how you want to.

Others have made suggestions about how to simplify your program, so are some simple ideas for how to condense the output..

I make two assumptions: that you have the user's inputs in lists called nouns and adjectives, as suggested in the other answers, and that you are printing your output to a terminal.

First, you might want to format the word lists as comma-separated words using str.join. Then, you can use textwrap.fill to split lines between words instead of in the middle of words.

```<code>import textwrap, shutil

# Use the other answers' suggestions to put words into these lists.
nouns = []

# Some basic pre-processing using <<a href="https://docs.python.org/3/tutorial/classes.html#generator-expressions" rel="nofollow noreferrer">generator expression</a>> (see also <<a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">list comprehensions</a>>)

# Remove trailing spaces, make all-lowercase, remove duplicates, and sort alphabetically
nouns = sorted(set(noun.strip().lower() for noun in nouns))

# Get width of terminal (80 if not using a terminal)
width = shutil.get_terminal_size().columns

print("Nouns",
      "=====",
      textwrap.fill(", ".join(nouns), width),
      sep="\n")  # separate outputs by newlines
</code>```

To do more advanced formatting, like formatting the words as a table, you need to process the data a bit more, because you need to know how wide each column can be. Alternatively, you can use one of the existing libraries. For example, NumPy is a popular scientific package with advanced (multi-dimensional) arrays as its biggest feature, and it neatly formats them in a grid for display. A more advanced, but possibly more useful library is Pandas, which largely revolves around an object (the DataFrame) that more or less represents a table of data, including headers.

Also, if you are asking for words from schoolchildren, even if you tell them to keep the words safe for school, make sure to look them over yourself, because children who think inappropriate words are funny are not likely to listen (some might even put them in just because you asked them not to). You'll also want to look over the words to remove duplicates and correct misspellings.

Body:
I am working on a project to use in an elementary school where teachers and students will submit a list of adjectives and nouns that we will then use in a creative LEGO build challenge each week.

I am trying to learn python so please bear with me. I created a program asking people to submit 26 adjectives and 10 nouns. I want to take the screenshot and use as a the guide for the kids to build with.

I am not sure how to create a table or other structure to display the information all on one screen and more readable.

I would love any help! My code is below.

print("Thank you for helping with a creative LEGO project")
print("Please remember to keep words school safe and readable for elementary students")

adj1 = input("Give me a adjective ")
adj2 = input("Give me a adjective ")
adj3 = input("Give me a adjective ")
adj4 = input("Give me a adjective ")
adj5 = input("Give me a adjective ")
adj6 = input("Give me a adjective ")
adj7 = input("Give me a adjective ")
adj8 = input("Give me a adjective ")
adj9 = input("Give me a adjective ")
adj10 = input("Give me a adjective ")
adj11 = input("Give me a adjective ")
adj12 = input("Give me a adjective ")
adj13 = input("Give me a adjective ")
adj14 = input("Give me a adjective ")
adj15 = input("Give me a adjective ")
adj16 = input("Give me a adjective ")
adj17 = input("Give me a adjective ")
adj18 = input("Give me a adjective ")
adj19 = input("Give me a adjective ")
adj20 = input("Give me a adjective ")
adj21 = input("Give me a adjective ")
adj22 = input("Give me a adjective ")
adj23 = input("Give me a adjective ")
adj24 = input("Give me a adjective ")
adj25 = input("Give me a adjective ")
adj26 = input("Give me a adjective ")

print("Nice job coming up with all of those adjectives")
print("Now we are moving on to nouns")
print("Here we go!")

noun1 = input("Give me a noun ")
noun2 = input("Give me a noun ")
noun3 = input("Give me a noun ")
noun4 = input("Give me a noun ")
noun5 = input("Give me a noun ")
noun6 = input("Give me a noun ")
noun7 = input("Give me a noun ")
noun8 = input("Give me a noun ")
noun9 = input("Give me a noun ")
noun10 = input("Give me a noun ")

print("A = " + adj1)
print("B = " + adj2)
print("C = " + adj3)
print("D = " + adj4)
print("E = " + adj5)
print("F = " + adj6)
print("G = " + adj7)
print("H = " + adj8)
print("I = " + adj9)
print("J = " + adj10)
print("K = " + adj11)
print("L = " + adj12)
print("M = " + adj13)
print("N = " + adj14)
print("O = " + adj15)
print("P = " + adj16)
print("Q = " + adj17)
print("R = " + adj18)
print("S = " + adj19)
print("T = " + adj20)
print("U = " + adj21)
print("V = " + adj22)
print("W = " + adj23)
print("X = " + adj24)
print("Y = " + adj25)
print("Z = " + adj26)

print("1-3 = " + noun1)
print("4-6 = " + noun2)
print("7-9 = " + noun3)
print("10-12 = " + noun4)
print("13-15 = " + noun5)
print("16-18 = " + noun6)
print("19-21 = " + noun7)
print("22-25 = " + noun8)
print("26-28 = " + noun9)
print("29-31 = " + noun10)

Body:
Before my suggestions, I'd like to note that writing a Python program for this task may not be an ideal solution.

Given how you described your goal, it sounds to me like Google Forms or another survey service would easier to set up and easier for people to fill out. And with the results in a spreadsheet, you might find it easier to manipulate them to look how you want to.

Others have made suggestions about how to simplify your program, so are some simple ideas for how to condense the output..

I make two assumptions: that you have the user's inputs in lists called nouns and adjectives, as suggested in the other answers, and that you are printing your output to a terminal.

First, you might want to format the word lists as comma-separated words using str.join. Then, you can use textwrap.fill to split lines between words instead of in the middle of words.

import textwrap, shutil

# Use the other answers' suggestions to put words into these lists.
nouns = []

# Some basic pre-processing using <generator expression> (see also <list comprehensions>)

# Remove trailing spaces, make all-lowercase, remove duplicates, and sort alphabetically
nouns = sorted(set(noun.strip().lower() for noun in nouns))

# Get width of terminal (80 if not using a terminal)
width = shutil.get_terminal_size().columns

print("Nouns",
      "=====",
      textwrap.fill(", ".join(nouns), width),
      sep="\n")  # separate outputs by newlines

To do more advanced formatting, like formatting the words as a table, you need to process the data a bit more, because you need to know how wide each column can be. Alternatively, you can use one of the existing libraries. For example, NumPy is a popular scientific package with advanced (multi-dimensional) arrays as its biggest feature, and it neatly formats them in a grid for display. A more advanced, but possibly more useful library is Pandas, which largely revolves around an object (the DataFrame) that more or less represents a table of data, including headers.

Also, if you are asking for words from schoolchildren, even if you tell them to keep the words safe for school, make sure to look them over yourself, because children who think inappropriate words are funny are not likely to listen (some might even put them in just because you asked them not to). You'll also want to look over the words to remove duplicates and correct misspellings.


问:
Phusion Passenger on cPanel (Apache) "Cannot GET" (Express); the same code works on localhost and Heroku
My Nodejs app works well on localhost & Heroku, but fails on my cPanel hosting with Phusion Passenger (CloudLinux).

When I look in the node_modules folder, express is there.

Does anyone know how to get my app up and running?

This is the error log:

```<code>App 1268608 output: internal/modules/cjs/loader.js:775
App 1268608 output:     throw err;
App 1268608 output:     ^
App 1268608 output:
App 1268608 output: Error: Cannot find module 'express'
App 1268608 output: Require stack:
App 1268608 output: - /home/futur/w2/server.js
App 1268608 output: - /opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts/node-loader.js
App 1268608 output:     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:772:15)
App 1268608 output:     at Function.Module._load (internal/modules/cjs/loader.js:677:27)
App 1268608 output:     at Module.require (internal/modules/cjs/loader.js:830:19)
App 1268608 output:     at Module.require (/opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts/node-loader.js:80:25)
App 1268608 output:     at require (internal/modules/cjs/helpers.js:68:18)
App 1268608 output:     at Object.<anonymous> (/home/futur/w2/server.js:1:17)
App 1268608 output:     at Module._compile (internal/modules/cjs/loader.js:936:30)
App 1268608 output:     at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
App 1268608 output:     at Module.load (internal/modules/cjs/loader.js:790:32)
App 1268608 output:     at Function.Module._load (internal/modules/cjs/loader.js:703:12) {
App 1268608 output:   code: 'MODULE_NOT_FOUND',
App 1268608 output:   requireStack: [
App 1268608 output:     '/home/futur/w2/server.js',
App 1268608 output:     '/opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts/node-loader.js'
App 1268608 output:   ]
App 1268608 output: }
App 1271723 output: app is running on port 3002
App 1400344 output: app is running on port 3002 ```
```

答:
I solved the issue - the problem with Phusion Passenger is that the root path isn't '/', it's '/yourAppURL' (in my case '/w2' (https://futuristicon.com/w2/).

Really weird, since root is '/' with all other environments (as I mentioned in the question - app worked flawlessly on Heroku & localhost env).

Important: routes others than root won't work out of the box. You will have to, for some reason, manually create an empty folder named the same as your route parameter, inside the folder in which your .htaccess lives.

For example, if you wanted to make a route like this:

```<code>app.get('/w2/signup', (req, res) => {
res.send('Signup!')
})
</code>```

You would have to create a new folder named signup (not the application root folder, but the folder of your app's URL)

Body:
My Nodejs app works well on localhost & Heroku, but fails on my cPanel hosting with Phusion Passenger (CloudLinux).

When I look in the node_modules folder, express is there.

Does anyone know how to get my app up and running?

This is the error log:

App 1268608 output: internal/modules/cjs/loader.js:775
App 1268608 output:     throw err;
App 1268608 output:     ^
App 1268608 output:
App 1268608 output: Error: Cannot find module 'express'
App 1268608 output: Require stack:
App 1268608 output: - /home/futur/w2/server.js
App 1268608 output: - /opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts/node-loader.js
App 1268608 output:     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:772:15)
App 1268608 output:     at Function.Module._load (internal/modules/cjs/loader.js:677:27)
App 1268608 output:     at Module.require (internal/modules/cjs/loader.js:830:19)
App 1268608 output:     at Module.require (/opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts/node-loader.js:80:25)
App 1268608 output:     at require (internal/modules/cjs/helpers.js:68:18)
App 1268608 output:     at Object.<anonymous> (/home/futur/w2/server.js:1:17)
App 1268608 output:     at Module._compile (internal/modules/cjs/loader.js:936:30)
App 1268608 output:     at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
App 1268608 output:     at Module.load (internal/modules/cjs/loader.js:790:32)
App 1268608 output:     at Function.Module._load (internal/modules/cjs/loader.js:703:12) {
App 1268608 output:   code: 'MODULE_NOT_FOUND',
App 1268608 output:   requireStack: [
App 1268608 output:     '/home/futur/w2/server.js',
App 1268608 output:     '/opt/passenger-5.3.7-9.el7.cloudlinux/src/helper-scripts/node-loader.js'
App 1268608 output:   ]
App 1268608 output: }
App 1271723 output: app is running on port 3002
App 1400344 output: app is running on port 3002 ```

Body:
I solved the issue - the problem with Phusion Passenger is that the root path isn't '/', it's '/yourAppURL' (in my case '/w2' (https://futuristicon.com/w2/).

Really weird, since root is '/' with all other environments (as I mentioned in the question - app worked flawlessly on Heroku & localhost env).

Important: routes others than root won't work out of the box. You will have to, for some reason, manually create an empty folder named the same as your route parameter, inside the folder in which your .htaccess lives.

For example, if you wanted to make a route like this:

app.get('/w2/signup', (req, res) => {
res.send('Signup!')
})

You would have to create a new folder named signup (not the application root folder, but the folder of your app's URL)