问:
Python TCP Server using select()
this is my first entry @stackoverflow;-))

I need a Python3 TCP server, which sends all inputs of the clients to the other participants. The server works, but unfortunately the message is only returned to the sending client. As soon as the second client sends something, it gets all entries.The entries are therefore available in the output queue.

Why are the entries not recognized by select ()?

Thx for the support.

`

```<code>import select
import socket
import sys
import queue

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)

server_address = ('192.168.100.28', 8888)
print ("starting up on %s port %s" % server_address)
server.bind(server_address)

server.listen(5)

inputs = [ server ]
outputs = [ ]
message_queues = {}

while inputs:
    print ("\nwaiting for the next event")
    readable, writable, exceptional = select.select(inputs, outputs, inputs)
</code>```

Handle inputs

```<code>for s in readable:

    if s is server:
        # A "readable" server socket is ready to accept a connection
        connection, client_address = s.accept()
        print ("new connection from", client_address)
        connection.setblocking(0)
        inputs.append(connection)

        # Give the connection a queue for data we want to send
        message_queues[connection] = queue.Queue()
    else:
        data = s.recv(1024)
        if data:
            # A readable client socket has data
            print ('received "%s" from %s' % (data, s.getpeername()))
            # Add output channel for response
            #message_queues[s].put(data)
            if s not in outputs:
                outputs.append(s)
            for aQueue in message_queues:
                message_queues[aQueue].put(data)
                # AQueue.send ("Test".encode())
        else:
            # Interpret empty result as closed connection
            print ("closing", client_address, "after reading no data")
            # Stop listening for input on the connection
            if s in outputs:
                outputs.remove(s)
            inputs.remove(s)
            s.close()

            # Remove message queue
            del message_queues[s]
</code>```

Handle outputs

```<code>for s in writable:
    try:
        next_msg = message_queues[s].get_nowait()
    except queue.Empty:
        # No messages waiting so stop checking for writability.
        print ("output queue for", s.getpeername(), "is empty")
        outputs.remove(s)
    else:
        print ('sending "%s" to %s' % (next_msg, s.getpeername()))
        s.send(next_msg)
</code>```

Handle "exceptional conditions"

```<code>for s in exceptional:
    print ("handling exceptional condition for", s.getpeername())
    # Stop listening for input on the connection
    inputs.remove(s)
    if s in outputs:
        outputs.remove(s)
    s.close()

    # Remove message queue
    del message_queues[s]
</code>```

`

答:
Your problem is that you only add a peer to the output list when you read something from it. You should instead do it when you write somthing to its message queue.

The receiving part should become:

```<code>        ...
        data = s.recv(1024)
        if data:
            # A readable client socket has data
            print ('received "%s" from %s' % (data, s.getpeername()))
            # Add output channel for response
            #message_queues[s].put(data)
            # if s not in outputs:
            #    outputs.append(s)
            for aQueue in message_queues:
                message_queues[aQueue].put(data)
                if aQueue not in outputs:       # enqueue the msg
                    outputs.append(aQueue)      # and ask select to warn when it can be sent
                # AQueue.send ("Test".encode())
        else:
            ...
</code>```

According to your own requirements, you should only enqueue messages for other participants:

```<code>            for aQueue in message_queues:
                if aQueue != s:      # only send to other participants
                    ...
</code>```

Finally, you often test existence of a socket in outputs. That let think that a set would be more appropriate than a list.

Title: Python TCP Server using select()

Body:
this is my first entry @stackoverflow;-))

I need a Python3 TCP server, which sends all inputs of the clients to the other participants. The server works, but unfortunately the message is only returned to the sending client. As soon as the second client sends something, it gets all entries.The entries are therefore available in the output queue.

Why are the entries not recognized by select ()?

Thx for the support.

`

import select
import socket
import sys
import queue

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setblocking(0)

server_address = ('192.168.100.28', 8888)
print ("starting up on %s port %s" % server_address)
server.bind(server_address)

server.listen(5)

inputs = [ server ]
outputs = [ ]
message_queues = {}

while inputs:
    print ("\nwaiting for the next event")
    readable, writable, exceptional = select.select(inputs, outputs, inputs)

Handle inputs

for s in readable:

    if s is server:
        # A "readable" server socket is ready to accept a connection
        connection, client_address = s.accept()
        print ("new connection from", client_address)
        connection.setblocking(0)
        inputs.append(connection)

        # Give the connection a queue for data we want to send
        message_queues[connection] = queue.Queue()
    else:
        data = s.recv(1024)
        if data:
            # A readable client socket has data
            print ('received "%s" from %s' % (data, s.getpeername()))
            # Add output channel for response
            #message_queues[s].put(data)
            if s not in outputs:
                outputs.append(s)
            for aQueue in message_queues:
                message_queues[aQueue].put(data)
                # AQueue.send ("Test".encode())
        else:
            # Interpret empty result as closed connection
            print ("closing", client_address, "after reading no data")
            # Stop listening for input on the connection
            if s in outputs:
                outputs.remove(s)
            inputs.remove(s)
            s.close()

            # Remove message queue
            del message_queues[s]

Handle outputs

for s in writable:
    try:
        next_msg = message_queues[s].get_nowait()
    except queue.Empty:
        # No messages waiting so stop checking for writability.
        print ("output queue for", s.getpeername(), "is empty")
        outputs.remove(s)
    else:
        print ('sending "%s" to %s' % (next_msg, s.getpeername()))
        s.send(next_msg)

Handle "exceptional conditions"

for s in exceptional:
    print ("handling exceptional condition for", s.getpeername())
    # Stop listening for input on the connection
    inputs.remove(s)
    if s in outputs:
        outputs.remove(s)
    s.close()

    # Remove message queue
    del message_queues[s]

`

Body:
Your problem is that you only add a peer to the output list when you read something from it. You should instead do it when you write somthing to its message queue.

The receiving part should become:

        ...
        data = s.recv(1024)
        if data:
            # A readable client socket has data
            print ('received "%s" from %s' % (data, s.getpeername()))
            # Add output channel for response
            #message_queues[s].put(data)
            # if s not in outputs:
            #    outputs.append(s)
            for aQueue in message_queues:
                message_queues[aQueue].put(data)
                if aQueue not in outputs:       # enqueue the msg
                    outputs.append(aQueue)      # and ask select to warn when it can be sent
                # AQueue.send ("Test".encode())
        else:
            ...

According to your own requirements, you should only enqueue messages for other participants:

            for aQueue in message_queues:
                if aQueue != s:      # only send to other participants
                    ...

Finally, you often test existence of a socket in outputs. That let think that a set would be more appropriate than a list.


来源: stackexchange

问:
TypeScript error with Promise.reject
Why do I receive the following compilation error with this TypeScript method which I wrote:

```<code>getFile(path: string): Promise<FileEntry> {
  return this.file.resolveLocalFilesystemUrl(path)
    .then(entry => {
      if (entry.isFile) {
        return <FileEntry>entry;
      } else {
        let err = new FileError(13);
        err.message = 'input is not a file';
        return Promise.reject(err);
      }
    });
}
</code>```

I get the error:

```<code>Argument of type '(entry: Entry) => Promise<never> | FileEntry' is not assignable to parameter of type '(value: Entry) => PromiseLike<never>'. Type 'Promise<never> | FileEntry' is not assignable to type 'PromiseLike<never>'. Type 'FileEntry' is not assignable to type 'PromiseLike<never>'. Property 'then' is  missing in type 'FileEntry'.
</code>```

The definition for resolveLocalFilesystemUrl is as follows:

```<code>resolveLocalFilesystemUrl(fileUrl: string): Promise<Entry>;
</code>```

FileEntry is a subclass of Entry, hence the casted return. However, the error is around Promise.reject.

If I change my reject line to the following, it works:

```<code>return Promise.reject<FileEntry>(err);
</code>```

Do I need to return Promise.reject(...) and what is the correct implementation?

答:
You shouldn't really return a resolved or rejected promise inside of your promise chain.

When you want to indicate an error you should just throw an error:

```<code>else
   let err = new FileError(13);
   err.message = 'input is not a file';
   throw err;
</code>```

ContentLicense: CC BY-SA 3.0

Title: TypeScript error with Promise.reject

Body:
Why do I receive the following compilation error with this TypeScript method which I wrote:

getFile(path: string): Promise<FileEntry> {
  return this.file.resolveLocalFilesystemUrl(path)
    .then(entry => {
      if (entry.isFile) {
        return <FileEntry>entry;
      } else {
        let err = new FileError(13);
        err.message = 'input is not a file';
        return Promise.reject(err);
      }
    });
}

I get the error:

Argument of type '(entry: Entry) => Promise<never> | FileEntry' is not assignable to parameter of type '(value: Entry) => PromiseLike<never>'. Type 'Promise<never> | FileEntry' is not assignable to type 'PromiseLike<never>'. Type 'FileEntry' is not assignable to type 'PromiseLike<never>'. Property 'then' is  missing in type 'FileEntry'.

The definition for resolveLocalFilesystemUrl is as follows:

resolveLocalFilesystemUrl(fileUrl: string): Promise<Entry>;

FileEntry is a subclass of Entry, hence the casted return. However, the error is around Promise.reject.

If I change my reject line to the following, it works:

return Promise.reject<FileEntry>(err);

Do I need to return Promise.reject(...) and what is the correct implementation?

