问:
WCF - maxReceivedMessageSize
I have a problem setting maxReceivedMessageSize for larger files.

I'm getting:

The maximum message size quota for
  incoming messages (65536) has been
  exceeded. To increase the quota, use
  the MaxReceivedMessageSize property on
  the appropriate binding element.

Here is my server side configuration:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="HTTPBaseAddress" value="http://localhost:8080/WelcomeMessage/"/>
    <add key="HTTPFileTransferAddress" value="http://localhost:8080/FileTransfer/"/>
  </appSettings>
  <system.web>
    <compilation debug="false" />
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <system.serviceModel>
    <services>
      <service name="FS.Services.MessageService" behaviorConfiguration="MyServiceTypeBehaviors">
        <endpoint contract="FS.Interfaces.IMessageService" address="" binding="wsHttpBinding"/>
    </service>
      <service name="FS.Services.FileTransferService" behaviorConfiguration="MyServiceTypeBehaviors">
        <endpoint contract="FS.Interfaces.IFileTransferService" address="" binding="basicHttpBinding" bindingConfiguration="streamedHttpBinding"/>
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="streamedHttpBinding"
                 messageEncoding="Text"
                 transferMode="Streamed"
                 maxReceivedMessageSize="400000000"/>
       </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceTypeBehaviors">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
</code>```

Here is my client side configuration:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <client>
      <endpoint address="" binding="wsHttpBinding" contract="FS.Services.IMessageService"
        name="FS.Services.MessageService" />
      <endpoint address="" binding="basicHttpBinding" bindingConfiguration="streamedHttpBinding"
        contract="FS.Services.IFileTransferService" name="FS.Services.FileTransferService" />
    </client>
    <bindings>
      <basicHttpBinding>
        <binding name="streamedHttpBinding" maxReceivedMessageSize="400000000"
          messageEncoding="Text" transferMode="Streamed"/>
      </basicHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>
</code>```

This is how i connect the client:

```<code>BasicHttpBinding binding2 = new BasicHttpBinding("streamedHttpBinding");
EndpointAddress endpoint2 = new EndpointAddress("http://localhost:8080/FileTransfer");
ChannelFactory<IFileTransferService> channelFactory2 = new ChannelFactory<IFileTransferService>(binding2, endpoint2);
IFileTransferService proxy2 = channelFactory2.CreateChannel();
((IClientChannel)proxy2).Open();
</code>```

Also I would like to transfer any type of files up to 500mb using stream messages.
Can someone please provide me with configuration (or solution) that would support that?

Thanx!

答:
Your client side config doesn't have any <client> tag that would reference the server, and to which you could apply the binding configuration with your increased message size......

On your server side, you need to define the service and its endpoints:

```<code><services>
   <service name="YourNamespace.YourServiceClass">
       <endpoint name="endpoint1"
                 address="http://server:8888/YourService.svc"
                 binding="basicHttpBinding"
                 bindingConfiguration="lageMessageTransfer"
                 contract="IYourServiceContract" />
   </service>
</services>
</code>```

On your client side, you need to define your client endpoint connecting to one of the service endpoints

```<code><client>
   <endpoint name="Default"
             address="http://server:8888/YourService.svc"
             binding="basicHttpBinding"
             bindingConfiguration="lageMessageTransfer"
             contract="IYourServiceContract" />
</client>
</code>```

Update: ok, now I see your config fine - but where is your client endpoint connecting to?? You don't have any address= defined!

```<code> <client>
    <endpoint name="FS.Services.FileTransferService"
              address=""
              binding="basicHttpBinding"
              bindingConfiguration="streamedHttpBinding"
              contract="FS.Services.IFileTransferService" />
 </client>
</code>```

Title: WCF - maxReceivedMessageSize

Body:
I have a problem setting maxReceivedMessageSize for larger files.

I'm getting:

The maximum message size quota for
  incoming messages (65536) has been
  exceeded. To increase the quota, use
  the MaxReceivedMessageSize property on
  the appropriate binding element.

Here is my server side configuration:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="HTTPBaseAddress" value="http://localhost:8080/WelcomeMessage/"/>
    <add key="HTTPFileTransferAddress" value="http://localhost:8080/FileTransfer/"/>
  </appSettings>
  <system.web>
    <compilation debug="false" />
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  <system.serviceModel>
    <services>
      <service name="FS.Services.MessageService" behaviorConfiguration="MyServiceTypeBehaviors">
        <endpoint contract="FS.Interfaces.IMessageService" address="" binding="wsHttpBinding"/>
    </service>
      <service name="FS.Services.FileTransferService" behaviorConfiguration="MyServiceTypeBehaviors">
        <endpoint contract="FS.Interfaces.IFileTransferService" address="" binding="basicHttpBinding" bindingConfiguration="streamedHttpBinding"/>
      </service>
    </services>
    <bindings>
      <basicHttpBinding>
        <binding name="streamedHttpBinding"
                 messageEncoding="Text"
                 transferMode="Streamed"
                 maxReceivedMessageSize="400000000"/>
       </basicHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceTypeBehaviors">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Here is my client side configuration:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <client>
      <endpoint address="" binding="wsHttpBinding" contract="FS.Services.IMessageService"
        name="FS.Services.MessageService" />
      <endpoint address="" binding="basicHttpBinding" bindingConfiguration="streamedHttpBinding"
        contract="FS.Services.IFileTransferService" name="FS.Services.FileTransferService" />
    </client>
    <bindings>
      <basicHttpBinding>
        <binding name="streamedHttpBinding" maxReceivedMessageSize="400000000"
          messageEncoding="Text" transferMode="Streamed"/>
      </basicHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>

This is how i connect the client:

BasicHttpBinding binding2 = new BasicHttpBinding("streamedHttpBinding");
EndpointAddress endpoint2 = new EndpointAddress("http://localhost:8080/FileTransfer");
ChannelFactory<IFileTransferService> channelFactory2 = new ChannelFactory<IFileTransferService>(binding2, endpoint2);
IFileTransferService proxy2 = channelFactory2.CreateChannel();
((IClientChannel)proxy2).Open();

Also I would like to transfer any type of files up to 500mb using stream messages.
Can someone please provide me with configuration (or solution) that would support that?

Thanx!

Body:
Your client side config doesn't have any <client> tag that would reference the server, and to which you could apply the binding configuration with your increased message size......

On your server side, you need to define the service and its endpoints:

<services>
   <service name="YourNamespace.YourServiceClass">
       <endpoint name="endpoint1"
                 address="http://server:8888/YourService.svc"
                 binding="basicHttpBinding"
                 bindingConfiguration="lageMessageTransfer"
                 contract="IYourServiceContract" />
   </service>
</services>

On your client side, you need to define your client endpoint connecting to one of the service endpoints

<client>
   <endpoint name="Default"
             address="http://server:8888/YourService.svc"
             binding="basicHttpBinding"
             bindingConfiguration="lageMessageTransfer"
             contract="IYourServiceContract" />
</client>

Update: ok, now I see your config fine - but where is your client endpoint connecting to?? You don't have any address= defined!

 <client>
    <endpoint name="FS.Services.FileTransferService"
              address=""
              binding="basicHttpBinding"
              bindingConfiguration="streamedHttpBinding"
              contract="FS.Services.IFileTransferService" />
 </client>


来源: stackexchange

问:
glMapBufferRange freezing OpenGL driver
After generating a set of data using a compute shader and storing it in a Shader Storage buffer, I am attempting to read from that buffer to print out the data using the code:

```<code>#define INDEX_AT(x,y,z,i)   (xyzToId(Vec3i((x), (y), (z)),\
                                     Vec3i(NUM_RAYS_X,\
                                           NUM_RAYS_Y,\
                                           POINTS_ON_RAY))\
                             * 3 + (i))
PRINT_GL_ERRORS();
glBindBuffer(GL_SHADER_STORAGE_BUFFER, dPositionBuffer);
float* data_ptr = NULL;
for (int ray_i = 0; ray_i < POINTS_ON_RAY; ray_i++)
{
    for (int y = 0; y < NUM_RAYS_Y; y++)
    {
        int x = 0;
        data_ptr = NULL;
        data_ptr = (float*)glMapBufferRange(
            GL_SHADER_STORAGE_BUFFER,
            INDEX_AT(x, y, ray_i, 0) * sizeof(float),
            3 * (NUM_RAYS_X) * sizeof(float),
            GL_MAP_READ_BIT);
        if (data_ptr == NULL)
        {
            PRINT_GL_ERRORS();
            return false;
        }
        else
        {
            for (int x = 0; x < NUM_RAYS_X; x++)
            {
                std::cout << "("
                    << data_ptr[x * 3 + 0] << ","
                    << data_ptr[x * 3 + 1] << ","
                    << data_ptr[x * 3 + 2] << ") , ";
            }
        }

        glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
        PRINT_GL_ERRORS();
        std::cout << std::endl;
    }

    std::cout << "\n" << std::endl;
}
</code>```

where the function xyzToId converts three dimensional coordinates into a one-dimensional index.

When I attempt to run this, however, the program crashes at the call to glMapBufferRange, giving the error message:

```<code>The NVIDIA OpenGL driver lost connection with the display driver due to exceeding the Windows Time-Out limit and is unable to continue.
The application must close.

Error code: 7
Would you like to visit
http://nvidia.custhelp.com/cgi-bin/nvidia.cfg/php/enduser/std_adp.php?p_faqid=3007
for help?
</code>```

The buffer that I am mapping is not very large at all, only 768 floats, and previous calls to glMapBuffer on a different shader storage buffer (of only two floats) completed with no problems. I can't seem to find any information relevant to this error online, and everything that I have read about the speed of glMapBufferRange indicates that a buffer of this size should only take on the order of tens of milliseconds to map, not the two second timeout that the program is crashing on.

Am I missing something about how glMapBufferRange should be used?

答:
It was an unrelated error. Today I learned that OpenGL sometimes buffers commands, and several actions (like mapping a buffer) forces it to finish all the commands in its queue. In this case, it was the action of actually dispatching the compute shader itself.

