问:
How to read CSV file in Python?
I'm using Spyder for Python 2.7 on Windows 8. I'm trying to open and read a csv file and see all the data stored in it, but this is what I get instead:

```<code>runfile('C:/Users/John/Documents/Python Scripts/FLInsuraneFile.py', wdir='C:/Users/John/Documents/Python Scripts')
<_io.TextIOWrapper name='FL_insurance_sample.csv' mode='r' encoding='cp1252'>
</code>```

How can I open the file properly?

答:
First things first, you must understand the inner-workings of a CSV file.
CSV file are made up of rows and columns, like this:

```<code>| NAME  |  AGE |  ROOM |
| ---------------------|
| Kaleb |  15  |   256 |
| ---------------------|
| John  |  15  |   257 |
| ---------------------|
| Anna  |  16  |   269 |
</code>```

Where the vertical elements are columns, and the horizontal elements are rows. Rows contain many types of data, like name/age/room. Columns contain only one type of data, like name.

Moving on, here is an example function to read the CSV.
Please carefully study the code.

```<code>def read_csv(csv_file):
    data = []
    with open(csv_file, 'r') as f:

        # create a list of rows in the CSV file
        rows = f.readlines()

        # strip white-space and newlines
        rows = list(map(lambda x:x.strip(), rows))

        for row in rows:

            # further split each row into columns assuming delimiter is comma
            row = row.split(',')

            # append to data-frame our new row-object with columns
            data.append(row)

    return data
</code>```

Now why would I do that? Well, this function allows you to access your CSV file by row/column. Meaning it is easier to index. Look at this example using the above function:

```<code>csvFile = 'test.csv'

# invoke our function
data = read_csv(csvFile)

# get row 1, column 2 of file
print(data[1][2])

# get entirety of row 2
print(data[2])

# get row 0, columns 1 & 2
print(data[0][1], data[0][2])
</code>```

As you can see, we can easily access different parts of the file by using our read_csv() function and creating a nested-list object. Finally, if you want to print to the entire file, you simply use a for loop after creating the data-object.

```<code>data = read_csv(csvFile)

for row in data:
    print(row)
</code>```

In conclusion, Pandas is great for big-data science, but if you just
want to read/access the CSV, this function is just fine. No need to install big packages for little tasks, unless of course you want to :) .

Good luck!

Title: How to read CSV file in Python?

Body:
I'm using Spyder for Python 2.7 on Windows 8. I'm trying to open and read a csv file and see all the data stored in it, but this is what I get instead:

runfile('C:/Users/John/Documents/Python Scripts/FLInsuraneFile.py', wdir='C:/Users/John/Documents/Python Scripts')
<_io.TextIOWrapper name='FL_insurance_sample.csv' mode='r' encoding='cp1252'>

How can I open the file properly?

Body:
First things first, you must understand the inner-workings of a CSV file.
CSV file are made up of rows and columns, like this:

| NAME  |  AGE |  ROOM |
| ---------------------|
| Kaleb |  15  |   256 |
| ---------------------|
| John  |  15  |   257 |
| ---------------------|
| Anna  |  16  |   269 |

Where the vertical elements are columns, and the horizontal elements are rows. Rows contain many types of data, like name/age/room. Columns contain only one type of data, like name.

Moving on, here is an example function to read the CSV.
Please carefully study the code.

def read_csv(csv_file):
    data = []
    with open(csv_file, 'r') as f:

        # create a list of rows in the CSV file
        rows = f.readlines()

        # strip white-space and newlines
        rows = list(map(lambda x:x.strip(), rows))

        for row in rows:

            # further split each row into columns assuming delimiter is comma
            row = row.split(',')

            # append to data-frame our new row-object with columns
            data.append(row)

    return data

Now why would I do that? Well, this function allows you to access your CSV file by row/column. Meaning it is easier to index. Look at this example using the above function:

csvFile = 'test.csv'

# invoke our function
data = read_csv(csvFile)

# get row 1, column 2 of file
print(data[1][2])

# get entirety of row 2
print(data[2])

# get row 0, columns 1 & 2
print(data[0][1], data[0][2])

As you can see, we can easily access different parts of the file by using our read_csv() function and creating a nested-list object. Finally, if you want to print to the entire file, you simply use a for loop after creating the data-object.

data = read_csv(csvFile)

for row in data:
    print(row)

In conclusion, Pandas is great for big-data science, but if you just
want to read/access the CSV, this function is just fine. No need to install big packages for little tasks, unless of course you want to :) .

Good luck!


来源: stackexchange

问:
Lookup Operation in Network File System
Can some one explain the lookup operation in NFS v3.0 in detail. Operations occurring on client side and server side.  </p>

答:
This is something you should probably read up about and too generic for stackoverflow. The RFC says the following:

The LOOKUP procedure is used by the client to traverse
     multicomponent file names (pathnames). Each call to LOOKUP is
     used to resolve one segment of a pathname. There are two reasons
     for restricting LOOKUP to a single segment: it is hard to
     standardize a common format for hierarchical file names and the
     client and server may have different mappings of pathnames to
     file systems. This would imply that either the client must break
     the path name at file system attachment points, or the server
     must know about the client's file system attachment points. In
     NFS version 3 protocol implementations, it is the client that
     constructs the hierarchical file name space using mounts to
     build a hierarchy. Support utilities, such as the Automounter,
     provide a way to manage a shared, consistent image of the file
     name space while still being driven by the client mount
     process.

See https://www.ietf.org/rfc/rfc1813.txt for more information.

ContentLicense: CC BY-SA 3.0

Title: Lookup Operation in Network File System


问:
coturn: Need help configurating my server correctly
I am trying to set up a STUN/TURN server on my local computer for a webrtc application of me. I decided to use coturn. Note that my server is running behind a NAT.

So i fired up my Ubuntu VM and installed it. After reading through the wiki I got it working, atleast on my local network. For testing purposes, i use this site. Therefore, when i try it there with 192.168.178.25:3478, it works. When i try it with "public-ip":3478, it doesnt.

This told me, it is working locally and it should be a port/NAT issue. What i did:

1) I set the VM to Bridging

2) I opened the port 3478 on my router. To test if this is really working, i used telnet on a remote machine and it worked. Another test was that i set up a quick apache server on my local machine on port 3478 and it could be accessed from the outside. This told me that there is, or should be, not port/NAT issue and my turn server should be working.

Any ideas?

I am running my server with the following command:

"sudo turnserver -X "public-ip" -listening-port=3478 -v

The turnserver.conf looks something like this:

fingerprint

realm="myRealm"

lt-cred-mech

user=test:test

As telnet and apache server are both working, i am pretty sure i have a configuration issue. I basically spent the weekend trying and im really lost on what could be wrong.

Thanks for any help!

答:
From the documentation of turnserver

-X, --external-ip <public-ip>[/private-ip] TURN Server public/private address mapping, if the server is behind NAT. In that situation, if a -X is used in form "-X " then that ip will be reported as relay IP address of all allocations. This scenario works only in a simple case when one single relay address is to be used, and no CHANGE_REQUEST STUN functionality is required. That single relay address must be mapped by NAT to the 'external' IP. The "external-ip" value, if not empty, is returned in XOR-RELAYED-ADDRESS field. For that 'external' IP, NAT must forward ports directly (relayed port 12345 must be always mapped to the same 'external' port 12345). In more complex case when more than one IP address is involved, that option must be used several times, each entry must have form "-X ", to map all involved addresses. CHANGE_REQUEST NAT discovery STUN functionality will work correctly, if the addresses are mapped properly, even when the TURN server itself is behind A NAT. By default, this value is empty, and no address mapping is used.

So, it is not enough that you expose only the listening port from the inside LAN to the public network but all ports that you are going to use to relay. Please, note what is said in the same documentation:

--min-port <port> Lower bound of the UDP port range for relay endpoints allocation. Default value is 49152, according to RFC 5766.

  --max-port <port> Upper bound of the UDP port range for relay endpoints allocation. Default value is 65535, according to RFC 5766.

You should choose a range of ports in the server, configure with them the options --min-port and --max-port  and create a NAT rule to expose those ports to the public side of the router without change.


问:
Using polymorphism in (Surface)UserControl?
My (Surface)UserControls share a big amount of code. So I'd like to define an abstract super class where I can define this common code and behaviour.

But how do I define an abstract super class for a (Surface)UserControl? I tried to just subclass the code-behind file of a SurfaceUserControl, but then I get the following error:

```<code>Partial declarations of 'Prototype_Concept_2.views.DependencyExpander' must not specify different base classes  C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Concept_2\Prototype_Concept_2\views\DependencyExpander.xaml.cs
</code>```

答: The base control which you derive the usercontrols from need not be a SurfaceUserControl. So create a templated custom control which can be derived from SurfaceContentControl and put most of the code to be shared on that base class. </p>

OwnerDisplayName: anon

ContentLicense: CC BY-SA 2.5

Body:
My (Surface)UserControls share a big amount of code. So I'd like to define an abstract super class where I can define this common code and behaviour.

But how do I define an abstract super class for a (Surface)UserControl? I tried to just subclass the code-behind file of a SurfaceUserControl, but then I get the following error:

Partial declarations of 'Prototype_Concept_2.views.DependencyExpander' must not specify different base classes  C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Concept_2\Prototype_Concept_2\views\DependencyExpander.xaml.cs


问:
Memory Address showing? C++
Not really sure what's going on here, I'm using Clion as my IDE which I don't believe has anything to do with this but I figured I'd add that information. My confusion comes from a function that I wrote

```<code>int Arry()
{

int Mynumbers [5] = {10};

    std::cout << Mynumbers;
}
</code>```

something simple. It should be assigning 5 integers the value of 10. But when I print out Mynumbers I am shown the memory address. Why is this happening, I thought that was what calling pointers was for. Thank you for your time.

Sincerely,
Nicholas