Body:
You shouldn't really return a resolved or rejected promise inside of your promise chain.

When you want to indicate an error you should just throw an error:

else
   let err = new FileError(13);
   err.message = 'input is not a file';
   throw err;


问:
How can I generate a GUID in Vim?
Vim doesn't have a built-in GUID generator.

For the project I'm working on, I can rely on Powershell being available, so the following gives me a GUID string:

```<code>[guid]::NewGuid().ToString()
</code>```

I call this within a substitution, as follows:

```<code>%s/foo/\=system('[guid]::NewGuid().ToString()')[:2]/
</code>```

While this works, it flashes up a window for each substitution and it's quite slow.

What I really want is a way to generate GUIDs within Vim, portably and quickly.

答:
I got here because the question-title asks how to create an UUID, however the question-text actually wants to replace existing textblocks with a newly created UUID.

Marius Gedminas' Answer got me very far, and if anyone else needs to create and insert an UUID, here is how:

```<code>function! Guid()
python << EOF
import uuid, vim
vim.command("normal i" + str(uuid.uuid4()) )
EOF
endfunction
</code>```

If you want to map it to <alt+G>: map <m-g> :call Guid() <cr>

(In case your Gvim crashes upon invoking Python, read this)

Title: How can I generate a GUID in Vim?

Body:
Vim doesn't have a built-in GUID generator.

For the project I'm working on, I can rely on Powershell being available, so the following gives me a GUID string:

[guid]::NewGuid().ToString()

I call this within a substitution, as follows:

%s/foo/\=system('[guid]::NewGuid().ToString()')[:2]/

While this works, it flashes up a window for each substitution and it's quite slow.

What I really want is a way to generate GUIDs within Vim, portably and quickly.

Body:
I got here because the question-title asks how to create an UUID, however the question-text actually wants to replace existing textblocks with a newly created UUID.

Marius Gedminas' Answer got me very far, and if anyone else needs to create and insert an UUID, here is how:

function! Guid()
python << EOF
import uuid, vim
vim.command("normal i" + str(uuid.uuid4()) )
EOF
endfunction

If you want to map it to <alt+G>: map <m-g> :call Guid() <cr>

(In case your Gvim crashes upon invoking Python, read this)


问:
django form validation based on whether field has value

When I submit an empty form with a phone_type selected (for formHomePhone) the form returns its self without a value selected in phone_type stipulating This field is required

As you can see from the view The first phone number in the form is required but the other phone numbers are not. I only want to process them if there is a value present. Though when I click submit on an empty form the additional phone number fields throw up an error from the UKPhoneNumberField > Phone number must include an area code. How can I only validate when there is a number in the respected field?

I have a view.py file like this

```<code>def new_client_view(request):
    if request.method == 'POST':
        formDetails = ClientDetailsForm(request.POST)
        formAddress = ClientAddressForm(request.POST)
        formHomePhone = ClientPhoneForm(request.POST)
        formWorkPhone = ClientOtherPhoneForm(request.POST)
        formMobilePhone = ClientOtherPhoneForm(request.POST)
        if formDetails.is_valid() and formAddress.is_valid() and formHomePhone.is_valid():
            c = Client()
            c.save()
            fd = formDetails.save(commit=False)
            fd.client = c
            fd.created_by = request.user
            fd.save()
            fa = formAddress.save(commit=False)
            fa.client = c
            fa.created_by = request.user
            fa.save()
            fph = formHomePhone.save(commit=False)
            fph.client = c
            fph.created_by = request.user
            fph.save()
            if 'p2-number' in request.POST and request.POST['p2-number']:
                fpw = formWorkPhone.save(commit=False)
                fpw.client = c.id
                fpw.created_by = request.user
                if fpw.is_valid():
                    fpw.save()
            if 'p3-number' in request.POST and request.POST['p3-number']:
                fpm = formMobilePhone.save(commit=False)
                fpm.client = c
                fpm.created_by = request.user
                if fpm.is_valid():
                    fpm.save()
            return render_to_response('client/client.html', context_instance=RequestContext(request))
        else:
            return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))

    else:
        formAddress = ClientAddressForm()
        formDetails = ClientDetailsForm()
        formHomePhone = ClientPhoneForm(initial={'phone_type':'home'}, prefix="p1")
        formWorkPhone = ClientPhoneForm(initial={'phone_type':'work'}, prefix="p2")
        formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'}, prefix="p3")
        return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))
</code>```

a forms.py like this:

```<code>class ClientDetailsForm(ModelForm):
    class Meta:
        model = ClientDetails
        exclude = ('client', 'created', 'created_by')

class ClientAddressForm(ModelForm):
    class Meta:
        model = ClientAddress
        exclude = ('client', 'created', 'created_by')

class ClientPhoneForm(ModelForm):
    number = UKPhoneNumberField()

    class Meta:
        model = ClientPhone
        exclude = ('client', 'created', 'created_by')

class ClientOtherPhoneForm(ModelForm):
    number = UKPhoneNumberField(required=False)

    class Meta:
        model = ClientPhone
        exclude = ('client', 'created', 'created_by')
</code>```

and a models.py like this:

```<code>MARITAL_STATUS_CHOICES = (
    ...
)

NAME_TITLE_CHOICES = (
    ...
)

PHONE_CHOICES = (
    ('home', 'Home'),
    ('home2', 'Home 2'),
    ('mobi', 'Mobile'),
    ('mobi2', 'Mobile 2'),
    ('work', 'Work'),
    ('work2', 'Work 2'),
)

class Client(models.Model):
    closed = models.DateTimeField(blank=True, null=True)
    closed_by = models.ForeignKey(User, blank=True, null=True)
    comment = models.TextField(blank=True, null=True)

    def __unicode__(self):
        return u'%s' % (self.id)

class ClientDetails(models.Model):
    ...

class ClientAddress(models.Model):
    ...

class ClientPhone(models.Model):
    client = models.ForeignKey(Client, null=True)
    created = models.DateTimeField(default=datetime.now)
    created_by = models.ForeignKey(User, blank=True, null=True)
    phone_type = models.CharField(max_length=5, choices=PHONE_CHOICES)
    number = models.CharField(max_length=24)
</code>```

BTW(my new_client_view function is not very DRY I know. Any recommendations would be gratefully received)