Today I also learned that indexing a shader storage buffer out of bounds will cause the OpenGL driver to freeze up just like it would if it was taking to long to complete.

All in all, this was largely a case of errors masquerading as different errors and popping up in the wrong spot.

ContentLicense: CC BY-SA 3.0

Title: glMapBufferRange freezing OpenGL driver

Body:
After generating a set of data using a compute shader and storing it in a Shader Storage buffer, I am attempting to read from that buffer to print out the data using the code:

#define INDEX_AT(x,y,z,i)   (xyzToId(Vec3i((x), (y), (z)),\
                                     Vec3i(NUM_RAYS_X,\
                                           NUM_RAYS_Y,\
                                           POINTS_ON_RAY))\
                             * 3 + (i))
PRINT_GL_ERRORS();
glBindBuffer(GL_SHADER_STORAGE_BUFFER, dPositionBuffer);
float* data_ptr = NULL;
for (int ray_i = 0; ray_i < POINTS_ON_RAY; ray_i++)
{
    for (int y = 0; y < NUM_RAYS_Y; y++)
    {
        int x = 0;
        data_ptr = NULL;
        data_ptr = (float*)glMapBufferRange(
            GL_SHADER_STORAGE_BUFFER,
            INDEX_AT(x, y, ray_i, 0) * sizeof(float),
            3 * (NUM_RAYS_X) * sizeof(float),
            GL_MAP_READ_BIT);
        if (data_ptr == NULL)
        {
            PRINT_GL_ERRORS();
            return false;
        }
        else
        {
            for (int x = 0; x < NUM_RAYS_X; x++)
            {
                std::cout << "("
                    << data_ptr[x * 3 + 0] << ","
                    << data_ptr[x * 3 + 1] << ","
                    << data_ptr[x * 3 + 2] << ") , ";
            }
        }

        glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
        PRINT_GL_ERRORS();
        std::cout << std::endl;
    }

    std::cout << "\n" << std::endl;
}

where the function xyzToId converts three dimensional coordinates into a one-dimensional index.

When I attempt to run this, however, the program crashes at the call to glMapBufferRange, giving the error message:

The NVIDIA OpenGL driver lost connection with the display driver due to exceeding the Windows Time-Out limit and is unable to continue.
The application must close.

Error code: 7
Would you like to visit
http://nvidia.custhelp.com/cgi-bin/nvidia.cfg/php/enduser/std_adp.php?p_faqid=3007
for help?

The buffer that I am mapping is not very large at all, only 768 floats, and previous calls to glMapBuffer on a different shader storage buffer (of only two floats) completed with no problems. I can't seem to find any information relevant to this error online, and everything that I have read about the speed of glMapBufferRange indicates that a buffer of this size should only take on the order of tens of milliseconds to map, not the two second timeout that the program is crashing on.

Am I missing something about how glMapBufferRange should be used?


问:
How to Disable Specific Dates in MaterializeCSS datepicker
trying to disable some specific dates in materializeCSS datepicker, but not getting any way to implement this feature.</p>

答:
This is an example of how to receive a JSON of allowed dates and show them in the timepicker.</p>

```<code>var $input = $('.datepicker').pickadate()
var picker = $input.pickadate('picker');

picker.stop();
picker.start();

$.get("/dates",
    { id: this.value },
    function(data) {

        let value=[];
        $.each(data, function(key, element) {
            let fecha=new Date(element.date);
            value.push([fecha.getFullYear(),
                fecha.getMonth(),
                fecha.getDate()+1]);
        });
        picker.set('disable', value);
        picker.set('disable', 'flip');
        picker.open(false);

    });
</code>```

Body:
This is an example of how to receive a JSON of allowed dates and show them in the timepicker.

var $input = $('.datepicker').pickadate()
var picker = $input.pickadate('picker');

picker.stop();
picker.start();

$.get("/dates",
    { id: this.value },
    function(data) {

        let value=[];
        $.each(data, function(key, element) {
            let fecha=new Date(element.date);
            value.push([fecha.getFullYear(),
                fecha.getMonth(),
                fecha.getDate()+1]);
        });
        picker.set('disable', value);
        picker.set('disable', 'flip');
        picker.open(false);

    });


问:
Randomly selecting from Pandas groups with equal probability -- unexpected behavior
I have 12 unique groups that I am trying to randomly sample from, each with a different number of observations. I want to randomly sample from the entire population (dataframe) with each group having the same probability of being selected from. The simplest example of this would be a dataframe with 2 groups.

```<code>    groups  probability
0       a       0.25
1       a       0.25
2       b       0.5
</code>```

using np.random.choice(df['groups'], p=df['probability'], size=100) Each iteration will now have a 50% chance of selecting group a and a 50% chance of selecting group b

To come up with the probabilities I used the formula:

```<code>(1. / num_groups) / size_of_groups
</code>```

or in Python:

```<code>num_groups = len(df['groups'].unique())  # 2
size_of_groups = df.groupby('label').size()  # {a: 2, b: 1}
(1. / num_groups) / size_of_groups
</code>```

Which returns

```<code>    groups
a    0.25
b    0.50
</code>```

This works great until I get past 10 unique groups, after which I start getting weird distributions. Here is a small example:

```<code>np.random.seed(1234)

group_size = 12
groups = np.arange(group_size)

probs = np.random.uniform(size=group_size)
probs = probs / probs.sum()

g = np.random.choice(groups, size=10000, p=probs)
df = pd.DataFrame({'groups': g})

prob_map = ((1. / len(df['groups'].unique())) / df.groupby('groups').size()).to_dict()

df['probability'] = df['groups'].map(prob_map)

plt.hist(np.random.choice(df['groups'], p=df['probability'], size=10000, replace=True))
plt.xticks(np.arange(group_size))
plt.show()
</code>```

I would expect a fairly uniform distribution with a large enough sample size, but I am getting these wings when the number of groups is 11+. If I change the group_size variable to 10 or lower, I do get the desired uniform distribution.

I can't tell if the problem is with my formula for calculating the probabilities, or possibly a floating point precision problem? Anyone know a better way to accomplish this, or a fix for this example?

Thanks in advance!

答:
There is no problem about your calculations. Your resulting array is:

```<code>arr = np.random.choice(df['groups'], p=df['probability'], size=10000, replace=True)
</code>```

If you check the value counts:

```<code>pd.Series(arr).value_counts().sort_index()
Out:
0     855
1     800
2     856
3     825
4     847
5     835
6     790
7     847
8     834
9     850
10    806
11    855
dtype: int64
</code>```

It is pretty close to a uniform distribution. The problem is with the default number of bins (10) of the histogram. Instead, try this:

```<code>bins = np.linspace(-0.5, 10.5, num=12)
pd.Series(arr).plot.hist(bins=bins)
</code>```

Body:
I have 12 unique groups that I am trying to randomly sample from, each with a different number of observations. I want to randomly sample from the entire population (dataframe) with each group having the same probability of being selected from. The simplest example of this would be a dataframe with 2 groups.

    groups  probability
0       a       0.25
1       a       0.25
2       b       0.5

using np.random.choice(df['groups'], p=df['probability'], size=100) Each iteration will now have a 50% chance of selecting group a and a 50% chance of selecting group b

To come up with the probabilities I used the formula:

(1. / num_groups) / size_of_groups

or in Python:

num_groups = len(df['groups'].unique())  # 2
size_of_groups = df.groupby('label').size()  # {a: 2, b: 1}
(1. / num_groups) / size_of_groups

Which returns

    groups
a    0.25
b    0.50

This works great until I get past 10 unique groups, after which I start getting weird distributions. Here is a small example:

np.random.seed(1234)

group_size = 12
groups = np.arange(group_size)

probs = np.random.uniform(size=group_size)
probs = probs / probs.sum()

g = np.random.choice(groups, size=10000, p=probs)
df = pd.DataFrame({'groups': g})

prob_map = ((1. / len(df['groups'].unique())) / df.groupby('groups').size()).to_dict()

df['probability'] = df['groups'].map(prob_map)

plt.hist(np.random.choice(df['groups'], p=df['probability'], size=10000, replace=True))
plt.xticks(np.arange(group_size))
plt.show()

I would expect a fairly uniform distribution with a large enough sample size, but I am getting these wings when the number of groups is 11+. If I change the group_size variable to 10 or lower, I do get the desired uniform distribution.

I can't tell if the problem is with my formula for calculating the probabilities, or possibly a floating point precision problem? Anyone know a better way to accomplish this, or a fix for this example?

Thanks in advance!

Body:
There is no problem about your calculations. Your resulting array is:

arr = np.random.choice(df['groups'], p=df['probability'], size=10000, replace=True)

If you check the value counts:

pd.Series(arr).value_counts().sort_index()
Out:
0     855
1     800
2     856
3     825
4     847
5     835
6     790
7     847
8     834
9     850
10    806
11    855
dtype: int64

It is pretty close to a uniform distribution. The problem is with the default number of bins (10) of the histogram. Instead, try this:

bins = np.linspace(-0.5, 10.5, num=12)
pd.Series(arr).plot.hist(bins=bins)


问:
Workaround for lack of look-behind for Javascript regex
I have a working Python regex statement as:

```<code>regex = re.compile(r"(?<=(==))(.*)(?=(==))")
myList = regex.findall(contents)
</code>```

For context, the input string may resemble (for example):

```<code>== Test User ==
Comment here

== Test User 2 ==
Comment here
</code>```

And I wish to extract the username, and the related comment on the line below.

I want to use this regex in my Javascript program, however Javascript lacks look-behind functionality.

Is there a suitable workaround for this?

答:
You do not need any lookbehind here, even in Python you could get rid of it and use the following expression with re.findall (just remove / and /gm and compile with re.M flag):

```<code>/^==\s*(.*?)\s*==\s*(.*(?:\r?\n(?!\r?\n).*)*)/gm
</code>```

See the regex demo.

Details:

^ - start of string

==\s* - two = symbols and then 0+ whitespaces

