问:
Validation and rejection on accepts_nested_attributes
I'm having trouble wrapping my head around accepts_nested_attributes_for and the best way to integrate it into my process.

I have a collection of Cartons which have a ProductCode and CartonNumber assigned through the ProductCarton join table. ProductCode and CartonNumber are unique, so whenever a new carton is created, the Carton is assigned to the respective ProductCarton id if it exists, otherwise it's created.

Example:

ProductCarton(1) = ProductCode1-CartonNumber1

ProductCarton(2) = ProductCode2-CartonNumber1

ProductCarton(3) = ProductCode1-CartonNumber2

etc

Now if a new Carton is created with ProductCode1-CartonNumber1, it's id is 1 as it already exists.

```<code>class ProductCarton < ApplicationRecord
  has_many :cartons
  # product_code and carton_number both contain a unique :name field
  belongs_to :product_code
  belongs_to :carton_number
</code>```

The reason for this is for the SaleOrder and SaleOrderRule model, A user can specify a ProductCarton and a quantity with which can be picked from, any Carton with the associated ID is eligible to be picked.

My problem begins here, I'm struggling on where and how to implement the validation for insert rules as a few things need to happen:

Resolve the entered ProductCode and CartonNumber to ProductCarton id (if there is one, otherwise display an error)

Check quantity specified is not greater than the number of Cartons in stock with the id of ProductCarton

So I have my SaleOrder controller accepting a list of nested parameters

```<code>     sale_order_rules_attributes: [
       :quantity,
       product_carton_attributes: [
         product_code_attributes: [
           :product_code
         ],
         carton_number_attributes: [
           :carton_number
         ]
       ]

     ])
</code>```

Obviously all this currently does is created a new set of everything if it doesn't exist, which isn't what i want to do, I'm just trying to find the "Rails" way to go about resolving the ProductCarton relationship and assigning it as well as properly handling the errors that can occur through the whole process, my initial attempt was resolving it in the SaleOrder model with a before_validation, but i couldn't figure out how to add/remove the rules if they didn't pass the requirements.

Sorry if this is a ramble, any help is much appreciated.

答:
Smth like</p>
```<code># controller

def create
  product_cartons = ProductCarton.where(...)
  @sale_order = SaleOrder.new(
    product_cartons = product_cartons
    ...
  )

  if @sale_order.save
    # render success
  else
    # validation failed, render errors
  end
end

# sale_order.rb

class SaleOrder
  validate :in_stock
  ...

  def in_stock
    unless product_cartons.each(&:in_stock?)
        errors.add(:product_cartons, :out_of_stock)
    end
  end
end
</code>```

Body:
I'm having trouble wrapping my head around accepts_nested_attributes_for and the best way to integrate it into my process.

I have a collection of Cartons which have a ProductCode and CartonNumber assigned through the ProductCarton join table. ProductCode and CartonNumber are unique, so whenever a new carton is created, the Carton is assigned to the respective ProductCarton id if it exists, otherwise it's created.

Example:

ProductCarton(1) = ProductCode1-CartonNumber1

ProductCarton(2) = ProductCode2-CartonNumber1

ProductCarton(3) = ProductCode1-CartonNumber2

etc

Now if a new Carton is created with ProductCode1-CartonNumber1, it's id is 1 as it already exists.

class ProductCarton < ApplicationRecord
  has_many :cartons
  # product_code and carton_number both contain a unique :name field
  belongs_to :product_code
  belongs_to :carton_number

The reason for this is for the SaleOrder and SaleOrderRule model, A user can specify a ProductCarton and a quantity with which can be picked from, any Carton with the associated ID is eligible to be picked.

My problem begins here, I'm struggling on where and how to implement the validation for insert rules as a few things need to happen:

Resolve the entered ProductCode and CartonNumber to ProductCarton id (if there is one, otherwise display an error)

Check quantity specified is not greater than the number of Cartons in stock with the id of ProductCarton

So I have my SaleOrder controller accepting a list of nested parameters

     sale_order_rules_attributes: [
       :quantity,
       product_carton_attributes: [
         product_code_attributes: [
           :product_code
         ],
         carton_number_attributes: [
           :carton_number
         ]
       ]

     ])

Obviously all this currently does is created a new set of everything if it doesn't exist, which isn't what i want to do, I'm just trying to find the "Rails" way to go about resolving the ProductCarton relationship and assigning it as well as properly handling the errors that can occur through the whole process, my initial attempt was resolving it in the SaleOrder model with a before_validation, but i couldn't figure out how to add/remove the rules if they didn't pass the requirements.

Sorry if this is a ramble, any help is much appreciated.

Body:
Smth like

# controller

def create
  product_cartons = ProductCarton.where(...)
  @sale_order = SaleOrder.new(
    product_cartons = product_cartons
    ...
  )

  if @sale_order.save
    # render success
  else
    # validation failed, render errors
  end
end

# sale_order.rb

class SaleOrder
  validate :in_stock
  ...

  def in_stock
    unless product_cartons.each(&:in_stock?)
        errors.add(:product_cartons, :out_of_stock)
    end
  end
end


来源: stackexchange

问:
IEnumerable<T> from Enumerable.FromRange().Select() vs ToList()
This really stumped me, as I expected 'pass by reference' behavior.  I expected this code to print "5,5,5", but instead it prints "7,7,7".

```<code>IEnumerable<MyObj> list = Enumerable.Range(0, 3).Select(x => new MyObj { Name = 7 });
Alter(list);
Console.WriteLine(string.Join(',',list.Select(x => x.Name.ToString())));
Console.ReadLine();

void Alter(IEnumerable<MyObj> list)
{
    foreach(MyObj obj in list)
    {
        obj.Name = 5;
    }
}

class MyObj
{
    public int Name { get; set; }
}
</code>```

Whereas this prints "7,7,7" as expected.

```<code>IEnumerable<MyObj> list = Enumerable.Range(0, 3).Select(x => new MyObj { Name = 7 }).ToList();
Alter(list);
Console.WriteLine(string.Join(',',list.Select(x => x.Name.ToString())));
Console.ReadLine();

void Alter(IEnumerable<MyObj> list)
{
    foreach(MyObj obj in list)
    {
        obj.Name = 5;
    }
}

class MyObj
{
    public int Name { get; set; }
}
</code>```

Obviously this is a simplified version of the actual code I was writing.  This feels a lot more like behavior I've run into with a property that instantiates a new instance of an object.  Here I understand why I would get a new instance every time I reference Mine.

```<code>public MyObj Mine => new MyObj();
</code>```

I was just very surprised to see this behavior in the above code, where it feels more like I've "locked in" the enumerated objects.  Can anyone help me understand this?

答:
Select produces an object that has lazy evaluation. This means all steps are executed on demand.

So, when this line gets executed:

```<code>IEnumerable<MyObj> list = Enumerable.Range(0, 3).Select(x => new MyObj { Name = 7 });
</code>```

no MyObj instance is created yet - only the enumerable that has all the information to compute what you've indicated.

When you call Alter, this gets executed during iteration via foreach and all objects get 5 assigned to their properties.

But when you print it, everything gets executed again here:

```<code>Console.WriteLine(string.Join(',',list.Select(x => x.Name.ToString())));
</code>```

So during execution of string.Join, brand new MyObj instances are created with new MyObj { Name = 7 } and printed.

ContentLicense: CC BY-SA 4.0

Body:
This really stumped me, as I expected 'pass by reference' behavior.  I expected this code to print "5,5,5", but instead it prints "7,7,7".

IEnumerable<MyObj> list = Enumerable.Range(0, 3).Select(x => new MyObj { Name = 7 });
Alter(list);
Console.WriteLine(string.Join(',',list.Select(x => x.Name.ToString())));
Console.ReadLine();

void Alter(IEnumerable<MyObj> list)
{
    foreach(MyObj obj in list)
    {
        obj.Name = 5;
    }
}

class MyObj
{
    public int Name { get; set; }
}

Whereas this prints "7,7,7" as expected.

IEnumerable<MyObj> list = Enumerable.Range(0, 3).Select(x => new MyObj { Name = 7 }).ToList();
Alter(list);
Console.WriteLine(string.Join(',',list.Select(x => x.Name.ToString())));
Console.ReadLine();

void Alter(IEnumerable<MyObj> list)
{
    foreach(MyObj obj in list)
    {
        obj.Name = 5;
    }
}

class MyObj
{
    public int Name { get; set; }
}

Obviously this is a simplified version of the actual code I was writing.  This feels a lot more like behavior I've run into with a property that instantiates a new instance of an object.  Here I understand why I would get a new instance every time I reference Mine.

public MyObj Mine => new MyObj();

I was just very surprised to see this behavior in the above code, where it feels more like I've "locked in" the enumerated objects.  Can anyone help me understand this?

Body:
Select produces an object that has lazy evaluation. This means all steps are executed on demand.

So, when this line gets executed:

IEnumerable<MyObj> list = Enumerable.Range(0, 3).Select(x => new MyObj { Name = 7 });

no MyObj instance is created yet - only the enumerable that has all the information to compute what you've indicated.

When you call Alter, this gets executed during iteration via foreach and all objects get 5 assigned to their properties.

But when you print it, everything gets executed again here:

Console.WriteLine(string.Join(',',list.Select(x => x.Name.ToString())));

So during execution of string.Join, brand new MyObj instances are created with new MyObj { Name = 7 } and printed.


问:
Bad UTF-8 without BOM encoding
I converted all my files to UTF-8 without BOM encoding using Notepad++. I have no problem with BOMs anymore but the UTF without BOM encoding is simply not working, it's as if my site was encoded in ANSI. All special characters display either as: Â, Ãš or Ã¡.

What can be the reason for this and how can I fix it?

http://chusmix.com/?ciudad=Pilar

Thanks

答:
You have to tell the browser to accept it as UTF-8 so it will properly parse multibyte characters. Add this meta tag in your  tag with the rest of your metas:

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

Update

For HTML5, use this tag instead:

<meta charset="utf-8">

ContentLicense: CC BY-SA 3.0

Title: Bad UTF-8 without BOM encoding

Body:
You have to tell the browser to accept it as UTF-8 so it will properly parse multibyte characters. Add this meta tag in your <head> tag with the rest of your metas:

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

Update

For HTML5, use this tag instead:

<meta charset="utf-8">