答:
I found an answer that goes something like this (yes I know it's stupid!)

```<code>def new_client_view(request):
    if request.method == 'POST':
        formDetails = ClientDetailsForm(request.POST)
        formAddress = ClientAddressForm(request.POST)
        formHomePhone = ClientPhoneForm(request.POST)
        if formDetails.is_valid() and formAddress.is_valid() and formHomePhone.is_valid():
            c = Client()
            c.save()
            fd = formDetails.save(commit=False)
            fd.client = c
            fd.created_by = request.user
            fd.save()
            fa = formAddress.save(commit=False)
            fa.client = c
            fa.created_by = request.user
            fa.save()
            fph = formHomePhone.save(commit=False)
            fph.client = c
            fph.created_by = request.user
            fph.save()
            if 'p2-number' in request.POST and request.POST['p2-number']:
                formWorkPhone = ClientOtherPhoneForm(request.POST)
                fpw = formWorkPhone.save(commit=False)
                fpw.client = c.id
                fpw.created_by = request.user
                # if the work number is valid
                if fpw.is_valid():
                    # check the mobile number before you save the work number
                    if 'p3-number' in request.POST and request.POST['p3-number']:
                        formMobilePhone = ClientOtherPhoneForm(request.POST)
                        fpm = formMobilePhone.save(commit=False)
                        fpm.client = c
                        fpm.created_by = request.user
                        # if the mobile number is good then there is no more checking to do
                        if fpm.is_valid():
                            fpm.save()
                        # else load up the form again with the error for the mobile phone and the original
                        # data for the mobile phone and the work phone
                        else:
                            formWorkPhone = ClientOtherPhoneForm(request.POST)
                            return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))
                    # if the work number is valid and the mobile field wasn't used then just save the work number
                    fpw.save()
                # if the work number is not valid then find out if a mobile number
                # was entered and feed it back to the form
                else:
                    if 'p3-number' in request.POST and request.POST['p3-number']:
                        formMobilePhone = ClientOtherPhoneForm(request.POST)
                    else:
                        formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'}, prefix="p3")
                    return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))

            return render_to_response('client/client.html', context_instance=RequestContext(request))
        # if the form doesn't validate then you need to find out if the optional fields contain data,
        # and if so load that data back into the form
        else:
            if 'p2-number' in request.POST and request.POST['p2-number']:
                formWorkPhone = ClientOtherPhoneForm(request.POST, prefix="p2")
            else:
                formWorkPhone = ClientPhoneForm(initial={'phone_type':'work'}, prefix="p2")
            if 'p3-number' in request.POST and request.POST['p3-number']:
                formMobilePhone = ClientOtherPhoneForm(request.POST, prefix="p3")
            else:
                formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'}, prefix="p3")

            return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))

    else:
        formAddress = ClientAddressForm()
        formDetails = ClientDetailsForm()
        formHomePhone = ClientPhoneForm(initial={'phone_type':'home'}, prefix="p1")
        formWorkPhone = ClientPhoneForm(initial={'phone_type':'work'}, prefix="p2")
        formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'}, prefix="p3")
        return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))
</code>```

I think I need to overwrite the is_valid function on the form to make sure there is data in one of the fields before doing something like super.is_valid() (else returning true so I don't raise an error for an empty form) and also a pre-save function on the form that takes the user and client objects and puts them into the fields and checks there is a phone number before saving.

Overwrite is_valid() to make sure blank values can get through

Create pre-save() to load in User and Client into the model and abort if you can if there is no value for number

THIS IS CRAZY!!!

The only other thing I can think of is making phone_type and number in the ClientPhone model blank=True, null=True so that I can have optional phone fields

THATS CRAZY AS WELL!!!

Why should I have to break the integrity of my model just to have an option field in one of my forms???

EDIT:

view.py turned out cleaner when I did the following to the forms.py file:

```<code>class ClientDetailsForm(ModelForm):
    class Meta:
        model = ClientDetails
        exclude = ('client', 'created', 'created_by')

    def CustomSave(self,c,u):
        t = self.save(commit=False)
        t.client = c
        t.created_by = u
        t.first_name = self.cleaned_data['first_name'].capitalize()
        t.middle_name = self.cleaned_data['first_name'].capitalize()
        t.last_name = self.cleaned_data['first_name'].capitalize()
        t.save()

class ClientAddressForm(ModelForm):
    class Meta:
        model = ClientAddress
        exclude = ('client', 'created', 'created_by')

    def CustomSave(self,c,u):
        t = self.save(commit=False)
        t.client = c
        t.created_by = u
        t.address_1 = self.cleaned_data['address_1'].capitalize()
        t.address_2 = self.cleaned_data['address_2'].capitalize()
        t.address_3 = self.cleaned_data['address_3'].capitalize()
        t.address_4 = self.cleaned_data['address_4'].capitalize()
        t.post_code = self.cleaned_data['post_code'].upper()
        t.save()

class ClientPhoneForm(ModelForm):
    number = UKPhoneNumberField()

    class Meta:
        model = ClientPhone
        exclude = ('client', 'created', 'created_by')

    def CustomSave(self,c,u):
        t = self.save(commit=False)
        t.client = c
        t.created_by = u
        t.save()

class ClientOtherPhoneForm(ModelForm):
    number = UKPhoneNumberField(required=False)

    class Meta:
        model = ClientPhone
        exclude = ('client', 'created', 'created_by')

    def CustomSave(self,c,u):
        t = self.save(commit=False)
        t.client = c
        t.created_by = u
        t.save()
</code>```

ContentLicense: CC BY-SA 2.5

Body:
When I submit an empty form with a phone_type selected (for formHomePhone) the form returns its self without a value selected in phone_type stipulating This field is required

As you can see from the view The first phone number in the form is required but the other phone numbers are not. I only want to process them if there is a value present. Though when I click submit on an empty form the additional phone number fields throw up an error from the UKPhoneNumberField > Phone number must include an area code. How can I only validate when there is a number in the respected field?

I have a view.py file like this

def new_client_view(request):
    if request.method == 'POST':
        formDetails = ClientDetailsForm(request.POST)
        formAddress = ClientAddressForm(request.POST)
        formHomePhone = ClientPhoneForm(request.POST)
        formWorkPhone = ClientOtherPhoneForm(request.POST)
        formMobilePhone = ClientOtherPhoneForm(request.POST)
        if formDetails.is_valid() and formAddress.is_valid() and formHomePhone.is_valid():
            c = Client()
            c.save()
            fd = formDetails.save(commit=False)
            fd.client = c
            fd.created_by = request.user
            fd.save()
            fa = formAddress.save(commit=False)
            fa.client = c
            fa.created_by = request.user
            fa.save()
            fph = formHomePhone.save(commit=False)
            fph.client = c
            fph.created_by = request.user
            fph.save()
            if 'p2-number' in request.POST and request.POST['p2-number']:
                fpw = formWorkPhone.save(commit=False)
                fpw.client = c.id
                fpw.created_by = request.user
                if fpw.is_valid():
                    fpw.save()
            if 'p3-number' in request.POST and request.POST['p3-number']:
                fpm = formMobilePhone.save(commit=False)
                fpm.client = c
                fpm.created_by = request.user
                if fpm.is_valid():
                    fpm.save()
            return render_to_response('client/client.html', context_instance=RequestContext(request))
        else:
            return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))

    else:
        formAddress = ClientAddressForm()
        formDetails = ClientDetailsForm()
        formHomePhone = ClientPhoneForm(initial={'phone_type':'home'}, prefix="p1")
        formWorkPhone = ClientPhoneForm(initial={'phone_type':'work'}, prefix="p2")
        formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'}, prefix="p3")
        return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))

a forms.py like this:

class ClientDetailsForm(ModelForm):
    class Meta:
        model = ClientDetails
        exclude = ('client', 'created', 'created_by')

class ClientAddressForm(ModelForm):
    class Meta:
        model = ClientAddress
        exclude = ('client', 'created', 'created_by')

class ClientPhoneForm(ModelForm):
    number = UKPhoneNumberField()

    class Meta:
        model = ClientPhone
        exclude = ('client', 'created', 'created_by')

class ClientOtherPhoneForm(ModelForm):
    number = UKPhoneNumberField(required=False)

    class Meta:
        model = ClientPhone
        exclude = ('client', 'created', 'created_by')

and a models.py like this:

MARITAL_STATUS_CHOICES = (
    ...
)

NAME_TITLE_CHOICES = (
    ...
)

PHONE_CHOICES = (
    ('home', 'Home'),
    ('home2', 'Home 2'),
    ('mobi', 'Mobile'),
    ('mobi2', 'Mobile 2'),
    ('work', 'Work'),
    ('work2', 'Work 2'),
)

class Client(models.Model):
    closed = models.DateTimeField(blank=True, null=True)
    closed_by = models.ForeignKey(User, blank=True, null=True)
    comment = models.TextField(blank=True, null=True)

    def __unicode__(self):
        return u'%s' % (self.id)

class ClientDetails(models.Model):
    ...

class ClientAddress(models.Model):
    ...

class ClientPhone(models.Model):
    client = models.ForeignKey(Client, null=True)
    created = models.DateTimeField(default=datetime.now)
    created_by = models.ForeignKey(User, blank=True, null=True)
    phone_type = models.CharField(max_length=5, choices=PHONE_CHOICES)
    number = models.CharField(max_length=24)

BTW(my new_client_view function is not very DRY I know. Any recommendations would be gratefully received)

Body:
I found an answer that goes something like this (yes I know it's stupid!)

def new_client_view(request):
    if request.method == 'POST':
        formDetails = ClientDetailsForm(request.POST)
        formAddress = ClientAddressForm(request.POST)
        formHomePhone = ClientPhoneForm(request.POST)
        if formDetails.is_valid() and formAddress.is_valid() and formHomePhone.is_valid():
            c = Client()
            c.save()
            fd = formDetails.save(commit=False)
            fd.client = c
            fd.created_by = request.user
            fd.save()
            fa = formAddress.save(commit=False)
            fa.client = c
            fa.created_by = request.user
            fa.save()
            fph = formHomePhone.save(commit=False)
            fph.client = c
            fph.created_by = request.user
            fph.save()
            if 'p2-number' in request.POST and request.POST['p2-number']:
                formWorkPhone = ClientOtherPhoneForm(request.POST)
                fpw = formWorkPhone.save(commit=False)
                fpw.client = c.id
                fpw.created_by = request.user
                # if the work number is valid
                if fpw.is_valid():
                    # check the mobile number before you save the work number
                    if 'p3-number' in request.POST and request.POST['p3-number']:
                        formMobilePhone = ClientOtherPhoneForm(request.POST)
                        fpm = formMobilePhone.save(commit=False)
                        fpm.client = c
                        fpm.created_by = request.user
                        # if the mobile number is good then there is no more checking to do
                        if fpm.is_valid():
                            fpm.save()
                        # else load up the form again with the error for the mobile phone and the original
                        # data for the mobile phone and the work phone
                        else:
                            formWorkPhone = ClientOtherPhoneForm(request.POST)
                            return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))
                    # if the work number is valid and the mobile field wasn't used then just save the work number
                    fpw.save()
                # if the work number is not valid then find out if a mobile number
                # was entered and feed it back to the form
                else:
                    if 'p3-number' in request.POST and request.POST['p3-number']:
                        formMobilePhone = ClientOtherPhoneForm(request.POST)
                    else:
                        formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'}, prefix="p3")
                    return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))

            return render_to_response('client/client.html', context_instance=RequestContext(request))
        # if the form doesn't validate then you need to find out if the optional fields contain data,
        # and if so load that data back into the form
        else:
            if 'p2-number' in request.POST and request.POST['p2-number']:
                formWorkPhone = ClientOtherPhoneForm(request.POST, prefix="p2")
            else:
                formWorkPhone = ClientPhoneForm(initial={'phone_type':'work'}, prefix="p2")
            if 'p3-number' in request.POST and request.POST['p3-number']:
                formMobilePhone = ClientOtherPhoneForm(request.POST, prefix="p3")
            else:
                formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'}, prefix="p3")

            return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))

    else:
        formAddress = ClientAddressForm()
        formDetails = ClientDetailsForm()
        formHomePhone = ClientPhoneForm(initial={'phone_type':'home'}, prefix="p1")
        formWorkPhone = ClientPhoneForm(initial={'phone_type':'work'}, prefix="p2")
        formMobilePhone = ClientPhoneForm(initial={'phone_type':'mobi'}, prefix="p3")
        return render_to_response('client/new_client.html', {'formDetails': formDetails, 'formAddress': formAddress, 'formHomePhone': formHomePhone, 'formWorkPhone': formWorkPhone, 'formMobilePhone': formMobilePhone}, context_instance=RequestContext(request))