(.*?) - Group 1 capturing any 0+ chars other than line break chars as few as possible up to the first occurrence of the subsequent subpatterns

\s*==\s* - two =s enclosed with 0+ whitespaces

(.*(?:\r?\n(?!\r?\n).*)*)  - Group 2 capturing

.* - the rest of the line

(?:\r?\n(?!\r?\n).*)*  - zero or more sequences of

\r?\n(?!\r?\n) - a CRLF or LF (line break) not followed with LF or CRLF (another line break)

.*  - any 0+ chars other than line break chars (the whole line).

JS demo:

var s = `== Test User ==
Comment here, one line only

== Test User 2 ==
Comment here
with line 2`;
var rx = /^==\s*(.*?)\s*==\s*(.*(?:\r?\n(?!\r?\n).*)*)/gm;
var results = [], m;
while(m=rx.exec(s)) {
  console.log("--- New match found ---");
  console.log("User:", m[1]);
  console.log("Comment:", m[2]);
}```

Body:
I have a working Python regex statement as:

regex = re.compile(r"(?<=(==))(.*)(?=(==))")
myList = regex.findall(contents)

For context, the input string may resemble (for example):

== Test User ==
Comment here

== Test User 2 ==
Comment here

And I wish to extract the username, and the related comment on the line below.

I want to use this regex in my Javascript program, however Javascript lacks look-behind functionality.

Is there a suitable workaround for this?

Body:
You do not need any lookbehind here, even in Python you could get rid of it and use the following expression with re.findall (just remove / and /gm and compile with re.M flag):

/^==\s*(.*?)\s*==\s*(.*(?:\r?\n(?!\r?\n).*)*)/gm

See the regex demo.

Details:

^ - start of string

==\s* - two = symbols and then 0+ whitespaces

(.*?) - Group 1 capturing any 0+ chars other than line break chars as few as possible up to the first occurrence of the subsequent subpatterns

\s*==\s* - two =s enclosed with 0+ whitespaces

(.*(?:\r?\n(?!\r?\n).*)*)  - Group 2 capturing

.* - the rest of the line

(?:\r?\n(?!\r?\n).*)*  - zero or more sequences of

\r?\n(?!\r?\n) - a CRLF or LF (line break) not followed with LF or CRLF (another line break)

.*  - any 0+ chars other than line break chars (the whole line).

JS demo:

var s = `== Test User ==
Comment here, one line only

== Test User 2 ==
Comment here
with line 2`;
var rx = /^==\s*(.*?)\s*==\s*(.*(?:\r?\n(?!\r?\n).*)*)/gm;
var results = [], m;
while(m=rx.exec(s)) {
  console.log("--- New match found ---");
  console.log("User:", m[1]);
  console.log("Comment:", m[2]);
}


问:
Removing instances from HAProxy during AWS CodeDeploy
Our application requires the use of HAProxy to load balance and route traffic (one per AZ), ALBs and ELBs are not configurable enough for our purposes. When deploying new code via AWS CodeDeploy, we would like the instances being patched to be placed into Maintenance Mode (removed from load balancing, connections drained). We have modified the default CodeDeploy lifecycle bash scripts to remove the instances from their respective HAProxy instances by sending an SSM Run Command to HAProxy from the instances in question. Currently this modification doesn't work, and the reason for failure is unknown. The script works when executed manually step by step (at least to the current point of failure). The part that fails is either the test that returns "$INSTANCE_ID doesn't seem to be in an AZ with a HAProxy instance, skipping deregistration.", or the setting of $HAPROXY_ID which aforementioned test depends on. The script runs just fine up until that point, but at that point, exits because it can't find the HAProxy instance ID.

I have checked IAM role permissions/credentials, environment variables, and file permissions which all appear to be correct. Normally I would place more logging into the script to debug, but deployments are too few and far between for us to make that practical.

My question: Is there a better way to do this? I can only guess we're not the only ones to use HAProxy with CodeDeploy, and there has to be a reliable method of doing this. Below is the current code being used that is not working.

```<code>#!/bin/bash
#
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
#  http://aws.amazon.com/apache2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.

. $(dirname $0)/common_functions.sh

if [[ "$DEPLOYMENT_GROUP_NAME" != "redacted" ]]; then
  msg "ELB Deregistration doesn't need to happen when not on redacted."
  exit
fi

msg "Running AWS CLI with region: $(get_instance_region)"

# get this instance's ID
INSTANCE_ID=$(get_instance_id)
if [ $? != 0 -o -z "$INSTANCE_ID" ]; then
    error_exit "Unable to get this instance's ID; cannot continue."
fi

# Get current time
msg "Started $(basename $0) at $(/bin/date "+%F %T")"
start_sec=$(/bin/date +%s.%N)

msg "Checking if instance $INSTANCE_ID is part of an AutoScaling group"
asg=$(autoscaling_group_name $INSTANCE_ID)
if [ $? == 0 -a -n "${asg}" ]; then
    msg "Found AutoScaling group for instance $INSTANCE_ID: ${asg}"

    msg "Checking that installed CLI version is at least at version required for AutoScaling Standby"
    check_cli_version
    if [ $? != 0 ]; then
        error_exit "CLI must be at least version ${MIN_CLI_X}.${MIN_CLI_Y}.${MIN_CLI_Z} to work with AutoScaling Standby"
    fi

    msg "Attempting to put instance into Standby"
    autoscaling_enter_standby $INSTANCE_ID "${asg}"
    if [ $? != 0 ]; then
        error_exit "Failed to move instance into standby"
    else
        msg "Instance is in standby"
    fi
fi

msg "Instance is not part of an ASG, continuing..."

## Get the instanceID of the HAProxy instance in this AZ and ENVIRONMENT - Will there ever be more than one???

HAPROXY_ID=$(/usr/local/bin/aws ec2 describe-instances --region us-east-1 --filters "Name=availability-zone,Values=$(/usr/bin/curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)" "Name=tag:deployment_group,Values=haproxy.$ENVIRONMENT" --output text  | \
grep INSTANCES | \
awk '{print $8}' )

HAPROXY_IP=$(/usr/local/bin/aws ec2 describe-instances --region us-east-1 --filters "Name=availability-zone,Values=$(/usr/bin/curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)" "Name=tag:deployment_group,Values=haproxy.$ENVIRONMENT" --output text  | \
grep INSTANCES | \
awk '{print $13}' )

if test -z "$HAPROXY_ID"; then
    msg "$INSTANCE_ID doesn't seem to be in an AZ with a HAProxy instance, skipping deregistration."
    exit
fi

## Put the current instance into MAINT mode with the HAProxy instance via SSM

msg "Deregistering $INSTANCE_ID from HAProxy $HAPROXY_ID"

DEREGCMD="{\"commands\":[\"haproxyctl disable server bk_app_servers/$INSTANCEID\"],\"executionTimeout\":[\"3600\"]}"

/usr/local/bin/aws ssm send-command \
--document-name "AWS-RunShellScript" \
--instance-ids "$HAPROXY_ID" \
--parameters "$DEREGCMD" \
--timeout-seconds 600 \
--output-s3-bucket-name "redacted" \
--output-s3-key-prefix "haproxy-codedeploy/deregister" \
--region us-east-1

if [ $? != 0 ]; then
    error_exit "Failed to send SSM command to deregister instance $INSTANCE_ID from HAProxy $HAPROXY_ID"
fi

## Wait for all connections to drain from instance

SESS_COUNT=$(/usr/bin/curl -s "http://$HAPROXY_IP:<portredacted>/<urlredacted>" | grep $INSTANCEID | awk -F "," '{print $5}')
DRAIN_TIME=60

msg "Initial session count: $SESS_COUNT"

while [[ "$SESS_COUNT" -gt 0 ]]; do
    if [[ "$COUNTER" -gt "$DRAIN_TIME" ]]; then
        msg "Instance failed to drain all connections within $DRAIN_TIME seconds. Continuing to deploy anyway."
        break
    fi
    msg $SESS_COUNT
    sleep 1
    COUNTER=$(($COUNTER + 1))
    SESS_COUNT=$(/usr/bin/curl -s "http://$HAPROXY_IP:<portredacted>/<urlredacted>" | grep $INSTANCEID | awk -F "," '{print $5}')
done

msg "Finished $(basename $0) at $(/bin/date "+%F %T")"

end_sec=$(/bin/date +%s.%N)
elapsed_seconds=$(echo "$end_sec - $start_sec" | /usr/bin/bc)