问:
Only one usage of each socket address (protocol/network address/port) is normally permitted when AppPool is recycled
I have a .net Core application hosted on IIS.
The application initializes WebSocketServer, by adding a wrapper class as a HostedService.
The hosted service execute the Start() method seen below on its StartAsync() and the Destroy() method on its StopAsync() method.
The problem that whenever the related application pool is recycled - the error in the title appears ("Only one usage of each socket address (protocol/network address/port) is normally permitted"). It happens because there is a new working process that starts-up and trying to use the ports of the socket before there is a shutdown of the current Working process which still use the socket with the same ports.
I'm trying to find a way of avoiding that situation, programmatically or by configuration.
Here is my code of the HostedService:

```<code>using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Linq;
using System.Net.WebSockets;
using WebSocketSharp.Server;

namespace XXXX
{
    public class WebsocketServerWrapper
    {
        // Thats an websocket server , he will host our service as web socket service.
        private static WebSocketServer wss;
        private static readonly object LockObject = new object();

        public static IConfiguration Config { get; set; }

        public static bool IsCreated()
        {
            return wss != null;
        }

        public static bool HasChannels()
        {
            if(IsCreated())
            {
                return wss.WebSocketServices.Paths.Any();
            }

            return false;
        }

        public static bool IsListening()
        {
            if (wss != null)
            {
                return wss.IsListening;
            }

            return false;
        }

        public static void AddChannel(string channel)
        {
            if (wss.WebSocketServices.Paths.Any((path) => path == channel) == false)
            {
                    wss.AddWebSocketService(channel,() => new <class that treats the socket behaviour itself>(Config));
            }
        }

        public static bool Start()
        {
            wss.Start();

            if (IsListening())
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool Destroy()
        {
             var isDestroyed = false;

            if(IsCreated())
            {
                removeWebSocketServices();
                wss.Stop();
                wss = null;
                isDestroyed = true;
            }

            return isDestroyed;
        }
        internal static void removeWebSocketServices()
        {
            var channels = wss?.WebSocketServices?.Paths?.ToList() ?? null;
            if (channels != null)
            {
                channels.ForEach(channel => { wss.RemoveWebSocketService(channel); channel = null; });
            }
        }

        public static bool CreateWSSServer()
        {
            bool isCreationSucceeded = false;

            if(!IsCreated())
            {
                lock(LockObject)
                {
                    try
                    {
                        var wssUrl = Config.GetValue<string>(<WebsocketServerUrl adress>);

                        wss = new WebSocketServer($"ws://{wssUrl}");
                        isCreationSucceeded = true;
                    }
                    catch (WebSocketException wse)
                    {
                        Debug.WriteLine(wse);
                        return isCreationSucceeded;
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e);
                        return isCreationSucceeded;
                    }
                }
            }

            isCreationSucceeded = true;

            return isCreationSucceeded;
        }

    }
}
</code>```

答: I found a solution to that scenario (edited it in the question) - it turns out that the scenario of the server starts-up with new worker process before the "old" worker process shutdown  is not rare - there is a parameter in the application pool under Recycling => Disable Overlapped Recycle - if it set to true (it is false by default), then the startup with new Working process will occur only after the current worker process will shut-down

Body:
I have a .net Core application hosted on IIS.
The application initializes WebSocketServer, by adding a wrapper class as a HostedService.
The hosted service execute the Start() method seen below on its StartAsync() and the Destroy() method on its StopAsync() method.
The problem that whenever the related application pool is recycled - the error in the title appears ("Only one usage of each socket address (protocol/network address/port) is normally permitted"). It happens because there is a new working process that starts-up and trying to use the ports of the socket before there is a shutdown of the current Working process which still use the socket with the same ports.
I'm trying to find a way of avoiding that situation, programmatically or by configuration.
Here is my code of the HostedService:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Linq;
using System.Net.WebSockets;
using WebSocketSharp.Server;

namespace XXXX
{
    public class WebsocketServerWrapper
    {
        // Thats an websocket server , he will host our service as web socket service.
        private static WebSocketServer wss;
        private static readonly object LockObject = new object();

        public static IConfiguration Config { get; set; }

        public static bool IsCreated()
        {
            return wss != null;
        }

        public static bool HasChannels()
        {
            if(IsCreated())
            {
                return wss.WebSocketServices.Paths.Any();
            }

            return false;
        }

        public static bool IsListening()
        {
            if (wss != null)
            {
                return wss.IsListening;
            }

            return false;
        }

        public static void AddChannel(string channel)
        {
            if (wss.WebSocketServices.Paths.Any((path) => path == channel) == false)
            {
                    wss.AddWebSocketService(channel,() => new <class that treats the socket behaviour itself>(Config));
            }
        }

        public static bool Start()
        {
            wss.Start();

            if (IsListening())
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool Destroy()
        {
             var isDestroyed = false;

            if(IsCreated())
            {
                removeWebSocketServices();
                wss.Stop();
                wss = null;
                isDestroyed = true;
            }

            return isDestroyed;
        }
        internal static void removeWebSocketServices()
        {
            var channels = wss?.WebSocketServices?.Paths?.ToList() ?? null;
            if (channels != null)
            {
                channels.ForEach(channel => { wss.RemoveWebSocketService(channel); channel = null; });
            }
        }

        public static bool CreateWSSServer()
        {
            bool isCreationSucceeded = false;

            if(!IsCreated())
            {
                lock(LockObject)
                {
                    try
                    {
                        var wssUrl = Config.GetValue<string>(<WebsocketServerUrl adress>);

                        wss = new WebSocketServer($"ws://{wssUrl}");
                        isCreationSucceeded = true;
                    }
                    catch (WebSocketException wse)
                    {
                        Debug.WriteLine(wse);
                        return isCreationSucceeded;
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e);
                        return isCreationSucceeded;
                    }
                }
            }

            isCreationSucceeded = true;

            return isCreationSucceeded;
        }

    }
}


问:
jQuery UI " $("#datepicker").datepicker is not a function"
When i use DatePicker, jQuery's UI plugin, in an existing .aspx page I get errors that:

```<code>$("#datepicker").datepicker is not a function
</code>```

However, when I copy and paste the same code that creates and uses the datePicker to an HTML file that's also in the same directory as the aspx page, it works flawlessly. This leads me to assume that there are some JS files in the aspx page that's preventing the datePicker or maybe jQuery's UI JS files to load properly.

Can anyone confirm my beliefs or provide any tips on finding the culprit that's interfering with jQuery's UI plugins?

答: referencing jQuery twice might cuase the issue.</p>

Body:
When i use DatePicker, jQuery's UI plugin, in an existing .aspx page I get errors that:

$("#datepicker").datepicker is not a function

However, when I copy and paste the same code that creates and uses the datePicker to an HTML file that's also in the same directory as the aspx page, it works flawlessly. This leads me to assume that there are some JS files in the aspx page that's preventing the datePicker or maybe jQuery's UI JS files to load properly.

Can anyone confirm my beliefs or provide any tips on finding the culprit that's interfering with jQuery's UI plugins?


问:
valid prop not works in the styled-component. It gives a warning
When the input is invalid, ErrorMassage should be shown. But not works, and warning about valid prop (unresolved variable valid):

```<code>import React, {useState} from 'react';
import ReactDOM from 'react-dom';
import styled from "styled-components";

const Div = styled.div``;
const Input = styled.input``;
const ErrorMessage = styled.p`
   display: ${props => props.valid ? 'block' : 'none'};
`;

function App(){
    const [value, setValue] = useState('');
    const [validity, setValidity] = useState(false);
    const handleChange = (e) => {
        setValue(e.target.value);
        setValidity(e.target.checkValidity() ? false : true);
    }
    return(
    <>
        <Div>
        <Input
        value = {value}
        onChange = {handleChange}
        >
        </Input>
        </Div>
        <ErrorMessage valid={validity}>Error</ErrorMessage>
    </>
    );
}

ReactDOM.render(<App />, document.getElementById('root'));
</code>```

This is my codesandbox: https://codesandbox.io/s/musing-fast-df2qt

Note to warning:

答:
shouldForwardProp

As the type error explained, valid is a invalid prop. You should use shouldForwardProp in your styled component so the valid prop does not get passed down to the p element.

https://styled-components.com/docs/api#shouldforwardprop

```<code>const ErrorMessage = styled('p', { shouldForwardProp: (prop) => prop !== 'valid'})`
  display: ${(props) => (props.valid ? "block" : "none")};
`;
</code>```

And your following check...

```<code> setValidity(e.target.checkValidity() ? false : true);
</code>```

Is the above really what you want? You will probably just want to set it to the following, which is the proper code style and naming.

```<code> setValidity(e.target.checkValidity());
</code>```

your styled component

This also brings to your styled component which is also, wrong (IMO)

```<code>display: ${(props) => (props.valid ? "block" : "none")};
</code>```

should probably be, the following, since you only want to display when valid === false

```<code>display: ${(props) => (props.valid ? "none" : "block")};
</code>```

Body:
When the input is invalid, ErrorMassage should be shown. But not works, and warning about valid prop (unresolved variable valid):

import React, {useState} from 'react';
import ReactDOM from 'react-dom';
import styled from "styled-components";

const Div = styled.div``;
const Input = styled.input``;
const ErrorMessage = styled.p`
   display: ${props => props.valid ? 'block' : 'none'};
`;

function App(){
    const [value, setValue] = useState('');
    const [validity, setValidity] = useState(false);
    const handleChange = (e) => {
        setValue(e.target.value);
        setValidity(e.target.checkValidity() ? false : true);
    }
    return(
    <>

        <Input
        value = {value}
        onChange = {handleChange}
        >
        </Input>

        <ErrorMessage valid={validity}>Error</ErrorMessage>
    </>
    );
}

ReactDOM.render(<App />, document.getElementById('root'));

This is my codesandbox: https://codesandbox.io/s/musing-fast-df2qt

Note to warning:

Body:
shouldForwardProp

As the type error explained, valid is a invalid prop. You should use shouldForwardProp in your styled component so the valid prop does not get passed down to the p element.

https://styled-components.com/docs/api#shouldforwardprop

const ErrorMessage = styled('p', { shouldForwardProp: (prop) => prop !== 'valid'})`
  display: ${(props) => (props.valid ? "block" : "none")};
`;

And your following check...

 setValidity(e.target.checkValidity() ? false : true);

Is the above really what you want? You will probably just want to set it to the following, which is the proper code style and naming.

 setValidity(e.target.checkValidity());

your styled component

This also brings to your styled component which is also, wrong (IMO)

display: ${(props) => (props.valid ? "block" : "none")};

should probably be, the following, since you only want to display when valid === false

display: ${(props) => (props.valid ? "none" : "block")};