I think I need to overwrite the is_valid function on the form to make sure there is data in one of the fields before doing something like super.is_valid() (else returning true so I don't raise an error for an empty form) and also a pre-save function on the form that takes the user and client objects and puts them into the fields and checks there is a phone number before saving.

Overwrite is_valid() to make sure blank values can get through

Create pre-save() to load in User and Client into the model and abort if you can if there is no value for number

THIS IS CRAZY!!!

The only other thing I can think of is making phone_type and number in the ClientPhone model blank=True, null=True so that I can have optional phone fields

THATS CRAZY AS WELL!!!

Why should I have to break the integrity of my model just to have an option field in one of my forms???

EDIT:

view.py turned out cleaner when I did the following to the forms.py file:

class ClientDetailsForm(ModelForm):
    class Meta:
        model = ClientDetails
        exclude = ('client', 'created', 'created_by')

    def CustomSave(self,c,u):
        t = self.save(commit=False)
        t.client = c
        t.created_by = u
        t.first_name = self.cleaned_data['first_name'].capitalize()
        t.middle_name = self.cleaned_data['first_name'].capitalize()
        t.last_name = self.cleaned_data['first_name'].capitalize()
        t.save()

class ClientAddressForm(ModelForm):
    class Meta:
        model = ClientAddress
        exclude = ('client', 'created', 'created_by')

    def CustomSave(self,c,u):
        t = self.save(commit=False)
        t.client = c
        t.created_by = u
        t.address_1 = self.cleaned_data['address_1'].capitalize()
        t.address_2 = self.cleaned_data['address_2'].capitalize()
        t.address_3 = self.cleaned_data['address_3'].capitalize()
        t.address_4 = self.cleaned_data['address_4'].capitalize()
        t.post_code = self.cleaned_data['post_code'].upper()
        t.save()

class ClientPhoneForm(ModelForm):
    number = UKPhoneNumberField()

    class Meta:
        model = ClientPhone
        exclude = ('client', 'created', 'created_by')

    def CustomSave(self,c,u):
        t = self.save(commit=False)
        t.client = c
        t.created_by = u
        t.save()

class ClientOtherPhoneForm(ModelForm):
    number = UKPhoneNumberField(required=False)

    class Meta:
        model = ClientPhone
        exclude = ('client', 'created', 'created_by')

    def CustomSave(self,c,u):
        t = self.save(commit=False)
        t.client = c
        t.created_by = u
        t.save()


问:
Firebase Listener does not identify or resume connection after idle time
My project is to identify whether the client is online or offline. I use the code made available in the Android-Firebase documentation, which uses an EventListener in ".info / connected".

```<code>// since I can connect from multiple devices, we store each connection instance separately
// any time that connectionsRef's value is null (i.e. has no children) I am offline
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myConnectionsRef = database.getReference("users/joe/connections");

// stores the timestamp of my last disconnect (the last time I was seen online)
final DatabaseReference lastOnlineRef = database.getReference("/users/joe/lastOnline");

final DatabaseReference connectedRef = database.getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    boolean connected = snapshot.getValue(Boolean.class);
    if (connected) {
      DatabaseReference con = myConnectionsRef.push();

      // when this device disconnects, remove it
      con.onDisconnect().removeValue();

      // when I disconnect, update the last time I was seen online
      lastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP);

      // add this device to my connections list
      // this value could contain info about the device or a timestamp too
      con.setValue(Boolean.TRUE);
    }
  }

  @Override
  public void onCancelled(DatabaseError error) {
    System.err.println("Listener was cancelled at .info/connected");
  }
});
</code>```

This method correctly identifies when the user terminates or reopens the application or when minor disconnections occur on the internet. However, I did a test turn off the Wifi of the device for a time of 2 minutes, it is identified in the Firebase Database that is not connected, but when I turn on the Wifi, resuming the internet connection, Firebase does not recognize the active connection, appears as if the user still remained inactive.

This code snippet was inserted into the onCreate method of my MainActivity.

Can anyone tell me why this occurs?

EDIT: Attachments

Error log:

11-14 10:12:55.272 27901-27926/com.example.davi.projetofirebase D/PersistentConnection: pc_0 - Trying to fetch auth token

11-14 10:12:55.276 27901-27926/com.example.davi.projetofirebase D/PersistentConnection: pc_0 - Successfully fetched token, opening connection

11-14 10:12:55.281 27901-27926/com.example.davi.projetofirebase D/Connection: conn_14 - Opening a connection

11-14 10:12:55.293 27901-27926/com.example.davi.projetofirebase D/WebSocket: ws_14 - WebSocket error.
                                                                               bkx: unknown host: s-usc1c-nss-208.firebaseio.com
                                                                                at bku.d(:com.google.android.gms.DynamiteModulesC@11746448:102)
                                                                                at bkv.run(:com.google.android.gms.DynamiteModulesC@11746448:4)
                                                                                at java.lang.Thread.run(Thread.java:760)
                                                                                Caused by: java.net.UnknownHostException: s-usc1c-nss-208.firebaseio.com
                                                                                at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:174)
                                                                                at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
                                                                                at java.net.Socket.connect(Socket.java:586)
                                                                                at com.android.org.conscrypt.OpenSSLSocketImpl.connect(OpenSSLSocketImpl.java:265)
                                                                                at com.android.org.conscrypt.OpenSSLSocketImpl.connect(OpenSSLSocketImpl.java:252)
                                                                                at java.net.Socket.(Socket.java:427)
                                                                                at java.net.Socket.(Socket.java:210)
                                                                                at javax.net.ssl.SSLSocket.(SSLSocket.java:906)
                                                                                at com.android.org.conscrypt.OpenSSLSocketImpl.(OpenSSLSocketImpl.java:192)
                                                                                at com.android.org.conscrypt.OpenSSLSocketFactoryImpl.createSocket(OpenSSLSocketFactoryImpl.java:68)
                                                                                at bku.d(:com.google.android.gms.DynamiteModulesC@11746448:94)
                                                                                at bkv.run(:com.google.android.gms.DynamiteModulesC@11746448:4)
                                                                                at java.lang.Thread.run(Thread.java:760)

11-14 10:12:55.294 27901-27926/com.example.davi.projetofirebase D/WebSocket: ws_14 - closing itself

11-14 10:12:55.295 27901-27926/com.example.davi.projetofirebase D/Connection: conn_14 - Realtime connection failed

11-14 10:12:55.295 27901-27926/com.example.davi.projetofirebase D/Connection: conn_14 - closing realtime connection

11-14 10:12:55.295 27901-27926/com.example.davi.projetofirebase D/PersistentConnection: pc_0 - Got on disconnect due to OTHER

11-14 10:12:55.296 27901-27926/com.example.davi.projetofirebase D/PersistentConnection: pc_0 - Scheduling connection attempt

11-14 10:12:55.297 27901-27926/com.example.davi.projetofirebase D/ConnectionRetryHelper: Scheduling retry in 27403ms

11-14 10:12:55.304 27901-27926/com.example.davi.projetofirebase D/WebSocket: ws_14 - closed

11-14 10:13:02.947 27901-27926/com.example.davi.projetofirebase D/PersistentConnection: pc_0 - Connection interrupted for: connection_idle

11-14 10:13:02.960 27901-27926/com.example.davi.projetofirebase D/ConnectionRetryHelper: Cancelling existing retry attempt

答:
As Franks says, if you enable debug logging for the client, will be able for sure to see the state of the connection, whether the client is reestablishing its connection or not.

```<code>public synchronized void setLogLevel (Logger.Level logLevel)
</code>```

By default, this is set to INFO. This includes any internal errors (ERROR) and any security debug messages (INFO) that the client receives. Set to DEBUG to turn on the diagnostic logging, and NONE to disable all logging.

Body:
My project is to identify whether the client is online or offline. I use the code made available in the Android-Firebase documentation, which uses an EventListener in ".info / connected".

// since I can connect from multiple devices, we store each connection instance separately
// any time that connectionsRef's value is null (i.e. has no children) I am offline
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myConnectionsRef = database.getReference("users/joe/connections");

// stores the timestamp of my last disconnect (the last time I was seen online)
final DatabaseReference lastOnlineRef = database.getReference("/users/joe/lastOnline");

final DatabaseReference connectedRef = database.getReference(".info/connected");
connectedRef.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    boolean connected = snapshot.getValue(Boolean.class);
    if (connected) {
      DatabaseReference con = myConnectionsRef.push();

      // when this device disconnects, remove it
      con.onDisconnect().removeValue();

      // when I disconnect, update the last time I was seen online
      lastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP);

      // add this device to my connections list
      // this value could contain info about the device or a timestamp too
      con.setValue(Boolean.TRUE);
    }
  }

  @Override
  public void onCancelled(DatabaseError error) {
    System.err.println("Listener was cancelled at .info/connected");
  }
});

This method correctly identifies when the user terminates or reopens the application or when minor disconnections occur on the internet. However, I did a test turn off the Wifi of the device for a time of 2 minutes, it is identified in the Firebase Database that is not connected, but when I turn on the Wifi, resuming the internet connection, Firebase does not recognize the active connection, appears as if the user still remained inactive.