msg "Elapsed time: $elapsed_seconds"
</code>```

答:
At the moment the only option for you is to add more logging and issue a deployment to test out this script and then look at your deployment logs. It sounds like you don't know why it's failing and only the logs can tell you that.

Try adding logging and seeing what happens. We should be just executing your script as is so it shouldn't act any differently but it's hard to tell without seeing the logs.

Good luck,
-Asaf

Body:
Our application requires the use of HAProxy to load balance and route traffic (one per AZ), ALBs and ELBs are not configurable enough for our purposes. When deploying new code via AWS CodeDeploy, we would like the instances being patched to be placed into Maintenance Mode (removed from load balancing, connections drained). We have modified the default CodeDeploy lifecycle bash scripts to remove the instances from their respective HAProxy instances by sending an SSM Run Command to HAProxy from the instances in question. Currently this modification doesn't work, and the reason for failure is unknown. The script works when executed manually step by step (at least to the current point of failure). The part that fails is either the test that returns "$INSTANCE_ID doesn't seem to be in an AZ with a HAProxy instance, skipping deregistration.", or the setting of $HAPROXY_ID which aforementioned test depends on. The script runs just fine up until that point, but at that point, exits because it can't find the HAProxy instance ID.

I have checked IAM role permissions/credentials, environment variables, and file permissions which all appear to be correct. Normally I would place more logging into the script to debug, but deployments are too few and far between for us to make that practical.

My question: Is there a better way to do this? I can only guess we're not the only ones to use HAProxy with CodeDeploy, and there has to be a reliable method of doing this. Below is the current code being used that is not working.

#!/bin/bash
#
# Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
#
#  http://aws.amazon.com/apache2.0
#
# or in the "license" file accompanying this file. This file is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
# express or implied. See the License for the specific language governing
# permissions and limitations under the License.

. $(dirname $0)/common_functions.sh

if [[ "$DEPLOYMENT_GROUP_NAME" != "redacted" ]]; then
  msg "ELB Deregistration doesn't need to happen when not on redacted."
  exit
fi

msg "Running AWS CLI with region: $(get_instance_region)"

# get this instance's ID
INSTANCE_ID=$(get_instance_id)
if [ $? != 0 -o -z "$INSTANCE_ID" ]; then
    error_exit "Unable to get this instance's ID; cannot continue."
fi

# Get current time
msg "Started $(basename $0) at $(/bin/date "+%F %T")"
start_sec=$(/bin/date +%s.%N)

msg "Checking if instance $INSTANCE_ID is part of an AutoScaling group"
asg=$(autoscaling_group_name $INSTANCE_ID)
if [ $? == 0 -a -n "${asg}" ]; then
    msg "Found AutoScaling group for instance $INSTANCE_ID: ${asg}"

    msg "Checking that installed CLI version is at least at version required for AutoScaling Standby"
    check_cli_version
    if [ $? != 0 ]; then
        error_exit "CLI must be at least version ${MIN_CLI_X}.${MIN_CLI_Y}.${MIN_CLI_Z} to work with AutoScaling Standby"
    fi

    msg "Attempting to put instance into Standby"
    autoscaling_enter_standby $INSTANCE_ID "${asg}"
    if [ $? != 0 ]; then
        error_exit "Failed to move instance into standby"
    else
        msg "Instance is in standby"
    fi
fi

msg "Instance is not part of an ASG, continuing..."

## Get the instanceID of the HAProxy instance in this AZ and ENVIRONMENT - Will there ever be more than one???

HAPROXY_ID=$(/usr/local/bin/aws ec2 describe-instances --region us-east-1 --filters "Name=availability-zone,Values=$(/usr/bin/curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)" "Name=tag:deployment_group,Values=haproxy.$ENVIRONMENT" --output text  | \
grep INSTANCES | \
awk '{print $8}' )

HAPROXY_IP=$(/usr/local/bin/aws ec2 describe-instances --region us-east-1 --filters "Name=availability-zone,Values=$(/usr/bin/curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)" "Name=tag:deployment_group,Values=haproxy.$ENVIRONMENT" --output text  | \
grep INSTANCES | \
awk '{print $13}' )

if test -z "$HAPROXY_ID"; then
    msg "$INSTANCE_ID doesn't seem to be in an AZ with a HAProxy instance, skipping deregistration."
    exit
fi

## Put the current instance into MAINT mode with the HAProxy instance via SSM

msg "Deregistering $INSTANCE_ID from HAProxy $HAPROXY_ID"

DEREGCMD="{\"commands\":[\"haproxyctl disable server bk_app_servers/$INSTANCEID\"],\"executionTimeout\":[\"3600\"]}"

/usr/local/bin/aws ssm send-command \
--document-name "AWS-RunShellScript" \
--instance-ids "$HAPROXY_ID" \
--parameters "$DEREGCMD" \
--timeout-seconds 600 \
--output-s3-bucket-name "redacted" \
--output-s3-key-prefix "haproxy-codedeploy/deregister" \
--region us-east-1

if [ $? != 0 ]; then
    error_exit "Failed to send SSM command to deregister instance $INSTANCE_ID from HAProxy $HAPROXY_ID"
fi

## Wait for all connections to drain from instance

SESS_COUNT=$(/usr/bin/curl -s "http://$HAPROXY_IP:<portredacted>/<urlredacted>" | grep $INSTANCEID | awk -F "," '{print $5}')
DRAIN_TIME=60

msg "Initial session count: $SESS_COUNT"

while [[ "$SESS_COUNT" -gt 0 ]]; do
    if [[ "$COUNTER" -gt "$DRAIN_TIME" ]]; then
        msg "Instance failed to drain all connections within $DRAIN_TIME seconds. Continuing to deploy anyway."
        break
    fi
    msg $SESS_COUNT
    sleep 1
    COUNTER=$(($COUNTER + 1))
    SESS_COUNT=$(/usr/bin/curl -s "http://$HAPROXY_IP:<portredacted>/<urlredacted>" | grep $INSTANCEID | awk -F "," '{print $5}')
done

msg "Finished $(basename $0) at $(/bin/date "+%F %T")"

end_sec=$(/bin/date +%s.%N)
elapsed_seconds=$(echo "$end_sec - $start_sec" | /usr/bin/bc)

msg "Elapsed time: $elapsed_seconds"


问:
Preserving order with PostgreSQL and Rails
I'm running some elasticsearch queries and then taking those results and converting them into Active Record. Of course, order is not preserved.

I've had this working before but now I'm using Ruby 2.3.1 an Rails 5.1.1.

I've tried all of the following solutions so I'm beginning to think this is some bug with this environment.

```<code>def self.find_ordered(ids)
  order_clause = "CASE id "
  ids.each_with_index do |id, index|
    order_clause << sanitize_sql_array(["WHEN ? THEN ? ", id, index])
  end
  order_clause << sanitize_sql_array(["ELSE ? END", ids.length])
  where(id: ids).order(order_clause)
end
</code>```

Also:

```<code>def self.order_by_ids(ids)
  order_by = ["case"]
  ids.each_with_index.map do |id, index|
    order_by << "WHEN id='#{id}' THEN #{index}"
  end
  order_by << "end"
  order(order_by.join(" "))
end
</code>```

And https://github.com/panorama-ed/order_as_specified gem:

```<code>Product.order_as_specified(id: [ids])
</code>```

And https://github.com/khiav223577/find_with_order:

```<code>Product.find_with_order([ids])
</code>```

All of these should work, but all default back to numerical order after being run. I'm running them in the console so no code could be being run after.

Edit: Example of request in console.

```<code>Product.where(id: [100,5,10]).order_by_ids([100,5,10]).pluck(:id)
  (127.0ms)  SELECT "products"."id" FROM "products" WHERE
  "products"."id" IN (100, 5, 10) ORDER BY "products"."id" ASC, case
 WHEN id='100' THEN 0 WHEN id='5' THEN 1 WHEN id='10' THEN 2 end
 => [5, 10, 100]
</code>```

答:
Looking at the final SQL from your logs we see this:

```<code>ORDER BY "products"."id" ASC, ...
</code>```

That suggests that something somewhere is doing:

```<code>order(:id)
</code>```

The usual suspect when things mysteriously appear in your queries is a default_scope in your model. I tend to think that default scopes are evil, doubly so when they include an order call.

Go looking for a default scope and get rid of it. If you can't get rid of it (because something somewhere is depending on it), then kludge around it by throwing a reorder('') or reorder(nil) into your query before adding your order by case ... stuff or use reorder('case ... end') to replace whatever ORDER BY is there in one go; something like this:

```<code>def self.order_by_ids(ids)
  #... as before
  reorder(order_by.join(" "))
end

def self.order_by_ids(ids)
  #... as before
  reorder(nil).order(order_by.join(" "))
end

def self.order_by_ids(ids)
  #... as before
  reorder('').order(order_by.join(" "))
end

# etc.
</code>```

You can also use unscope(:order) but unscope can do things you don't want so it is better to use reorder as it does exactly what you want and nothing else.

Body:
I'm running some elasticsearch queries and then taking those results and converting them into Active Record. Of course, order is not preserved.

I've had this working before but now I'm using Ruby 2.3.1 an Rails 5.1.1.

I've tried all of the following solutions so I'm beginning to think this is some bug with this environment.

def self.find_ordered(ids)
  order_clause = "CASE id "
  ids.each_with_index do |id, index|
    order_clause << sanitize_sql_array(["WHEN ? THEN ? ", id, index])
  end
  order_clause << sanitize_sql_array(["ELSE ? END", ids.length])
  where(id: ids).order(order_clause)
end

Also:

def self.order_by_ids(ids)
  order_by = ["case"]
  ids.each_with_index.map do |id, index|
    order_by << "WHEN id='#{id}' THEN #{index}"
  end
  order_by << "end"
  order(order_by.join(" "))
end

And https://github.com/panorama-ed/order_as_specified gem:

Product.order_as_specified(id: [ids])

And https://github.com/khiav223577/find_with_order:

Product.find_with_order([ids])

All of these should work, but all default back to numerical order after being run. I'm running them in the console so no code could be being run after.

Edit: Example of request in console.

Product.where(id: [100,5,10]).order_by_ids([100,5,10]).pluck(:id)
  (127.0ms)  SELECT "products"."id" FROM "products" WHERE
  "products"."id" IN (100, 5, 10) ORDER BY "products"."id" ASC, case
 WHEN id='100' THEN 0 WHEN id='5' THEN 1 WHEN id='10' THEN 2 end
 => [5, 10, 100]

Body:
Looking at the final SQL from your logs we see this:

ORDER BY "products"."id" ASC, ...

That suggests that something somewhere is doing:

order(:id)

The usual suspect when things mysteriously appear in your queries is a default_scope in your model. I tend to think that default scopes are evil, doubly so when they include an order call.

Go looking for a default scope and get rid of it. If you can't get rid of it (because something somewhere is depending on it), then kludge around it by throwing a reorder('') or reorder(nil) into your query before adding your order by case ... stuff or use reorder('case ... end') to replace whatever ORDER BY is there in one go; something like this:

def self.order_by_ids(ids)
  #... as before
  reorder(order_by.join(" "))
end

def self.order_by_ids(ids)
  #... as before
  reorder(nil).order(order_by.join(" "))
end

def self.order_by_ids(ids)
  #... as before
  reorder('').order(order_by.join(" "))
end

# etc.

You can also use unscope(:order) but unscope can do things you don't want so it is better to use reorder as it does exactly what you want and nothing else.


问:
Using CSS for layout, clearing float for stating on next line ?? Need to create a layout of 2 cols and 5 rows
I have created a layout using DIVs rather than tables. It seems to be working... I had to clear:none after each div consisting of column and content.

But i end up with an extra line under each 2 columns before the other 2 columns start. I will outlay my code below, what am i doing wrong?.. What i want to do is create a table like layout but using divs consisting of 5 rows and each row have 2 columns.

```<code> <div id="column1" style="float:left;width:200px;">1st Title</div>
 <div id="container1" style="float:left;"> <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList></div>
 <div style="clear:both;"></div>
 <div id="column2" style="float:left;width:200px;">2nd Title</div>
 <div id="container2" style="float:left;"> <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList></div>
 <div style="clear:both;"></div>