答:
In C++, you can think of an array as a pointer to a memory address (this isn't strictly true, and others can explain the subtle differences). When you are calling cout on your array name, you are asking for it's contents: the memory address.

If you wish to see what's in the array, you can use a simple for loop:

```<code>for (int i = 0; i < 5; i++)
  std::cout << Mynumbers[i] << " ";
</code>```

Title: Memory Address showing? C++

Body:
Not really sure what's going on here, I'm using Clion as my IDE which I don't believe has anything to do with this but I figured I'd add that information. My confusion comes from a function that I wrote

int Arry()
{

int Mynumbers [5] = {10};

    std::cout << Mynumbers;
}

something simple. It should be assigning 5 integers the value of 10. But when I print out Mynumbers I am shown the memory address. Why is this happening, I thought that was what calling pointers was for. Thank you for your time.

Sincerely,
Nicholas

Body:
In C++, you can think of an array as a pointer to a memory address (this isn't strictly true, and others can explain the subtle differences). When you are calling cout on your array name, you are asking for it's contents: the memory address.

If you wish to see what's in the array, you can use a simple for loop:

for (int i = 0; i < 5; i++)
  std::cout << Mynumbers[i] << " ";


问:
How do I adjust subplots from a .fig file in Matlab
I have a .fig file with 9 subplots, arranged 3 by 3. Now I want to add labels with I have written in plotlabels(i) to subplot i, on point (xcoordinates(i),0.01). I try this

```<code>plotlabels = ['A','B','C','D','E','F','G','H','I'];
xcoordinates = [30,1000,1000,1000,1000,1000,1000,1000,1000];
fig = openfig('degreedistribution.fig');

for i = drange(1,9)
     subplot(3,3,i);
     text(xcoordinates(i),0.01,plotlabels(i),'FontWeight','bold'); hold on
end
</code>```

The figure is returned with subplot 1, 4 and 7 (the left column) blanc. In the other subplots, the proper label is added in the right location. I have checked that the locations of the labels in subplot 1, 4 and 7 are compatible with the plots. So what is happening?

答:
A minimal working example would be helpful.

You can manually assign each text to its parent axis:

```<code>for i = 1:9
     t = text(xcoordinates(i),0.01,plotlabels(i),'FontWeight','bold');
     t.Parent = fig.Children(i);
end
</code>```

Body:
I have a .fig file with 9 subplots, arranged 3 by 3. Now I want to add labels with I have written in plotlabels(i) to subplot i, on point (xcoordinates(i),0.01). I try this

plotlabels = ['A','B','C','D','E','F','G','H','I'];
xcoordinates = [30,1000,1000,1000,1000,1000,1000,1000,1000];
fig = openfig('degreedistribution.fig');

for i = drange(1,9)
     subplot(3,3,i);
     text(xcoordinates(i),0.01,plotlabels(i),'FontWeight','bold'); hold on
end

The figure is returned with subplot 1, 4 and 7 (the left column) blanc. In the other subplots, the proper label is added in the right location. I have checked that the locations of the labels in subplot 1, 4 and 7 are compatible with the plots. So what is happening?

Body:
A minimal working example would be helpful.

You can manually assign each text to its parent axis:

for i = 1:9
     t = text(xcoordinates(i),0.01,plotlabels(i),'FontWeight','bold');
     t.Parent = fig.Children(i);
end


问:
JQuery UI dialog - *Dialog not a function* error
I am developing a site using pinax. In one of my templates I am trying to open a simple jquery dialog box. However I keep getting the "Dialog not a function" javascript error. I am using jquery 1.2.6 and jquery-ui 1.6. My javascript and HTML are as follows:

```<code><html>
<head>
<link type="text/css" href="/site_media/smoothness/ui.all.css" rel="stylesheet" />
<script src="/site_media/jquery.js" type="text/javascript"></script>
<script src="/site_media/ui/ui.core.js" type="text/javascript"></script>
<script src="/site_media/ui/ui.draggable.js" type="text/javascript"></script>
<script src="/site_media/ui/ui.resizeable.js" type="text/javascript"></script>
<script src="/site_media/ui/ui.dialog.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
                    $('#dialogbox').dialog();
            });
 </script>
 </head>
 <body>
   <div id="dialogbox" title="dialog title">
     <p>Test dialog</p>
   </div>
 </body>
 </html>
</code>```

Can someone please explain why this is happening?

答:
I had the same problem. Mine was self inflicted from a jQuery UI update from 1.11.4 to 1.12.1. I installed the upgrade using NuGet and NuGet removed the old 1.11.4 reference from my project but never added the new project reference.

Running locally the application worked great, but when deploying it the new 1.12.1 file never made it with the publish. I hope this helps someone else.

Body:
I am developing a site using pinax. In one of my templates I am trying to open a simple jquery dialog box. However I keep getting the "Dialog not a function" javascript error. I am using jquery 1.2.6 and jquery-ui 1.6. My javascript and HTML are as follows:

<link type="text/css" href="/site_media/smoothness/ui.all.css" rel="stylesheet" />

Test dialog

Can someone please explain why this is happening?


问:
Python: Understanding dictionary view objects
I've been trying to understand built-in view objects return by .items(), .values(), .keys() in Python 3 or similarly by .viewitems(), .viewvalues(), .viewkeys(). There are other threads on that subject but none (even the doc) seems to described how they work internally.

The main gain here seems to be efficienty compared to the copy of type list returned in Python 2. There are often compared to a window to the dictionnary items (like in this thread).

But what is that window and why is it more efficient ?

The only thing I can see is that the view objects seems to be  set-like objects, which are generally faster for membership testing. But is this the only factor ?

Code sample

```<code>>>> example_dict = {'test':'test'}
>>> example_dict.items()
dict_items([('test', 'test')])
>>> type(example_dict.items())
<class 'dict_items'>
</code>```

So, my question is regarding this dict_items class. How does that work internally?

答:
Dict views store a reference to their parent dict, and they translate operations on the view to corresponding operations on the dict.

Iteration over a dict view is more efficient than building a list and iterating over that, because building a list takes time and memory that you don't have to spend with the view. The old way, Python would iterate over the dict's underlying storage to build a new list, and then you would iterate over the list. Iterating over a dict view uses an iterator that walks through the dict's underlying storage directly, skipping the unnecessary list step.

Dict views also support efficient containment tests and setlike intersection/difference/etc. operations, because they get to perform direct hash lookups on the underlying dict instead of iterating through a list and checking equality element by element.

If you want to see the concrete implementation used by CPython, you can take a look in the official repository, but this implementation is subject to change. It has changed, repeatedly.

Body:
I've been trying to understand built-in view objects return by .items(), .values(), .keys() in Python 3 or similarly by .viewitems(), .viewvalues(), .viewkeys(). There are other threads on that subject but none (even the doc) seems to described how they work internally.

The main gain here seems to be efficienty compared to the copy of type list returned in Python 2. There are often compared to a window to the dictionnary items (like in this thread).

But what is that window and why is it more efficient ?

The only thing I can see is that the view objects seems to be  set-like objects, which are generally faster for membership testing. But is this the only factor ?

Code sample

>>> example_dict = {'test':'test'}
>>> example_dict.items()
dict_items([('test', 'test')])
>>> type(example_dict.items())
<class 'dict_items'>

So, my question is regarding this dict_items class. How does that work internally?

ContentLicense: CC BY-SA 4.0


问:
OpenStack: launch instance with raw disk format
I have some headache with my OpenStack. What i'm trying to do is to create instance which disk is in RAW format instead of default qcow.

My disk image from which I'm trying to create the instance is in raw format too. I've created the image via:

```<code>openstack image create --public --disk-format raw --container-format bare --file CentOS-7-x86_64-GenericCloud-1710.raw CentOS_7_raw
</code>```

But when I launch instance from it I see that the disk is converted to Qcow2(v3) format.

Is there any possibility to run an instance with raw format disk?

Body:
I have some headache with my OpenStack. What i'm trying to do is to create instance which disk is in RAW format instead of default qcow.

My disk image from which I'm trying to create the instance is in raw format too. I've created the image via:

openstack image create --public --disk-format raw --container-format bare --file CentOS-7-x86_64-GenericCloud-1710.raw CentOS_7_raw

But when I launch instance from it I see that the disk is converted to Qcow2(v3) format.

Is there any possibility to run an instance with raw format disk?

Body:
Upload image to glance:

# openstack image create --public --disk-format raw --container-format bare --file CentOS-7-x86_64-GenericCloud-1710.raw CentOS_7_raw
+------------------+------------------------------------------------------+
| Field            | Value                                                |
+------------------+------------------------------------------------------+
| checksum         | 9d9cf225d36976b25eba247cb5f85d89                     |
| container_format | bare                                                 |
| created_at       | 2017-11-13T20:27:39Z                                 |
| disk_format      | raw                                                  |
| file             | /v2/images/8a18ee68-1d9e-4a2a-8277-ff29035d7011/file |
| id               | 8a18ee68-1d9e-4a2a-8277-ff29035d7011                 |
| min_disk         | 0                                                    |
| min_ram          | 0                                                    |
| name             | CentOS_7_raw                                         |
| owner            | 253f0c717bba45f8adf5c530b7194069                     |
| protected        | False                                                |
| schema           | /v2/schemas/image                                    |
| size             | 8589934592                                           |
| status           | active                                               |
| tags             |                                                      |
| updated_at       | 2017-11-13T20:28:01Z                                 |
| virtual_size     | None                                                 |
| visibility       | public                                               |
+------------------+------------------------------------------------------+

Change /etc/nova/nova.conf. Update images_type parameter to raw:

# VM Images format. If default is specified, then use_cow_images flag is used
# instead of this one. (string value)
# Allowed values: raw, qcow2, lvm, rbd, ploop, default
#images_type=default
images_type=raw

Restart nova:

# openstack-service restart nova
# openstack-service status nova
MainPID=1485 Id=openstack-nova-api.service ActiveState=active
MainPID=1500 Id=openstack-nova-cert.service ActiveState=active
MainPID=1509 Id=openstack-nova-compute.service ActiveState=active
MainPID=1483 Id=openstack-nova-conductor.service ActiveState=active
MainPID=1525 Id=openstack-nova-consoleauth.service ActiveState=active
MainPID=1481 Id=openstack-nova-novncproxy.service ActiveState=active
MainPID=1511 Id=openstack-nova-scheduler.service ActiveState=active

Create instance:

# nova boot --image 8a18ee68-1d9e-4a2a-8277-ff29035d7011 --nic net-id=e6db9b9e-4782-44dc-8d99-6bdb9744793d --key openstack --config-drive=True --flavor 3 raw
+--------------------------------------+-----------------------------------------------------+
| Property                             | Value                                               |
+--------------------------------------+-----------------------------------------------------+
| OS-DCF:diskConfig                    | MANUAL                                              |
| OS-EXT-AZ:availability_zone          |                                                     |
| OS-EXT-SRV-ATTR:host                 | -                                                   |
| OS-EXT-SRV-ATTR:hypervisor_hostname  | -                                                   |
| OS-EXT-SRV-ATTR:instance_name        | instance-00000558                                   |
| OS-EXT-STS:power_state               | 0                                                   |
| OS-EXT-STS:task_state                | scheduling                                          |
| OS-EXT-STS:vm_state                  | building                                            |
| OS-SRV-USG:launched_at               | -                                                   |
| OS-SRV-USG:terminated_at             | -                                                   |
| accessIPv4                           |                                                     |
| accessIPv6                           |                                                     |
| adminPass                            | CTXhRYZv8bc3                                        |
| config_drive                         | True                                                |
| created                              | 2017-11-13T20:36:15Z                                |
| flavor                               | m1.medium (3)                                       |
| hostId                               |                                                     |
| id                                   | 0d7aaf0a-0b29-4c6e-b049-270beab7d9c2                |
| image                                | CentOS_7_raw (8a18ee68-1d9e-4a2a-8277-ff29035d7011) |
| key_name                             | openstack                                           |
| metadata                             | {}                                                  |
| name                                 | raw                                                 |
| os-extended-volumes:volumes_attached | []                                                  |
| progress                             | 0                                                   |
| security_groups                      | default                                             |
| status                               | BUILD                                               |
| tenant_id                            | 253f0c717bba45f8adf5c530b7194069                    |
| updated                              | 2017-11-13T20:36:15Z                                |
| user_id                              | f8a7f21341624657b81c882431966265                    |
+--------------------------------------+-----------------------------------------------------+

Check status:

# nova list
+--------------------------------------+------+--------+------------+-------------+-------------------------+
| ID                                   | Name | Status | Task State | Power State | Networks                |
+--------------------------------------+------+--------+------------+-------------+-------------------------+
| 0d7aaf0a-0b29-4c6e-b049-270beab7d9c2 | raw  | ACTIVE | -          | Running     | network-1=192.168.0.139 |
+--------------------------------------+------+--------+------------+-------------+-------------------------+

Check image file:

# qemu-img info /var/lib/nova/instances/0d7aaf0a-0b29-4c6e-b049-270beab7d9c2/disk
image: /var/lib/nova/instances/0d7aaf0a-0b29-4c6e-b049-270beab7d9c2/disk
file format: raw
virtual size: 40G (42949672960 bytes)
disk size: 8.0G

# ls -alh /var/lib/nova/instances/0d7aaf0a-0b29-4c6e-b049-270beab7d9c2/disk
-rw-r--r--. 1 qemu qemu 40G Nov 13 20:51 /var/lib/nova/instances/0d7aaf0a-0b29-4c6e-b049-270beab7d9c2/disk


问:
JavaScript Reset Input with a Condition
I am trying to reset some input fields for a login if the loginDiv display is none, however it is not working at all.

Desired Outcome: click the login button, so long as the loginDiv display is none, the two input fields will be reset.

Here is my code:

// LOGIN
const logDiv = document.getElementById('loginDiv');
const wrong = document.getElementById('wrong');
const user = document.getElementById('user');
const pass = document.getElementById('pass');
const log = document.getElementById('logBtn');

log.addEventListener('click', () => {
  if (user.value == 'f' && pass.value == 'f') {
    logDiv.style.display = 'none';
    wrong.style.display = 'none';
  } else {
    wrong.style.display = 'block';
  }
});

// LOGOUT

const logout = document.getElementById('logout');

logout.addEventListener('click', () => {
  if (logDiv.style.display == 'none') {
    logDiv.style.display = 'block';
  }
});

function resetForm() {
  if (logDiv.style.display == 'none') {
    user.reset();
    pass.reset();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="loginDiv">
  <input id="user" type="text" placeholder="username"></input>
  <input id="pass" type="password" placeholder="password"></input>
  <button id="logBtn" onclick="resetForm()">login</button>
</div>
<div id="wrong" style="display: none;">
  <p id="wrongText">incorrect login info.</p>
</div>

<div id="logoutDiv">
  <button id="logout" type="button">logout</button>
</div></code>```

答:
You could set the value of user and password textbox to empty string after the username and password has been verified.

```<code>user.value = "";
pass.value = "";
</code>```

// LOGIN
const logDiv = document.getElementById('loginDiv');
const wrong = document.getElementById('wrong');
const user = document.getElementById('user');
const pass = document.getElementById('pass');
const log = document.getElementById('logBtn');

log.addEventListener('click', () => {
  if (user.value == 'f' && pass.value == 'f') {
    user.value = "";
    pass.value = "";
    logDiv.style.display = 'none';
    wrong.style.display = 'none';
  } else {
    wrong.style.display = 'block';
  }
});

// LOGOUT

const logout = document.getElementById('logout');

logout.addEventListener('click', () => {
  if (logDiv.style.display == 'none') {
    logDiv.style.display = 'block';
  }
});

function resetForm() {
  if (logDiv.style.display == 'none') {
    user.reset();
    pass.reset();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="loginDiv">
  <input id="user" type="text" placeholder="username"></input>
  <input id="pass" type="password" placeholder="password"></input>
  <button id="logBtn" onclick="resetForm()">login</button>
</div>
<div id="wrong" style="display: none;">
  <p id="wrongText">incorrect login info.</p>
</div>

<div id="logoutDiv">
  <button id="logout" type="button">logout</button>
</div></code>```

Title: JavaScript Reset Input with a Condition

Body:
I am trying to reset some input fields for a login if the loginDiv display is none, however it is not working at all.

Desired Outcome: click the login button, so long as the loginDiv display is none, the two input fields will be reset.

Here is my code:

// LOGIN
const logDiv = document.getElementById('loginDiv');
const wrong = document.getElementById('wrong');
const user = document.getElementById('user');
const pass = document.getElementById('pass');
const log = document.getElementById('logBtn');

log.addEventListener('click', () => {
  if (user.value == 'f' && pass.value == 'f') {
    logDiv.style.display = 'none';
    wrong.style.display = 'none';
  } else {
    wrong.style.display = 'block';
  }
});

// LOGOUT

const logout = document.getElementById('logout');

logout.addEventListener('click', () => {
  if (logDiv.style.display == 'none') {
    logDiv.style.display = 'block';
  }
});

function resetForm() {
  if (logDiv.style.display == 'none') {
    user.reset();
    pass.reset();
  }
}

  <input id="user" type="text" placeholder="username"></input>
  <input id="pass" type="password" placeholder="password"></input>
  <button id="logBtn" onclick="resetForm()">login</button>

incorrect login info.

  <button id="logout" type="button">logout</button>

Body:
You could set the value of user and password textbox to empty string after the username and password has been verified.

user.value = "";
pass.value = "";

// LOGIN
const logDiv = document.getElementById('loginDiv');
const wrong = document.getElementById('wrong');
const user = document.getElementById('user');
const pass = document.getElementById('pass');
const log = document.getElementById('logBtn');

log.addEventListener('click', () => {
  if (user.value == 'f' && pass.value == 'f') {
    user.value = "";
    pass.value = "";
    logDiv.style.display = 'none';
    wrong.style.display = 'none';
  } else {
    wrong.style.display = 'block';
  }
});

// LOGOUT

const logout = document.getElementById('logout');

logout.addEventListener('click', () => {
  if (logDiv.style.display == 'none') {
    logDiv.style.display = 'block';
  }
});

function resetForm() {
  if (logDiv.style.display == 'none') {
    user.reset();
    pass.reset();
  }
}

<div id="loginDiv">
  <input id="user" type="text" placeholder="username"></input>
  <input id="pass" type="password" placeholder="password"></input>
  <button id="logBtn" onclick="resetForm()">login</button>
</div>
<div id="wrong" style="display: none;">
  <p id="wrongText">incorrect login info.</p>
</div>

<div id="logoutDiv">
  <button id="logout" type="button">logout</button>
</div>


问:
Filter stream using correlation between stream elements
Let’s say there’s a Person class that looks like this:

```<code>public class Person {
    private int id;
    private String discriminator;
    // some other fields plus getters/setters
}
</code>```

Now I have a Stream of Person elements and that stream may contain multiple Person instances that have same id, but different discriminator values, i.e. [Person{“id”: 1, “discriminator”: “A”}, Person{“id”: 1, “discriminator”: “B”}, Person{“id”: 2, “discriminator”: “A”}, ...]

What I’d like to do is to filter out all Person instances  with some id if there’s at least one Person instance with that id that has a particular discriminator value. So, continuing with the above example, filtering by discriminator value “A” would yield an empty collection (after the reduction operation, of course) and filtering by discriminator value “B” would yield a collection not containing any Person instance with id equal to 1.

I know I can reduce the stream using groupingBy collector and group elements by Person.id and then remove the mapping from the resulting Map if the mapped list contains a Person element with the specified discriminator value, but am still wondering if there’s a simpler way to achieve the same result?

答:
Eugenes answer works great, but I personally prefer a single statement. So I took his code and put it all together into a single operation. Which looks like this:

```<code>final List<Person> result = persons.stream()
    .filter(p -> "B".equalsIgnoreCase(p.getDiscriminator()))
    .map(Person::getId)
    .collect(
        () -> new ArrayList<>(persons),
        ( list, id ) -> list.removeIf(p -> p.getId() == id),
        ( a, b ) -> {throw new UnsupportedOperationException();}
    );
</code>```

Probably need to mention that the copy of persons is needed, else the Stream will corrupt and encounters null values.

SideNote: This version is currently throwing an UnsupportedOperationException when trying to use in parallel.

Body:
Let’s say there’s a Person class that looks like this:

public class Person {
    private int id;
    private String discriminator;
    // some other fields plus getters/setters
}

Now I have a Stream of Person elements and that stream may contain multiple Person instances that have same id, but different discriminator values, i.e. [Person{“id”: 1, “discriminator”: “A”}, Person{“id”: 1, “discriminator”: “B”}, Person{“id”: 2, “discriminator”: “A”}, ...]

What I’d like to do is to filter out all Person instances  with some id if there’s at least one Person instance with that id that has a particular discriminator value. So, continuing with the above example, filtering by discriminator value “A” would yield an empty collection (after the reduction operation, of course) and filtering by discriminator value “B” would yield a collection not containing any Person instance with id equal to 1.

I know I can reduce the stream using groupingBy collector and group elements by Person.id and then remove the mapping from the resulting Map if the mapped list contains a Person element with the specified discriminator value, but am still wondering if there’s a simpler way to achieve the same result?

Body:
Eugenes answer works great, but I personally prefer a single statement. So I took his code and put it all together into a single operation. Which looks like this:

final List<Person> result = persons.stream()
    .filter(p -> "B".equalsIgnoreCase(p.getDiscriminator()))
    .map(Person::getId)
    .collect(
        () -> new ArrayList<>(persons),
        ( list, id ) -> list.removeIf(p -> p.getId() == id),
        ( a, b ) -> {throw new UnsupportedOperationException();}
    );

Probably need to mention that the copy of persons is needed, else the Stream will corrupt and encounters null values.

SideNote: This version is currently throwing an UnsupportedOperationException when trying to use in parallel.


问:
convert WPF WebBrowser to WinForms
I am trying to convert a WPF WebBrowser control to a WinForms WebBrowser control using this code:

```<code>System.Windows.Forms.WebBrowser wb = myWebBrowser as System.Windows.Forms.WebBrowser();
</code>```

I am getting this error:

"Cannot convert type 'System.Windows.Controls.WebBrowser' to 'System.Windows.Forms.WebBrowser' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion"

Any help would be appreciated.

Thanks!

答:
You can't : they are 2 completely different class hierarchies (apparently both wrappers around an ActiveX component)

If you are desperate, you may try getting information through the Handle field, but this will put you in unmanaged land.

Title: convert WPF WebBrowser to WinForms

Body:
I am trying to convert a WPF WebBrowser control to a WinForms WebBrowser control using this code:

System.Windows.Forms.WebBrowser wb = myWebBrowser as System.Windows.Forms.WebBrowser();

I am getting this error:

"Cannot convert type 'System.Windows.Controls.WebBrowser' to 'System.Windows.Forms.WebBrowser' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion"

Any help would be appreciated.

Thanks!


问:
2 dimensional arrays with dictionary in each cell
I have a little issue with the following code. I first create a 2 dimensional array that I fill in with dictionaries (the same dictionary for each cell actually). Now, when I update a cell changing of of the value in the dictionary, all the dictionaries in the whole array are changed and not only array[0][0]. See the code below:

```<code>dict_cell = {'item1': 20, 'item2': 25}
width = 2
height = 2
array = []
for i in range(height):
    row=[]
    for j in range(width):
        row.append(dict_cell)
    array.append(row)
array[0][0]['item1'] =2
print array
</code>```

I get the following output:

```<code>[[{'item2': 25, 'item1': 2},
  {'item2': 25, 'item1': 2}],
 [{'item2': 25, 'item1': 2},
  {'item2': 25, 'item1': 2}]]
</code>```

when I would like to have:

```<code>[[{'item2': 25, 'item1': 2},
  {'item2': 25, 'item1': 20}],
 [{'item2': 25, 'item1': 20},
  {'item2': 25, 'item1': 20}]]
</code>```

Any suggestions?
Note: I can not use numpy.

答:
The way python works is that when you're appending dict_cell to row, it adds a pointer to the dictionary. So, in effect, you're basically linking the same dictionary a bunch of times! It's thus unsurprising that all dictionaries are changing when you modify one of the entries.

The simplest change to fix this is to directly create multiple dictionaries, using dict_cell as the template. Replace your append in the for loop with this:

```<code>    row.append(dict_cell.copy())
</code>```

Body:
I have a little issue with the following code. I first create a 2 dimensional array that I fill in with dictionaries (the same dictionary for each cell actually). Now, when I update a cell changing of of the value in the dictionary, all the dictionaries in the whole array are changed and not only array[0][0]. See the code below:

dict_cell = {'item1': 20, 'item2': 25}
width = 2
height = 2
array = []
for i in range(height):
    row=[]
    for j in range(width):
        row.append(dict_cell)
    array.append(row)
array[0][0]['item1'] =2
print array

I get the following output:

[[{'item2': 25, 'item1': 2},
  {'item2': 25, 'item1': 2}],
 [{'item2': 25, 'item1': 2},
  {'item2': 25, 'item1': 2}]]

when I would like to have:

[[{'item2': 25, 'item1': 2},
  {'item2': 25, 'item1': 20}],
 [{'item2': 25, 'item1': 20},
  {'item2': 25, 'item1': 20}]]

Any suggestions?
Note: I can not use numpy.

Body:
The way python works is that when you're appending dict_cell to row, it adds a pointer to the dictionary. So, in effect, you're basically linking the same dictionary a bunch of times! It's thus unsurprising that all dictionaries are changing when you modify one of the entries.

The simplest change to fix this is to directly create multiple dictionaries, using dict_cell as the template. Replace your append in the for loop with this:

    row.append(dict_cell.copy())


问:
Incompatible pointer types (double pointers)
In a function that asks a double pointer like this one:

```<code>#include <stdlib.h>

void    prueba(void **ap)
{
    *ap = NULL;
}
</code>```

compiled with the following main:

```<code>#include <stdlib.h>
#include <stdio.h>

void    prueba(void **ap);

int        main(void)
{
    char *str;

    str = (char *)malloc(sizeof(char) * 5);
    prueba(&str);
    if (str == NULL)
        printf("NULL");
    return (0);
}
</code>```

I get this warning with gcc:

```<code>main2.c:11:9: warning: incompatible pointer types passing 'char **' to parameter of type 'void **' [-Wincompatible-pointer-types]
        prueba(&str);
               ^~~~
main2.c:4:23: note: passing argument to parameter 'ap' here
void    prueba(void **ap);
</code>```

But if i do the same but with simple pointers, that is give a pointer to char to a function who asks for a void pointer, gcc compiles without warnings, for example, the following compiles right:
function:

```<code>#include <stdlib.h>

void    prueba(void *ap)
{
    ap = NULL;
}
</code>```

main:

```<code>#include <stdlib.h>
#include <stdio.h>

void    prueba(void *ap);

int        main(void)
{
    char *str;

    str = (char *)malloc(sizeof(char) * 5);
    prueba(str);
    if (str == NULL)
        printf("NULL");
    return (0);
}
</code>```

So my question is, why it works with simple pointers but it does not work with double pointers (or greater i guess)?

答:
A void * can freely be assigned to or from any object pointer freely.  This freedom does not extends to void **, as that is a distinct type.

Also, your fixed program won't work as expected, since ap = NULL; only changes the local variable inside of prueba and not the parameter passed in.

Change your original program to accept a char ** instead of a void **.

Body:
In a function that asks a double pointer like this one:

#include <stdlib.h>

void    prueba(void **ap)
{
    *ap = NULL;
}

compiled with the following main:

#include <stdlib.h>
#include <stdio.h>

void    prueba(void **ap);

int        main(void)
{
    char *str;

    str = (char *)malloc(sizeof(char) * 5);
    prueba(&str);
    if (str == NULL)
        printf("NULL");
    return (0);
}

I get this warning with gcc:

main2.c:11:9: warning: incompatible pointer types passing 'char **' to parameter of type 'void **' [-Wincompatible-pointer-types]
        prueba(&str);
               ^~~~
main2.c:4:23: note: passing argument to parameter 'ap' here
void    prueba(void **ap);

But if i do the same but with simple pointers, that is give a pointer to char to a function who asks for a void pointer, gcc compiles without warnings, for example, the following compiles right:
function:

#include <stdlib.h>

void    prueba(void *ap)
{
    ap = NULL;
}

main:

#include <stdlib.h>
#include <stdio.h>

void    prueba(void *ap);

int        main(void)
{
    char *str;

    str = (char *)malloc(sizeof(char) * 5);
    prueba(str);
    if (str == NULL)
        printf("NULL");
    return (0);
}

So my question is, why it works with simple pointers but it does not work with double pointers (or greater i guess)?


问:
Excel 2010 Unpivot Data or Utilize MySQL for Unpivot
I've got a lot of data in an Excel sheet that I need reformatted.  I am trying to achieve this by using Pivot Table but I'm not sure it is possible.

Here is current data set (SKU is unique currently):

I need it to look more like this (where SKU is NOT unique):

I'm willing to throw my current sheet into a MySQL database and query it if I can figure out a good query to utilize as well.

Any ideas on where to go from here would be appreciated.

答: It looks like you're wanting to unpivot your data (i.e. turn it from a crosstab into a flat file), although some of your desired output looks weird. Look at my answer to this question: convert cross table to list to make pivot table</p>


问:
In Delphi how do I find which Variable (integer) is the largest
I have four integer variables named C,S,F and U, each get assigned values depending on the outcome of a file routine, they stand for Checked, Successful, Failed and UserDefined.  what is the best way to find out which variable holds the largest value?

答:
Try something like this:</p>

```<code>var
  C, S, F, U: Integer;

  function WhichIsHighest(const Values: array of Integer): Integer;
  var
    I, Highest: Integer;
  begin
    Result := Low(Values);
    Highest := Values[Result];
    for I := Result+1 to High(Values) do begin
      if Values[I] > Highest then begin
        Result := I;
        Highest := Values[I];
      end;
    end;

begin
  ... set C, S, F, U as needed ...

  case WhichIsHighest([C, S, F, U]) of
    0: ...; // C is highest
    1: ...; // S is highest
    2: ...; // F is highest
    3: ...; // U is highest
  end;
end;
</code>```

Body:
Try something like this:

var
  C, S, F, U: Integer;

  function WhichIsHighest(const Values: array of Integer): Integer;
  var
    I, Highest: Integer;
  begin
    Result := Low(Values);
    Highest := Values[Result];
    for I := Result+1 to High(Values) do begin
      if Values[I] > Highest then begin
        Result := I;
        Highest := Values[I];
      end;
    end;

begin
  ... set C, S, F, U as needed ...

  case WhichIsHighest([C, S, F, U]) of
    0: ...; // C is highest
    1: ...; // S is highest
    2: ...; // F is highest
    3: ...; // U is highest
  end;
end;


问:
Firebase Database: why do the key/ref in my queried datasnapshot refer to its parent?
I would like to delete an entry from the realtime database that i looked up through a query but i am getting unexpected results for both the ref and key properties.

```<code>ref('photos/users/USERID')
    .orderByChild('photoname')
    .equalTo('photoname i want to look up')
    .limitToFirst(1)
    .query('once')
    .then(snapshot => {
        // correct data at 'photos/users/USERID/PHOTOID'
        const entry = snapshot.val();

        // seems to be the ref to photos/users/USERID'
        const ref = snapshot.ref;

        // seems to be USERID
        const key = snapshot.key
    })
</code>```

Why aren't these the ref/key to the entry i just found? And what is the best approach to remove this entry?

答: Your ref and key are based on ref('photos/users/USERID'), not the filtered subset you have created.  Is there any reason you wouldn't call ref('photos/users/USERID/PHOTOID')?</p>

Body:
I would like to delete an entry from the realtime database that i looked up through a query but i am getting unexpected results for both the ref and key properties.

ref('photos/users/USERID')
    .orderByChild('photoname')
    .equalTo('photoname i want to look up')
    .limitToFirst(1)
    .query('once')
    .then(snapshot => {
        // correct data at 'photos/users/USERID/PHOTOID'
        const entry = snapshot.val();

        // seems to be the ref to photos/users/USERID'
        const ref = snapshot.ref;

        // seems to be USERID
        const key = snapshot.key
    })

Why aren't these the ref/key to the entry i just found? And what is the best approach to remove this entry?


问:
How to adjust space between layouts in a QVBoxLayout
I've seen how to adjust the space between widgets in a layout:
Space between widgets in QVBoxLayout. However, I want to know how to adjust space between layouts added to a layout.

For example:

```<code>layout = QVBoxLayout()
h1_layout = QHBoxLayout()
h2_layout = QHBoxLayout()
layout.addLayout(h1_layout)
layout.addLayout(h2_layout)
</code>```

I would like the contents of h1_layout and h2_layout to be placed close to each other rather than spaced across the vertical layout.

答:
I assume you want the contents of the two horizontal layouts to be aligned at the top of the vertical layout, and not stretched out to fill the entire space available. If so, you can achieve this by adding an expanding spacer to the bottom of the vertical layout:

```<code>layout = QVBoxLayout()
h1_layout = QHBoxLayout()
h2_layout = QHBoxLayout()
layout.addLayout(h1_layout)
layout.addLayout(h2_layout)
# add expanding spacer
layout.addStretch()
</code>```

Another way to achieve a similar effect, is to set the alignment of the parent layout:

```<code>layout.setAlignment(QtCore.Qt.AlignTop)
</code>```

Body:
I've seen how to adjust the space between widgets in a layout:
Space between widgets in QVBoxLayout. However, I want to know how to adjust space between layouts added to a layout.

For example:

layout = QVBoxLayout()
h1_layout = QHBoxLayout()
h2_layout = QHBoxLayout()
layout.addLayout(h1_layout)
layout.addLayout(h2_layout)

I would like the contents of h1_layout and h2_layout to be placed close to each other rather than spaced across the vertical layout.

Body:
I assume you want the contents of the two horizontal layouts to be aligned at the top of the vertical layout, and not stretched out to fill the entire space available. If so, you can achieve this by adding an expanding spacer to the bottom of the vertical layout:

layout = QVBoxLayout()
h1_layout = QHBoxLayout()
h2_layout = QHBoxLayout()
layout.addLayout(h1_layout)
layout.addLayout(h2_layout)
# add expanding spacer
layout.addStretch()

Another way to achieve a similar effect, is to set the alignment of the parent layout:

layout.setAlignment(QtCore.Qt.AlignTop)


问:
Scalars and forced callsite readability?
I'm wondering what is currently the recommended way of disambiguating parameters and improving call site readability for functions by leveraging the type system. The trivial example is

```<code>int total(int price, int amount) {
  return price * total;
}
</code>```

where it's hard to tell precisely what a call like total(10, 2)means, i.e. which parameter is which (in this case you don't get a bug if you mess up the order, because of commutativity of multiplication).

Basically, you can quickly do something like:

```<code>enum class ScalarTypeTag { PriceTag, AmountTag, TotalTag};

template<typename T, ScalarTypeTag K>
struct ScalarWrapper {
  explicit ScalarWrapper(T value) : value_{value} {}
  T value_;
};

using Price = ScalarWrapper<int, ScalarTypeTag::PriceTag>;
using Amount = ScalarWrapper<int, ScalarTypeTag::PriceTag>;
using Total = ScalarWrapper<int, ScalarTypeTag::TotalTag>;

Total ComputeTotal(Price p, Amount n) {
  return Total(p.value_ * n.value_);
}
</code>```

This would then make it very difficult for the caller to mix up the argument order while at the same time being a zero cost abstraction as the compiler will optimize away the wrapping type. I'm basically interested in how to do this, so that it:

Minimizes the extra code needed by a user.

Makes it trivial to add new types (without mistakes)

Is a zero cost abstraction (compared to just replacing the types by the underlying types).

In the example above, I've on purpose introduced a bug by forgetting to change the tag on Amount to AmountTag after copy pasting, so Amount is actually the same type as Price, so we could still accidentally mess up the parameter order and the compiler wouldn't catch it. It would be preferable to minimize the chance of bloopers like this.

In other words, how to maximize the utility of this construct while minimizing the amount of caused annoyance?

UPDATE: Another problem is that this implementation would (probably, haven't checked) also prevent something like a copy of a std::vector of these to be optimized to a memcpy instead of a loop, so it wouldn't be completely zero cost.

答:
```<code>struct tag_t {constexpr tag_t(){}};

inline constexpr tag_t price{}
inline constexpr tag_t amount{};
inline constexpr tag_t total{};

template<class T, tag_t const* tag>
struct scalar_t {
  T t;
  constexpr explicit scalar_t( T tin ):t(std::move(tin)) {}
  constexpr scalar_t( scalar_t const& ) = default;
  constexpr scalar_t( scalar_t && ) = default;
  constexpr scalar_t& operator=( scalar_t const& ) = default;
  constexpr scalar_t& operator=( scalar_t && ) = default;
  constexpr scalar_t() = default;
  constexpr ~scalar_t() = default;
};

template<auto x, tag_t const* tag >
constexpr auto scalar = scalar_t<std::decay_t<decltype(x)>, tag>(x);

template<tag_t const* tag>
using iscalar_t = scalar_t<int, tag>;

scalar_t<int, &total> ComputeTotal( scalar_t<int, &price> p, scalar_t<int, &amount> n ) {
  return scalar_t<int, &total>( p.t * n.t );
}
</code>```

callers can do

```<code>int x = 33;
auto total = ComputeTotal( scalar<7, &price>, iscalar_t<&amount>( x ) );
</code>```

and pass in compile-time values or runtime values with a cast.

We don't do type aliases, instead we use pointers to tags for our tags.  Anyone can create a new scalar tag, and its constexpr address is its identity.

This allows distributed scalar type generation.

Body:
I'm wondering what is currently the recommended way of disambiguating parameters and improving call site readability for functions by leveraging the type system. The trivial example is

int total(int price, int amount) {
  return price * total;
}

where it's hard to tell precisely what a call like total(10, 2)means, i.e. which parameter is which (in this case you don't get a bug if you mess up the order, because of commutativity of multiplication).

Basically, you can quickly do something like:

enum class ScalarTypeTag { PriceTag, AmountTag, TotalTag};

template<typename T, ScalarTypeTag K>
struct ScalarWrapper {
  explicit ScalarWrapper(T value) : value_{value} {}
  T value_;
};

using Price = ScalarWrapper<int, ScalarTypeTag::PriceTag>;
using Amount = ScalarWrapper<int, ScalarTypeTag::PriceTag>;
using Total = ScalarWrapper<int, ScalarTypeTag::TotalTag>;

Total ComputeTotal(Price p, Amount n) {
  return Total(p.value_ * n.value_);
}

This would then make it very difficult for the caller to mix up the argument order while at the same time being a zero cost abstraction as the compiler will optimize away the wrapping type. I'm basically interested in how to do this, so that it:

Minimizes the extra code needed by a user.

Makes it trivial to add new types (without mistakes)

Is a zero cost abstraction (compared to just replacing the types by the underlying types).

In the example above, I've on purpose introduced a bug by forgetting to change the tag on Amount to AmountTag after copy pasting, so Amount is actually the same type as Price, so we could still accidentally mess up the parameter order and the compiler wouldn't catch it. It would be preferable to minimize the chance of bloopers like this.

In other words, how to maximize the utility of this construct while minimizing the amount of caused annoyance?

UPDATE: Another problem is that this implementation would (probably, haven't checked) also prevent something like a copy of a std::vector of these to be optimized to a memcpy instead of a loop, so it wouldn't be completely zero cost.

Body:
struct tag_t {constexpr tag_t(){}};

inline constexpr tag_t price{}
inline constexpr tag_t amount{};
inline constexpr tag_t total{};

template<class T, tag_t const* tag>
struct scalar_t {
  T t;
  constexpr explicit scalar_t( T tin ):t(std::move(tin)) {}
  constexpr scalar_t( scalar_t const& ) = default;
  constexpr scalar_t( scalar_t && ) = default;
  constexpr scalar_t& operator=( scalar_t const& ) = default;
  constexpr scalar_t& operator=( scalar_t && ) = default;
  constexpr scalar_t() = default;
  constexpr ~scalar_t() = default;
};

template<auto x, tag_t const* tag >
constexpr auto scalar = scalar_t<std::decay_t<decltype(x)>, tag>(x);

template<tag_t const* tag>
using iscalar_t = scalar_t<int, tag>;

scalar_t<int, &total> ComputeTotal( scalar_t<int, &price> p, scalar_t<int, &amount> n ) {
  return scalar_t<int, &total>( p.t * n.t );
}

callers can do

int x = 33;
auto total = ComputeTotal( scalar<7, &price>, iscalar_t<&amount>( x ) );

and pass in compile-time values or runtime values with a cast.

We don't do type aliases, instead we use pointers to tags for our tags.  Anyone can create a new scalar tag, and its constexpr address is its identity.

This allows distributed scalar type generation.


问:
paperclip error while reporcessing after rails 3 upgrade
I have paperclip working uploading and saving different styles for images but when i go to crop the image using jcrop from railscasts tutorial it doesnt crop image.   I get this error

```<code>[paperclip] identify -format %wx%h '/var/folders/z+/z+KzOZBFE9irCpbMKKBGFk+++TI/-Tmp-/paperclip-reprocess20110118-19757-1wtrjaj-0[0]' 2>/dev/null
[paperclip] convert '/var/folders/z+/z+KzOZBFE9irCpbMKKBGFk+++TI/-Tmp-/paperclip-reprocess20110118-19757-1wtrjaj-0[0]' -crop 28x32+13+15-resize "400x400>" '/var/folders/z+/z+KzOZBFE9irCpbMKKBGFk+++TI/-Tmp-/paperclip-reprocess20110118-19757-1wtrjaj-020110118-19757-1a5n558-0.jpg' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::PaperclipError: There was an error processing the thumbnail for paperclip-reprocess20110118-19757-1wtrjaj-0>
</code>```

This was working in rails 2.3.9 but hvae just upgraded to rails 3.0.3    I have got all latest gems etc.

The cropper.rb file is as follows and is in the initializers dir

```<code>module Paperclip
  class Cropper < Thumbnail
    def transformation_command
      if crop_command
        crop_command + super.join(" ").sub(/ -crop \S+/, '')
      else
        super
      end
    end

    def crop_command
      target = @attachment.instance

      if target.cropping?
        " -crop #{target.crop_w.to_i}x#{target.crop_h.to_i}+#{target.crop_x.to_i}+#{target.crop_y.to_i}"
      end
    end
  end
end
</code>```

The sizes are getting into this but no actually cropping the image.

Please can anyone help with this ?

thanks alot
Richard Moss

答:
Hereis my working file:</p>

```<code>module Paperclip
  class Cropper < Thumbnail
    def transformation_command
      if crop_command
        crop_command + super.join(' ').sub(/ -crop \S+/, '').split(' ') # super returns     an array like this: ["-resize", "100x", "-crop", "100x100+0+0", "+repage"]
      else
        super
      end
    end

    def crop_command
      target = @attachment.instance
      if target.cropping?
        ["-crop", "#{target.crop_w}x#{target.crop_h}+#{target.crop_x}+#{target.crop_y}"]
      end
    end
  end
end
</code>```

Body:
I have paperclip working uploading and saving different styles for images but when i go to crop the image using jcrop from railscasts tutorial it doesnt crop image.   I get this error

[paperclip] identify -format %wx%h '/var/folders/z+/z+KzOZBFE9irCpbMKKBGFk+++TI/-Tmp-/paperclip-reprocess20110118-19757-1wtrjaj-0[0]' 2>/dev/null
[paperclip] convert '/var/folders/z+/z+KzOZBFE9irCpbMKKBGFk+++TI/-Tmp-/paperclip-reprocess20110118-19757-1wtrjaj-0[0]' -crop 28x32+13+15-resize "400x400>" '/var/folders/z+/z+KzOZBFE9irCpbMKKBGFk+++TI/-Tmp-/paperclip-reprocess20110118-19757-1wtrjaj-020110118-19757-1a5n558-0.jpg' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::PaperclipError: There was an error processing the thumbnail for paperclip-reprocess20110118-19757-1wtrjaj-0>

This was working in rails 2.3.9 but hvae just upgraded to rails 3.0.3    I have got all latest gems etc.

The cropper.rb file is as follows and is in the initializers dir

module Paperclip
  class Cropper < Thumbnail
    def transformation_command
      if crop_command
        crop_command + super.join(" ").sub(/ -crop \S+/, '')
      else
        super
      end
    end

    def crop_command
      target = @attachment.instance

      if target.cropping?
        " -crop #{target.crop_w.to_i}x#{target.crop_h.to_i}+#{target.crop_x.to_i}+#{target.crop_y.to_i}"
      end
    end
  end
end

The sizes are getting into this but no actually cropping the image.

Please can anyone help with this ?

thanks alot
Richard Moss

Body:
Hereis my working file:

module Paperclip
  class Cropper < Thumbnail
    def transformation_command
      if crop_command
        crop_command + super.join(' ').sub(/ -crop \S+/, '').split(' ') # super returns     an array like this: ["-resize", "100x", "-crop", "100x100+0+0", "+repage"]
      else
        super
      end
    end

    def crop_command
      target = @attachment.instance
      if target.cropping?
        ["-crop", "#{target.crop_w}x#{target.crop_h}+#{target.crop_x}+#{target.crop_y}"]
      end
    end
  end
end


问:
DynamoDB to Redshift
I am asking this in context of loading data from DynamoDb into Redshift. Per the Redshift Docs:

To avoid consuming excessive amounts of provisioned read throughput, we recommend that you not load data from Amazon DynamoDB tables that are in production environments.

My data is in Production, so how do I get it out of there?

Alternately is DynamoDB Streams a better overall choice to move data from DynamoDB into Redshift? (I understand this does not add to my RCU cost.)

答:
The warning is due to the fact that the export could consume much of your read capacity for a period of time, which would impact your production environment.

Some options:

Do it at night when you don't need as much capacity

Set READRATIO to a low value so that it consumes less of the capacity

Temporarily increase the Read Capacity Units of the table when performing the export (you can decrease capacity four times a day)

DynamoDB Streams provides a stream of data representing changes to a DynamoDB table. You would need to process these streams using AWS Lambda to send the data somewhere for loading into Redshift. For example, you could populate another DynamoDB table and use it for importing into Redshift. Or, you could write the data to Amazon S3 and import from there into Redshift. However, this involves lots of moving parts.

Title: DynamoDB to Redshift


问:
Azure DevOps and Outlook Integration
Looking for information on how to integrate VSTS to Office365: Outlook.  Essentially looking for a method whereby a team member that does a great amount of fix-it tickets can drop them into the Azure DevOps Project from Outlook as many of those tickets get passed to her from users through email.

A right click >> add new task from Outlook to Azure DevOps would be ideal.

答:
There is no built-in feature, but you can work miracles with Microsoft Flow, basically, the If This Then That from Microsoft. it comes with built-in tasks to trigger on Outlook/Office 365. Moving an email to a specific folder or tagging it with a specific tag would be enough for Flow to trigger a rule.

This template rule uses the "When an email is tagged" and this template rule creates a Bug work item based on a trigger. Combining these two should let you achieve what you're looking for.

If you want integration in the Outlook Windows client, then there are a couple of commercial options available: There are a couple of add-ins for Outlook. Team Companion, TeamLook and TFS Work Item from Outlook spring to mind.

An alternative option is to use an Azure Function which is triggered by Azure DevOps Service Hooks. Not sure if you can bind an Azure Function to an Office 365 mailbox. Flow could act as an intermediary here as well.

Title: Azure DevOps and Outlook Integration


问:
Scheme: how to get first atom from list
I need help with one issue: I can't handle how to get the first atom from the list in SCHEME language. I think I should make a loop, something like "while" and compare each element on boolean (?atom) and print first matched item.
Unfortunately, It's difficult for me to handle scheme syntax.
Please, can you propose any solution for me?</p>

```<code>define func ?atom:
(define (atom? x) (not (or (pair? x) (null? x))))
</code>```

答:
In your question you have the definition to atom? that returns #t if the argument is an atom and #f otherwise.

The function should handle the empty list. eg. What should happen when you do this:

```<code>(first-atom '())
</code>```

Thus you need to check if the argument is the empty list and return whatever you supposed to return when there are no atoms in the arguments. Then you'll have a else expression that handles the rest.

You can use first to get the first element to check if it is an atom and then return it or you recure with the rest of the list.

Now here is something very similar that finds the number of elements in a list:

```<code>(define (length lst)
  (if (null? lst)
      0                          ; obviously a 0 length list
      (+ 1 (length (cdr lst))))) ; obviously one plus whatever length the rest is
</code>```

Imagine what happens if you do (length '(1 2)). It does (+ 1 (length '(2))) which again does (+ 1 (+ 1 (length '()))) which again does (+ 1 (+ 1 0)). Simple as that. All loops are recursive functions in Scheme.

You reference to while indicates you might be familiar with other programming languages. I knew C, C++, Pascal, perl, PHP, and Java when starting to learn Lisp and I suddenly realized all the languages I knew were only subtle dialects of one language, Algol. I wasn't learning my sixth language, but my second. Scheme doesn't have a while loop. It has recursion. you need to get a book and start at the first page as if you didn't know how to program at all as assimilation from Algol will point you in the wrong direction.

Title: Scheme: how to get first atom from list

Body:
I need help with one issue: I can't handle how to get the first atom from the list in SCHEME language. I think I should make a loop, something like "while" and compare each element on boolean (?atom) and print first matched item.
Unfortunately, It's difficult for me to handle scheme syntax.
Please, can you propose any solution for me?

define func ?atom:
(define (atom? x) (not (or (pair? x) (null? x))))

Body:
In your question you have the definition to atom? that returns #t if the argument is an atom and #f otherwise.

The function should handle the empty list. eg. What should happen when you do this:

(first-atom '())

Thus you need to check if the argument is the empty list and return whatever you supposed to return when there are no atoms in the arguments. Then you'll have a else expression that handles the rest.

You can use first to get the first element to check if it is an atom and then return it or you recure with the rest of the list.

Now here is something very similar that finds the number of elements in a list:

(define (length lst)
  (if (null? lst)
      0                          ; obviously a 0 length list
      (+ 1 (length (cdr lst))))) ; obviously one plus whatever length the rest is

Imagine what happens if you do (length '(1 2)). It does (+ 1 (length '(2))) which again does (+ 1 (+ 1 (length '()))) which again does (+ 1 (+ 1 0)). Simple as that. All loops are recursive functions in Scheme.

You reference to while indicates you might be familiar with other programming languages. I knew C, C++, Pascal, perl, PHP, and Java when starting to learn Lisp and I suddenly realized all the languages I knew were only subtle dialects of one language, Algol. I wasn't learning my sixth language, but my second. Scheme doesn't have a while loop. It has recursion. you need to get a book and start at the first page as if you didn't know how to program at all as assimilation from Algol will point you in the wrong direction.


问:
Presto and Hive
I'm trying to enable basic SQL querying of CSV files located in an s3 directory.  Presto seemed like a natural fit (the files are 10s GB).  As I went through the setup in Presto, I tried creating a table using the Hive connector.  It was not clear to me if I only needed the hive metastore to save my table configurations in Presto, or if I have to create them in there first.

The documentation makes it seem that you can use Presto without having to CONFIGURE Hive, but using Hive syntax.  Is that accurate?  My experiences are that AWS S3 has not been able to connect.

答: Presto syntax is similar to Hive syntax. For most simple queries, the identical syntax would function in both. However, there are some key differences that make Presto and Hive not entirely the same thing. For example, in Hive, you might use LATERAL VIEW EXPLODE, whereas in Presto you'd use CROSS JOIN UNNEST. There are many such examples of nuanced syntactical differences between the two.

Title: Presto and Hive


问:
How to change the same characters in a string to different values in python?
I'm trying to implement a basic converting program, changing stars to either  or  depending on if they are the first or second of a pair, but regardless of what I do my program changes all the stars to  or .

```<code>line = "*ju*bil*ee*"
star_counter = 0
new_line = line
    for character in line:
         if character is "*":
            star_counter += 1
            if star_counter%2 == 0:
                new_line = line.replace(character, "</em>")
            else:
                new_line = line.replace(character, "<em>")
</code>```

答:
Solution using cycle and imap from itertools:

```<code>from itertools import cycle, imap

em = iter(cycle(['<em>','</em>']))

def emEm(c):
    if c == '*':
        return em.next()
    else:
       return c

line = imap(emEm,"*ju*bil*ee*")
print(''.join(line))
</code>```

cycle(['','']) lazyly repeats  and  as often as needed

emEm implements the decider logic for imap

imap executes the logic on each character of the string

Problem: with odd number of * you get a not well formed html - tag opens but does not close - but you could check that beforehand.

Body:
I'm trying to implement a basic converting program, changing stars to either  or  depending on if they are the first or second of a pair, but regardless of what I do my program changes all the stars to  or .

line = "*ju*bil*ee*"
star_counter = 0
new_line = line
    for character in line:
         if character is "*":
            star_counter += 1
            if star_counter%2 == 0:
                new_line = line.replace(character, "")
            else:
                new_line = line.replace(character, "")

Body:
Solution using cycle and imap from itertools:

from itertools import cycle, imap

em = iter(cycle(['<em>','</em>']))

def emEm(c):
    if c == '*':
        return em.next()
    else:
       return c

line = imap(emEm,"*ju*bil*ee*")
print(''.join(line))

cycle(['<em>','</em>']) lazyly repeats <em> and </em> as often as needed

emEm implements the decider logic for imap

imap executes the logic on each character of the string

Problem: with odd number of * you get a not well formed html - tag opens but does not close - but you could check that beforehand.


问:
Why is Enumeration in Collection Framework not defined for ArrayList objects where as it is defined for Vector objects?
```<code>public static void main(String[] args) {

    ArrayList v1 = new ArrayList();
    v1.add(123);
    v1.add(153);
    v1.add(125);

    Enumeration en = v1.elements(); // This line gives error.
    v1.add(4000);
    while(en.hasMoreElements())
    {
        System.out.println(en.nextElement());
    }

    System.out.println(v1);
}
</code>```

Why there is an error in case of ArrayList but not in case of Vector?

答:
Because Enumeration is a legacy class.

As the Vector class.

List and Collection more generally favor the use of Iterator to iterate on elements of them.

Iterator also provides a removal operation that Enumeration doesn't have.

You can read in the Enumeration javadoc :

NOTE: The functionality of this interface is duplicated by the
  Iterator interface. In addition, Iterator adds an optional remove
  operation, and has shorter method names. New implementations should
  consider using Iterator in preference to Enumeration.

Body:
public static void main(String[] args) {

    ArrayList v1 = new ArrayList();
    v1.add(123);
    v1.add(153);
    v1.add(125);

    Enumeration en = v1.elements(); // This line gives error.
    v1.add(4000);
    while(en.hasMoreElements())
    {
        System.out.println(en.nextElement());
    }

    System.out.println(v1);
}

Why there is an error in case of ArrayList but not in case of Vector?


问:
Syntax for CHECKing inserted value against another table's
I'm adding a table in my Database:

```<code>***Enrollments***
CourseID
Student ID
EnrollmentDateTime
</code>```

I already have a table:

```<code>***Courses***
CourseID
StartDate
</code>```

When someone's inserted data into the Enrollments table, I want to check whether the enrollment date is lesser than/ before the start date; I know what needs to be done, but am lacking the syntax on how to do so. So far, I have the following, but am at a loss on how to proceed.

```<code>Create Table Enrollments(
    StudentID int NOT NULL Foreign Key REFERENCES dbo.Students(StudentID),
    CourseID int NOT NULL Foreign Key REFERENCES dbo.Courses(CourseID),
    EnrollmentDateTime Datetime NOT NULL CHECK (dbo.fCheckDate(EnrollmentDateTime, CourseID) = 1))
</code>```

...

```<code>create function dbo.fCheckDate (@StartDate Datetime, @CourseID int)
Returns bit
AS
Begin
 Return(SELECT E.StartDate
    FROM dbo.Enrollments E
    WHERE @CourseID = E.CourseID
End
go
</code>```

答:
Such function-based checks are quite expensive.  But, you need a function to return the course date:</p>

```<code>create function dbo.getStartDate (@CourseID int)
Returns datetime
AS
Begin
     Return (SELECT c.StartDate
             FROM dbo.Courses c
             WHERE c.CourseID = @CourseID
            );
End;

Create Table Enrollments (
    StudentID int NOT NULL Foreign Key REFERENCES dbo.Students(StudentID),
    CourseID int NOT NULL Foreign Key REFERENCES dbo.Courses(CourseID),
    EnrollmentDateTime Datetime NOT NULL CHECK (EnrollmentDateTime < getStartDate(CourseID))
);
</code>```

Body:
I'm adding a table in my Database:

***Enrollments***
CourseID
Student ID
EnrollmentDateTime

I already have a table:

***Courses***
CourseID
StartDate

When someone's inserted data into the Enrollments table, I want to check whether the enrollment date is lesser than/ before the start date; I know what needs to be done, but am lacking the syntax on how to do so. So far, I have the following, but am at a loss on how to proceed.

Create Table Enrollments(
    StudentID int NOT NULL Foreign Key REFERENCES dbo.Students(StudentID),
    CourseID int NOT NULL Foreign Key REFERENCES dbo.Courses(CourseID),
    EnrollmentDateTime Datetime NOT NULL CHECK (dbo.fCheckDate(EnrollmentDateTime, CourseID) = 1))

...

create function dbo.fCheckDate (@StartDate Datetime, @CourseID int)
Returns bit
AS
Begin
 Return(SELECT E.StartDate
    FROM dbo.Enrollments E
    WHERE @CourseID = E.CourseID
End
go

Body:
Such function-based checks are quite expensive.  But, you need a function to return the course date:

create function dbo.getStartDate (@CourseID int)
Returns datetime
AS
Begin
     Return (SELECT c.StartDate
             FROM dbo.Courses c
             WHERE c.CourseID = @CourseID
            );
End;

Create Table Enrollments (
    StudentID int NOT NULL Foreign Key REFERENCES dbo.Students(StudentID),
    CourseID int NOT NULL Foreign Key REFERENCES dbo.Courses(CourseID),
    EnrollmentDateTime Datetime NOT NULL CHECK (EnrollmentDateTime < getStartDate(CourseID))
);


问:
Using polymorphism in (Surface)UserControl?
My (Surface)UserControls share a big amount of code. So I'd like to define an abstract super class where I can define this common code and behaviour.

But how do I define an abstract super class for a (Surface)UserControl? I tried to just subclass the code-behind file of a SurfaceUserControl, but then I get the following error:

```<code>Partial declarations of 'Prototype_Concept_2.views.DependencyExpander' must not specify different base classes  C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Concept_2\Prototype_Concept_2\views\DependencyExpander.xaml.cs
</code>```

答:
The problem is that your Xaml file is probably still starting with:

```<code><UserControl x:Class="..."
</code>```

However, if you derive your class from a different type (not UserControl, but SurfaceUserControl), then you're saying that the same class subclasses two classes.

While you can make a custom control, and subclass that, I personally find that this can be more problematic than expected.  I would recommend trying to handle this differently.

Instead of trying to create a single superclass for the UserControl, it's often easier to use encapsulation to delegate the responsibility to a single class.  Each UserControl can handle the shared behavior this way.  Alternatively, you could use a shared DataContext (or a shared hierarchy there).

Body:
My (Surface)UserControls share a big amount of code. So I'd like to define an abstract super class where I can define this common code and behaviour.

But how do I define an abstract super class for a (Surface)UserControl? I tried to just subclass the code-behind file of a SurfaceUserControl, but then I get the following error:

Partial declarations of 'Prototype_Concept_2.views.DependencyExpander' must not specify different base classes  C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Concept_2\Prototype_Concept_2\views\DependencyExpander.xaml.cs

Body:
The problem is that your Xaml file is probably still starting with:

<UserControl x:Class="..."

However, if you derive your class from a different type (not UserControl, but SurfaceUserControl), then you're saying that the same class subclasses two classes.

While you can make a custom control, and subclass that, I personally find that this can be more problematic than expected.  I would recommend trying to handle this differently.

Instead of trying to create a single superclass for the UserControl, it's often easier to use encapsulation to delegate the responsibility to a single class.  Each UserControl can handle the shared behavior this way.  Alternatively, you could use a shared DataContext (or a shared hierarchy there).


问:
Spring says that Request method 'DELETE' not supported, when trying to delete database item
I'm working on a school project, where you add Todo-items to database, show them, and grant user acces to individual pages created to each item. I'm using Spring and my Delete button nor individual pages showing specific task aren't working. In this project we use JPA to handle database.

Heres my TodoItemDatabaseController:

```<code>package wad.tododatabase;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class TodoItemDatabaseController {

    @Autowired
    private TodoRepository todoRepository;

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute
        ("items", this.todoRepository.findAll());
        return "index";
    }
</code>```

Here is the Delete that is not working.

```<code>    @DeleteMapping("/{itemId}")
    public String remove(Model model, @PathVariable Long itemId) {
        this.todoRepository.delete(this.todoRepository.getOne(itemId));
        return "redirect:/";
    }

    @PostMapping("/")
    public String post(@RequestParam String name) {
        if (!name.trim().isEmpty()) {
            TodoItem item = new TodoItem(name);
            todoRepository.save(item);
        }

        return "redirect:/";
    }
</code>```

Here I'm trying to get specific id, to create individual page for the item.

```<code>    @GetMapping("/{id}")
    public String findOne(Model model, @PathVariable Long id) {
        TodoItem t1 = todoRepository.getOne(id);
        t1.count();
        model.addAttribute("item", t1);
        return "item";
    }

}
</code>```

Here are my html files. I post the DELETE part of the index.html file, and item.html, which is the page of individual to-do item.

Index.html:

```<code><table>
            <tr>
                <th>Task name</th>
                <th></th>
            </tr>

            <tr th:each="item : ${items}">
                <td><a th:href="@{/{item}(item=${item.id})}" th:text="${item.name}">Item name</a></td>
                <td><form th:action="@{/{item}(item=${item.id})}" th:method="DELETE"><input type="submit" value="Done!"/></form></td>
            </tr>
        </table>
</code>```

Item.html:

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>TodoDatabase</title>
    </head>

    <body>
        <h1 th:text="${item.name}">item name</h1>

        <p>Item has been checked a total of <span th:text="${item.checked}">-1</span> times.</p>

        <a th:href="@{/}">Back to listing.</a>
    </body>
</html>
</code>```

Spring also gives 2 WARN statments, I guess they are warnings:

```<code>2017-11-13 21:52:13.902  WARN 29312 --- [nio-8080-exec-4] o.s.web.servlet.PageNotFound             : Request method 'DELETE' not supported
2017-11-13 21:52:13.903  WARN 29312 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'DELETE' not supported
</code>```

Here is my TodoRepository interface:

```<code>package wad.tododatabase;

/**
 *
 * @author riku
 *
 */
import org.springframework.data.jpa.repository.JpaRepository;

public interface TodoRepository extends JpaRepository<TodoItem, Long> {

}
</code>```

Any advice how to get this work?

答:
Have a try with this adnotation:</p>

```<code>@RequestMapping(value = "/{itemId}"", method = RequestMethod.DELETE)
    public @ResponseBody String remove(Model model, @PathVariable Long itemId) {
        this.todoRepository.delete(this.todoRepository.getOne(itemId));
        return "redirect:/";
    }
</code>```

Body:
I'm working on a school project, where you add Todo-items to database, show them, and grant user acces to individual pages created to each item. I'm using Spring and my Delete button nor individual pages showing specific task aren't working. In this project we use JPA to handle database.

Heres my TodoItemDatabaseController:

package wad.tododatabase;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class TodoItemDatabaseController {

    @Autowired
    private TodoRepository todoRepository;

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute
        ("items", this.todoRepository.findAll());
        return "index";
    }

Here is the Delete that is not working.

    @DeleteMapping("/{itemId}")
    public String remove(Model model, @PathVariable Long itemId) {
        this.todoRepository.delete(this.todoRepository.getOne(itemId));
        return "redirect:/";
    }

    @PostMapping("/")
    public String post(@RequestParam String name) {
        if (!name.trim().isEmpty()) {
            TodoItem item = new TodoItem(name);
            todoRepository.save(item);
        }

        return "redirect:/";
    }

Here I'm trying to get specific id, to create individual page for the item.

    @GetMapping("/{id}")
    public String findOne(Model model, @PathVariable Long id) {
        TodoItem t1 = todoRepository.getOne(id);
        t1.count();
        model.addAttribute("item", t1);
        return "item";
    }

}

Here are my html files. I post the DELETE part of the index.html file, and item.html, which is the page of individual to-do item.

Index.html:

                Task name

                Item name
                <form th:action="@{/{item}(item=${item.id})}" th:method="DELETE"><input type="submit" value="Done!"/></form>

Item.html:

<!DOCTYPE html>

        <title>TodoDatabase</title>

item name

Item has been checked a total of -1 times.

        Back to listing.

Spring also gives 2 WARN statments, I guess they are warnings:

2017-11-13 21:52:13.902  WARN 29312 --- [nio-8080-exec-4] o.s.web.servlet.PageNotFound             : Request method 'DELETE' not supported
2017-11-13 21:52:13.903  WARN 29312 --- [nio-8080-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'DELETE' not supported

Here is my TodoRepository interface:

package wad.tododatabase;

/**
 *
 * @author riku
 *
 */
import org.springframework.data.jpa.repository.JpaRepository;

public interface TodoRepository extends JpaRepository<TodoItem, Long> {

}

Any advice how to get this work?

Body:
Have a try with this adnotation:

@RequestMapping(value = "/{itemId}"", method = RequestMethod.DELETE)
    public @ResponseBody String remove(Model model, @PathVariable Long itemId) {
        this.todoRepository.delete(this.todoRepository.getOne(itemId));
        return "redirect:/";
    }


问:
Need help converting pseudo code to an 80x86 Assembly language program with the MASM assembler
I'm using Visual Studio 2012, editing the .asm file inside a windows32 solution.

This is the pseudo code that needs to be changed into assembly:

```<code>Declare a 32-bit integer array A[10] in memory

repeat
Prompt for and input user's array length L
until 0 <= L <= 10

for i := 0 to (L-1)
Prompt for and input A[i]
end for

while (First character of prompted input string for searching = 'Y' or 'y')
Prompt for and input value V to be searched
found := FALSE
  for i := 0 to (L-1)
    if V = A[i] then
found := TRUE
break
    end if
  end for

  if (found) then
Display message that value was found at position i
  else
Display message that value was not found
  end if
end while
</code>```

I can manage the inputs, loops, and jumps well enough but the things tripping me up are making the array have a length that the user inputs, and running through the array to compare the values. What would help me out the most is if someone would make and explain a segments of code to help me understand the parts I'm not getting. I've tried searching for it online but nearly everything I've come across uses a different assembler making it hard to dissect.

My code thus far is:

```<code>.586
.MODEL FLAT
INCLUDE io.h            ; header file for input/output
.STACK 4096

.DATA
lengthA DWORD   ?
promptL BYTE    "Please enter a length of the array between 0 and 10: ", 0
string  BYTE    40 DUP (?)
A       DWORD   0  DUP (?)

.CODE
_MainProc PROC

Reread: input   promptL, string, 40     ; read ASCII characters
        atod    string                  ; convert to integer
        ;while (promptL < 0 or > 10)
            cmp eax, 0
            jl  Reread
            cmp eax, 10
            jg  Reread
        ;end while
        mov     lengthA, eax            ; store in memory

_MainProc ENDP
END                             ; end of source code
</code>```

After checking that the user input is within range I just hit a brick wall and am not sure how to set up the array A to have the specified length or even if I declared A correctly.

答:
You can't modify the assembly-time constant at runtime. The DUP directive is that, assembly-time directive reserving memory space by emitting the "init" value as many times, as you want, into resulting machine code. That forms a fixed executable, which is limited to that size used during assembling.

As your maximum L is 10, you can reserve array for the maximum possible size:

```<code>A       DWORD   10  DUP (?)
</code>```

And then later in the code you will have to fetch the [lengthA] to know how many elements are used (to make it look as dynamically resized array and to not process remaining unused part of that reserve after address A).

Other option is to reserve memory dynamically at runtime, either by calling OS service for allocation of heap memory, or reserving the array on stack. But both options are considerably more advanced than using the fixed-size memory like above.

I don't see in your pseudo code any request for dynamic memory allocation, the solution with fixed size array looks OK to me, especially if you are struggling with it already, then you are probably not ready to program your own dynamic memory manager/allocator.

EDIT: Actually the pseudo code does specify you should reserve fixed size memory, I somehow overlooked it at first read:

```<code>Declare a 32-bit integer array A[10] in memory
</code>```

So example of pseudo code using the [lengthA]:

```<code>    ; for i := 0 to (L-1)
    xor     edi,edi         ; index i
input_loop:
    cmp     edi,[lengthA]
    jge     input_loop_ends ; if (i >= L), end for

    ; TODO: Prompt for and input A[i]
    ; eax = input value, preserve edi (!)
    mov     [A + 4*edi],eax ; store value into A[i]

    ; end for
    inc     edi             ; ++i
    jmp     input_loop

input_loop_ends:
    ; memory at address A contains L many DWORD values from user
</code>```

Body:
I'm using Visual Studio 2012, editing the .asm file inside a windows32 solution.

This is the pseudo code that needs to be changed into assembly:

Declare a 32-bit integer array A[10] in memory

repeat
Prompt for and input user's array length L
until 0 <= L <= 10

for i := 0 to (L-1)
Prompt for and input A[i]
end for

while (First character of prompted input string for searching = 'Y' or 'y')
Prompt for and input value V to be searched
found := FALSE
  for i := 0 to (L-1)
    if V = A[i] then
found := TRUE
break
    end if
  end for

  if (found) then
Display message that value was found at position i
  else
Display message that value was not found
  end if
end while

I can manage the inputs, loops, and jumps well enough but the things tripping me up are making the array have a length that the user inputs, and running through the array to compare the values. What would help me out the most is if someone would make and explain a segments of code to help me understand the parts I'm not getting. I've tried searching for it online but nearly everything I've come across uses a different assembler making it hard to dissect.

My code thus far is:

.586
.MODEL FLAT
INCLUDE io.h            ; header file for input/output
.STACK 4096

.DATA
lengthA DWORD   ?
promptL BYTE    "Please enter a length of the array between 0 and 10: ", 0
string  BYTE    40 DUP (?)
A       DWORD   0  DUP (?)

.CODE
_MainProc PROC

Reread: input   promptL, string, 40     ; read ASCII characters
        atod    string                  ; convert to integer
        ;while (promptL < 0 or > 10)
            cmp eax, 0
            jl  Reread
            cmp eax, 10
            jg  Reread
        ;end while
        mov     lengthA, eax            ; store in memory

_MainProc ENDP
END                             ; end of source code

After checking that the user input is within range I just hit a brick wall and am not sure how to set up the array A to have the specified length or even if I declared A correctly.

Body:
You can't modify the assembly-time constant at runtime. The DUP directive is that, assembly-time directive reserving memory space by emitting the "init" value as many times, as you want, into resulting machine code. That forms a fixed executable, which is limited to that size used during assembling.

As your maximum L is 10, you can reserve array for the maximum possible size:

A       DWORD   10  DUP (?)

And then later in the code you will have to fetch the [lengthA] to know how many elements are used (to make it look as dynamically resized array and to not process remaining unused part of that reserve after address A).

Other option is to reserve memory dynamically at runtime, either by calling OS service for allocation of heap memory, or reserving the array on stack. But both options are considerably more advanced than using the fixed-size memory like above.

I don't see in your pseudo code any request for dynamic memory allocation, the solution with fixed size array looks OK to me, especially if you are struggling with it already, then you are probably not ready to program your own dynamic memory manager/allocator.

EDIT: Actually the pseudo code does specify you should reserve fixed size memory, I somehow overlooked it at first read:

Declare a 32-bit integer array A[10] in memory

So example of pseudo code using the [lengthA]:

    ; for i := 0 to (L-1)
    xor     edi,edi         ; index i
input_loop:
    cmp     edi,[lengthA]
    jge     input_loop_ends ; if (i >= L), end for

    ; TODO: Prompt for and input A[i]
    ; eax = input value, preserve edi (!)
    mov     [A + 4*edi],eax ; store value into A[i]

    ; end for
    inc     edi             ; ++i
    jmp     input_loop

input_loop_ends:
    ; memory at address A contains L many DWORD values from user