This code snippet was inserted into the onCreate method of my MainActivity.

Can anyone tell me why this occurs?

EDIT: Attachments

Error log:

11-14 10:12:55.272 27901-27926/com.example.davi.projetofirebase D/PersistentConnection: pc_0 - Trying to fetch auth token

11-14 10:12:55.276 27901-27926/com.example.davi.projetofirebase D/PersistentConnection: pc_0 - Successfully fetched token, opening connection

11-14 10:12:55.281 27901-27926/com.example.davi.projetofirebase D/Connection: conn_14 - Opening a connection

11-14 10:12:55.293 27901-27926/com.example.davi.projetofirebase D/WebSocket: ws_14 - WebSocket error.
                                                                               bkx: unknown host: s-usc1c-nss-208.firebaseio.com
                                                                                at bku.d(:com.google.android.gms.DynamiteModulesC@11746448:102)
                                                                                at bkv.run(:com.google.android.gms.DynamiteModulesC@11746448:4)
                                                                                at java.lang.Thread.run(Thread.java:760)
                                                                                Caused by: java.net.UnknownHostException: s-usc1c-nss-208.firebaseio.com
                                                                                at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:174)
                                                                                at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
                                                                                at java.net.Socket.connect(Socket.java:586)
                                                                                at com.android.org.conscrypt.OpenSSLSocketImpl.connect(OpenSSLSocketImpl.java:265)
                                                                                at com.android.org.conscrypt.OpenSSLSocketImpl.connect(OpenSSLSocketImpl.java:252)
                                                                                at java.net.Socket.(Socket.java:427)
                                                                                at java.net.Socket.(Socket.java:210)
                                                                                at javax.net.ssl.SSLSocket.(SSLSocket.java:906)
                                                                                at com.android.org.conscrypt.OpenSSLSocketImpl.(OpenSSLSocketImpl.java:192)
                                                                                at com.android.org.conscrypt.OpenSSLSocketFactoryImpl.createSocket(OpenSSLSocketFactoryImpl.java:68)
                                                                                at bku.d(:com.google.android.gms.DynamiteModulesC@11746448:94)
                                                                                at bkv.run(:com.google.android.gms.DynamiteModulesC@11746448:4)
                                                                                at java.lang.Thread.run(Thread.java:760)

11-14 10:12:55.294 27901-27926/com.example.davi.projetofirebase D/WebSocket: ws_14 - closing itself

11-14 10:12:55.295 27901-27926/com.example.davi.projetofirebase D/Connection: conn_14 - Realtime connection failed

11-14 10:12:55.295 27901-27926/com.example.davi.projetofirebase D/Connection: conn_14 - closing realtime connection

11-14 10:12:55.295 27901-27926/com.example.davi.projetofirebase D/PersistentConnection: pc_0 - Got on disconnect due to OTHER

11-14 10:12:55.296 27901-27926/com.example.davi.projetofirebase D/PersistentConnection: pc_0 - Scheduling connection attempt

11-14 10:12:55.297 27901-27926/com.example.davi.projetofirebase D/ConnectionRetryHelper: Scheduling retry in 27403ms

11-14 10:12:55.304 27901-27926/com.example.davi.projetofirebase D/WebSocket: ws_14 - closed

11-14 10:13:02.947 27901-27926/com.example.davi.projetofirebase D/PersistentConnection: pc_0 - Connection interrupted for: connection_idle

11-14 10:13:02.960 27901-27926/com.example.davi.projetofirebase D/ConnectionRetryHelper: Cancelling existing retry attempt

Body:
As Franks says, if you enable debug logging for the client, will be able for sure to see the state of the connection, whether the client is reestablishing its connection or not.

public synchronized void setLogLevel (Logger.Level logLevel)

By default, this is set to INFO. This includes any internal errors (ERROR) and any security debug messages (INFO) that the client receives. Set to DEBUG to turn on the diagnostic logging, and NONE to disable all logging.


问:
Sun Grid Engine: submitted jobs by qsub command
I am using Sun Grid Engine queuing system.

Assume I submitted multiple jobs using a script that looks like:

```<code>#! /bin/bash
for i in 1 2 3 4 5
do
    sh qsub.sh python run.py ${i}
done
</code>```

qsub.sh looks like:

```<code>#! /bin/bash
echo cd `pwd` \; "$@" | qsub
</code>```

Assuming that 5 jobs are running, I want to find out which command each job is executing.

By using qstat -f, I can see which node is running which jobID, but not what specific command each jobID is related to.

So for example, I want to check which jobID=xxxx is running python run.py 3 and so on.

How can I do this?

答: I think you'll see it if you use qstat -j *. See https://linux.die.net/man/1/qstat-ge .

Body:
I am using Sun Grid Engine queuing system.

Assume I submitted multiple jobs using a script that looks like:

#! /bin/bash
for i in 1 2 3 4 5
do
    sh qsub.sh python run.py ${i}
done

qsub.sh looks like:

#! /bin/bash
echo cd `pwd` \; "$@" | qsub

Assuming that 5 jobs are running, I want to find out which command each job is executing.

By using qstat -f, I can see which node is running which jobID, but not what specific command each jobID is related to.

So for example, I want to check which jobID=xxxx is running python run.py 3 and so on.

How can I do this?


问:
Scroll Activity Toolbar off screen scrolling Recyclerview in fragment
I have an activity that hosts 2 fragments, I am currently using a coordinator layout in both fragments with appbarlayout and toolbar layout, I have set it up this way to scroll the toolbar off screen with my recyclerview.  This has been causing my layout issues as I've posted here So I am looking to change my approach.  If I can the activity will host the tool bar/app bar layout in a coordinator layout.

The problem with this approach is that the 2 fragments have recyclerviews with views at the bottom (buttons).  So I'm wondering if it's possible to transfer the scroll from the fragment recyclerview by setting the appbehaviour while maintaining the position of the buttons on the bottom?

Any help on this would be appreciated as I've spent days trying to figure out the alternative approach linked above.

Thanks

答:
Yes it's possible, I'm doing this in an activity with a ViewPager, you just need to add

```<code>app:layout_behavior="@string/appbar_scrolling_view_behavior"
</code>```

in the layout that holds the fragments (in my case the viewpager)

Body:
Yes it's possible, I'm doing this in an activity with a ViewPager, you just need to add

app:layout_behavior="@string/appbar_scrolling_view_behavior"

in the layout that holds the fragments (in my case the viewpager)


问:
Refer to a relative cell within a formula set by apps script
I'm attempting to have GAS set formulas into various cells in my spreadsheet.

This works:

```<code>sheet1.getRange(rowID, 14).setValue("=iferror(vlookup(M2,'sheet2'!C:O,13,false),\"\")");
</code>```

But I need the row in the formula to be relative (not always M2).

I thought this would work:

```<code>sheet1.getRange(rowID, 14).setValue("=iferror(vlookup(M" & rowID & ",'sheet2'!C:O,13,false),\"\")");
</code>```

But it pastes a 0 in the cell.  What's up with that?

答:
Take a look to the following blog about using Spreadsheet relative cell references.

Try the use of the indirect function. It will helps you to automatically generate the next cell in a relative way. Let me know how you go with it.

Body:
I'm attempting to have GAS set formulas into various cells in my spreadsheet.

This works:

sheet1.getRange(rowID, 14).setValue("=iferror(vlookup(M2,'sheet2'!C:O,13,false),\"\")");

But I need the row in the formula to be relative (not always M2).

I thought this would work:

sheet1.getRange(rowID, 14).setValue("=iferror(vlookup(M" & rowID & ",'sheet2'!C:O,13,false),\"\")");

But it pastes a 0 in the cell.  What's up with that?


问:
In C, when would type casting a char to an integer not return a value between 0 and 127?
A common interview question asks to write an algorithm that detects duplicates in a string.
Using a character array of length 128 to keep track of the characters already seen is a good way to solve this problem in linear time.

In C we would type something like

```<code>char seen_chars[128];
unsigned char c;

/* set seen_chars to all zeros, assign c */

seen_chars[ c ] = 1;
</code>```

To mark character c as seen. Of course this relies on

```<code>(int) c
</code>```

returning a value between 0 and 127.

I'm wondering when would this fail? What are the assumptions that make this code work correctly?

答:
I'm wondering when would this fail?

Whenever you have any characters above 127.

Whenever you have a multi-byte encoding like UTF-8.

Body:
A common interview question asks to write an algorithm that detects duplicates in a string.
Using a character array of length 128 to keep track of the characters already seen is a good way to solve this problem in linear time.

In C we would type something like

char seen_chars[128];
unsigned char c;

/* set seen_chars to all zeros, assign c */

seen_chars[ c ] = 1;

To mark character c as seen. Of course this relies on

(int) c

returning a value between 0 and 127.

I'm wondering when would this fail? What are the assumptions that make this code work correctly?


问:
'System.OutOfMemoryException' was thrown when there is still plenty of memory free
This is my code:

```<code>int size = 100000000;
double sizeInMegabytes = (size * 8.0) / 1024.0 / 1024.0; //762 mb
double[] randomNumbers = new double[size];
</code>```

Exception:
Exception of type 'System.OutOfMemoryException' was thrown.

I have 4GB memory on this machine 2.5GB is free when I start this running, there is clearly enough space on the PC to handle the 762mb of 100000000 random numbers. I need to store as many random numbers as possible given available memory. When I go to production there will be 12GB on the box and I want to make use of it.