问:
What is DDD's Aggregate in SpringBoot MVC?
Suppose I've a bunch of microservices, each written on SpringBoot MVC (REST, Controller, Service, etc..)

Can anybody explain what is DDD's Aggregate in SpringBoot MVC? is it a controller? Or is it a specific microservice which is a root for some other microservices?

In other words, is aggregate something within a service with a controller's endpoint as a root? or is aggregate a sub-set of microservices with a particular SpringBoot application/service as an entry point to them?

答:
Two things here.

Spring MVC is a boundary layer to translate between HTTP and internals of the app. The internals are where all the DDD happens, not the boundary itself

Spring Boot is for bootstrapping an application with all the common tools and making a runnable deployment unit.

So, in case of DDD an HTTP request comes to Spring MVC layer, there a domain request is instantiated and passed to domain core for execution. Domain response then comes back and is translated into HTTP response by Spring MVC layer.


问:
Jobs stuck in "waiting" in bull queue node.js
I had a bunch of jobs in bull queue when one got stuck for 1+ hours (normally takes ~2 minutes to run), but didn't fail. I was unable to remove the job from the active state with the bull arena UI that I use, so I deleted the key of the active job in Redis.

That removed the stuck active job, but now the queue isn't pulling any jobs off of the waiting list.

Any ideas? Any thoughts on how to fix it?

答:
I faced similar issue a moment ago. However, I was able to overcome the challenge by changing the order of my program functions that did specific task such as defining the queue, adding to the queue and defining a process.

Initially I had a flow like this

Create queue

Define the process

Add to the queue

But after facing the issue I changed it to

Create queue

Add to the queue

Define the process


问:
Flutter convert Byte to String
So that you have all the context... in python I run the following code:
https://www.delftstack.com/es/howto/python/convert-string-to-ascii-python/

```<code>def to_ascii(text):
    ascii_values = [ord(character) for character in text]
    return ascii_values
text = input("Enter a string: ")
print(to_ascii(text))
</code>```

If I write "hello" it throws me the following:
[104, 101, 108, 108, 111]

My problem is with Flutter. I get that value and since I don't know flutter I don't know how to put it to text (utf8).

```<code>builder: (c, snapshot) {
   final value = snapshot.data;

...

subtitle: Text(value.toString()),
</code>```

value.toString() return [104, 101, 108, 108, 111]

How do I put it in utf8 ("Hello")?

Complete code:

```<code>@override
  Widget build(BuildContext context) {
    return StreamBuilder<List<int>>(
      stream: characteristic.value,
      initialData: characteristic.lastValue,
      builder: (c, snapshot) {
        final value = snapshot.data;

        //convert value ascii to utf8
        //var decoded = utf8.decode(value);

        return ExpansionTile(
          title: ListTile(
            title: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text('Characteristic'),
                Text(
                    '0x${characteristic.uuid.toString().toUpperCase().substring(4, 8)}',
                    style: Theme.of(context).textTheme.bodyText1?.copyWith(
                        color: Theme.of(context).textTheme.caption?.color))
              ],
            ),
            subtitle: Text(value),
            contentPadding: EdgeInsets.all(0.0),
          ),
          trailing: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              IconButton(
                icon: Icon(
                  Icons.lightbulb_outline,
                  color: Theme.of(context).iconTheme.color?.withOpacity(0.5),
                ),
                onPressed: turnOff,
              ),
              IconButton(
                icon: Icon(Icons.lightbulb,
                    color: Theme.of(context).iconTheme.color?.withOpacity(0.5)),
                onPressed: turnOn,
              ),
              //iconButton for add
              IconButton(
                icon: Icon(
                  Icons.add_circle,
                  color: Theme.of(context).iconTheme.color?.withOpacity(0.5),
                ),
                onPressed: extraButton,
              ),
              IconButton(
                icon: Icon(
                    characteristic.isNotifying
                        ? Icons.sync_disabled
                        : Icons.sync,
                    color: Theme.of(context).iconTheme.color?.withOpacity(0.5)),
                onPressed: onNotificationPressed,
              )
            ],
          ),
          children: descriptorTiles,
        );
      },
    );
  }
}
</code>```

答:
```<code>import 'dart:convert' show utf8;
var decoded = utf8.decode(value);
</code>```

See also https://api.dartlang.org/stable/1.24.3/dart-convert/UTF8-constant.html

There are also encoder and decoder to be used with streams

```<code>File.openRead().transform(utf8.decoder).
See also
</code>```

https://www.dartlang.org/articles/libraries/converters-and-codecs#converter

Title: Flutter convert Byte to String

Body:
So that you have all the context... in python I run the following code:
https://www.delftstack.com/es/howto/python/convert-string-to-ascii-python/

def to_ascii(text):
    ascii_values = [ord(character) for character in text]
    return ascii_values
text = input("Enter a string: ")
print(to_ascii(text))

If I write "hello" it throws me the following:
[104, 101, 108, 108, 111]

My problem is with Flutter. I get that value and since I don't know flutter I don't know how to put it to text (utf8).

builder: (c, snapshot) {
   final value = snapshot.data;

...

subtitle: Text(value.toString()),

value.toString() return [104, 101, 108, 108, 111]

How do I put it in utf8 ("Hello")?

Complete code:

@override
  Widget build(BuildContext context) {
    return StreamBuilder<List<int>>(
      stream: characteristic.value,
      initialData: characteristic.lastValue,
      builder: (c, snapshot) {
        final value = snapshot.data;

        //convert value ascii to utf8
        //var decoded = utf8.decode(value);

        return ExpansionTile(
          title: ListTile(
            title: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text('Characteristic'),
                Text(
                    '0x${characteristic.uuid.toString().toUpperCase().substring(4, 8)}',
                    style: Theme.of(context).textTheme.bodyText1?.copyWith(
                        color: Theme.of(context).textTheme.caption?.color))
              ],
            ),
            subtitle: Text(value),
            contentPadding: EdgeInsets.all(0.0),
          ),
          trailing: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              IconButton(
                icon: Icon(
                  Icons.lightbulb_outline,
                  color: Theme.of(context).iconTheme.color?.withOpacity(0.5),
                ),
                onPressed: turnOff,
              ),
              IconButton(
                icon: Icon(Icons.lightbulb,
                    color: Theme.of(context).iconTheme.color?.withOpacity(0.5)),
                onPressed: turnOn,
              ),
              //iconButton for add
              IconButton(
                icon: Icon(
                  Icons.add_circle,
                  color: Theme.of(context).iconTheme.color?.withOpacity(0.5),
                ),
                onPressed: extraButton,
              ),
              IconButton(
                icon: Icon(
                    characteristic.isNotifying
                        ? Icons.sync_disabled
                        : Icons.sync,
                    color: Theme.of(context).iconTheme.color?.withOpacity(0.5)),
                onPressed: onNotificationPressed,
              )
            ],
          ),
          children: descriptorTiles,
        );
      },
    );
  }
}

Body:
import 'dart:convert' show utf8;
var decoded = utf8.decode(value);

See also https://api.dartlang.org/stable/1.24.3/dart-convert/UTF8-constant.html

There are also encoder and decoder to be used with streams

File.openRead().transform(utf8.decoder).
See also

https://www.dartlang.org/articles/libraries/converters-and-codecs#converter


问:
Can we get estimated plan of a statement in SQL Server as a select query result set OR automate SSMS - display estimated plan command via .NET
Using SSMS for the following statement I can see the estimated plan using Display Estimated Plan command.

```<code>select * from adventtureworks.table1;
</code>```

However if I need to get the estimated plan as a result set of select statement, what sql statements do I have to execute?

I need the result in xml format so that I can display in a .net app/ else is there a way to automate the SSMS Display Estimated Plan command via .NET?

答:
You can retrieve the estimated execution plan with:

```<code>SET SHOWPLAN_XML ON
</code>```

Note that with this option turned on, SQL is no longer executed.  The plan to execute it is generated and returned.

Body:
Using SSMS for the following statement I can see the estimated plan using Display Estimated Plan command.

select * from adventtureworks.table1;

However if I need to get the estimated plan as a result set of select statement, what sql statements do I have to execute?

I need the result in xml format so that I can display in a .net app/ else is there a way to automate the SSMS Display Estimated Plan command via .NET?

Body:
You can retrieve the estimated execution plan with:

SET SHOWPLAN_XML ON

Note that with this option turned on, SQL is no longer executed.  The plan to execute it is generated and returned.


问:
rigidbody.velocity assign attempt for 'gameobject' is not valid. Input velocity is {NaN, NaN, NaN}
I am working on a game in Unity and I am currently getting this error when pulling up my menu.

Here is the script

```<code>private void OnAnimatorMove()
    {
        float delta = Time.deltaTime;
        enemyManager.enemyRigidBody.drag = 0;
        Vector3 deltaPosition = anim.deltaPosition;
        deltaPosition.y = 0;
        Vector3 velocity = deltaPosition / delta;
        enemyManager.enemyRigidBody.velocity = velocity;

    }
</code>```

答:
Sounds like OnAnimatorMove is also being called outside of PlayMode where Time.deltaTime most probably is simply 0

=> division by 0 => generally not a good thing to do ;)

You could probably avoid that by checking

```<code>private void OnAnimatorMove()
{
    if(! Application.isPlaying) return;

    ...
}
</code>```

or maybe

```<code>if(Mathf.Approximately(Time.deltaTime, 0f)) return;
</code>```

Also see this thread

Body:
I am working on a game in Unity and I am currently getting this error when pulling up my menu.

Here is the script

private void OnAnimatorMove()
    {
        float delta = Time.deltaTime;
        enemyManager.enemyRigidBody.drag = 0;
        Vector3 deltaPosition = anim.deltaPosition;
        deltaPosition.y = 0;
        Vector3 velocity = deltaPosition / delta;
        enemyManager.enemyRigidBody.velocity = velocity;

    }

Body:
Sounds like OnAnimatorMove is also being called outside of PlayMode where Time.deltaTime most probably is simply 0

=> division by 0 => generally not a good thing to do ;)

You could probably avoid that by checking

private void OnAnimatorMove()
{
    if(! Application.isPlaying) return;

    ...
}

or maybe

if(Mathf.Approximately(Time.deltaTime, 0f)) return;

Also see this thread


问:
What does AWS ECS exception Container.image contains invalid char means?
We use CircleCi in our workflow in order to deploy PHP site as docker image on ElasticBeanstalk server.
The build jobs in CircleCi is defined as follows:

```<code>deploy:
    docker:
      - image: docker:17.05.0-ce-git
    steps:
      - checkout
      - setup_remote_docker
      - run:
          name: Install dependencies
          command: |
            apk add --no-cache \
              py-pip=9.0.0-r1
            pip install \
              awscli \
              awsebcli --upgrade
      - run:
          name: Login to AWS
          command: |
            login="$(aws ecr get-login --no-include-email --region us-west-2)"
            ${login}
      - run:
          name: Deploy to Elastic Beanstalk
          command: |
            echo "Commit sha: ${CIRCLE_SHA1}"
            if [ "${CIRCLE_BRANCH}" == "docker" ]; then
              sed -i'' -e "s/%BUILD_NUM%/${CIRCLE_SHA1}/g" Dockerrun.aws.json
              eb deploy sales-web -l $CIRCLE_SHA1
            fi
</code>```

In Dockerrun.aws.json under containerDefinitions we have (#### are correct values for application id and repository name in ECS)

```<code>{
            "essential": true,
            "image": "####.dkr.ecr.us-west-2.amazonaws.com/####:%BUILD_NUM%",
            "memory": 2048,
            "name": "web-container",
            "portMappings": [
                {
                    "containerPort": 80,
                    "hostPort": 80
                }
            ]
        }
</code>```

The Login to AWS step is successful and image is uploaded, the environment sales-web starts to update but fails

```<code>2018-03-02 16:10:41 UTC+0200    ERROR   Failed to deploy application.
2018-03-02 16:10:41 UTC+0200    ERROR   Service:AmazonECS, Code:ClientException, Message:Container.image contains invalid characters., Class:com.amazonaws.services.ecs.model.ClientException
2018-03-02 16:09:52 UTC+0200    INFO    Environment update is starting.
</code>```

We have made sure that image is built correctly ( we can upload it ti CircleCi server, start the container and run phpunit tests). There is .elasticbeanstalk folder in root directory of project with valid config.yml file.

Have tried and googled for 2 days with no luck.
Will appreciate any help or guidence to understand what this error message means. If any additional details are neccessary I will provide them, just ask.

答:
I had a similar error returned when trying to deploy with Dockerrun.aws.json. For my case I had a space in the image name attribute as shown below. Make sure your Dockerrun.aws.json file is defined correctly</p>
```<code>{
    "AWSEBDockerrunVersion": 2,
    "volumes": [
      {
        "name": "demo-app",
        "host": {
          "sourcePath": "/var/app/current/demo-app"
        }
      }
    ],
    "containerDefinitions": [
      {
        "name": "demo-app",
        "image": " foo.dkr.ecr.me-south-1.amazonaws.com/foo:latest",
        "essential": true,
        "memory": 378,
        "links": ["redis"],
        "command": ["./entrypoint.sh"],
        "portMappings": [
          {
            "hostPort": 80,
            "containerPort": 5000
          }
        ],

        "mountPoints": [
          {
            "sourceVolume": "demo-app",
            "containerPath": "/src",
            "readOnly": true
          }
        ]
      },
    {
      "name": "redis",
      "image": "redis:latest",
      "essential": false,
      "memory": 128
  }
    ]
  }
</code>```

Body:
We use CircleCi in our workflow in order to deploy PHP site as docker image on ElasticBeanstalk server.
The build jobs in CircleCi is defined as follows:

deploy:
    docker:
      - image: docker:17.05.0-ce-git
    steps:
      - checkout
      - setup_remote_docker
      - run:
          name: Install dependencies
          command: |
            apk add --no-cache \
              py-pip=9.0.0-r1
            pip install \
              awscli \
              awsebcli --upgrade
      - run:
          name: Login to AWS
          command: |
            login="$(aws ecr get-login --no-include-email --region us-west-2)"
            ${login}
      - run:
          name: Deploy to Elastic Beanstalk
          command: |
            echo "Commit sha: ${CIRCLE_SHA1}"
            if [ "${CIRCLE_BRANCH}" == "docker" ]; then
              sed -i'' -e "s/%BUILD_NUM%/${CIRCLE_SHA1}/g" Dockerrun.aws.json
              eb deploy sales-web -l $CIRCLE_SHA1
            fi

In Dockerrun.aws.json under containerDefinitions we have (#### are correct values for application id and repository name in ECS)

{
            "essential": true,
            "image": "####.dkr.ecr.us-west-2.amazonaws.com/####:%BUILD_NUM%",
            "memory": 2048,
            "name": "web-container",
            "portMappings": [
                {
                    "containerPort": 80,
                    "hostPort": 80
                }
            ]
        }

The Login to AWS step is successful and image is uploaded, the environment sales-web starts to update but fails

2018-03-02 16:10:41 UTC+0200    ERROR   Failed to deploy application.
2018-03-02 16:10:41 UTC+0200    ERROR   Service:AmazonECS, Code:ClientException, Message:Container.image contains invalid characters., Class:com.amazonaws.services.ecs.model.ClientException
2018-03-02 16:09:52 UTC+0200    INFO    Environment update is starting.

We have made sure that image is built correctly ( we can upload it ti CircleCi server, start the container and run phpunit tests). There is .elasticbeanstalk folder in root directory of project with valid config.yml file.

Have tried and googled for 2 days with no luck.
Will appreciate any help or guidence to understand what this error message means. If any additional details are neccessary I will provide them, just ask.

Body:
I had a similar error returned when trying to deploy with Dockerrun.aws.json. For my case I had a space in the image name attribute as shown below. Make sure your Dockerrun.aws.json file is defined correctly

{
    "AWSEBDockerrunVersion": 2,
    "volumes": [
      {
        "name": "demo-app",
        "host": {
          "sourcePath": "/var/app/current/demo-app"
        }
      }
    ],
    "containerDefinitions": [
      {
        "name": "demo-app",
        "image": " foo.dkr.ecr.me-south-1.amazonaws.com/foo:latest",
        "essential": true,
        "memory": 378,
        "links": ["redis"],
        "command": ["./entrypoint.sh"],
        "portMappings": [
          {
            "hostPort": 80,
            "containerPort": 5000
          }
        ],

        "mountPoints": [
          {
            "sourceVolume": "demo-app",
            "containerPath": "/src",
            "readOnly": true
          }
        ]
      },
    {
      "name": "redis",
      "image": "redis:latest",
      "essential": false,
      "memory": 128
  }
    ]
  }


问:
docker compose file not working: replicas Additional property replicas is not allowed
docker version: 17.03.1-ce

Trying to get the docker-compose.yml working from the getting started tutorials.

```<code>version: "3"
   services:
     web:
       image: tuhina/friendlyhello:2.0
     deploy:
       replicas: 5
       resources:
         limits:
           cpus: "0.1"
           memory: 50M
      restart_policy:
        condition: on-failure
      ports:
        - "80:80"
      networks:
        - webnet
    networks:
      webnet:
</code>```

Getting this error:

```<code>replicas Additional property replicas is not allowed
</code>```

What have I typed in wrong?

Thanks.

edit: docker-compose version 1.11.2, build dfed245

答:
This happened to me because I was using docker-compose version 2 but my docker-compose.yml file was for version 1.

My docker-compose.yml file was initially like this:

```<code>web:
    image: nginx
    restart: always
</code>```

So when I would run docker-compose up , I was getting this error:

```<code>(root) Additional property web is not allowed
</code>```

I downgraded to docker-compose version 1 like this:

```<code>docker-compose disable-v2
</code>```

Now it was working. To get it to work for v2, first I enabled v2:

```<code>docker-compose enable-v2
</code>```

Then I updated my docker-compose.yml like below because docker-compose v2, web can not be the top/outermost value.

```<code>services:
  web:
    image: nginx
    restart: always
</code>```

I checked the version of docker-compose I was using:

```<code>docker-compose --version
</code>```

I found that I was running version v2.2.3 , before the upgrade it had been  1.29.2.

These days docker-compose comes as part of docker itself. Try below command:

```<code>docker compose version
</code>```

Body:
docker version: 17.03.1-ce

Trying to get the docker-compose.yml working from the getting started tutorials.

version: "3"
   services:
     web:
       image: tuhina/friendlyhello:2.0
     deploy:
       replicas: 5
       resources:
         limits:
           cpus: "0.1"
           memory: 50M
      restart_policy:
        condition: on-failure
      ports:
        - "80:80"
      networks:
        - webnet
    networks:
      webnet:

Getting this error:

replicas Additional property replicas is not allowed

What have I typed in wrong?

Thanks.

edit: docker-compose version 1.11.2, build dfed245

Body:
This happened to me because I was using docker-compose version 2 but my docker-compose.yml file was for version 1.

My docker-compose.yml file was initially like this:

web:
    image: nginx
    restart: always

So when I would run docker-compose up , I was getting this error:

(root) Additional property web is not allowed

I downgraded to docker-compose version 1 like this:

docker-compose disable-v2

Now it was working. To get it to work for v2, first I enabled v2:

docker-compose enable-v2

Then I updated my docker-compose.yml like below because docker-compose v2, web can not be the top/outermost value.

services:
  web:
    image: nginx
    restart: always

I checked the version of docker-compose I was using:

docker-compose --version

I found that I was running version v2.2.3 , before the upgrade it had been  1.29.2.

These days docker-compose comes as part of docker itself. Try below command:

docker compose version


问:
Serve springdoc swagger-ui in subdirectory nginx
I have read the docs about how to serve springdoc behind a reverse proxy (https://springdoc.org/index.html#how-can-i-deploy-springdoc-openapi-ui-behind-a-reverse-proxy) and also checked all of the questions about the topic but still having a problem.

I'm serving a spring-boot (2.6.2 version) application in a subdirectory with nginx:

```<code>location /subdirectory/ {
                proxy_pass http://127.0.0.1:8080/;
                proxy_redirect off;
                proxy_buffer_size 128k;
                proxy_buffers 4 256k;
                proxy_busy_buffers_size 256k;

                proxy_set_header Host $http_host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-Proto https;
                proxy_set_header X-Forwarded-Prefix "/subdirectory/";
                proxy_set_header X-Forwarded-Host $http_x_forwarded_host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-NginX-Proxy true;

                proxy_set_header X-Forwarded-Protocol https;
                proxy_set_header X-Forwarded-Ssl on;
                proxy_set_header X-Url-Scheme https;
        }
</code>```

I have also configured Spring Boot as per docs:

application.properties:

```<code>server.forward-headers-strategy=framework
server.tomcat.redirect-context-root=false
</code>```

When I visit my domain for a normal request to the Spring Boot API works fine, e.g.:

```<code>GET https://example.com/subdirectory/countries - OK 200 Returns the expected JSON
</code>```

But when I try to visit the springdoc swagger-ui with:

```<code>GET https://example.com/subdirectory/swagger-ui/index.html - OK 200
</code>```

I get a 200 OK but the .css and .js files requests return 404. I see a blank page and nothing about swagger. Am I missing something?

答:
I think you are missing forwarding filter.</p>
```<code>@Bean
ForwardedHeaderFilter forwardedHeaderFilter() {
   return new ForwardedHeaderFilter();
}
</code>```

Body:
I have read the docs about how to serve springdoc behind a reverse proxy (https://springdoc.org/index.html#how-can-i-deploy-springdoc-openapi-ui-behind-a-reverse-proxy) and also checked all of the questions about the topic but still having a problem.

I'm serving a spring-boot (2.6.2 version) application in a subdirectory with nginx:

location /subdirectory/ {
                proxy_pass http://127.0.0.1:8080/;
                proxy_redirect off;
                proxy_buffer_size 128k;
                proxy_buffers 4 256k;
                proxy_busy_buffers_size 256k;

                proxy_set_header Host $http_host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-Proto https;
                proxy_set_header X-Forwarded-Prefix "/subdirectory/";
                proxy_set_header X-Forwarded-Host $http_x_forwarded_host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-NginX-Proxy true;

                proxy_set_header X-Forwarded-Protocol https;
                proxy_set_header X-Forwarded-Ssl on;
                proxy_set_header X-Url-Scheme https;
        }

I have also configured Spring Boot as per docs:

application.properties:

server.forward-headers-strategy=framework
server.tomcat.redirect-context-root=false

When I visit my domain for a normal request to the Spring Boot API works fine, e.g.:

GET https://example.com/subdirectory/countries - OK 200 Returns the expected JSON

But when I try to visit the springdoc swagger-ui with:

GET https://example.com/subdirectory/swagger-ui/index.html - OK 200

I get a 200 OK but the .css and .js files requests return 404. I see a blank page and nothing about swagger. Am I missing something?

Body:
I think you are missing forwarding filter.

@Bean
ForwardedHeaderFilter forwardedHeaderFilter() {
   return new ForwardedHeaderFilter();
}


问:
How to fill/complete null/zero cells with a fixed number in an Excel table?
I have a table with some null/zero cells of a column.

I would like to replace the null/zero value with a fixed number such as 9999. Is there an automated way to do this in Excel?

答:
If its all about Zero and Null then Try following formula

```<code>=IFERROR(1/(1/(E2)),"9999")
</code>```

You can use any other formula by replacing E2 with your formula

Or you can use Custom Formatting, Select your Table Column, Press CTRL+1 Or Go to Custom Formatting and Click on Custom at the bottom of appeared window and in the custom bar put this format

```<code>0;-0;9999;"9999"
</code>```

Hope it works for you

Body:
If its all about Zero and Null then Try following formula

=IFERROR(1/(1/(E2)),"9999")

You can use any other formula by replacing E2 with your formula

Or you can use Custom Formatting, Select your Table Column, Press CTRL+1 Or Go to Custom Formatting and Click on Custom at the bottom of appeared window and in the custom bar put this format

0;-0;9999;"9999"

Hope it works for you


问:
Filter by a column value in a 3D matrix in R
Edit: I've included a reproducible example.

I am trying to do some simple operation in one of my matrices. My matrices are 3D arrays which contain capture-recapture data.

Rows are individuals
Columns from 1 to 7 are sampling occasions (years)
Column 8 sex of the individual: 1 males 2 females

```<code>libray(abind)
CH <- array(c(1,0,1,1,1,1,0), dim = c(5,7,10))
sex <- c(1,1,2,2,1)
CH_with_sex <- abind(CH, array(sex, replace(dim(CH), 2, 1)), along = 2)

CH_with_sex

, , 1

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    0    0    1    1    1
[2,]    0    0    1    1    1    1    1    1
[3,]    1    1    1    1    0    0    1    2
[4,]    1    0    0    1    1    1    1    2
[5,]    1    1    1    1    1    0    0    1

, , 2

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    0    0    1    1    1
[2,]    0    0    1    1    1    1    1    1
[3,]    1    1    1    1    0    0    1    2
[4,]    1    0    0    1    1    1    1    2
[5,]    1    1    1    1    1    0    0    1
</code>```
```<code>dim(CH_with_sex)
[1]  5  8 10
</code>```

My aim is to separate males and females from this 3D array and have 2 different arrays: one for the males and another one for females. I thought of making it by filtering for the column 8  but I can't find the way to do it. I end up breaking or losing the matrix structure. Any advice?

My desired output would be this for males:

```<code>, , 1

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    0    0    1    1    1
[2,]    0    0    1    1    1    1    1    1
[3,]    1    1    1    1    1    0    0    1

, , 2

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    0    0    1    1    1
[2,]    0    0    1    1    1    1    1    1
[3,]    1    1    1    1    1    0    0    1
</code>```

And this for females:

```<code>, , 1

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    1    0    0    1    2
[2,]    1    0    0    1    1    1    1    2

, , 2

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    1    0    0    1    2
[2,]    1    0    0    1    1    1    1    2
</code>```

答:
Here, x is your three-dimensional array CH_with_sex, and l is a list of two three-dimensional arrays splitting x by sex.

d <- dim(x)
f <- function(i) x[i, , , drop = FALSE]
l <- c(tapply(seq_len(d[1L]), x[, d[2L], 1L], f, simplify = FALSE))

dim(l[[1]])
## [1]  3  8 10
dim(l[[2]])
## [1]  2  8 10
```

Body:
Edit: I've included a reproducible example.

I am trying to do some simple operation in one of my matrices. My matrices are 3D arrays which contain capture-recapture data.

Rows are individuals
Columns from 1 to 7 are sampling occasions (years)
Column 8 sex of the individual: 1 males 2 females

libray(abind)
CH <- array(c(1,0,1,1,1,1,0), dim = c(5,7,10))
sex <- c(1,1,2,2,1)
CH_with_sex <- abind(CH, array(sex, replace(dim(CH), 2, 1)), along = 2)

CH_with_sex

, , 1

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    0    0    1    1    1
[2,]    0    0    1    1    1    1    1    1
[3,]    1    1    1    1    0    0    1    2
[4,]    1    0    0    1    1    1    1    2
[5,]    1    1    1    1    1    0    0    1

, , 2

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    0    0    1    1    1
[2,]    0    0    1    1    1    1    1    1
[3,]    1    1    1    1    0    0    1    2
[4,]    1    0    0    1    1    1    1    2
[5,]    1    1    1    1    1    0    0    1

dim(CH_with_sex)
[1]  5  8 10

My aim is to separate males and females from this 3D array and have 2 different arrays: one for the males and another one for females. I thought of making it by filtering for the column 8  but I can't find the way to do it. I end up breaking or losing the matrix structure. Any advice?

My desired output would be this for males:

, , 1

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    0    0    1    1    1
[2,]    0    0    1    1    1    1    1    1
[3,]    1    1    1    1    1    0    0    1

, , 2

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    0    0    1    1    1
[2,]    0    0    1    1    1    1    1    1
[3,]    1    1    1    1    1    0    0    1

And this for females:

, , 1

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    1    0    0    1    2
[2,]    1    0    0    1    1    1    1    2

, , 2

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    1    1    1    0    0    1    2
[2,]    1    0    0    1    1    1    1    2


问:
Line annotation from data on ggplotly object across facets
I have a ggplot bar graph which displays year on year population data from a certain location, and is faceted based on designation, e.g. Resident or Visitor:

(Some bins are empty because there is no data from that period, which is expected).

The bar graph will be converted to a ggplotly object in order to place in a shiny app, where the end user will be able to change the location with a picker, and will be faceted by Status, i.e. Resident and Visitor.

What I want is a line and text annotation on the ggplotly object which shows the number of unique people per location from the same dataframe as the bar chart, as in my paint.net example below, and it matches the appropriate Status, e.g. data comes from residents_from_census for residents, and visitors_from_census for the visitor facet:

The value of the y-axis can't be hardcoded in, because it will change as the user changes location.

Minimum reproducible example with dummy dataframe:

```<code>library(tidyverse)
library(plotly)

dummy <- data.frame(
  location = rep(c("317056", "317057"), 6),
  period = rep(c("2019_yoy", "2020_yoy", "2021_yoy"), 4),
  unique_agents = c(318, 219, NA, 1127, 34, 108, 2346, 113, 1546, 1112, NA, 0),
  Status = rep(c("Resident", "Visitor"), each = 6),
  visitors_from_census = rep(127, 12),
  residents_from_census = rep(643, 12)
) %>% mutate(
  period = as.factor(period)
)

graph.object <- dummy %>%
  filter(
    location == "317056"
  ) %>%
  arrange(
    period
  ) %>%
  ggplot(
    aes(
      x = period,
      y = unique_agents,
      fill = period
    )
  ) + geom_bar(
    stat = "identity",
    position = position_dodge()
  ) + facet_wrap(
    ~Status, ncol = 1
  )

# Convert to plotly object
ggplotly(graph.object)
</code>```

答:
You can add the horizontal line on the plot using geom_hline.

Here's what it will look like:

```<code>geom_bar(
    stat = "identity",
    position = position_dodge()
  ) +
  geom_hline(yintercept = dummy$unique_agents_from_census[1], show.legend = T) +
</code>```

And to annotate the line you can use either annotate or geom_text.

```<code>geom_text(aes(x = dummy$period[1], y = dummy$unique_agents_from_census[1] + 10, label = paste("Census location", dummy$unique_agents_from_census[1])))
</code>```

P.S: Please notice that I've passed only the first index in geom_hline and geom_text as you will need the same while moving to shiny.

The output:

EDIT
In Order to get the hline in the faceted plot, you'll need to manipulate the data frame a little bit.

I've added an extra column called yintercet so that it could be used in the hline.

Here's how you can do it:

```<code>dummy <- dummy %>%
  group_by(Status) %>%
  mutate(yintercept = ifelse((Status == "Resident"), residents_from_census[Status == "Resident"],
         visitors_from_census[Status == "Visitor"]))
</code>```

I've used ifelse to check is the Status. And based on it column yintercept is filled with appropriate values.

The plot can be plotted using the following code:

```<code>graph.object <- dummy %>%
  filter(
    location == "317056"
  ) %>%
  arrange(
    period
  ) %>%
  ggplot(
    aes(
      x = period,
      y = unique_agents,
      fill = period
    )
  ) + geom_bar(
    stat = "identity",
    position = position_dodge()
  ) +  facet_wrap(
    ~Status, ncol = 1
  ) +
  geom_hline(data = dummy, aes(yintercept = yintercept), show.legend = T) +
  geom_text(data = dummy, aes(x = period[1], y = yintercept + 50, label = paste(Status, "from census: ", yintercept)))

ggplotly(graph.object)
</code>```

Output:

Body:
I have a ggplot bar graph which displays year on year population data from a certain location, and is faceted based on designation, e.g. Resident or Visitor:

(Some bins are empty because there is no data from that period, which is expected).

The bar graph will be converted to a ggplotly object in order to place in a shiny app, where the end user will be able to change the location with a picker, and will be faceted by Status, i.e. Resident and Visitor.

What I want is a line and text annotation on the ggplotly object which shows the number of unique people per location from the same dataframe as the bar chart, as in my paint.net example below, and it matches the appropriate Status, e.g. data comes from residents_from_census for residents, and visitors_from_census for the visitor facet:

The value of the y-axis can't be hardcoded in, because it will change as the user changes location.

Minimum reproducible example with dummy dataframe:

library(tidyverse)
library(plotly)

dummy <- data.frame(
  location = rep(c("317056", "317057"), 6),
  period = rep(c("2019_yoy", "2020_yoy", "2021_yoy"), 4),
  unique_agents = c(318, 219, NA, 1127, 34, 108, 2346, 113, 1546, 1112, NA, 0),
  Status = rep(c("Resident", "Visitor"), each = 6),
  visitors_from_census = rep(127, 12),
  residents_from_census = rep(643, 12)
) %>% mutate(
  period = as.factor(period)
)

graph.object <- dummy %>%
  filter(
    location == "317056"
  ) %>%
  arrange(
    period
  ) %>%
  ggplot(
    aes(
      x = period,
      y = unique_agents,
      fill = period
    )
  ) + geom_bar(
    stat = "identity",
    position = position_dodge()
  ) + facet_wrap(
    ~Status, ncol = 1
  )

# Convert to plotly object
ggplotly(graph.object)

Body:
You can add the horizontal line on the plot using geom_hline.

Here's what it will look like:

geom_bar(
    stat = "identity",
    position = position_dodge()
  ) +
  geom_hline(yintercept = dummy$unique_agents_from_census[1], show.legend = T) +

And to annotate the line you can use either annotate or geom_text.

geom_text(aes(x = dummy$period[1], y = dummy$unique_agents_from_census[1] + 10, label = paste("Census location", dummy$unique_agents_from_census[1])))

P.S: Please notice that I've passed only the first index in geom_hline and geom_text as you will need the same while moving to shiny.

The output:

EDIT
In Order to get the hline in the faceted plot, you'll need to manipulate the data frame a little bit.

I've added an extra column called yintercet so that it could be used in the hline.

Here's how you can do it:

dummy <- dummy %>%
  group_by(Status) %>%
  mutate(yintercept = ifelse((Status == "Resident"), residents_from_census[Status == "Resident"],
         visitors_from_census[Status == "Visitor"]))

I've used ifelse to check is the Status. And based on it column yintercept is filled with appropriate values.

The plot can be plotted using the following code:

graph.object <- dummy %>%
  filter(
    location == "317056"
  ) %>%
  arrange(
    period
  ) %>%
  ggplot(
    aes(
      x = period,
      y = unique_agents,
      fill = period
    )
  ) + geom_bar(
    stat = "identity",
    position = position_dodge()
  ) +  facet_wrap(
    ~Status, ncol = 1
  ) +
  geom_hline(data = dummy, aes(yintercept = yintercept), show.legend = T) +
  geom_text(data = dummy, aes(x = period[1], y = yintercept + 50, label = paste(Status, "from census: ", yintercept)))

ggplotly(graph.object)

Output:


问:
Call to a member function givePermissionTo() on null
I'm trying to learn Spatie Laravel Permission Package. When trying to insert data to models has permissions table it gives the below error in postman. I don't know clearly how to insert data. I used the guide of spatie documentation.

error,

Call to a member function givePermissionTo() on null

here is my controller function

```<code>public function models()
    {

        Role::create(['name'=>'writer']);
        Permission::create(['name'=>'edit post']);

        Auth::id()->givePermissionTo('edit articles');

        return 'hello';
    }
</code>```

I don't know if the question is clear enough. Please tell me if it's not clear.

答:
Auth::id() return the id of the authenticated user, but you need to call givePermissionTo on a user object, not a user id.
try</p>
```<code>Auth::user()->givePermissionTo('edit articles');
</code>```

Body:
I'm trying to learn Spatie Laravel Permission Package. When trying to insert data to models has permissions table it gives the below error in postman. I don't know clearly how to insert data. I used the guide of spatie documentation.

error,

Call to a member function givePermissionTo() on null

here is my controller function

public function models()
    {

        Role::create(['name'=>'writer']);
        Permission::create(['name'=>'edit post']);

        Auth::id()->givePermissionTo('edit articles');

        return 'hello';
    }

I don't know if the question is clear enough. Please tell me if it's not clear.

Body:
Auth::id() return the id of the authenticated user, but you need to call givePermissionTo on a user object, not a user id.
try

Auth::user()->givePermissionTo('edit articles');


问:
Cloudfront serving over own SSL certificate
does anyone know if its possible to serve with cloudfront over https with your own certificate while using your own CNAME?
i can't even find a way to set up my own SSL cert over S3... so im not sure if this is even possible.

UPDATE: if someone is interested in an update about this issue - maxcdn.com offers to host your SSL cert on your domain for only $59 flat fee a month.

it's not amazon but it even supports pulling from your server and hosting forever or if you send a cache control header for whatever time you specify until it fetches the original url again.

the whole offer is pretty neat. :D

答:
PLEASE NOTE THE EDITS & UPDATES BELOW
I am resurrecting this because Amazon is running a survey (as of this writing) which asks customers on feedback for their produce roadmap.

<s>See the post on this survey being available:
https://forums.aws.amazon.com/thread.jspa?threadID=26488&tstart=30

and the direct survey link:
http://aws.qualtrics.com/SE/?SID=SV_9yvAN5PK8abJIFK</s>

EDIT: Noticed a post from June 11, 2012 that AWS had updated the survey link:

See the post on this survey being available:
https://forums.aws.amazon.com/thread.jspa?messageID=363869

New Survey Link:
http://aws.qualtrics.com/SE/?SID=SV_e4eM1cRblPaccFS

I think it is worth the time to provide them feedback about making CNAME + SSL a supported feature.

EDIT: Announced on June 11, 2013, custom SSL Certs with dedicated IPs are now supported with CloudFront on AWS:

See the feature announcement on the AWS Blog: http://aws.typepad.com/aws/2013/06/custom-ssl-domain-names-root-domain-hosting-for-amazon-cloudfront.html

One item of consideration before counting on going this route, you need to see significant value from deviating from the https://[distribution].cloudfront.net route as the pricing is $600 USD per month for hosting custom SSL certs.

EDIT: Announced on March 5, 2014, custom SSL Certs using Server Name Indication (SNI) are now supported with CloudFront on AWS -- NO ADDITIONAL CHARGE:

As wikichen noted below, AWS now supports custom SSL Certs via SNI. This is HUGE as it opens the possibility of leveraging AWS' existing infrastructure (IP addresses). As such, AWS does not charge extra for this service! To learn more, read about it on the AWS blog post: http://aws.typepad.com/aws/2014/03/server-name-indication-sni-and-http-redirection-for-amazon-cloudfront.html

One item that should be noted though, Server Name Indication (SNI) does have some drawbacks that should be considered before relying on it completely. In particular it is not supported by some older browsers. If want to understand this better, see: Is SNI actually used and supported in browsers?

EDIT: AWS announced on January 21, 2016, they supply custom SSL Certs for FREE!

To read about the full announcement on the AWS site: https://aws.amazon.com/blogs/aws/new-aws-certificate-manager-deploy-ssltls-based-apps-on-aws/

Amazon has announced a new service called AWS Certificate Manager, offering free SSL/TLS certificates for AWS resources.

These certificates are usually purchased from third-party certificate providers like Symantec, Comodo and RapidSSL and can cost anywhere from $50 to hundreds of dollars, depending on the level of identity verification performed.

The process of obtaining a new certificate has always been a bit messy, requiring the generation of a Certificate Signing Request on the server being protected, sending that request to a certificate provider, and then installing the certificate once it is received. Since Amazon is managing the whole process, all of that goes away and certificates can be quickly issued and provisioned on AWS resources automatically.

There are a few limitations to the certificates. Amazon only provides domain validated certificates, a simple verification where domain validation takes place via email. If you want an Extended Validation certificate, you may stick with their current certificate providers. In addition, the certificates cannot be used for code signing or email encryption.


问:
Best way to redirect all HTTP to HTTPS in IIS and redirect to FQDN
I've read https://serverfault.com/questions/893315/best-way-to-redirect-all-http-to-https-in-iis and IIS URL Rewrite for redirect to FQDN and was wondering what the best way was to combine the two to effectively redirect something like http://skateboarders to https://skateboarders.domain.com

Would it result in something like the below?

```<code><system.webServer>
  <rewrite>
    <globalRules>
      <rule name="Redirect to HTTPS" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
        <match url="*" ignoreCase="true" negate="false" />
        <conditions logicalGrouping="MatchAny" trackAllCaptures="false">
          <add input="{HTTPS}" ignoreCase="true" matchType="Pattern" negate="false" pattern="OFF" />
        </conditions>
        <action type="Redirect" url="https://skateboarders.domain.com/{REQUEST_URI}" appendQueryString="false" redirectType="Permanent" />
      </rule>
    </globalRules>
  </rewrite>
</system.webServer>
</code>```

or

```<code><rule name="Intranet redirect" stopProcessing="true">
    <match url="(.*)" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^intranet$" />
        <add input="{HTTPS}" pattern="^OFF$" />
    </conditions>
    <action type="Redirect" url="https://skateboarders.domain.com/{R:0}" />
</rule>
</code>```

答:
What about try this rule?</p>
```<code><rule name="ReverseProxyInboundRule1" stopProcessing="true">
                <match url="(.*)" />
                <action type="Redirect" url="https://skateboarders.domain.com/{R:1}" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="skateboarders" />
                    <add input="{HTTPS}" pattern="Off" />
                </conditions>
            </rule>
</code>```

Body:
I've read https://serverfault.com/questions/893315/best-way-to-redirect-all-http-to-https-in-iis and IIS URL Rewrite for redirect to FQDN and was wondering what the best way was to combine the two to effectively redirect something like http://skateboarders to https://skateboarders.domain.com

Would it result in something like the below?

<system.webServer>
  <rewrite>
    <globalRules>
      <rule name="Redirect to HTTPS" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
        <match url="*" ignoreCase="true" negate="false" />
        <conditions logicalGrouping="MatchAny" trackAllCaptures="false">
          <add input="{HTTPS}" ignoreCase="true" matchType="Pattern" negate="false" pattern="OFF" />
        </conditions>
        <action type="Redirect" url="https://skateboarders.domain.com/{REQUEST_URI}" appendQueryString="false" redirectType="Permanent" />
      </rule>
    </globalRules>
  </rewrite>
</system.webServer>

or

<rule name="Intranet redirect" stopProcessing="true">
    <match url="(.*)" />
    <conditions>
        <add input="{HTTP_HOST}" pattern="^intranet$" />
        <add input="{HTTPS}" pattern="^OFF$" />
    </conditions>
    <action type="Redirect" url="https://skateboarders.domain.com/{R:0}" />
</rule>

Body:
What about try this rule?

<rule name="ReverseProxyInboundRule1" stopProcessing="true">
                <match url="(.*)" />
                <action type="Redirect" url="https://skateboarders.domain.com/{R:1}" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="skateboarders" />
                    <add input="{HTTPS}" pattern="Off" />
                </conditions>
            </rule>


问:
The correct way to bundle CSS modules
I have a weird thing happening when my css modules are exported with the * as styles becomes inaccessible when I bundle my code and use it in other repo's.

The response from styles when bundled:

```<code>{default: {... my class names} }
</code>```

When I change my code to import styles from '...' it works when bundled because styles is the default but fails the tests because styles does not have access to the named exports.

rollup config.js

```<code>
import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import typescript from 'rollup-plugin-typescript2'
import { terser } from 'rollup-plugin-terser'
import postcss from 'rollup-plugin-postcss'
import postCssConfig from '@cinch-labs/postcss-config'
import pkg from './package.json'
import { designTokens, toJSON } from './src/tokens'

const extensions = ['.ts', '.tsx']

// stylelint does work but the postcss one needed to be removed
const postcssPlugins = postCssConfig(toJSON(designTokens)).filter(
  ({ postcssPlugin }: { postcssPlugin: string }) => postcssPlugin !== 'stylelint',
)

export default [
  {
    input: './src/index.ts',
    output: [
      {
        file: pkg.main,
        format: 'cjs',
      },
      {
        file: pkg.module,
        format: 'es',
      },
    ],
    plugins: [
      postcss({
        modules: true,
        extract: false,
        syntax: 'postcss-scss',
        plugins: postcssPlugins,
        use: ['sass'],
      }),
      resolve({
        extensions,
      }),
      commonjs(),
      typescript({ tsconfig: 'tsconfig.rollup.json' }),
      terser(),
    ],
    external: ['react', 'react-dom'],
  },
]

</code>```

test.component.tsx

```<code>import React from 'react'
import classNames from 'classnames'

// I expected the bundler to resolve this for me...
import * as styles from './text.module.scss'

import { TextProps } from './text.types'

export const Text: React.FC<TextProps> = ({
  children,
  fontSize = 'm',
  fontWeight = 'medium',
  fontStyle = 'normal',
  lineHeight = 'body',
  element = 'p',
  className,
  ...props
}) => {
  const HtmlEl = element

  const classes = classNames(
    {
      [styles[`textSize${fontSize.toUpperCase()}`]]: fontSize,
      [styles[`textWeight${fontWeight.toUpperCase()}`]]: fontWeight,
      [styles[`textLineHeight${lineHeight.toUpperCase()}`]]: lineHeight,
      [styles[`textFontStyle${fontStyle.toUpperCase()}`]]: fontStyle,
    },
    className,
  )

  // classes returns undefined when bundled because of commonjs format.

  return (
    <HtmlEl className={classes} {...props}>
      {children}
    </HtmlEl>
  )
}
</code>```

I know this is due to the way common JS works however I would expect for the import * as styles to work. When I change it to import styles from './text.module.scss' it works fine when bundled but does not work in tests.

答:
for me to compile and include with rollup.js the scss into the bundle/build worked adding:

```<code>plugins: [
      postcss({
        modules: true,
        extract: false,
        syntax: 'postcss-scss',
        use: ['sass'],
      }),
],
</code>```

Hope this will help someone else in this journey :)

Title: The correct way to bundle CSS modules

Body:
I have a weird thing happening when my css modules are exported with the * as styles becomes inaccessible when I bundle my code and use it in other repo's.

The response from styles when bundled:

{default: {... my class names} }

When I change my code to import styles from '...' it works when bundled because styles is the default but fails the tests because styles does not have access to the named exports.

rollup config.js

import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import typescript from 'rollup-plugin-typescript2'
import { terser } from 'rollup-plugin-terser'
import postcss from 'rollup-plugin-postcss'
import postCssConfig from '@cinch-labs/postcss-config'
import pkg from './package.json'
import { designTokens, toJSON } from './src/tokens'

const extensions = ['.ts', '.tsx']

// stylelint does work but the postcss one needed to be removed
const postcssPlugins = postCssConfig(toJSON(designTokens)).filter(
  ({ postcssPlugin }: { postcssPlugin: string }) => postcssPlugin !== 'stylelint',
)

export default [
  {
    input: './src/index.ts',
    output: [
      {
        file: pkg.main,
        format: 'cjs',
      },
      {
        file: pkg.module,
        format: 'es',
      },
    ],
    plugins: [
      postcss({
        modules: true,
        extract: false,
        syntax: 'postcss-scss',
        plugins: postcssPlugins,
        use: ['sass'],
      }),
      resolve({
        extensions,
      }),
      commonjs(),
      typescript({ tsconfig: 'tsconfig.rollup.json' }),
      terser(),
    ],
    external: ['react', 'react-dom'],
  },
]

test.component.tsx

import React from 'react'
import classNames from 'classnames'

// I expected the bundler to resolve this for me...
import * as styles from './text.module.scss'

import { TextProps } from './text.types'

export const Text: React.FC<TextProps> = ({
  children,
  fontSize = 'm',
  fontWeight = 'medium',
  fontStyle = 'normal',
  lineHeight = 'body',
  element = 'p',
  className,
  ...props
}) => {
  const HtmlEl = element

  const classes = classNames(
    {
      [styles[`textSize${fontSize.toUpperCase()}`]]: fontSize,
      [styles[`textWeight${fontWeight.toUpperCase()}`]]: fontWeight,
      [styles[`textLineHeight${lineHeight.toUpperCase()}`]]: lineHeight,
      [styles[`textFontStyle${fontStyle.toUpperCase()}`]]: fontStyle,
    },
    className,
  )

  // classes returns undefined when bundled because of commonjs format.

  return (
    <HtmlEl className={classes} {...props}>
      {children}
    </HtmlEl>
  )
}

I know this is due to the way common JS works however I would expect for the import * as styles to work. When I change it to import styles from './text.module.scss' it works fine when bundled but does not work in tests.

Body:
for me to compile and include with rollup.js the scss into the bundle/build worked adding:

plugins: [
      postcss({
        modules: true,
        extract: false,
        syntax: 'postcss-scss',
        use: ['sass'],
      }),
],

Hope this will help someone else in this journey :)


问:
Unable to log in with provided credentials django DRF
My first time trying django REST api , I am doing some athentification , now i facing this error whene i run this commande  :  [curl -X POST -d "username=&password=" http://127.0.0.1:8000/api/auth/login/]
error : {"non_field_errors":["Unable to log in with provided credentials."]}

views.py :

```<code>class CreateUserAPIView(CreateAPIView):
    serializer_class = CreateUserSerializer
    permission_classes = [AllowAny]

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        # We create a token than will be used for future auth
        token = Token.objects.create(user=serializer.instance)
        token_data = {"token": token.key}
        return Response(
            {**serializer.data, **token_data},
            status=status.HTTP_201_CREATED,
            headers=headers
        )

</code>```

serializers.py

```<code>class CreateUserSerializer(serializers.ModelSerializer):
    username = serializers.CharField()
    password = serializers.CharField(write_only=True,
                                     style={'input_type': 'password'})

    class Meta:
        model = get_user_model()
        fields = ('username', 'password', 'first_name', 'last_name')
        write_only_fields = ('password')
        read_only_fields = ('is_staff', 'is_superuser', 'is_active',)

    def create(self, validated_data):
        user = super(CreateUserSerializer, self).create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user

</code>```

urls.py

```<code>
urlpatterns = [
    path('auth/login/',
        obtain_auth_token,
        name='auth_user_login'),
    path('auth/register/',
        CreateUserAPIView.as_view(),
        name='auth_user_create'),
    path('auth/logout/',
        LogoutUserAPIView.as_view(),
        name='auth_user_logout')
]

</code>```

答:
Adding this in settings.py fixed it for me</p>
```<code>AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend"
)
</code>```

Body:
My first time trying django REST api , I am doing some athentification , now i facing this error whene i run this commande  :  [curl -X POST -d "username=&password=" http://127.0.0.1:8000/api/auth/login/]
error : {"non_field_errors":["Unable to log in with provided credentials."]}

views.py :

class CreateUserAPIView(CreateAPIView):
    serializer_class = CreateUserSerializer
    permission_classes = [AllowAny]

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        # We create a token than will be used for future auth
        token = Token.objects.create(user=serializer.instance)
        token_data = {"token": token.key}
        return Response(
            {**serializer.data, **token_data},
            status=status.HTTP_201_CREATED,
            headers=headers
        )

serializers.py

class CreateUserSerializer(serializers.ModelSerializer):
    username = serializers.CharField()
    password = serializers.CharField(write_only=True,
                                     style={'input_type': 'password'})

    class Meta:
        model = get_user_model()
        fields = ('username', 'password', 'first_name', 'last_name')
        write_only_fields = ('password')
        read_only_fields = ('is_staff', 'is_superuser', 'is_active',)

    def create(self, validated_data):
        user = super(CreateUserSerializer, self).create(validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user

urls.py

urlpatterns = [
    path('auth/login/',
        obtain_auth_token,
        name='auth_user_login'),
    path('auth/register/',
        CreateUserAPIView.as_view(),
        name='auth_user_create'),
    path('auth/logout/',
        LogoutUserAPIView.as_view(),
        name='auth_user_logout')
]

Body:
Adding this in settings.py fixed it for me

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend"
)


问:
Symfony console application: dependency injection
A Symfony novice here. After reading some of the Symfony documentation and some answers here at SO, I am now almost completely confused.
I am trying to use the console application component and create a small db-aware console application.

Many people state that in order to use Symfony's DI features it would be enough to inherit my command class not from Symfony\Component\Console\Command\Command but from ContainerAwareCommand.
However when I try this I get a Method Not Found error on an application::getKernel() call.

I have a feeling that DI features are in fact not available in a console application based on the console component. Is there another kind of Symfony console application, for example, based on the full-blown framework?

I very much like the simple framework provided by the console component Symfony\Component\Console\Application. But the question is then - what to do for dependency injection and DBAL? All examples that I find seem to refer to the full Symfony framework and get me just all the more stuck.

答:
You could use a solution I just pushed it to packagist.org. Includes full working symfony/dependency-injection. You're welcome to give it a shot. use composer to create your own project composer create-project coral-media/crune project_dir or just clone the repository.
https://packagist.org/packages/coral-media/crune
You only need to install DBAL dependencies (I don't suggest ORM if you don't really need it). Configure connection parameters in .env and just define a service to handle connection. That service can be injected in your Commands using public setMyService($myService) method with @required annotation. Also you could create a Connection class and bind is as parameter in your command constructor.The crune boilerplate also supports autowire and autoconfiguring features.


问:
Curl showing gzip but chrome showing no gzip header
```<code>curl -I -H 'Accept-Encoding: gzip,deflate' https://example.com/a.min.js

HTTP/1.1 200 OK
Server: nginx
Date: Thu, 22 Jun 2017 02:45:49 GMT
Content-Type: application/javascript; charset=utf-8
Content-Length: 5430
Connection: keep-alive
X-Accel-Version: 0.01
Last-Modified: Sat, 14 Jan 2017 12:50:18 GMT
Accept-Ranges: bytes
Vary: Accept-Encoding,User-Agent
Content-Encoding: gzip
X-Powered-By: PleskLin
Cache-Control: max-age=2628000, private
</code>```

Here it is very clear that file is gzipped but in case of chrome, pagespeed and gtmetrix they are mentioning this file is not compressed.
There is no content encoding in header when i view in chrome.

Also my homepage is being compressed with gzipp. when using varvy service they are saying your local files are not compressed.

I have enabled compression in nginx and apache both. also in .htaccess. but this is very weired.

答:
I think it has something to do with caching.

If I had to guess, I'd say each curl request grabs a fresh response from the server with gzip encoding. Chrome on the other hand, utilizes caching which seems to store the file after decompressing it. Chrome then serves you the decompressed file (no gzip encoding) from cache.

I ran into a similar problem with chrome dev tools, and noticed that the content-encoding header was included only when I disabled caching (or hard refreshed)

This forum goes a little more in-depth about it

Body:
curl -I -H 'Accept-Encoding: gzip,deflate' https://example.com/a.min.js

HTTP/1.1 200 OK
Server: nginx
Date: Thu, 22 Jun 2017 02:45:49 GMT
Content-Type: application/javascript; charset=utf-8
Content-Length: 5430
Connection: keep-alive
X-Accel-Version: 0.01
Last-Modified: Sat, 14 Jan 2017 12:50:18 GMT
Accept-Ranges: bytes
Vary: Accept-Encoding,User-Agent
Content-Encoding: gzip
X-Powered-By: PleskLin
Cache-Control: max-age=2628000, private

Here it is very clear that file is gzipped but in case of chrome, pagespeed and gtmetrix they are mentioning this file is not compressed.
There is no content encoding in header when i view in chrome.

Also my homepage is being compressed with gzipp. when using varvy service they are saying your local files are not compressed.

I have enabled compression in nginx and apache both. also in .htaccess. but this is very weired.


问:
Why will there be no native properties in Java 7?
Is there any rational reason, why native properties will not be part of Java 7?</p>

答:
Not enough time?

Not yet specced properly?

Difficult to add to java due to java's implementation?

Deemed not important enough, ie other things were prioritiesed?

OwnerDisplayName: bwalliser

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: willcodejavaforfood


问:
indexing keys AND related columns or just keys to increase speed in mysql
So if I have an sql query like these:

```<code>SELECT title, document FROM docs WHERE id = "1" and type = "2"

SELECT title FROM docs WHERE id = "1"

SELECT title FROM docs WHERE member = "foo"
</code>```

to maximize speed for the first one i. would I have to index only the keys (id and type together? seperate?) ii. would I also have to index title and document (together,separate)

same type of questions apply for the second one, and for the third query i. would I have to index only member?
IM just trying to understand mysql retrieval and indexing.

答:
1) Index both id and type together, but not title and document

2) Index id only

3) index member only

in other word you have to index {id}, {id, type}, {member}

Body:
So if I have an sql query like these:

SELECT title, document FROM docs WHERE id = "1" and type = "2"

SELECT title FROM docs WHERE id = "1"

SELECT title FROM docs WHERE member = "foo"

to maximize speed for the first one i. would I have to index only the keys (id and type together? seperate?) ii. would I also have to index title and document (together,separate)

same type of questions apply for the second one, and for the third query i. would I have to index only member?
IM just trying to understand mysql retrieval and indexing.


答:
@brombeer was right. the issue was in the Auth::id() It says the authenticated user is not accessed in.
I changed my function line Auth::id()->givePermissionTo('edit articles'); to auth()->user()->givePermissionTo('edit articles');. Also the called __construct() function like this,

```<code>public function __construct()
    {
        $this->middleware('auth');
    }
</code>```

Then I accessed as an authorized user and inserted log in the token as a bearer token in postman. Then the issue was fixed.

Title: Call to a member function givePermissionTo() on null

Body:
@brombeer was right. the issue was in the Auth::id() It says the authenticated user is not accessed in.
I changed my function line Auth::id()->givePermissionTo('edit articles'); to auth()->user()->givePermissionTo('edit articles');. Also the called __construct() function like this,

public function __construct()
    {
        $this->middleware('auth');
    }

Then I accessed as an authorized user and inserted log in the token as a bearer token in postman. Then the issue was fixed.


问:
"Method Not Allowed" error in Flask after submitting form data
After clicking on Submit in my form I am getting "Method Not Allowed
The method is not allowed for the requested URL."

The required code is below

hello.py

```<code>@app.route('/')
def home():
    return render_template("home.html")

@app.route('/register', methods=["GET", "POST"])
def register():

    if request.method == "POST":
#        data = {}
        name = request.form['name']
        place = request.form['place']
        descr = request.form['descr']
        email = request.form['email']
        collection.insert_one({'name': name, 'place': place, 'email': email, 'descr': descr})

    return render_template("register.html")
</code>```

register.html

```<code><form action="." method="post">

            <h1> COMPLAINT FORM </h1>

            <input class="box" type="text" name="name" id="name"
            placeholder="Name"  required /><br>

            <input class="box" type="place" name="place" id="place"
            placeholder="Place" required /><br>

            <input class="box" type="email" name="email" id="email"
            placeholder="E-Mail " required /><br>

            <input class="box" type="text" name="descr" id="descr"
            placeholder="Enter Description " required /><br>

            <input type="submit" id="submitDetails"
            name="submitDetails" value="Submit" /><br>

            </form>
</code>```

I also tried including a redirect link in form action="." but it throws the same error.

答:
The problem is in the way you want to redirect from the /register endpoint to the home. You want to post something to the home so the code should be as follows:

hello.py

@app.route('/', methods=["GET", "POST"])
def home():
    return render_template("home.html")

@app.route('/register', methods=["GET", "POST"])
def register():

    if request.method == "POST":
#        data = {}
        name = request.form['name']
        place = request.form['place']
        descr = request.form['descr']
        email = request.form['email']
        collection.insert_one({'name': name, 'place': place, 'email': email, 'descr': descr})

    return render_template("register.html")
```
<p><strong>register.html</strong></p>
<pre class="lang-html prettyprint-override"><code><form action="/" method="post">

            <h1> COMPLAINT FORM </h1>

            <input class="box" type="text" name="name" id="name"
            placeholder="Name"  required /><br>

            <input class="box" type="place" name="place" id="place"
            placeholder="Place" required /><br>

            <input class="box" type="email" name="email" id="email"
            placeholder="E-Mail " required /><br>

            <input class="box" type="text" name="descr" id="descr"
            placeholder="Enter Description " required /><br>

            <input type="submit" id="submitDetails"
            name="submitDetails" value="Submit" /><br>

            </form>
</code>```

Body:
After clicking on Submit in my form I am getting "Method Not Allowed
The method is not allowed for the requested URL."

The required code is below

hello.py

@app.route('/')
def home():
    return render_template("home.html")

@app.route('/register', methods=["GET", "POST"])
def register():

    if request.method == "POST":
#        data = {}
        name = request.form['name']
        place = request.form['place']
        descr = request.form['descr']
        email = request.form['email']
        collection.insert_one({'name': name, 'place': place, 'email': email, 'descr': descr})

    return render_template("register.html")

register.html

<form action="." method="post">

 COMPLAINT FORM

            <input class="box" type="text" name="name" id="name"
            placeholder="Name"  required />

            <input class="box" type="place" name="place" id="place"
            placeholder="Place" required />

            <input class="box" type="email" name="email" id="email"
            placeholder="E-Mail " required />

            <input class="box" type="text" name="descr" id="descr"
            placeholder="Enter Description " required />

            <input type="submit" id="submitDetails"
            name="submitDetails" value="Submit" />

            </form>

I also tried including a redirect link in form action="." but it throws the same error.

Body:
The problem is in the way you want to redirect from the /register endpoint to the home. You want to post something to the home so the code should be as follows:

hello.py

@app.route('/', methods=["GET", "POST"])
def home():
    return render_template("home.html")

@app.route('/register', methods=["GET", "POST"])
def register():

    if request.method == "POST":
#        data = {}
        name = request.form['name']
        place = request.form['place']
        descr = request.form['descr']
        email = request.form['email']
        collection.insert_one({'name': name, 'place': place, 'email': email, 'descr': descr})

    return render_template("register.html")

register.html

<form action="/" method="post">

            <h1> COMPLAINT FORM </h1>

            <input class="box" type="text" name="name" id="name"
            placeholder="Name"  required /><br>

            <input class="box" type="place" name="place" id="place"
            placeholder="Place" required /><br>

            <input class="box" type="email" name="email" id="email"
            placeholder="E-Mail " required /><br>

            <input class="box" type="text" name="descr" id="descr"
            placeholder="Enter Description " required /><br>

            <input type="submit" id="submitDetails"
            name="submitDetails" value="Submit" /><br>

            </form>