</code>```

答:
Here is a CSS class that would make the problem all go away.</p>

```<code>.clearfix:after {
    content: ".";
    display: block;
    height: 0px;
    clear: both;
    visibility: hidden;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have created a layout using DIVs rather than tables. It seems to be working... I had to clear:none after each div consisting of column and content.

But i end up with an extra line under each 2 columns before the other 2 columns start. I will outlay my code below, what am i doing wrong?.. What i want to do is create a table like layout but using divs consisting of 5 rows and each row have 2 columns.

1st Title

 <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>

2nd Title

 <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>

Body:
Here is a CSS class that would make the problem all go away.

.clearfix:after {
    content: ".";
    display: block;
    height: 0px;
    clear: both;
    visibility: hidden;
}


问:
bash diff fails to found existing files when providing a path variable containing tilde (~)
I have a very surprising problem while trying to execute a diff command inside a bash script.

Here is a working code illustrating the point:

```<code>#!/bin/bash
cd
mkdir foo bar
head -c 1024 /dev/urandom >foo/qux
head -c 1024 /dev/urandom >bar/qux

# works properly as expected
diff ~/{foo,bar}/qux

folder="~"

# this fails with the ~ inside a variable
diff $folder/{foo,bar}/qux

# cleaning the mess
rm -rf foo bar
</code>```

So my question is:

Why ? :-)

答: Don't quote the ~ when assigning it to a variable. The ~ is only expanded by bash when you don't quote it.

Body:
I have a very surprising problem while trying to execute a diff command inside a bash script.

Here is a working code illustrating the point:

#!/bin/bash
cd
mkdir foo bar
head -c 1024 /dev/urandom >foo/qux
head -c 1024 /dev/urandom >bar/qux

# works properly as expected
diff ~/{foo,bar}/qux

folder="~"

# this fails with the ~ inside a variable
diff $folder/{foo,bar}/qux

# cleaning the mess
rm -rf foo bar

So my question is:

Why ? :-)


问:
Get size of memory available on the heap
This is platform dependent question for Linux. And if it matters, I'm asking specifically about pre-C++11.

I want to indirectly test a class's destructor by new and delete to see if all of the memory on the program's heap is deallocated, which could check for memory leaks.

```<code>object* x;        //pointer allocated on the stack
...               //measure available heap space
x = new object(); //allocated on the heap
delete x;         //deallocate that heap space
...               //measure again, see if it's the same
</code>```

I understand that Valgrind has Massif (...is there a C++ library for Massif..?), and that I can even run a memory leak check on my entire program, but code changes. Unit tests are important, and it bugs me to death that I can't fully unit test all of my code.

What code can I write that would measure available heap space?

答:
The distinction between stack and heap are somewhat vague in Linux.  Stack is just memory, the top of which, is handed to a clone() call which creates the new task.  This is true both for new processes and new threads.  The allocator operators are wrappers around system calls brk/sbrk.  Your best bet is to override the global operator new/operator new[] and operator delete/operator delete[] to do some sort of counting of the calls in such a way that you can examine it at run time.

A quick read through new expression can give you a good idea of order in which things happen when an object is created/destroyed (forgive me if you already know this) and operator new will tell the order in which allocators are looked up.  I may be wrong about this, but in order to have all allocators go through the same point of requesting memory from the OS, even the class-specific operator new would have to eventually call global operator new.

Well, the class-specific ones could use the allocator to mmap memory to a file or shmget to map the object to some storage in shared memory, but in both of those cases it wouldn't be part of what is traditionally referred to as "the heap."  The stack+heap both reside in what you see as "VIRT" memory when you run "top" in linux.

Short of that, the memory allocated by malloc and passed to the clone call (which, for instance, creates a new thread) to be the stack of a new thread will not be different from the memory used as heap.

Body:
This is platform dependent question for Linux. And if it matters, I'm asking specifically about pre-C++11.

I want to indirectly test a class's destructor by new and delete to see if all of the memory on the program's heap is deallocated, which could check for memory leaks.

object* x;        //pointer allocated on the stack
...               //measure available heap space
x = new object(); //allocated on the heap
delete x;         //deallocate that heap space
...               //measure again, see if it's the same

I understand that Valgrind has Massif (...is there a C++ library for Massif..?), and that I can even run a memory leak check on my entire program, but code changes. Unit tests are important, and it bugs me to death that I can't fully unit test all of my code.

What code can I write that would measure available heap space?


问:
How to make a a polygon using only the outer points with OpenCV?
Manually made example image of desired result

I'm getting list of corner coordinates every time an object moves. I want to make a fillpoly with those coordinates so that I can make make a mask of only the object that is moving. The problem is that the corner coordinates are not in order so the polylines goes to random points regardless of the previous point and there are also corners inside the object. I need only the outer corners of the object so that I can make an outline and fill it. Any help will be welcomed, thank you guys in advance.

答:
You're looking for the convexhull() function.

Here's a python tutorial and a C++ tutorial on it, that I thought was a better explanation.

NOTE that this won't give you exactly what you're looking for, but perhaps it is close enough for your application


问:
Getting a list out of an extractor -- or even a Match
First, I was like cool...

```<code>scala> var nameRE = """\W*(\w+)\W+(\w+)\W*""".r
nameRE: scala.util.matching.Regex = \W*(\w+)\W+(\w+)\W*

scala> var nameRE(first, last) = "Will Smith "
first: String = Will
last: String = Smith
</code>```

Then I was like darn...

```<code>scala> var listOfVowels = "(([aeiou])*)".r
listOfVowels: scala.util.matching.Regex = (([aeiou])*)

scala> var listOfVowels(vowels:List[String]) = "uoiea"
<console>:7: error: scrutinee is incompatible with pattern type;
 found   : List[String]
 required: java.lang.String
       var listOfVowels(vowels:List[String]) = "uoiea"
</code>```

Now I'm like huh ...

```<code>scala> (listOfVowels findFirstMatchIn "uoiea" get) subgroups
res35: List[String] = List(a)
</code>```