Does the CLR constrain me to a default max memory to start with? and how do I request more?

Update

I thought breaking this into smaller chunks and incrementally adding to my memory requirements would help if the issue is due to memory fragmentation, but it doesn't I can't get past a total ArrayList size of 256mb regardless of what I do tweaking blockSize.

```<code>private static IRandomGenerator rnd = new MersenneTwister();
private static IDistribution dist = new DiscreteNormalDistribution(1048576);
private static List<double> ndRandomNumbers = new List<double>();

private static void AddNDRandomNumbers(int numberOfRandomNumbers) {
    for (int i = 0; i < numberOfRandomNumbers; i++) {
      ndRandomNumbers.Add(dist.ICDF(rnd.nextUniform()));
  }
}
</code>```

From my main method:

```<code>int blockSize = 1000000;

while (true) {
  try
  {
    AddNDRandomNumbers(blockSize);
  }
  catch (System.OutOfMemoryException ex)
  {
    break;
  }
}
double arrayTotalSizeInMegabytes = (ndRandomNumbers.Count * 8.0) / 1024.0 / 1024.0;
</code>```

答:
Convert your solution to x64. If you still face an issue, grant max length to everything that throws an exception like below :</p>

```<code> var jsSerializer = new JavaScriptSerializer();
 jsSerializer.MaxJsonLength = Int32.MaxValue;
</code>```

Body:
This is my code:

int size = 100000000;
double sizeInMegabytes = (size * 8.0) / 1024.0 / 1024.0; //762 mb
double[] randomNumbers = new double[size];

Exception:
Exception of type 'System.OutOfMemoryException' was thrown.

I have 4GB memory on this machine 2.5GB is free when I start this running, there is clearly enough space on the PC to handle the 762mb of 100000000 random numbers. I need to store as many random numbers as possible given available memory. When I go to production there will be 12GB on the box and I want to make use of it.

Does the CLR constrain me to a default max memory to start with? and how do I request more?

Update

I thought breaking this into smaller chunks and incrementally adding to my memory requirements would help if the issue is due to memory fragmentation, but it doesn't I can't get past a total ArrayList size of 256mb regardless of what I do tweaking blockSize.

private static IRandomGenerator rnd = new MersenneTwister();
private static IDistribution dist = new DiscreteNormalDistribution(1048576);
private static List<double> ndRandomNumbers = new List<double>();

private static void AddNDRandomNumbers(int numberOfRandomNumbers) {
    for (int i = 0; i < numberOfRandomNumbers; i++) {
      ndRandomNumbers.Add(dist.ICDF(rnd.nextUniform()));
  }
}

From my main method:

int blockSize = 1000000;

while (true) {
  try
  {
    AddNDRandomNumbers(blockSize);
  }
  catch (System.OutOfMemoryException ex)
  {
    break;
  }
}
double arrayTotalSizeInMegabytes = (ndRandomNumbers.Count * 8.0) / 1024.0 / 1024.0;

Body:
Convert your solution to x64. If you still face an issue, grant max length to everything that throws an exception like below :

 var jsSerializer = new JavaScriptSerializer();
 jsSerializer.MaxJsonLength = Int32.MaxValue;


问:
Check ctrl button down at JS onclick function
I want to make an check in JavaScript for checking of the CTRL button is clicked. My php:

```<code><tr class="clickable" onclick="gotolink('<?= base_url() . invoices/createinvoice/' . $customer->Id; ?>')">
</code>```

my JS code:

```<code>function gotolink(url) {
        if (HERE THE CHECK FOR THE CTRL BUTTON){
           window.open(url,'_blank');
        }
        else{
            location.href = url;
        }
    }
</code>```

I don't know how to make the check. Could you help me?

答:
function gotolink(url, event) {
  console.log(event.ctrlKey);
  if (event.ctrlKey) {
    window.open(url, '_blank');
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="gotolink('google.com',event)">test</button></code>```

Body:
I want to make an check in JavaScript for checking of the CTRL button is clicked. My php:

<tr class="clickable" onclick="gotolink('<?= base_url() . invoices/createinvoice/' . $customer->Id; ?>')">

my JS code:

function gotolink(url) {
        if (HERE THE CHECK FOR THE CTRL BUTTON){
           window.open(url,'_blank');
        }
        else{
            location.href = url;
        }
    }

I don't know how to make the check. Could you help me?

Body:
function gotolink(url, event) {
  console.log(event.ctrlKey);
  if (event.ctrlKey) {
    window.open(url, '_blank');
  }
}

<button onclick="gotolink('google.com',event)">test</button>


问:
Generically replace Angular 2 route parameter and navigate
I'm building an Angular app in which most of the routes will pertain to a given project and contain a projectId.  In the top navigation area will be a drop-down list of projects.  When the user selects a project from the drop-down, it needs to navigate to the current route but with the projectId replaced with the new value.

This is very similar to Angular navigate to url by replacing an existing parameter, however their accepted answer  used query parameters; this needs to work on required route parameters.  Also the projectId may appear in different positions within the route, so this needs to generically be able to swap out a route parameter by name.

So hypothetically I might have the following routes:

```<code>project/:projectId/details
dashboard/status/:projectId/:year/:month/:day
admin/projects/:projectId
admin/contacts/:projectId/settings
admin/generalSettings
</code>```

Those routes are fictional but demonstrate that the projectId may appear in various positions and will not be preceded by any specific word (so I cannot e.g. look for a segment named "project" then grab the next segment).

Conceptually, I'd like to

Grab from the router the current route and maps of the route params (like paramMap), query params, and matrix params

Modify the values in those maps as needed, namely if the paramMap contains "projectId" then update it.

Hand the route and the maps back to the router to navigate there.

So it seems conceptually simple, but when I look at the Router's routerState and its tree of routes (which I don't quite understand) and the Router.navigate method, I don't see how to achieve this.  I don't have a problem with walking the route tree to re-build the route, so long as 1) it can be done generically without any knowledge of the app's route structure, and 2) the resulting route is identical to the original route (including query and matrix parameters) other than the change to the targeted route parameter (projectId).

答:
What about this:

I have the ActivatedRoute and Router injected into my service/component:

```<code>constructor(
    private route: ActivatedRoute,
    private router: Router) {}
</code>```

Then I made a method for changing the route matrix parameter. Parameters are the name of the matrix parameter to be replaced and the new value. I found no other way of looking up the parameter to replace other than comparing path segments with the parameters of the activated route.

```<code>changeParam(replaceParamName: string, val: any) {
    let replacePathParamIndex;
    let replacePathParamValue;
    this.route.params
        .map((params) => replacePathParamValue = params[replaceParamName])
        .mergeMap(() => this.route.url)
        .map((urlSegment) =>
            urlSegment.map((segment, ndx) => {
                if (segment.path === replacePathParamValue) {
                    replacePathParamIndex = ndx;
                }
                return segment.path;
            })
        )
        .subscribe((pathparts: any[]) => {
            pathparts[replacePathParamIndex] = val;
            this.router.navigate(pathparts);
    });
}
</code>```

Finally navigate to the replaced route by calling:

```<code>changeParam('projectId','newprojectid');
</code>```

Body:
I'm building an Angular app in which most of the routes will pertain to a given project and contain a projectId.  In the top navigation area will be a drop-down list of projects.  When the user selects a project from the drop-down, it needs to navigate to the current route but with the projectId replaced with the new value.

This is very similar to Angular navigate to url by replacing an existing parameter, however their accepted answer  used query parameters; this needs to work on required route parameters.  Also the projectId may appear in different positions within the route, so this needs to generically be able to swap out a route parameter by name.

So hypothetically I might have the following routes:

project/:projectId/details
dashboard/status/:projectId/:year/:month/:day
admin/projects/:projectId
admin/contacts/:projectId/settings
admin/generalSettings

Those routes are fictional but demonstrate that the projectId may appear in various positions and will not be preceded by any specific word (so I cannot e.g. look for a segment named "project" then grab the next segment).

Conceptually, I'd like to

Grab from the router the current route and maps of the route params (like paramMap), query params, and matrix params

Modify the values in those maps as needed, namely if the paramMap contains "projectId" then update it.

Hand the route and the maps back to the router to navigate there.

So it seems conceptually simple, but when I look at the Router's routerState and its tree of routes (which I don't quite understand) and the Router.navigate method, I don't see how to achieve this.  I don't have a problem with walking the route tree to re-build the route, so long as 1) it can be done generically without any knowledge of the app's route structure, and 2) the resulting route is identical to the original route (including query and matrix parameters) other than the change to the targeted route parameter (projectId).

Body:
What about this:

I have the ActivatedRoute and Router injected into my service/component:

constructor(
    private route: ActivatedRoute,
    private router: Router) {}

Then I made a method for changing the route matrix parameter. Parameters are the name of the matrix parameter to be replaced and the new value. I found no other way of looking up the parameter to replace other than comparing path segments with the parameters of the activated route.

changeParam(replaceParamName: string, val: any) {
    let replacePathParamIndex;
    let replacePathParamValue;
    this.route.params
        .map((params) => replacePathParamValue = params[replaceParamName])
        .mergeMap(() => this.route.url)
        .map((urlSegment) =>
            urlSegment.map((segment, ndx) => {
                if (segment.path === replacePathParamValue) {
                    replacePathParamIndex = ndx;
                }
                return segment.path;
            })
        )
        .subscribe((pathparts: any[]) => {
            pathparts[replacePathParamIndex] = val;
            this.router.navigate(pathparts);
    });
}

Finally navigate to the replaced route by calling:

changeParam('projectId','newprojectid');


问:
React-native android Styling textInput
Is there a way to style the textInput in react-native android?
Like change the underlineColor when selected and the cursor color?</p>

答:
There is actually a prop doing this for TextInput :

selectionColor (to change cursor color as well as selection color)

underlineColorAndroid (to change the underline color of textInput in
Android)

```<code><TextInput
    underlineColorAndroid="#FF0000"
    selectionColor="rgba(0,0,0,0.4)"
/>
</code>```

Here is the documentation.

Title: React-native android Styling textInput

Body:
There is actually a prop doing this for TextInput :

selectionColor (to change cursor color as well as selection color)

underlineColorAndroid (to change the underline color of textInput in
Android)

<TextInput
    underlineColorAndroid="#FF0000"
    selectionColor="rgba(0,0,0,0.4)"
/>

Here is the documentation.


问:
All estimators should implement fit and transform
I am new to machine learning. pls help me with this error. below is my code:
I am trying to create a custom class catEncoder() to transform my categorical variables.

```<code>class DFSelector(BaseEstimator, TransformerMixin):
    def __init__(self, Attr):
        self.Attr = Attr
    def fit(self, X, y = None):
        return self
    def transform(self, X):
        print(self.Attr)
        return X[self.Attr].values

class catEncoder(BaseEstimator, TransformerMixin):
    def __init__(self):
        pass
    def fit(self, X, y = None):
        return self
    def transform(self, X):
        #Some-codes to encode variables
        return X.values

numPipeline = [
                ('selector', DFSelector(numAttr)),
                ('imputer', Imputer(strategy = 'median'))
]
catPipeline = [
                ('selector', DFSelector(catAttr)),
                ('encoder', catEncoder())
]
fullPipe = FeatureUnion(transformer_list = [
                                                ('nPipe', numPipeline),
                                                ('cPipe', catPipeline)
])
Xtrain_ready = fullPipe.fit_transform(Xtrain)
</code>```

I get this following error

```<code>TypeError: All estimators should implement fit and transform. '[('selector', DFSelector(Attr=array(['SibSp', 'Parch', 'Fare'], dtype=object))), ('imputer', Imputer(axis=0, copy=True, missing_values='NaN', strategy='median', verbose=0))]' (type <class 'list'>) doesn't
</code>```

答: Looking at the documentation, the issue seems to be that FeatureUnion expects a list of tuples of the form (string, transformer), where transformer is a transformer object. However, in your case it looks like you are passing tuples of the form (string, [multiple transformers]). My suggestion, without having a full view of your ML logic, is to try and split out those list of transformers into individual transformers and pass those to FeatureUnion.

Body:
I am new to machine learning. pls help me with this error. below is my code:
I am trying to create a custom class catEncoder() to transform my categorical variables.

class DFSelector(BaseEstimator, TransformerMixin):
    def __init__(self, Attr):
        self.Attr = Attr
    def fit(self, X, y = None):
        return self
    def transform(self, X):
        print(self.Attr)
        return X[self.Attr].values

class catEncoder(BaseEstimator, TransformerMixin):
    def __init__(self):
        pass
    def fit(self, X, y = None):
        return self
    def transform(self, X):
        #Some-codes to encode variables
        return X.values

numPipeline = [
                ('selector', DFSelector(numAttr)),
                ('imputer', Imputer(strategy = 'median'))
]
catPipeline = [
                ('selector', DFSelector(catAttr)),
                ('encoder', catEncoder())
]
fullPipe = FeatureUnion(transformer_list = [
                                                ('nPipe', numPipeline),
                                                ('cPipe', catPipeline)
])
Xtrain_ready = fullPipe.fit_transform(Xtrain)

I get this following error

TypeError: All estimators should implement fit and transform. '[('selector', DFSelector(Attr=array(['SibSp', 'Parch', 'Fare'], dtype=object))), ('imputer', Imputer(axis=0, copy=True, missing_values='NaN', strategy='median', verbose=0))]' (type <class 'list'>) doesn't


问:
VaryByCustom - Data being shown to wrong users
I'm using Windows Auth in an Intranet setting to Cache information pulled from Active Directory. The purpose of the Cache is to speed up the page, as reading from AD is not particularly fast, and doesn't need to be done every single time. (The data doesn't change all that often)

To do this, i'm setting a custom key in HttpContext.Application.

This is the code located in Global.asax to handle VaryByCustom:

```<code>public override string GetVaryByCustomString(HttpContext context, string arg)
        {
            System.Diagnostics.Debug.Print("GetVaryByCustomString : " + context.Application["BrowsingSession_Key"].ToString());
            if (arg == "BrowsingSession_Key")
            {
                object o = context.Application["BrowsingSession_Key"];
                if (o == null)
                {
                    o = Guid.NewGuid();
                    context.Application["BrowsingSession_Key"] = o;
                }
                return o.ToString();
            }
            return base.GetVaryByCustomString(context, arg);
        }
</code>```

In my BaseController (Inherited by all my controllers):

```<code>protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            //Custom Cache Initiation Variable
            if (HttpContext.Application["BrowsingSession_Key"] == null)
            {
                HttpContext.Application["BrowsingSession_Key"] = Guid.NewGuid();
                System.Diagnostics.Debug.Print("BaseController.Initialize : " + HttpContext.Application["BrowsingSession_Key"].ToString());
            }
        }
</code>```

And finally, in my method inside a controller:

```<code>[OutputCache(Duration = 300, VaryByCustom = "BrowsingSession_Key", Location = OutputCacheLocation.Server)]
        public ActionResult Index(HomeViewModel model)
//...
        return View("index", model);
    }
</code>```

The issue is simple - the first person to view the page has their info cached, and the Guid for BrowsingSession_Key is set.
However, the next user visits the page within the 5 minute window, and reaches the last users cached content.
As you can see - i'm attempting to give each user a unique BrowsingSession_Key, so that they get their own cached content.

I'm using VaryByCustom so that i can quickly invalidate the cache by assigning a new BrowsingSession_Key (Guid) to that user - and pull a non-cached copy of a page for them.

Can you see what's going wrong here?
From my testing - it seems Initialize is often called, as is GetVaryByCustomString, in the places you'd expect them to be called. However, i can't run debug as multiple users, so i can't see why they're getting the same Guid and the same outputcache.

答:
As it turns out, Application-level variables are not a good place to be storing per-user information, even temporarily.

In the end, i swapped over to using a cookie with a stored GUID, and invalidate the cookie (reset the GUID, or delete & Re-create). This meant multiple users were then able to use the site, with GetVaryByCustomString instead handling information stored in the Cookie.

This works for me - but i need to take into account the possibility of users swapping cookies, so will look further into encryption options.
For now - the answer is - Don't use Application-level variables this way, they're not suited to such tasks.

Body:
I'm using Windows Auth in an Intranet setting to Cache information pulled from Active Directory. The purpose of the Cache is to speed up the page, as reading from AD is not particularly fast, and doesn't need to be done every single time. (The data doesn't change all that often)

To do this, i'm setting a custom key in HttpContext.Application.

This is the code located in Global.asax to handle VaryByCustom:

public override string GetVaryByCustomString(HttpContext context, string arg)
        {
            System.Diagnostics.Debug.Print("GetVaryByCustomString : " + context.Application["BrowsingSession_Key"].ToString());
            if (arg == "BrowsingSession_Key")
            {
                object o = context.Application["BrowsingSession_Key"];
                if (o == null)
                {
                    o = Guid.NewGuid();
                    context.Application["BrowsingSession_Key"] = o;
                }
                return o.ToString();
            }
            return base.GetVaryByCustomString(context, arg);
        }

In my BaseController (Inherited by all my controllers):

protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            //Custom Cache Initiation Variable
            if (HttpContext.Application["BrowsingSession_Key"] == null)
            {
                HttpContext.Application["BrowsingSession_Key"] = Guid.NewGuid();
                System.Diagnostics.Debug.Print("BaseController.Initialize : " + HttpContext.Application["BrowsingSession_Key"].ToString());
            }
        }

And finally, in my method inside a controller:

[OutputCache(Duration = 300, VaryByCustom = "BrowsingSession_Key", Location = OutputCacheLocation.Server)]
        public ActionResult Index(HomeViewModel model)
//...
        return View("index", model);
    }

The issue is simple - the first person to view the page has their info cached, and the Guid for BrowsingSession_Key is set.
However, the next user visits the page within the 5 minute window, and reaches the last users cached content.
As you can see - i'm attempting to give each user a unique BrowsingSession_Key, so that they get their own cached content.

I'm using VaryByCustom so that i can quickly invalidate the cache by assigning a new BrowsingSession_Key (Guid) to that user - and pull a non-cached copy of a page for them.

Can you see what's going wrong here?
From my testing - it seems Initialize is often called, as is GetVaryByCustomString, in the places you'd expect them to be called. However, i can't run debug as multiple users, so i can't see why they're getting the same Guid and the same outputcache.


问:
How to query data from MYSQLdb with Python2.7 if I want query "date-1"?
So, I need to query data from MYSQLdb in every day, that's why I prefer to use a query which one I can query the actual date - 1 data. For example if I run my script today at Nov 13, I need the all information from Nov 12 (from the ACTUAL_DATE - on the picture).

I have got a column in the MYSQLdb, which looks like this :

Is this any query, is this any chance to query data with this "DATE - 1" logic? So I have to analyse the last 6 character in the ACTUAL_DATE columns, because the last 2 show the day, the last 4 show the months (year is not important!)

This MYSQLdb refresh in every day, that's why I need to find a way which one I can query the REAL DATE - 1 day from this table.

I know the code has to looking like this :

```<code>connection = MySQLdb.connect(host='localhost',
        user='user1',
        passwd='',
        db='database1',
        use_unicode=True,
        charset="utf8")