[ In case my question isn't obvious: how do I get a list of all the subgroups actually matched by a pattern, ideally in an extractor but in any case without writing a second-level matcher.  The correct answer here would be List(u, o, i, e, a) of course. ]

答:
To my knowledge it is not possible to convert a subpattern of type (E)* in a regular expression into a List of Strings. This would be because the regular expression mechanism used in Scala is implemented using the JDK's default implementation for regexes (java.util.Pattern, java.util.Matcher, etc.) and this implementation does just not support capturing multiplicities of subpatterns. In case of a match the subpattern (E)* will only capture the last match for that subpattern. To my knowledge, this behavior even holds true for the majority of regex implementations.

Although I believe your case to be a simplified version of your actual problem, a simple solution for the described case does exist :

```<code>scala> "[aeiou]".r findAllIn "hello, world!" toList
res1: List[String] = List(e, o, o)
</code>```

Hopefully that helps.

Body:
First, I was like cool...

scala> var nameRE = """\W*(\w+)\W+(\w+)\W*""".r
nameRE: scala.util.matching.Regex = \W*(\w+)\W+(\w+)\W*

scala> var nameRE(first, last) = "Will Smith "
first: String = Will
last: String = Smith

Then I was like darn...

scala> var listOfVowels = "(([aeiou])*)".r
listOfVowels: scala.util.matching.Regex = (([aeiou])*)

scala> var listOfVowels(vowels:List[String]) = "uoiea"
<console>:7: error: scrutinee is incompatible with pattern type;
 found   : List[String]
 required: java.lang.String
       var listOfVowels(vowels:List[String]) = "uoiea"

Now I'm like huh ...

scala> (listOfVowels findFirstMatchIn "uoiea" get) subgroups
res35: List[String] = List(a)

[ In case my question isn't obvious: how do I get a list of all the subgroups actually matched by a pattern, ideally in an extractor but in any case without writing a second-level matcher.  The correct answer here would be List(u, o, i, e, a) of course. ]

Body:
To my knowledge it is not possible to convert a subpattern of type (E)* in a regular expression into a List of Strings. This would be because the regular expression mechanism used in Scala is implemented using the JDK's default implementation for regexes (java.util.Pattern, java.util.Matcher, etc.) and this implementation does just not support capturing multiplicities of subpatterns. In case of a match the subpattern (E)* will only capture the last match for that subpattern. To my knowledge, this behavior even holds true for the majority of regex implementations.

Although I believe your case to be a simplified version of your actual problem, a simple solution for the described case does exist :

scala> "[aeiou]".r findAllIn "hello, world!" toList
res1: List[String] = List(e, o, o)

Hopefully that helps.


问:
Angular + Django REST Authentication credentials were not provided
I'm developing an API with Django REST. The client is a SPA in AngularJS running in node.js. Register and Login work fine, but when the user does logout the error message is showed:

{"detail":"Authentication credentials were not provided."}

I tried many solutions, like post 1 and post 2. but the problem continues. If my Angular files are in the server, my page works fine, but when I changed for a SPA created by yeoman, I have the credentials problem.

My settings.py

```<code>import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y6u0gy4ij&8uoo6@p*$qukwp$-07@-1gd)@)(l!-j&wmpot4h#'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',
    'rest_framework.authtoken',
    'authentication',
    'corsheaders',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware', #
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ServerLearn.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    )
}

WSGI_APPLICATION = 'ServerLearn.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

AUTH_USER_MODEL = 'authentication.Account'

CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api/v1/.*$'
</code>```

My models.py

```<code>from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models

from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings

# Create your models here.

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        token = Token.objects.create(user=instance)
        print(token)

class AccountManager(BaseUserManager):
    def create_user(self, username, password=None, **kwargs):
        if not username:
            raise ValueError("Need username.")

        if not kwargs.get("email"):
            raise ValueError("Need email.")

        account = self.model(
            username = username,
            email = self.normalize_email(kwargs.get("email")),
            name = kwargs.get("name"),
            age = kwargs.get("age"),
            gender = kwargs.get("gender"),
            #birth = kwargs.get("birth")
        )

        account.set_password(password)
        account.save()

        return account

    #admin
    #senhaadmin
    def create_superuser(self, username, password, **kwargs):
        account = self.model(
            username = username,
            email = self.normalize_email(kwargs.get("email")),
            name = "Admin",
            age = 31111,
            gender = 555,
        )

        account.is_admin = True
        account.set_password(password)
        account.save()

        return account

class Account(AbstractBaseUser):
    username = models.CharField(max_length = 50, unique = True)
    email = models.EmailField(unique = True)
    name = models.CharField(max_length = 100)
    age = models.PositiveSmallIntegerField()
    gender = models.PositiveSmallIntegerField()
    #birth = models.DateField(null = True, blank = True)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)
    is_admin = models.BooleanField(default = False)

    objects = AccountManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FILES = ['username', 'email', 'name', 'age', 'gender']

    def __unicode__ (self):
        return self.username
</code>```

My views.py

```<code>class AccountViewSet(viewsets.ModelViewSet):
    lookup_field = 'username'
    queryset = Account.objects.all()
    serializer_class = AccountSerializer

    def get_permissions(self):
        if self.request.method in permissions.SAFE_METHODS:
            return (permissions.AllowAny(),)

        if self.request.method == 'POST':
            return (permissions.AllowAny(),)

        return (permissions.IsAuthenticated(), IsAccountOwner(),)

    def create(self, request):
        serializer = self.serializer_class(data = request.data)

        if serializer.is_valid():
            Account.objects.create_user(**serializer.validated_data)

            return Response(serializer.validated_data, status = status.HTTP_201_CREATED)

        return Response({
            'status': 'Bad request',
            'message': 'Conta não pode ser criada'
            }, status = status.HTTP_400_BAD_REQUEST)

class LoginView(views.APIView):
    def post(self, request, format=None):
        data = json.loads(request.body.decode('utf-8'))

        username = data.get('username', None)
        password = data.get('password', None)

        account = authenticate(username=username, password=password)

        if account is not None:
            if account.is_active:
                login(request, account)

                serialized = AccountSerializer(account)

                return Response(serialized.data)
            else:
                return Response({
                    'status': 'Unauthorized',
                    'message': 'This account has been disabled.'
                }, status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response({
                'status': 'Unauthorized',
                'message': 'Username/password combination invalid.'
            }, status=status.HTTP_401_UNAUTHORIZED)

class LogoutView(views.APIView):

    #ERROR IN NEXT LINE
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request, format=None):

        logout(request)
        return Response({}, status=status.HTTP_204_NO_CONTENT)
</code>```

In my Angular application, in app.js

```<code>app.run(run);

run.$inject = ['$http'];

function run($http) {
      $http.defaults.xsrfHeaderName = 'X-CSRFToken';
      $http.defaults.xsrfCookieName = 'csrftoken';
}
</code>```

I get token after login with code:

```<code>$http.post('http://localhost:8000/api/v1/api-token-auth/', {
    username: username,
    password: password
}).then(tokenSuccessFn, tokenErrorFn);

function tokenSuccessFn(data, status, headers, config) {
    console.log("token:  ");
    console.log(JSON.stringify(data));
    $http.defaults.headers.common.Authorization = 'Token ' + $cookies.get("csrftoken");
}

function tokenErrorFn(data, status, headers, config) {
    console.error('token error !!!');
}
</code>```

The logout is

```<code>return $http.post('http://localhost:8000/api/v1/auth/logout/')
    .then(logoutSuccessFn, logoutErrorFn);

function logoutSuccessFn(data, status, headers, config) {
    Authentication.unauthenticate();

    window.location = '/';
}

function logoutErrorFn(data, status, headers, config) {
    console.error('Logout error !!!');
}
</code>```

答:
I found the problem. I didn't add the token to header correctly.

I get the token and storage in a local storage.

```<code>$http.post('http://localhost:8000/api/v1/api-token-auth/', {
    username: username,
    password: password
}).then(tokenSuccessFn, tokenErrorFn);

function tokenSuccessFn(data, status, headers, config) {

    localStorage.setItem('myApp.token',data['data'].token);
}

function tokenErrorFn(data, status, headers, config) {
    console.error('token error !!!');
}
</code>```

When the app (page) begins, I load the token from local storage in app.js:

```<code>app.run(['$http', function ($http) {

    $http.defaults.headers.common['Authorization'] = 'Token ' + localStorage.getItem('myApp.token');
}]);
</code>```

Thanks Ykh for the help.

Body:
I'm developing an API with Django REST. The client is a SPA in AngularJS running in node.js. Register and Login work fine, but when the user does logout the error message is showed:

{"detail":"Authentication credentials were not provided."}

I tried many solutions, like post 1 and post 2. but the problem continues. If my Angular files are in the server, my page works fine, but when I changed for a SPA created by yeoman, I have the credentials problem.

My settings.py

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y6u0gy4ij&8uoo6@p*$qukwp$-07@-1gd)@)(l!-j&wmpot4h#'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',
    'rest_framework.authtoken',
    'authentication',
    'corsheaders',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware', #
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ServerLearn.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    )
}

WSGI_APPLICATION = 'ServerLearn.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

AUTH_USER_MODEL = 'authentication.Account'

CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r'^/api/v1/.*$'

My models.py

from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models

from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
from django.conf import settings

# Create your models here.

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        token = Token.objects.create(user=instance)
        print(token)

class AccountManager(BaseUserManager):
    def create_user(self, username, password=None, **kwargs):
        if not username:
            raise ValueError("Need username.")

        if not kwargs.get("email"):
            raise ValueError("Need email.")

        account = self.model(
            username = username,
            email = self.normalize_email(kwargs.get("email")),
            name = kwargs.get("name"),
            age = kwargs.get("age"),
            gender = kwargs.get("gender"),
            #birth = kwargs.get("birth")
        )

        account.set_password(password)
        account.save()

        return account

    #admin
    #senhaadmin
    def create_superuser(self, username, password, **kwargs):
        account = self.model(
            username = username,
            email = self.normalize_email(kwargs.get("email")),
            name = "Admin",
            age = 31111,
            gender = 555,
        )

        account.is_admin = True
        account.set_password(password)
        account.save()

        return account

class Account(AbstractBaseUser):
    username = models.CharField(max_length = 50, unique = True)
    email = models.EmailField(unique = True)
    name = models.CharField(max_length = 100)
    age = models.PositiveSmallIntegerField()
    gender = models.PositiveSmallIntegerField()
    #birth = models.DateField(null = True, blank = True)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)
    is_admin = models.BooleanField(default = False)

    objects = AccountManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FILES = ['username', 'email', 'name', 'age', 'gender']

    def __unicode__ (self):
        return self.username

My views.py

class AccountViewSet(viewsets.ModelViewSet):
    lookup_field = 'username'
    queryset = Account.objects.all()
    serializer_class = AccountSerializer

    def get_permissions(self):
        if self.request.method in permissions.SAFE_METHODS:
            return (permissions.AllowAny(),)

        if self.request.method == 'POST':
            return (permissions.AllowAny(),)

        return (permissions.IsAuthenticated(), IsAccountOwner(),)

    def create(self, request):
        serializer = self.serializer_class(data = request.data)

        if serializer.is_valid():
            Account.objects.create_user(**serializer.validated_data)

            return Response(serializer.validated_data, status = status.HTTP_201_CREATED)

        return Response({
            'status': 'Bad request',
            'message': 'Conta não pode ser criada'
            }, status = status.HTTP_400_BAD_REQUEST)

class LoginView(views.APIView):
    def post(self, request, format=None):
        data = json.loads(request.body.decode('utf-8'))

        username = data.get('username', None)
        password = data.get('password', None)

        account = authenticate(username=username, password=password)

        if account is not None:
            if account.is_active:
                login(request, account)

                serialized = AccountSerializer(account)

                return Response(serialized.data)
            else:
                return Response({
                    'status': 'Unauthorized',
                    'message': 'This account has been disabled.'
                }, status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response({
                'status': 'Unauthorized',
                'message': 'Username/password combination invalid.'
            }, status=status.HTTP_401_UNAUTHORIZED)

class LogoutView(views.APIView):

    #ERROR IN NEXT LINE
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request, format=None):

        logout(request)
        return Response({}, status=status.HTTP_204_NO_CONTENT)

In my Angular application, in app.js

app.run(run);

run.$inject = ['$http'];

function run($http) {
      $http.defaults.xsrfHeaderName = 'X-CSRFToken';
      $http.defaults.xsrfCookieName = 'csrftoken';
}

I get token after login with code:

$http.post('http://localhost:8000/api/v1/api-token-auth/', {
    username: username,
    password: password
}).then(tokenSuccessFn, tokenErrorFn);

function tokenSuccessFn(data, status, headers, config) {
    console.log("token:  ");
    console.log(JSON.stringify(data));
    $http.defaults.headers.common.Authorization = 'Token ' + $cookies.get("csrftoken");
}

function tokenErrorFn(data, status, headers, config) {
    console.error('token error !!!');
}

The logout is

return $http.post('http://localhost:8000/api/v1/auth/logout/')
    .then(logoutSuccessFn, logoutErrorFn);

function logoutSuccessFn(data, status, headers, config) {
    Authentication.unauthenticate();

    window.location = '/';
}