cursor = connection.cursor()
query = """ select #I NEED SOMETHING HERE..
    from OSSZES
    into outfile '/tmp/test.csv'
    fields terminated by ';'
    enclosed by '"'
    lines terminated by '\n';
    """
cursor.execute(query)
connection.commit()
cursor.close()
</code>```

But how can I write this select query if it is exist in mysqldb?

答:
Maybe you can use a combination of 'pandas' and 'datetime' modules:</p>

```<code>import datetime as dt
import pandas as pd

df = pd.read_sql_table('OSSZES',connection)
df['ACTUAL_DATE'] = pd.to_datetime(df['ACTUAL_DATE'])
mask = df['ACTUAL_DATE'] < dt.date.today()
df_new = df.loc[mask]
df_new.to_csv('/tmp/test.csv')
</code>```

Body:
So, I need to query data from MYSQLdb in every day, that's why I prefer to use a query which one I can query the actual date - 1 data. For example if I run my script today at Nov 13, I need the all information from Nov 12 (from the ACTUAL_DATE - on the picture).

I have got a column in the MYSQLdb, which looks like this :

Is this any query, is this any chance to query data with this "DATE - 1" logic? So I have to analyse the last 6 character in the ACTUAL_DATE columns, because the last 2 show the day, the last 4 show the months (year is not important!)

This MYSQLdb refresh in every day, that's why I need to find a way which one I can query the REAL DATE - 1 day from this table.

I know the code has to looking like this :

connection = MySQLdb.connect(host='localhost',
        user='user1',
        passwd='',
        db='database1',
        use_unicode=True,
        charset="utf8")
cursor = connection.cursor()
query = """ select #I NEED SOMETHING HERE..
    from OSSZES
    into outfile '/tmp/test.csv'
    fields terminated by ';'
    enclosed by '"'
    lines terminated by '\n';
    """
cursor.execute(query)
connection.commit()
cursor.close()

But how can I write this select query if it is exist in mysqldb?

Body:
Maybe you can use a combination of 'pandas' and 'datetime' modules:

import datetime as dt
import pandas as pd

df = pd.read_sql_table('OSSZES',connection)
df['ACTUAL_DATE'] = pd.to_datetime(df['ACTUAL_DATE'])
mask = df['ACTUAL_DATE'] < dt.date.today()
df_new = df.loc[mask]
df_new.to_csv('/tmp/test.csv')


问:
Python unittest TestCase with inheritance
Currently I have many similar unittest TestCases. Each TestCase contains both data (input values + expected output values) and logic (call the SUT and compare the actual output with the expected output).

I would like to separate the data from the logic. Thus I want a base class that only contains the logic and a derived class that contains only the data. I came up with this so far:

```<code>import unittest

class MyClass():
    def __init__(self, input):
        self.input = input
    def get_result(self):
        return self.input * 2

class TestBase(unittest.TestCase):
    def check(self, input, expected_output):
        obj = self.class_under_test(input)
        actual_output = obj.get_result()
        self.assertEqual(actual_output, expected_output)

    def test_get_result(self):
        for value in self.values:
            self.check(value[0], value[1])

class TestMyClass(TestBase):
    def __init__(self, methodName='runTest'):
        unittest.TestCase.__init__(self, methodName)
        self.class_under_test = MyClass
        self.values = [(1, 2), (3, 6)]

unittest.main(exit = False)
</code>```

But this fails with the following error:

```<code>AttributeError: 'TestBase' object has no attribute 'values'
</code>```

Two questions:

Is my 'design' any good?

What's still needed to get it working?

答:
Python's unittest.main() executes all tests from all test classes in the current namespace.

One way to not run tests directly in your base class is to move it to a different module (e.g. move TestBase to testbase.py):

In the file which calls unittest.main(), be sure to not import that class into your namespace (don't use from testbase import * or similar):

```<code>import testbase

class TestMyClass1(testbase.TestBase):
    values = ((1, 2), (3, 4))
    class_under_test = MyClass1
</code>```

Body:
Currently I have many similar unittest TestCases. Each TestCase contains both data (input values + expected output values) and logic (call the SUT and compare the actual output with the expected output).

I would like to separate the data from the logic. Thus I want a base class that only contains the logic and a derived class that contains only the data. I came up with this so far:

import unittest

class MyClass():
    def __init__(self, input):
        self.input = input
    def get_result(self):
        return self.input * 2

class TestBase(unittest.TestCase):
    def check(self, input, expected_output):
        obj = self.class_under_test(input)
        actual_output = obj.get_result()
        self.assertEqual(actual_output, expected_output)

    def test_get_result(self):
        for value in self.values:
            self.check(value[0], value[1])

class TestMyClass(TestBase):
    def __init__(self, methodName='runTest'):
        unittest.TestCase.__init__(self, methodName)
        self.class_under_test = MyClass
        self.values = [(1, 2), (3, 6)]

unittest.main(exit = False)

But this fails with the following error:

AttributeError: 'TestBase' object has no attribute 'values'

Two questions:

Is my 'design' any good?

What's still needed to get it working?

Body:
Python's unittest.main() executes all tests from all test classes in the current namespace.

One way to not run tests directly in your base class is to move it to a different module (e.g. move TestBase to testbase.py):

In the file which calls unittest.main(), be sure to not import that class into your namespace (don't use from testbase import * or similar):

import testbase

class TestMyClass1(testbase.TestBase):
    values = ((1, 2), (3, 4))
    class_under_test = MyClass1


问:
How to get resource from JarPackageFragmentRoot?
For example for junit.jar I use getResource() and it returns null.</p>

答:
IResources only exist for parts of the file system that are in the workspace.  Since junit.jar is outside the workspace, there is no corresponding 'IResource' for it.  Eclipse's workspace handling is an abstraction over the underlying filesystem.  Only files inside the workspace are included.

However, there are some possibilities:

You can call the getJar() method.  It does not return an IResource, but it may be suitable for your purposes.

You can import the junit.jar file into your workspace and then call getResource() on it.

Neither of which are exactly what you want, most likely, but you need to realize that your stated goal is not what the Eclipse resource abstraction provides.


问:
Create Temporal Table in Azure DB
I am using SSMS 17 and are trying to create a temporal table in SQL Azure but for some reason the option Tables -> New -> Temporal Table is disabled.
I have created a basic Azure database which currently has no tables.
Does anybody know how to enable this feature or what I may be doing wrong?</p>

答:
You can use below screen shot also
just right click on table and follow below screen shot

Title: Create Temporal Table in Azure DB


问:
Call my own cellForRowAtIndexPath for PSMultiValueSpecifier cell
Using InAppSettingsKit (2.8 branch), how should I implement my own cellForRowAtIndexPath for that kind of setting's type (PSMultiValueSpecifier) ?

```<code>    <dict>
        <key>DefaultValue</key>
        <integer>0</integer>
        <key>Key</key>
        <string>theme</string>
        <key>Title</key>
        <string>Theme</string>
        <key>Titles</key>
        <array>
            <string>Light</string>
            <string>Dark</string>
        </array>
        <key>Type</key>
        <string>PSMultiValueSpecifier</string>
        <key>Values</key>
        <array>
            <integer>0</integer>
            <integer>1</integer>
        </array>
    </dict>
</code>```

I need to reconfigure all the cell to apply the current theme but I can't find a way to subclass (or provide the name of a subclass) to the IASKSpecifierValuesViewController  used to display the different choices on setting of type "PSMultiValueSpecifier"

Thanks!

答: The best way to accomplish this is by subclassing IASKSpecifierValuesViewController and using your subclass as a custom view controller. Of course you have to assign the currentSpecifier, settingsReader and settingsStore when the user selects the custom child pane by implementing the delegate method settingsViewController:tableView:didSelectCustomViewSpecifier:. Take a look at IASKAppSettingsViewController.m:711-718 to see what needs to be done.

Body:
Using InAppSettingsKit (2.8 branch), how should I implement my own cellForRowAtIndexPath for that kind of setting's type (PSMultiValueSpecifier) ?

    <dict>
        <key>DefaultValue</key>
        <integer>0</integer>
        <key>Key</key>
        <string>theme</string>
        <key>Title</key>
        <string>Theme</string>
        <key>Titles</key>
        <array>
            <string>Light</string>
            <string>Dark</string>
        </array>
        <key>Type</key>
        <string>PSMultiValueSpecifier</string>
        <key>Values</key>
        <array>
            <integer>0</integer>
            <integer>1</integer>
        </array>
    </dict>

I need to reconfigure all the cell to apply the current theme but I can't find a way to subclass (or provide the name of a subclass) to the IASKSpecifierValuesViewController  used to display the different choices on setting of type "PSMultiValueSpecifier"

Thanks!