function logoutErrorFn(data, status, headers, config) {
    console.error('Logout error !!!');
}

Body:
I found the problem. I didn't add the token to header correctly.

I get the token and storage in a local storage.

$http.post('http://localhost:8000/api/v1/api-token-auth/', {
    username: username,
    password: password
}).then(tokenSuccessFn, tokenErrorFn);

function tokenSuccessFn(data, status, headers, config) {

    localStorage.setItem('myApp.token',data['data'].token);
}

function tokenErrorFn(data, status, headers, config) {
    console.error('token error !!!');
}

When the app (page) begins, I load the token from local storage in app.js:

app.run(['$http', function ($http) {

    $http.defaults.headers.common['Authorization'] = 'Token ' + localStorage.getItem('myApp.token');
}]);

Thanks Ykh for the help.


问:
Action Cable: broadcast different template content depending on the current user
I have a delete link in a partial for a message that gets rendered in a chat by ActionCable. I'm checking with the following code if the current_user is admin or not and whether the user can see the link or not:

```<code><% if current_user.admin? %>
  <%= link_to '[x]', msg, method: :delete, remote: true, class: "del-link" %>
<% end %>
</code>```

But there happens to be an issue with this.
When a user, who is not admin submits a message, it gets rendered as 'not admin' for every user in the chat and the admin can see the link only after a refresh.
Vice versa it's the same, if an admin submits a message everyone can see the link.

Is there a way to solve this issue?

答:
Since you are rendering a single template and broadcasting that to everyone, this behavior is to be expected. The basic problem is that when rendering the template to broadcast, current_user is the user posting the message, not the user receiving the update through Action Cable.

You could solve the problem entirely on the client side by doing something like this:

```<code><%= link_to '[x]', msg, method: :delete, remote: true, class: "del-link admin-only" %>
</code>```

Then add this CSS rule:

```<code>body:not(.with-admin) .admin-only {
  display: none;
}
</code>```

And set the with-admin class on  if the current user is an admin:

```<code><body class="<%= "with-admin" if current_user.admin? %>">
  <!-- ... -->
</body>
</code>```

This way the visibility of admin-only elements is controlled by whether or not the current page was originally loaded as an admin, and the template broadcasted by Action Cable can have the same content for everyone.

Important: Make sure to validate the admin-ness of current_user in the destroy action before a message is actually deleted!

Body:
I have a delete link in a partial for a message that gets rendered in a chat by ActionCable. I'm checking with the following code if the current_user is admin or not and whether the user can see the link or not:

<% if current_user.admin? %>
  <%= link_to '[x]', msg, method: :delete, remote: true, class: "del-link" %>
<% end %>

But there happens to be an issue with this.
When a user, who is not admin submits a message, it gets rendered as 'not admin' for every user in the chat and the admin can see the link only after a refresh.
Vice versa it's the same, if an admin submits a message everyone can see the link.

Is there a way to solve this issue?

Body:
Since you are rendering a single template and broadcasting that to everyone, this behavior is to be expected. The basic problem is that when rendering the template to broadcast, current_user is the user posting the message, not the user receiving the update through Action Cable.

You could solve the problem entirely on the client side by doing something like this:

<%= link_to '[x]', msg, method: :delete, remote: true, class: "del-link admin-only" %>

Then add this CSS rule:

body:not(.with-admin) .admin-only {
  display: none;
}

And set the with-admin class on <body> if the current user is an admin:

<body class="<%= "with-admin" if current_user.admin? %>">
  <!-- ... -->
</body>

This way the visibility of admin-only elements is controlled by whether or not the current page was originally loaded as an admin, and the template broadcasted by Action Cable can have the same content for everyone.

Important: Make sure to validate the admin-ness of current_user in the destroy action before a message is actually deleted!


问:
Functions in JavaScript are not working
I created a function that could be called once the user focus on the input field;  when I tried to apply and test it myself though,  no function had been called.  I checked for my function,  it was well-written;  I found no syntax mistakes.  I created some tricks to find out what kind of a problem I had had: The outcome is that the same code could be applied with the event "onfocus", whereas the browser totally ignored my function even when I created the inline code within the tag "input"...Taking into notice I am using Firefox,  and the test was on Firefox 52.0.2 (32-bit) on Ubuntu Linux..

The testing function code:
(In script element):

```<code>function helpMe(){
  alert("Help Me!");
};
</code>```

(Within the input tag):

```<code>onfous="help me()" // NOT WORKING!
</code>```

(Within the input tag):

```<code>onfocus="alert('Help Me!')" // WORKING WELL!
</code>```

答:
you have a typo </p>

```<code><script>
   function helpMe(){ alert("Help Me!"); }
</script>
</code>```

<p>(Within the input tag): </p>

```<code>// here helpMe instead of help me ..
<input onfous="helpMe()"/>
</code>```

Title: Functions in JavaScript are not working

Body:
I created a function that could be called once the user focus on the input field;  when I tried to apply and test it myself though,  no function had been called.  I checked for my function,  it was well-written;  I found no syntax mistakes.  I created some tricks to find out what kind of a problem I had had: The outcome is that the same code could be applied with the event "onfocus", whereas the browser totally ignored my function even when I created the inline code within the tag "input"...Taking into notice I am using Firefox,  and the test was on Firefox 52.0.2 (32-bit) on Ubuntu Linux..

The testing function code:
(In script element):

function helpMe(){
  alert("Help Me!");
};

(Within the input tag):

onfous="help me()" // NOT WORKING!

(Within the input tag):

onfocus="alert('Help Me!')" // WORKING WELL!

Body:
you have a typo

<script>
   function helpMe(){ alert("Help Me!"); }
</script>

(Within the input tag):

// here helpMe instead of help me ..
<input onfous="helpMe()"/>


问:
Cloning a private repo is taking forever. Am I doing something wrong?
GitHub Desktop - Cloning a private repo is taking forever. Am I doing something wrong?

So when logged into GitHub, I'm looking at my private repo. So I click "Clone Repo" and open it in desktop. Then I choose where I want to clone it to, and now the little arrows in the upper left hand corner have just been spinning for like 10 minutes now.

Any idea why this is taking so long? Or am I doing something wrong? I'm logged into the account both on GitHub and GitHub Desktop that has access to this private repo. Is there something else that I should do? I'm not using command line, just using the GUI that GitHub Desktop has.

The repo is only about 120MB and my connection is 300 Mbps down / 20 Mbps up. doubt it's either. I am a Read Only user to the repo, though. Do read only users not have clone permissions?

This is an image of what I've been looking at. Nothing happening, no error messages, nothing. http://i.imgur.com/zsvjVun.png Just those two arrows going around and around.

Did a clone via Git Bash just now, and that worked fantastically. Not sure what the big difference is. Any ideas?

Thank you.

答:
I see what happened now. I was using GitHub Desktop's new Beta version on their site, instead of the old, stable, version.

I'm using the stable version instead of the beta version and it works great.

Thank you everyone for your time and assistance.


问:
Using COUNTIF, OFFSET, MATCH in Excel
I keep getting an error around this certain part of my COUNTIF function and cannot find out why. I believe it's cause the Offset function won't output a range. It seems to work fine if I manually put a range, but that isn't an option.

How do I get a range as an output using Match?

```<code>=COUNTIFS(OFFSET(Sheet2!$A$1,0,MATCH(I$1,Sheet2!1:1,0)),"*Accountable*")
</code>```

答:
Solved:

A.S.H's tip on keeping the ranges the same solved most of it.
The second bit I was running into was just a miscalculation of columns.
It needed to be the match function and then minus 1 column.

Title: Using COUNTIF, OFFSET, MATCH in Excel

Body:
I keep getting an error around this certain part of my COUNTIF function and cannot find out why. I believe it's cause the Offset function won't output a range. It seems to work fine if I manually put a range, but that isn't an option.

How do I get a range as an output using Match?

=COUNTIFS(OFFSET(Sheet2!$A$1,0,MATCH(I$1,Sheet2!1:1,0)),"*Accountable*")


问:
Is this kind of function calls permissible in C
```<code>char* p = init();
p = foo(p);        /* this one */
</code>```

the function foo prototype:

```<code>char* foo(char* p);
</code>```

Is it permissible to call foo that way, or does it fall in the Undefined Behavior category?

答: Yes, this is well-defined - there is a sequence point between the evaluation of the function arguments and the function call.  </p>

Body:
char* p = init();
p = foo(p);        /* this one */

the function foo prototype:

char* foo(char* p);

Is it permissible to call foo that way, or does it fall in the Undefined Behavior category?


问:
VBA, Parse by "|" and Transpose, Next row
I have the following data in a cells A1

```<code>|stack|over|flow|
</code>```

and cells A2..

```<code>|today|is|friday
</code>```

How can I delimit this and transpose it into a vertical/column based view view?

Delimiting will give me data row based, which is good but that I have to transpose this manually each time. I plan to do this for many rows. I realized this could be tricky as the next row will need to be pushed back down for each time.

Result A1:A6:

```<code>Stack

Over

flow

today

is

friday
</code>```

Edit

答:
This one manages an unlimited number of rows on column A</p>

```<code>Sub go()

    Dim strFoo As String
    Dim LastRow As Long
    Dim LastPosition As Long
    Dim MySheet As Worksheet
    Dim arr() As String
    Dim i As Long
    Dim j As Long

    Set MySheet = ActiveWorkbook.ActiveSheet

    MySheet.Range("A1").EntireColumn.Insert

    LastRow = MySheet.Cells(MySheet.Rows.Count, "B").End(xlUp).Row

    LastPosition = 1

    For i = 1 To LastRow

        strFoo = MySheet.Range("B" & i)

        If strFoo <> "" Then

            arr = Split(strFoo, "|")

            For j = 0 To UBound(arr)
                If arr(j) <> "" Then
                    MySheet.Range("A" & LastPosition) = arr(j)
                    LastPosition = LastPosition + 1
                End If
            Next j

        End If

    Next i

End Sub
</code>```

Body:
I have the following data in a cells A1

|stack|over|flow|

and cells A2..

|today|is|friday

How can I delimit this and transpose it into a vertical/column based view view?

Delimiting will give me data row based, which is good but that I have to transpose this manually each time. I plan to do this for many rows. I realized this could be tricky as the next row will need to be pushed back down for each time.

Result A1:A6:

Stack

Over

flow

today

is

friday

Edit

Body:
This one manages an unlimited number of rows on column A

Sub go()

    Dim strFoo As String
    Dim LastRow As Long
    Dim LastPosition As Long
    Dim MySheet As Worksheet
    Dim arr() As String
    Dim i As Long
    Dim j As Long

    Set MySheet = ActiveWorkbook.ActiveSheet

    MySheet.Range("A1").EntireColumn.Insert

    LastRow = MySheet.Cells(MySheet.Rows.Count, "B").End(xlUp).Row

    LastPosition = 1

    For i = 1 To LastRow

        strFoo = MySheet.Range("B" & i)

        If strFoo <> "" Then

            arr = Split(strFoo, "|")

            For j = 0 To UBound(arr)
                If arr(j) <> "" Then
                    MySheet.Range("A" & LastPosition) = arr(j)
                    LastPosition = LastPosition + 1
                End If
            Next j

        End If

    Next i

End Sub


问:
Swift Eureka - capture MultivaluedSection delete action
I am using swift Eureka library with MultivaluedSection component. I want to capture when a user delete a row and update my application state. I took a look at examples, they show how to enable delete action but none of them provides the ability to capture the delete action Do you know how to do it?

code from example:

```<code>class MultivaluedOnlyDeleteController: FormViewController {

    @IBOutlet weak var editButton: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.isEditing = false
        let nameList = ["family", "male", "female", "client"]

        let section = MultivaluedSection(multivaluedOptions: .Delete, footer: "you can swipe to delete when table.isEditing = false (Not Editing)")

        for tag in nameList {
            section <<< TextRow {
                            $0.placeholder = "Tag Name"
                            $0.value = tag
                        }
        }

        let section2 =  MultivaluedSection(multivaluedOptions: .Delete, footer: "")
        for _ in 1..<4 {
            section2 <<< PickerInlineRow<String> {
                            $0.title = "Tap to select"
                            $0.value = "client"
                            $0.options = nameList
                         }
        }

        editButton.title = tableView.isEditing ? "Done" : "Edit"
        editButton.target = self
        editButton.action = #selector(editPressed(sender:))

        form    +++

                section

                +++

                section2
    }

    func editPressed(sender: UIBarButtonItem){
        tableView.setEditing(!tableView.isEditing, animated: true)
        editButton.title = tableView.isEditing ? "Done" : "Edit"

    }
}
</code>```

答:
Just submitted a PR on GitHub but until it is approved feel free to use my forked repository.

Here is a small example what's new:

```<code>section <<< TextRow {
                  $0.placeholder = "Tag Name"
                  $0.value = tag
             }.willBeRemoved({ (textRow) in
                  // do your stuff here
            })
</code>```

If you use CocoaPods, as a temporary solution just replace

```<code>pod 'Eureka'
</code>```

with

```<code>pod 'Eureka', :git => 'https://github.com/AdamStreet/Eureka.git', :branch => 'multivaluedsection-delete-callback'
</code>```

Body:
I am using swift Eureka library with MultivaluedSection component. I want to capture when a user delete a row and update my application state. I took a look at examples, they show how to enable delete action but none of them provides the ability to capture the delete action Do you know how to do it?

code from example:

class MultivaluedOnlyDeleteController: FormViewController {

    @IBOutlet weak var editButton: UIBarButtonItem!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.isEditing = false
        let nameList = ["family", "male", "female", "client"]

        let section = MultivaluedSection(multivaluedOptions: .Delete, footer: "you can swipe to delete when table.isEditing = false (Not Editing)")

        for tag in nameList {
            section <<< TextRow {
                            $0.placeholder = "Tag Name"
                            $0.value = tag
                        }
        }

        let section2 =  MultivaluedSection(multivaluedOptions: .Delete, footer: "")
        for _ in 1..<4 {
            section2 <<< PickerInlineRow<String> {
                            $0.title = "Tap to select"
                            $0.value = "client"
                            $0.options = nameList
                         }
        }

        editButton.title = tableView.isEditing ? "Done" : "Edit"
        editButton.target = self
        editButton.action = #selector(editPressed(sender:))

        form    +++

                section

                +++

                section2
    }

    func editPressed(sender: UIBarButtonItem){
        tableView.setEditing(!tableView.isEditing, animated: true)
        editButton.title = tableView.isEditing ? "Done" : "Edit"

    }
}

Body:
Just submitted a PR on GitHub but until it is approved feel free to use my forked repository.

Here is a small example what's new:

section <<< TextRow {
                  $0.placeholder = "Tag Name"
                  $0.value = tag
             }.willBeRemoved({ (textRow) in
                  // do your stuff here
            })

If you use CocoaPods, as a temporary solution just replace

pod 'Eureka'

with

pod 'Eureka', :git => 'https://github.com/AdamStreet/Eureka.git', :branch => 'multivaluedsection-delete-callback'


问:
ARKit make an SCNLight point ahead where the camera is looking?
So I have access to the sceneView.pointOfViewand I want to make the AR experience feel like I am shining a flash light straight in front of my to objects I look at become lit as I point at them.

I tried to create a spotlight like this:

```<code>let spotLight = SCNLight()
spotLight.type = .spot
spotLight.spotInnerAngle = 60
spotLight.spotOuterAngle = 60
let spotNode = SCNNode()
spotNode.light = spotLight
spotNode.position = position
</code>```

I then thought that adding the light to the pointOfView node would make it so the light would move with the camera, meaning it would always shine light ahead...

```<code>sceneView.pointOfView?.addChildNode(spotLight)
</code>```

this is not working, the objects appear black, no light.

What am I doing wrong? I want to make it so the light points at what I look at through the AR experience, just as if I was holding a flashlight and I was shining light straight ahead....

Any suggestion?

答:
Are you looking for a virtual flashlight that realistically illuminates the real-world scene in the camera feed? That's a very tall order.

You're basically talking about projection-mapping a light cone onto every real-world surface that's visible, which requires detecting and modeling those surfaces, which is a whole lot more than the horizontal plane detection ARKit does.

(If you want to not-realistically illuminate the real-world scene, all you need to do is place a semi-transparent white circle in the middle of the view. Maybe get fancy with blend modes. For a tiny bit more realistic, vary the size of, or the 3D distance to, your circle based on hit-testing the center of your view against the AR scene.)

Do you want a virtual flashlight that illuminates the virtual objects you've placed in AR? That's easily doable. And in fact, your code is most of the way to doing that. The likely problems:

```<code>spotNode.position = position
</code>```

Your snippet above doesn't say where you're getting this position. If you want the spotlight node attached to the camera, it should be a zero vector. That is, you want it to have a neutral position in the local space of the camera node. Setting this vector to non-zero would offset your light source from the camera position by a constant displacement (possibly so much that it results in the light not doing anything useful in your scene).

```<code>sceneView.pointOfView?.addChildNode(spotLight)
</code>```

Depending on when this code runs, sceneView.pointOfView may be nil, and so you're not actually executing the addChildNode call. Check to make sure the camera node exists before adding a child to it. (I tried adding this code to the sample code from the ARKit WWDC17 session — if you put it in their ARSCNView.setup() function, you should see any virtual objects you place getting completely whited out by a bright spotlight.)

By the way, you don't necessarily need to add a child node to the pointOfView node to hold a light — the pointOfView node can have both a camera and a light attached.

Body:
So I have access to the sceneView.pointOfViewand I want to make the AR experience feel like I am shining a flash light straight in front of my to objects I look at become lit as I point at them.

I tried to create a spotlight like this:

let spotLight = SCNLight()
spotLight.type = .spot
spotLight.spotInnerAngle = 60
spotLight.spotOuterAngle = 60
let spotNode = SCNNode()
spotNode.light = spotLight
spotNode.position = position

I then thought that adding the light to the pointOfView node would make it so the light would move with the camera, meaning it would always shine light ahead...

sceneView.pointOfView?.addChildNode(spotLight)

this is not working, the objects appear black, no light.

What am I doing wrong? I want to make it so the light points at what I look at through the AR experience, just as if I was holding a flashlight and I was shining light straight ahead....

Any suggestion?

Body:
Are you looking for a virtual flashlight that realistically illuminates the real-world scene in the camera feed? That's a very tall order.

You're basically talking about projection-mapping a light cone onto every real-world surface that's visible, which requires detecting and modeling those surfaces, which is a whole lot more than the horizontal plane detection ARKit does.

(If you want to not-realistically illuminate the real-world scene, all you need to do is place a semi-transparent white circle in the middle of the view. Maybe get fancy with blend modes. For a tiny bit more realistic, vary the size of, or the 3D distance to, your circle based on hit-testing the center of your view against the AR scene.)

Do you want a virtual flashlight that illuminates the virtual objects you've placed in AR? That's easily doable. And in fact, your code is most of the way to doing that. The likely problems:

spotNode.position = position

Your snippet above doesn't say where you're getting this position. If you want the spotlight node attached to the camera, it should be a zero vector. That is, you want it to have a neutral position in the local space of the camera node. Setting this vector to non-zero would offset your light source from the camera position by a constant displacement (possibly so much that it results in the light not doing anything useful in your scene).

sceneView.pointOfView?.addChildNode(spotLight)

Depending on when this code runs, sceneView.pointOfView may be nil, and so you're not actually executing the addChildNode call. Check to make sure the camera node exists before adding a child to it. (I tried adding this code to the sample code from the ARKit WWDC17 session — if you put it in their ARSCNView.setup() function, you should see any virtual objects you place getting completely whited out by a bright spotlight.)

By the way, you don't necessarily need to add a child node to the pointOfView node to hold a light — the pointOfView node can have both a camera and a light attached.