问:
How to indicate which model's field raised a ValidationError?
Let's say I have a simple Django model:

```<code>class Transaction(models.Model):
    description = models.CharField('description', max_length=150,
                                   validators=[MinLengthValidator(2, 'Description\'s min length is 2'), ])
    amount = models.DecimalField('amount', max_digits=10, decimal_places=2,
                                 validators=[MinValueValidator(1, 'Min value is 1'), ])
    user = models.ForeignKey(User)

    # to trigger model fields' validation
    def clean(self, *args, **kwargs):
        super(Transaction, self).clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Transaction, self).save(*args, **kwargs)
</code>```

And I'd like to have a unit test, which precisely checks whether ValidationError is raised by description field and not by amount field (or any other).

So I have this piece of test, which in a primitive way checks if description field is present in e.exception:

```<code>def test_model_requires_description_min_2_characters(self):
    with self.assertRaises(ValidationError) as e:
        Transaction.objects.create(description='a', amount="50", user=self.user1)
    err_dict = eval(str(e.exception))
    self.assertIn('description', err_dict.keys())
</code>```

But I don't really like to use eval() and I believe there is more elegant way to indicate the source of ValidationError. How can I do this?

EDIT: my model class also includes overriden clean() and save() methods, so validators are running fine.

答:
Not all ValidationError objects have an error_dict. We can derive that from the implementation of the constructor of the ValidationError [GitHub]. It depends on whether the message (the first parameter of the construct) is a dictionary.

What we can do however is use getattr(..) [Python-doc] for this, with a fallback value, like:

```<code>def test_model_requires_description_min_2_characters(self):
    with self.assertRaises(ValidationError) as e:
        Transaction.objects.create(description='a', amount="50", user=self.user1)
    self.assertIn('description', <b>getattr(</b>e.exception, <b>'err_dict', {})</b>)</code>```

So given the error_dict does not exists, we will let getattr(..) return an empty dictionary, and hence the assertIn fails.

We can also implement a utility function for this, like:

```<code>_singleton = object()

class SomeTestCase(TestCase):

    def <b>assertKeyInErrorDict</b>(self, key, error):
        error_dict = getattr(error, 'err_dict', _singleton)
        if error_dict is _singleton:
            self.fail('The error {} has no error_dict'.format(error))
        else:
            self.assertIn(key, error_dict)

    def test_model_requires_description_min_2_characters(self):
        with self.assertRaises(ValidationError) as e:
            Transaction.objects.create(description='a', amount="50", user=self.user1)
        self.<b>assertKeyInErrorDict</b>('description', e.exception)</code>```

You can thus ass such assertKeyInErrorDict in a utility class that provides extra assert functions, and then use it in all subclasses, removing a lot of boilerplate code.

Body:
Let's say I have a simple Django model:

class Transaction(models.Model):
    description = models.CharField('description', max_length=150,
                                   validators=[MinLengthValidator(2, 'Description\'s min length is 2'), ])
    amount = models.DecimalField('amount', max_digits=10, decimal_places=2,
                                 validators=[MinValueValidator(1, 'Min value is 1'), ])
    user = models.ForeignKey(User)

    # to trigger model fields' validation
    def clean(self, *args, **kwargs):
        super(Transaction, self).clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Transaction, self).save(*args, **kwargs)

And I'd like to have a unit test, which precisely checks whether ValidationError is raised by description field and not by amount field (or any other).

So I have this piece of test, which in a primitive way checks if description field is present in e.exception:

def test_model_requires_description_min_2_characters(self):
    with self.assertRaises(ValidationError) as e:
        Transaction.objects.create(description='a', amount="50", user=self.user1)
    err_dict = eval(str(e.exception))
    self.assertIn('description', err_dict.keys())

But I don't really like to use eval() and I believe there is more elegant way to indicate the source of ValidationError. How can I do this?

EDIT: my model class also includes overriden clean() and save() methods, so validators are running fine.

Body:
Not all ValidationError objects have an error_dict. We can derive that from the implementation of the constructor of the ValidationError [GitHub]. It depends on whether the message (the first parameter of the construct) is a dictionary.

What we can do however is use getattr(..) [Python-doc] for this, with a fallback value, like:

def test_model_requires_description_min_2_characters(self):
    with self.assertRaises(ValidationError) as e:
        Transaction.objects.create(description='a', amount="50", user=self.user1)
    self.assertIn('description', getattr(e.exception, 'err_dict', {}))

So given the error_dict does not exists, we will let getattr(..) return an empty dictionary, and hence the assertIn fails.

We can also implement a utility function for this, like:

_singleton = object()

class SomeTestCase(TestCase):

    def assertKeyInErrorDict(self, key, error):
        error_dict = getattr(error, 'err_dict', _singleton)
        if error_dict is _singleton:
            self.fail('The error {} has no error_dict'.format(error))
        else:
            self.assertIn(key, error_dict)

    def test_model_requires_description_min_2_characters(self):
        with self.assertRaises(ValidationError) as e:
            Transaction.objects.create(description='a', amount="50", user=self.user1)
        self.assertKeyInErrorDict('description', e.exception)

You can thus ass such assertKeyInErrorDict in a utility class that provides extra assert functions, and then use it in all subclasses, removing a lot of boilerplate code.


来源: stackexchange

问:
Running .NET Core project in docker targeting x86 throws System.BadImageFormatException
I'm trying to build a simple 32 bit .NET Core Project.
I found this: https://github.com/dotnet/core/issues/901 and it actually solves the issue if I build my project locally however it's not gonna work if I build the project using Dockerfile (docker container is linux).

Dockerfile (Default):

```<code>FROM microsoft/dotnet:2.2-runtime AS base
WORKDIR /app

FROM microsoft/dotnet:2.2-sdk AS build
WORKDIR /src
COPY TestDocker.csproj TestDocker/
RUN dotnet restore TestDocker/TestDocker.csproj
COPY . ./TestDocker
WORKDIR /src/TestDocker
RUN dotnet build TestDocker.csproj -c Release -o /app

FROM build AS publish
RUN dotnet publish TestDocker.csproj -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "TestDocker.dll"]
</code>```

CsProj (only PlatformTarget has been changed)

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>

</Project>
</code>```

Build finishes successfuly and when I try to run it using docker run I get

```<code>Unhandled Exception: System.BadImageFormatException: Could not load file or asse
mbly '/app/TestDocker.dll'. An attempt was made to load a program with an incorr
ect format.
</code>```

If I print dotnet --info inside build then it clearly uses x64 ->

```<code>RID: debian.9-x64
</code>```

I suspect that I need somehow to force x86 dotnet, is there a separate dotnet sdk 32 bit image which I can use?

答:
The official Microsoft container images are tagged as x86_64. So you are probably out of luck. Worse, .NET Core doesn't even do releases for x86.

One option is to do everything yourself:

Build .NET Core 2.2 for Debian for x86: https://github.com/liserdarts/dotnetcore-build-x86-Linux. You can use the debian 386 container image for this. Then save this somewhere.

Build a debian container image, and install the .NET Core 2.2 SDK that you built in step 1 in it. You can see how Microsoft constructs their container images and adapt that as much as possible.

Use this self-built container image instead of FROM microsoft/dotnet:2.2-sdk.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to build a simple 32 bit .NET Core Project.
I found this: https://github.com/dotnet/core/issues/901 and it actually solves the issue if I build my project locally however it's not gonna work if I build the project using Dockerfile (docker container is linux).

Dockerfile (Default):

FROM microsoft/dotnet:2.2-runtime AS base
WORKDIR /app

FROM microsoft/dotnet:2.2-sdk AS build
WORKDIR /src
COPY TestDocker.csproj TestDocker/
RUN dotnet restore TestDocker/TestDocker.csproj
COPY . ./TestDocker
WORKDIR /src/TestDocker
RUN dotnet build TestDocker.csproj -c Release -o /app

FROM build AS publish
RUN dotnet publish TestDocker.csproj -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "TestDocker.dll"]

CsProj (only PlatformTarget has been changed)

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <PlatformTarget>x86</PlatformTarget>
  </PropertyGroup>

</Project>

Build finishes successfuly and when I try to run it using docker run I get

Unhandled Exception: System.BadImageFormatException: Could not load file or asse
mbly '/app/TestDocker.dll'. An attempt was made to load a program with an incorr
ect format.

If I print dotnet --info inside build then it clearly uses x64 ->

RID: debian.9-x64

I suspect that I need somehow to force x86 dotnet, is there a separate dotnet sdk 32 bit image which I can use?


问:
Problem with Ofbiz and ftl templates
i'm new to Ofbiz, and i'm trying this HelloWorld tutorial.

I am using Ofbiz 10.04 and the error i'm getting is:

```<code>java.io.FileNotFoundException: Template component://common/webcommon/includes/htmlTemplate.ftl not found.
</code>```

I searched Google and all i found were pages with SVN commits. Can someone help me? Is there something wrong with my Ofbiz configuration?

htmlTemplate.ftl is here:

```<code>$ ls -l framework/common/webcommon/includes/htmlTemplate.ftl
-rw-r--r-- 1 pacorg users 4988 2011-04-08 10:25 framework/common/webcommon/includes/htmlTemplate.ftl
</code>```

Thank you very much!

答:
Ok, i solved it.

On controller.xml, i changed:

```<code><view-map name="main" type="ftl" page="main.ftl"/>
</code>```

To:

```<code><view-map name="main" type="ftl" page="component://hello1/webapp/hello1/main.ftl"/>
</code>```

And now it works.

I hope it will be helpful to someone.

ContentLicense: CC BY-SA 3.0

Title: Problem with Ofbiz and ftl templates

Body:
i'm new to Ofbiz, and i'm trying this HelloWorld tutorial.

I am using Ofbiz 10.04 and the error i'm getting is:

java.io.FileNotFoundException: Template component://common/webcommon/includes/htmlTemplate.ftl not found.

I searched Google and all i found were pages with SVN commits. Can someone help me? Is there something wrong with my Ofbiz configuration?

htmlTemplate.ftl is here:

$ ls -l framework/common/webcommon/includes/htmlTemplate.ftl
-rw-r--r-- 1 pacorg users 4988 2011-04-08 10:25 framework/common/webcommon/includes/htmlTemplate.ftl

Thank you very much!

Body:
Ok, i solved it.

On controller.xml, i changed:

<view-map name="main" type="ftl" page="main.ftl"/>

To:

<view-map name="main" type="ftl" page="component://hello1/webapp/hello1/main.ftl"/>

And now it works.

I hope it will be helpful to someone.


问:
Can not import wxPython (Mac)
I thought I'd move from using Tkinter to wxPython, but I'm having some troubles. All I get is this:

```<code>>>> import wx
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named wx
</code>```

I have installed wxPython. When I run the uninstaller I clearly see that wxPython IS installed:

```<code>  1.  wxPython3.0-osx-cocoa-py2.7                 3.0.0.0

Enter the number of the install to examine or 'Q' to quit:
</code>```

When I start Python I see that my version should match the version of wxPython:

```<code>Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
</code>```

I'm on OS X 10.7.5 32-bit.

Any help would be awesome! :)

答:
In my case it worked by resetting the brew environment to 2.7:</p>

```<code>brew link --overwrite python@2
</code>```

Title: Can not import wxPython (Mac)

Body:
I thought I'd move from using Tkinter to wxPython, but I'm having some troubles. All I get is this:

>>> import wx
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named wx

I have installed wxPython. When I run the uninstaller I clearly see that wxPython IS installed:

  1.  wxPython3.0-osx-cocoa-py2.7                 3.0.0.0

Enter the number of the install to examine or 'Q' to quit:

When I start Python I see that my version should match the version of wxPython:

Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

I'm on OS X 10.7.5 32-bit.

Any help would be awesome! :)

Body:
In my case it worked by resetting the brew environment to 2.7:

brew link --overwrite python@2


问:
Finding command output with the highest number in substring
I need to parse the output of a command and find the substring after the backslash (i.e. app-v2.zip) for the file with the highest version
In the below command output, I want to find app-v2.zip because v2 is the highest. I know this takes a combination of bash commands but haven't figured it out.

Command output:

```<code>gs://artifacts/app-v1.zip
gs://artifacts/app-v2.zip
</code>```

Desired variable value:

```<code>app-v2.zip
</code>```

答:
You can use for example basename to get the file name, sort -V to sort version numbers and tail to get the newest version.

your-command \
    | sort -V \
    | tail -n1 \
    | xargs basename
```

Body:
I need to parse the output of a command and find the substring after the backslash (i.e. app-v2.zip) for the file with the highest version
In the below command output, I want to find app-v2.zip because v2 is the highest. I know this takes a combination of bash commands but haven't figured it out.

Command output:

gs://artifacts/app-v1.zip
gs://artifacts/app-v2.zip

Desired variable value:

app-v2.zip


问:
Sum and joined column data in same query
I am using Oracle DB and have the following query which throws the error:

ORA-00937: not a single-group group function

Query:

```<code>select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText';
</code>```

If I try to access the following individually, it works. As in calling sum separately, ct.CREAT_TS separately and so on.

The issue seems to be calling sum in this query. I plan to capture the output in an Object (Java if relevant). I expected the query to output  following. Is it possible to achieve this?

```<code>CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   8
2019-04-02 02:56:14.530000    SOME_EVENT 2
</code>```

After Given answers, getting following results where the sum value is split per column:

```<code>CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   2
2019-04-02 02:56:14.530000    SOME_EVENT 2   6
</code>```

答:
You can use window functions to put the total sum on each row:

```<code>select ev.EVENT, ct.CREAT_TS, sum(ct.TOT_CT),
       sum(sum(ct.TOT_CT)) over ()
from REF_CT ct inner join
     EVENT ev
     on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
where ct.TX = 'SomeText'
group by ev.EVENT, ct.CREAT_TS;
</code>```

I don't really recommend putting the value on only one row, but you can do that with window functions:

```<code>select ev.EVENT, ct.CREAT_TS, sum(ct.TOT_CT),
       (case when 1 = row_number() over (partition by ev.event order by ct.CREAT_TS)
             then sum(sum(ct.TOT_CT)) over ()
        end)
from REF_CT ct inner join
     EVENT ev
     on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
where ct.TX = 'SomeText'
group by ev.EVENT, ct.CREAT_TS
order by ev.EVENT, ct.CREAT_TS;
</code>```

The order by is very important if you want the grand total on the first row defined by CREAT_TS.

Body:
I am using Oracle DB and have the following query which throws the error:

ORA-00937: not a single-group group function

Query:

select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText';

If I try to access the following individually, it works. As in calling sum separately, ct.CREAT_TS separately and so on.

The issue seems to be calling sum in this query. I plan to capture the output in an Object (Java if relevant). I expected the query to output  following. Is it possible to achieve this?

CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   8
2019-04-02 02:56:14.530000    SOME_EVENT 2

After Given answers, getting following results where the sum value is split per column:

CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   2
2019-04-02 02:56:14.530000    SOME_EVENT 2   6

Body:
You can use window functions to put the total sum on each row:

select ev.EVENT, ct.CREAT_TS, sum(ct.TOT_CT),
       sum(sum(ct.TOT_CT)) over ()
from REF_CT ct inner join
     EVENT ev
     on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
where ct.TX = 'SomeText'
group by ev.EVENT, ct.CREAT_TS;

I don't really recommend putting the value on only one row, but you can do that with window functions:

select ev.EVENT, ct.CREAT_TS, sum(ct.TOT_CT),
       (case when 1 = row_number() over (partition by ev.event order by ct.CREAT_TS)
             then sum(sum(ct.TOT_CT)) over ()
        end)
from REF_CT ct inner join
     EVENT ev
     on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
where ct.TX = 'SomeText'
group by ev.EVENT, ct.CREAT_TS
order by ev.EVENT, ct.CREAT_TS;

The order by is very important if you want the grand total on the first row defined by CREAT_TS.


问:
How to fix "warning: could not open directory" after "git add ." command on Mac OS X Maverick
I'm new to R and RStudio and am currently taking online classes to learn more about data science. In one of my lectures, I'm being asked to create a project in RStudio prior to creating a repository in github and linking the project with git. In order to make a pre-existing project interact with git, the instructions in my lecture are telling me to navigate to the directory containing my project file by using the "cd" command followed by the location of the file and file name. My project file is currently located on my desktop so I typed in "cd ~ /Desktop/temporary_no_version_control" however, the directory doesn't seem to change and remains set on the original location of the file which was in Users/savannahkeiffer. Just so I could complete the assignment, I re-located the file to my user file and tried to follow the rest of the instructions which told me to type "git init" followed by "git add ." which is where I run into the "warning: could not open directory" warning.

I have a macbook which runs on OS X Maverick. I went into my system preferences > security and privacy and selected Full Disk Access where I manually allowed terminal to have access to all the files on my laptop. However, after closing and re-opening RStudio and attempting the commands again, I got the same error.

This is what I entered when I tried to change the directory

```<code>Savannahs-MacBook-Air-2:~ savannahkeiffer$ cd ~
/Desktop/temporary_no_version_control

Savannahs-MacBook-Air-2:~ savannahkeiffer$ git init
Reinitialized existing Git repository in
/Users/savannahkeiffer/.git/
</code>```

And what I got when I changed the location of the project on my laptop in order to complete the assignment (after already giving access to terminal)

```<code>Savannahs-MacBook-Air-2:~ savannahkeiffer$ cd ~
/Users/savannahkeiffer/first project/temporary_no_version_control

Savannahs-MacBook-Air-2:~ savannahkeiffer$ git init
Reinitialized existing Git repository in
/Users/savannahkeiffer/.git/

Savannahs-MacBook-Air-2:~ savannahkeiffer$ git add .

warning: could not open directory 'Pictures/Photos
Library.photoslibrary/': Operation not permitted

warning: could not open directory 'Library/Application
Support/MobileSync/': Operation not permitted

warning: could not open directory 'Library/Application
Support/CallHistoryTransactions/': Operation not permitted

warning: could not open directory 'Library/Application
Support/com.apple.TCC/': Operation not permitted

warning: could not open directory 'Library/Application
Support/AddressBook/': Operation not permitted
</code>```

And so on.. Is this a directory problem or a "git add ." command problem?

答:
It looks like what happened is that when you typed the cd command, you left a space in between the tilde and the rest of the path, so you changed back into your home directory (represented by the tilde). Then, when you tried to do a git init, you tried to initialize your home directory as a Git repository, and then ran into the fact that macOS restricts some programs (in your case, not Terminal, but maybe still Git) from accessing certain directories.

In the shell, the tilde is just a fancy way of spelling the environment variable $HOME, which points to your home directory (in this case, /Users/savannahkeiffer), so it should immediately precede the rest of the path without a space in between.

The best thing to do in this case is switch into your project directory and then initialize a repository there:

```<code>cd ~/Desktop/temporary_no_version_control # note the lack of space after the tilde
git init
</code>```

If you didn't intend for your home directory to be a repository (i.e., you're not storing your dotfiles in a repository there), then you will probably also want to remove the .git directory from your home directory by running rm -fr ~/.git. Be careful when typing this, as rm removes data without prompting and an unfortunate space could result in all your data being deleted.

Body:
I'm new to R and RStudio and am currently taking online classes to learn more about data science. In one of my lectures, I'm being asked to create a project in RStudio prior to creating a repository in github and linking the project with git. In order to make a pre-existing project interact with git, the instructions in my lecture are telling me to navigate to the directory containing my project file by using the "cd" command followed by the location of the file and file name. My project file is currently located on my desktop so I typed in "cd ~ /Desktop/temporary_no_version_control" however, the directory doesn't seem to change and remains set on the original location of the file which was in Users/savannahkeiffer. Just so I could complete the assignment, I re-located the file to my user file and tried to follow the rest of the instructions which told me to type "git init" followed by "git add ." which is where I run into the "warning: could not open directory" warning.

I have a macbook which runs on OS X Maverick. I went into my system preferences > security and privacy and selected Full Disk Access where I manually allowed terminal to have access to all the files on my laptop. However, after closing and re-opening RStudio and attempting the commands again, I got the same error.

This is what I entered when I tried to change the directory

Savannahs-MacBook-Air-2:~ savannahkeiffer$ cd ~
/Desktop/temporary_no_version_control

Savannahs-MacBook-Air-2:~ savannahkeiffer$ git init
Reinitialized existing Git repository in
/Users/savannahkeiffer/.git/

And what I got when I changed the location of the project on my laptop in order to complete the assignment (after already giving access to terminal)

Savannahs-MacBook-Air-2:~ savannahkeiffer$ cd ~
/Users/savannahkeiffer/first project/temporary_no_version_control

Savannahs-MacBook-Air-2:~ savannahkeiffer$ git init
Reinitialized existing Git repository in
/Users/savannahkeiffer/.git/

Savannahs-MacBook-Air-2:~ savannahkeiffer$ git add .

warning: could not open directory 'Pictures/Photos
Library.photoslibrary/': Operation not permitted

warning: could not open directory 'Library/Application
Support/MobileSync/': Operation not permitted

warning: could not open directory 'Library/Application
Support/CallHistoryTransactions/': Operation not permitted

warning: could not open directory 'Library/Application
Support/com.apple.TCC/': Operation not permitted

warning: could not open directory 'Library/Application
Support/AddressBook/': Operation not permitted

And so on.. Is this a directory problem or a "git add ." command problem?

Body:
It looks like what happened is that when you typed the cd command, you left a space in between the tilde and the rest of the path, so you changed back into your home directory (represented by the tilde). Then, when you tried to do a git init, you tried to initialize your home directory as a Git repository, and then ran into the fact that macOS restricts some programs (in your case, not Terminal, but maybe still Git) from accessing certain directories.

In the shell, the tilde is just a fancy way of spelling the environment variable $HOME, which points to your home directory (in this case, /Users/savannahkeiffer), so it should immediately precede the rest of the path without a space in between.

The best thing to do in this case is switch into your project directory and then initialize a repository there:

cd ~/Desktop/temporary_no_version_control # note the lack of space after the tilde
git init

If you didn't intend for your home directory to be a repository (i.e., you're not storing your dotfiles in a repository there), then you will probably also want to remove the .git directory from your home directory by running rm -fr ~/.git. Be careful when typing this, as rm removes data without prompting and an unfortunate space could result in all your data being deleted.


问:
How to return an HTML <div> tag from a javascript function in React?
I am working on a React application where I am trying to render text on the screen when a button is clicked. I have defined a function onButtonClick which gets triggered whenever the button is clicked. However, the HTML that I am returning from the function is not rendered on the screen. I am in the learning stages of React so please excuse me if the question seems silly.</p>

```<code>class App extends Component {

constructor() {
  super();

  this.state = {
    blockno:0

  }
}

OnButtonClick = () => {
  this.setState({blockno: this.state.blockno + 1})
  return(
      <div>
          <h3>Some text</h3>
      </div>
    );

}

render() {
return(
    <div>
        <Button onButtonClick={this.OnButtonClick}/>
    </div>
    );
}

}

</code>```

答:
What I see is that you are trying to build a counter. The value that you're returning from the click handler function can't be rendered, instead you need to manage it in the render function as follow:

    class App extends Component {
      constructor() {
        super();

        this.state = {
          blockno: 0
        }
      }

      OnButtonClick = () => {
        this.setState(prevState => ({ blockno: prevState.blockno + 1 }));
      }

      render() {
        return(

            {this.state.blockno > 0 &&
some text {this.state.blockno}
}
            <Button onButtonClick={this.OnButtonClick} />

        );
      }
    }
```

Also note that the setState method is asynchronous, please read the documentation https://reactjs.org/docs/react-component.html#setstate

Body:
I am working on a React application where I am trying to render text on the screen when a button is clicked. I have defined a function onButtonClick which gets triggered whenever the button is clicked. However, the HTML that I am returning from the function is not rendered on the screen. I am in the learning stages of React so please excuse me if the question seems silly.

class App extends Component {

constructor() {
  super();

  this.state = {
    blockno:0

  }
}

OnButtonClick = () => {
  this.setState({blockno: this.state.blockno + 1})
  return(

Some text

    );

}

render() {
return(

        <Button onButtonClick={this.OnButtonClick}/>

    );
}

}

Body:
What I see is that you are trying to build a counter. The value that you're returning from the click handler function can't be rendered, instead you need to manage it in the render function as follow:

    class App extends Component {
      constructor() {
        super();

        this.state = {
          blockno: 0
        }
      }

      OnButtonClick = () => {
        this.setState(prevState => ({ blockno: prevState.blockno + 1 }));
      }

      render() {
        return(
          <div>
            {this.state.blockno > 0 && <div>some text {this.state.blockno}</div>}
            <Button onButtonClick={this.OnButtonClick} />
          </div>
        );
      }
    }

Also note that the setState method is asynchronous, please read the documentation https://reactjs.org/docs/react-component.html#setstate


问:
Conditional formatting - cells in a range that having matching values from another range
I'm in a few Discord servers that let users hold auctions of in-game items to be exchanged for an unofficial in-game currency.  Since some users will bid but fail to follow through on the trade, I have a way of marking that user (for my own personal records) as a bad trader.  What I'm trying to do is set up conditional formatting on the row of the auction information to highlight in a red color if the ID of the user (long ID not their tag) matches someone on that list.  I have conditional formatting set up to highlight the rows for other reasons and those work great.

Using an arrayFormula() in column L, I've included this code:

LOOKUP(D2:D,Discord!F2:F)

It lists either N/A or the Discord ID number of the user if there's a match.  I then hide that column and have the conditional formatting formula as "=$D2:$D=$L2:$L" to find matches.

What I would like to do is to accomplish the same result but without using a dedicated column to do it.  Simply put, conditional formatting that will return true when a value from one row in the range matches a value from any row in another range.

答:
You can try this custom formula:

=countif(INDIRECT("Discord!$F2:$F"),$D1)>0

See it working in this example sheet:

https://docs.google.com/spreadsheets/d/1izTh57D58QiG_SOx-IyQW5SLwtAb0FqvDopeArgRnog/edit?usp=sharing


问:
Saving list data in python
I am wondering how I can save whatever I added to a list when I close a python file. For example, in this "my contact" program that I wrote below, if I add information about 'Jane Doe', what could I do so that next time I open up the same file, Jane Doe still exists.  </p>

```<code>def main():
    myBook = Book([{"name": 'John Doe', "phone": '123-456-7890', "address": '1000 Constitution Ave'}])
class Book:
    def __init__(self, peoples):
        self.peoples = peoples
        self.main_menu()
    def main_menu(self):
        print('Main Menu')
        print('1. Display Contact Names')
        print('2. Search For Contacts')
        print('3. Edit Contact')
        print('4. New Contact')
        print('5. Remove Contact')
        print('6. Exit')
        self.selection = input('Enter a # form the menu: ')
        if (self.selection == "1"):
            self.display_names()
        if (self.selection == "2"):
            self.search()
        if (self.selection == "3"):
            self.edit()
        if (self.selection == "4"):
            self.new()
        if (self.selection == "5"):
            self.delete()
        if (self.selection == "6"):
            self.end()
    def display_names(self):
        for people in self.peoples:
                print("Name: " + people["name"])
        self.main_menu()
    def search(self):
        searchname = input('What is the name of your contact: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                print("Name: " + self.peoples[index]["name"])
                print("Address: " + self.peoples[index]["address"])
                print("Phone: " + self.peoples[index]["phone"])
        self.main_menu()
    def edit(self):
        searchname = input('What is the name of the contact that you want to edit: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)
                name = input('What is your name: ')
                address = input('What is your address: ')
                phone = input('What is your phone number: ')
                self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def new(self):
        name = input('What is your name: ')
        address = input('What is your address: ')
        phone = input('What is your phone number: ')
        self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def delete(self):
        searchname = input('What is the name of the contact that you want to delete: ')
        for index in reversed(range(len(self.peoples))):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)

            print(searchname, 'has been removed')
        self.main_menu()
    def end(self):
        print('Thank you for using the contact book, have a nice day')
        print('Copyright Carson147 2019©, All Rights Reserved')

main()
</code>```

答:
As evinced by the many other answers, there are many ways to do this, but I thought it was helpful to have a example.

By changing the top of your file as so, you can use the shelve module.

There are a variety of other things you can fix in your code if you are curious, you could try https://codereview.stackexchange.com/ if you want more feedback.

```<code>import shelve

def main():
    default = [
        {'name': 'John Doe', 'phone': '123-456-7890',
         'address': '1000 Constitution Ave'}
    ]
    with Book('foo', default=default) as myBook:
        myBook.main_menu()

class Book:
    def __init__(self, filename, default=None):
        if default is None:
            default = []
        self._db = shelve.open(filename)
        self.people = self._db.setdefault('people', default)

    def __enter__(self):
        return self

    def __exit__(self):
        self._db['people'] = self.people
        self._db.close()
</code>```

Title: Saving list data in python

Body:
I am wondering how I can save whatever I added to a list when I close a python file. For example, in this "my contact" program that I wrote below, if I add information about 'Jane Doe', what could I do so that next time I open up the same file, Jane Doe still exists.

def main():
    myBook = Book([{"name": 'John Doe', "phone": '123-456-7890', "address": '1000 Constitution Ave'}])
class Book:
    def __init__(self, peoples):
        self.peoples = peoples
        self.main_menu()
    def main_menu(self):
        print('Main Menu')
        print('1. Display Contact Names')
        print('2. Search For Contacts')
        print('3. Edit Contact')
        print('4. New Contact')
        print('5. Remove Contact')
        print('6. Exit')
        self.selection = input('Enter a # form the menu: ')
        if (self.selection == "1"):
            self.display_names()
        if (self.selection == "2"):
            self.search()
        if (self.selection == "3"):
            self.edit()
        if (self.selection == "4"):
            self.new()
        if (self.selection == "5"):
            self.delete()
        if (self.selection == "6"):
            self.end()
    def display_names(self):
        for people in self.peoples:
                print("Name: " + people["name"])
        self.main_menu()
    def search(self):
        searchname = input('What is the name of your contact: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                print("Name: " + self.peoples[index]["name"])
                print("Address: " + self.peoples[index]["address"])
                print("Phone: " + self.peoples[index]["phone"])
        self.main_menu()
    def edit(self):
        searchname = input('What is the name of the contact that you want to edit: ')
        for index in range(len(self.peoples)):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)
                name = input('What is your name: ')
                address = input('What is your address: ')
                phone = input('What is your phone number: ')
                self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def new(self):
        name = input('What is your name: ')
        address = input('What is your address: ')
        phone = input('What is your phone number: ')
        self.peoples.append({"name": name, "phone": phone, "address": address})
        self.main_menu()
    def delete(self):
        searchname = input('What is the name of the contact that you want to delete: ')
        for index in reversed(range(len(self.peoples))):
            if (self.peoples[index]["name"] == searchname):
                self.peoples.pop(index)

            print(searchname, 'has been removed')
        self.main_menu()
    def end(self):
        print('Thank you for using the contact book, have a nice day')
        print('Copyright Carson147 2019©, All Rights Reserved')

main()

Body:
As evinced by the many other answers, there are many ways to do this, but I thought it was helpful to have a example.

By changing the top of your file as so, you can use the shelve module.

There are a variety of other things you can fix in your code if you are curious, you could try https://codereview.stackexchange.com/ if you want more feedback.

import shelve

def main():
    default = [
        {'name': 'John Doe', 'phone': '123-456-7890',
         'address': '1000 Constitution Ave'}
    ]
    with Book('foo', default=default) as myBook:
        myBook.main_menu()

class Book:
    def __init__(self, filename, default=None):
        if default is None:
            default = []
        self._db = shelve.open(filename)
        self.people = self._db.setdefault('people', default)

    def __enter__(self):
        return self

    def __exit__(self):
        self._db['people'] = self.people
        self._db.close()


问:
how to trigger a change event on a selectwhen changing it's value programmatically
so, using pure Javascript and DOM:

```<code>const select = document.querySelector('#my-select')

select.addEventListener('change', function(){
  console.log('changed', this.value)
})

select.value = 'some value from an existing option'
// this changes the select correctly, but it doesn't trigger the event
</code>```

Is there any way to correctly do this, without jQuery?

答:
You can force triggering the change event this way:</p>

```<code>select.dispatchEvent(new Event('change'));
</code>```

Body:
so, using pure Javascript and DOM:

const select = document.querySelector('#my-select')

select.addEventListener('change', function(){
  console.log('changed', this.value)
})

select.value = 'some value from an existing option'
// this changes the select correctly, but it doesn't trigger the event

Is there any way to correctly do this, without jQuery?

Body:
You can force triggering the change event this way:

select.dispatchEvent(new Event('change'));


问:
@JsonFormat not working in nested object
I have a very simple bean:

```<code>public class StatusBean {

 private String name;
 @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")
 private Date startDate;
 @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")
 private Date endDate;

 public String getName() {
    return name;
 }
 public void setName(String name) {
    this.name = name;
 }
 public Date getStartDate() {
    return startDate;
 }
 public void setStartDate(Date startDate) {
    this.startDate = startDate;
 }
 public Date getEndDate() {
    return endDate;
 }
 public void setEndDate(Date endDate) {
    this.endDate = endDate;
 }
}
</code>```

And I wrap it in another bean that I use to wrap objects for nice json formatting with messages and stuff:

```<code>public class ResponseBean {

private boolean success = false;
private String message;
private Object data;

public boolean isSuccess() {
    return success;
}
public void setSuccess(boolean success) {
    this.success = success;
}
public String getMessage() {
    return message;
}
public void setMessage(String message) {
    this.message = message;
}
public Object getData() {
    return data;
}
public void setData(Object data) {
    this.data = data;
}
}
</code>```

In my controller, I set the Status bean inside the response bean with a setData();

Spring serializes this out in JSON format,  however the output for the date is not formatting. I am getting the standard "yyyy-MM-DD" format.

Am I doing something wrong?  How do I get this to work?

答:
Possibility not write object with ObjectMapper

new ObjectMapper().writeValueAsString(MyObject);
```

<p>Full code example</p>

<pre class="lang-java prettyprint-override"><code>public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println(objectMapper.writeValueAsString(new Foo(new java.util.Date())));
        System.out.println(objectMapper.writeValueAsString(new Foo(new java.sql.Date(System.currentTimeMillis()))));
    }

    static class Foo {

        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy", timezone="EST")
        private Date birthdate;

        public Foo() {

        }

        public Foo(Date birthdate) {
            this.birthdate = birthdate;
        }

        public Date getBirthdate() {
            return birthdate;
        }

    }
</code>```

Body:
I have a very simple bean:

public class StatusBean {

 private String name;
 @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")
 private Date startDate;
 @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="MM-dd-yyyy")
 private Date endDate;

 public String getName() {
    return name;
 }
 public void setName(String name) {
    this.name = name;
 }
 public Date getStartDate() {
    return startDate;
 }
 public void setStartDate(Date startDate) {
    this.startDate = startDate;
 }
 public Date getEndDate() {
    return endDate;
 }
 public void setEndDate(Date endDate) {
    this.endDate = endDate;
 }
}

And I wrap it in another bean that I use to wrap objects for nice json formatting with messages and stuff:

public class ResponseBean {

private boolean success = false;
private String message;
private Object data;

public boolean isSuccess() {
    return success;
}
public void setSuccess(boolean success) {
    this.success = success;
}
public String getMessage() {
    return message;
}
public void setMessage(String message) {
    this.message = message;
}
public Object getData() {
    return data;
}
public void setData(Object data) {
    this.data = data;
}
}

In my controller, I set the Status bean inside the response bean with a setData();

Spring serializes this out in JSON format,  however the output for the date is not formatting. I am getting the standard "yyyy-MM-DD" format.

Am I doing something wrong?  How do I get this to work?

Body:
Possibility not write object with ObjectMapper

new ObjectMapper().writeValueAsString(MyObject);

Full code example

public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println(objectMapper.writeValueAsString(new Foo(new java.util.Date())));
        System.out.println(objectMapper.writeValueAsString(new Foo(new java.sql.Date(System.currentTimeMillis()))));
    }

    static class Foo {

        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy", timezone="EST")
        private Date birthdate;

        public Foo() {

        }

        public Foo(Date birthdate) {
            this.birthdate = birthdate;
        }

        public Date getBirthdate() {
            return birthdate;
        }

    }


问:
Why does webpack proxy do not work (Access-Control-Allow-Origin error)?
So, I am trying to bypass CORS on the server by proxying my requests. I am using webpack and axios.
So, here is webpack dev server options:

```<code>devServer: {
            contentBase: './build/',
            historyApiFallback: true,
            hot: true,
            quiet: true,
            open: false,
            port,
            noInfo: false,
            clientLogLevel: 'error',
            proxy: {
                '/api/**': {
                    target: 'http://mydev.com',
                    changeOrigin: true,
                    secure: false
                }
            }
        }
</code>```

and axios:

```<code>const axiosInstance = axios.create({
    baseURL: 'http://mydev.com',
    timeout: 30000,
    headers: {
        'Content-Type': 'application/json',
        'X-AUTH-TOKEN':
            'my-token
    },
    data: {}
});
</code>```

But still my origin is localhost and option request does not go through. Hence I am have this error.

Just to clarify: I want to make request from localhost to mydev.com with JSON content and bypass CORS settings.

Thanks!

答:
Webpack's proxy option actually creates a small reverse proxy server, which connects to your target endpoint.
In this case, your app (axios instance) should connect to your proxy:</p>

```<code>const axiosInstance = axios.create({
    baseURL: 'localhost:3000/api' // your local server here
    ...
});
</code>```

Body:
So, I am trying to bypass CORS on the server by proxying my requests. I am using webpack and axios.
So, here is webpack dev server options:

devServer: {
            contentBase: './build/',
            historyApiFallback: true,
            hot: true,
            quiet: true,
            open: false,
            port,
            noInfo: false,
            clientLogLevel: 'error',
            proxy: {
                '/api/**': {
                    target: 'http://mydev.com',
                    changeOrigin: true,
                    secure: false
                }
            }
        }

and axios:

const axiosInstance = axios.create({
    baseURL: 'http://mydev.com',
    timeout: 30000,
    headers: {
        'Content-Type': 'application/json',
        'X-AUTH-TOKEN':
            'my-token
    },
    data: {}
});

But still my origin is localhost and option request does not go through. Hence I am have this error.

Just to clarify: I want to make request from localhost to mydev.com with JSON content and bypass CORS settings.

Thanks!

Body:
Webpack's proxy option actually creates a small reverse proxy server, which connects to your target endpoint.
In this case, your app (axios instance) should connect to your proxy:

const axiosInstance = axios.create({
    baseURL: 'localhost:3000/api' // your local server here
    ...
});


问:
cant import sendgrid after pip installing it
I tried using pip install sendgrid, but got this error:

Collecting sendgrid
    Using cached https://files.pythonhosted.org/packages/24/21/9bea4c51f949497cdce11f46fd58f1a77c6fcccd926cc1bb4e14be39a5c0/sendgrid-5.6.0-py2.py3-none-any.whl
  Requirement already satisfied: python-http-client>=3.0 in /home/avin/.local/lib/python2.7/site-packages (from sendgrid) (3.1.0)
  Installing collected packages: sendgrid
  Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/sendgrid-5.6.0.dist-info'
  Consider using the --user option or check the permissions.

I used the --user as suggested and it run ok:

Collecting sendgrid
    Using cached https://files.pythonhosted.org/packages/24/21/9bea4c51f949497cdce11f46fd58f1a77c6fcccd926cc1bb4e14be39a5c0/sendgrid-5.6.0-py2.py3-none-any.whl
  Requirement already satisfied: python-http-client>=3.0 in /home/avin/.local/lib/python2.7/site-packages (from sendgrid) (3.1.0)
  Installing collected packages: sendgrid
  Successfully installed sendgrid-5.6.0

However, now, when running IPython, I can't import sendgrid...

ImportError: No module named sendgrid

pip -V = pip 19.0.3

答:
This is a very useful command pip install --ignore-installed <package>

It will make your life easy :)


问:
To count the frequency of each word
There's a directory with a few text files. How do I count the frequency  of each word in each file? A word means a set of characters that can contain the letters, the digits and the underlining characters.</p>

答:
```<code>string input= File.ReadAllText(filename);
var arr = input.Split(' ');
// finding frequencies of words in a string
IDictionary<string, int> dict = new Dictionary<string, int>();
foreach (var item in arr)
{
    var count = 0;
    if (dict.TryGetValue(item, out count))
        dict[item] = ++a;
    else
        dict.Add(item, 1);
}
</code>```

Title: To count the frequency of each word


问:
How to get Google Sign in for Android working with Hosted Domains
I am having trouble working with Google Sign in for Android when setting the Hosted Domain parameter. When it is set, there is no restriction on what domain the user can sign in with, which contradicts the documentation.

I am expecting what Google does on a browser when the HD parameter is set on the request_uri, which limits the sign in to accounts only on that domain, however, I only get the generic sign-in flow which allows all accounts.

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .setHostedDomain("example.com")
            .requestIdToken("WEB_CLIENT_ID.apps.googleusercontent.com")
            .requestEmail()
            .build();

    // Build a GoogleSignInClient with the options specified by gso.
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);

    findViewById(R.id.sign_in_button).setOnClickListener(this);
}

@Override
public void onClick(View v) {
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
}
</code>```

Note: I am not looking for work arounds for this issue, such as checking the domain after signing as we are trying to address this issue due to user experience complaints.

答:
In order to enable sign in for specific domains you have to configure your project on https://console.cloud.google.com/apis/credentials

From my experience, and as far as I know, the setHostedDomain("example.com") option will not restrict the email input on the login screen, it will only restrict by showing you the email addresses with that domain already registered on the device.

Body:
I am having trouble working with Google Sign in for Android when setting the Hosted Domain parameter. When it is set, there is no restriction on what domain the user can sign in with, which contradicts the documentation.

I am expecting what Google does on a browser when the HD parameter is set on the request_uri, which limits the sign in to accounts only on that domain, however, I only get the generic sign-in flow which allows all accounts.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .setHostedDomain("example.com")
            .requestIdToken("WEB_CLIENT_ID.apps.googleusercontent.com")
            .requestEmail()
            .build();

    // Build a GoogleSignInClient with the options specified by gso.
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);

    findViewById(R.id.sign_in_button).setOnClickListener(this);
}

@Override
public void onClick(View v) {
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

Note: I am not looking for work arounds for this issue, such as checking the domain after signing as we are trying to address this issue due to user experience complaints.


问:
Interface returning null after doing search
RecyclerView is updated after the search and mCallback returns null but before search works correctly.

AdapterHistorico.java

```<code> package com.beliasdev.cadjobel.adapter;

 import android.content.Context;

 import android.content.DialogInterface;
 import android.support.v7.app.AlertDialog;
 import android.support.v7.widget.RecyclerView;
 import android.text.TextUtils;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.AdapterView;
 import android.widget.ArrayAdapter;
 import android.widget.EditText;
 import android.widget.ImageView;
 import android.widget.LinearLayout;
 import android.widget.Spinner;
 import android.widget.TextView;
 import android.widget.Toast;

 import com.beliasdev.cadjobel.R;
 import com.beliasdev.cadjobel.utility.DrawableHelper;
 import com.bumptech.glide.Glide;

 import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;

 public class AdapterHistorico extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Spinner spinner1;
    private String dateold;
    private String datenew;
    private String compareValue;
    private String concluido;
    private String em_andamento;
    private String cancelado;
    private String concluido1;
    private String em_andamento1;
    private String cancelado1;
    private String status;
    private Context context;
    private LayoutInflater inflater;
    private IProcessFilter mCallback;
    private ArrayList<DataHistorico> data;
    //List<DataHistorico> data= Collections.emptyList();
    DataHistorico current;
    int currentPos=0;

    public AdapterHistorico(Context context, ArrayList<DataHistorico> data, IProcessFilter callback){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
        mCallback = callback;
    }

    public interface IProcessFilter {
        void onProcessFilter(DataHistorico produtos);
    }

   @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view=inflater.inflate(R.layout.container_historico, parent,false);

        MyHolder holder=new MyHolder(view);

        return holder;
    }

   @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
       final DataHistorico pedidos = data.get(position);

        values from list
        MyHolder myHolder= (MyHolder) holder;
        final DataHistorico current = data.get(position);

        dateold = current.pData;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yyyy 'ás' HH:mm:ss");
            datenew = df2.format(format.parse(dateold));

        } catch (ParseException e) {

            e.printStackTrace();
        }

        myHolder.txtPedidoNumero.setText("N° " + current.pNumero);

        myHolder.txtPedidoCliente.setText(current.pCliente);

        myHolder.txtPedidoData.setText(datenew);

        myHolder.txtPedidoTotal.setText("R$ " + current.pTotal);

        myHolder.edtPedido.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mCallback.onProcessFilter(pedidos); //NullPointerException here
            }
        });

        // load image into imageview using glide
        concluido = "concluido";
        cancelado = "cancelado";
        em_andamento= "em_andamento";
        status = current.pStatus;
        if (status.equals(concluido)) {
            Glide.with(context).load(R.drawable.ic_pedido_concluido).into(myHolder.imgPedidoStatus);
        } else if (status.equals(cancelado)) {
            Glide.with(context).load(R.drawable.ic_pedido_cancelado).into(myHolder.imgPedidoStatus);
        }else if (status.equals(em_andamento)) {
            Glide.with(context).load(R.drawable.ic_pedido_em_andamento).into(myHolder.imgPedidoStatus);
        }

    }

    // return total item from List
    @Override
    public int getItemCount() {
        return data.size();
    }

    class MyHolder extends RecyclerView.ViewHolder{

        TextView txtPedidoNumero;
        TextView txtPedidoCliente;
        ImageView imgPedidoStatus;
        TextView txtPedidoData;
        TextView txtPedidoTotal;
        ImageView edtPedido;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            txtPedidoNumero= (TextView) itemView.findViewById(R.id.txtPedidoNumero);
            txtPedidoCliente= (TextView) itemView.findViewById(R.id.txtPedidoCliente);
            imgPedidoStatus= (ImageView) itemView.findViewById(R.id.imgPedidoStatus);
            txtPedidoData = (TextView) itemView.findViewById(R.id.txtPedidoData);
            txtPedidoTotal = (TextView) itemView.findViewById(R.id.txtPedidoTotal);
            edtPedido = (ImageView) itemView.findViewById(R.id.edtPedido);
        }

    }

    }
</code>```

FragmentoHistorico.java

```<code>public class FragmentoHistorico extends Fragment implements AdapterHistorico.IProcessFilter {

[...]

public void onProcessFilter(DataHistorico pedidos) {

            EditarPedidoDialog(pedidos);

    }

private void EditarPedidoDialog(final DataHistorico pedidos){

        LayoutInflater inflater = LayoutInflater.from(getActivity());
        final View subView = inflater.inflate(R.layout.layout_edt_pedido, null);

[...]

 private class ProcurarPedido extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(getActivity());
    HttpURLConnection conn;
    URL url = null;
    private String searchQuery;
    private View rootView;

    public ProcurarPedido(String searchQuery, View rootView){
        this.searchQuery=searchQuery;
        this.rootView=rootView;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tAguarde...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL(ADMIN_PANEL_URL + "public/procurar-pedido-app.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Erro na conexão!");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }

    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        Log.v("result", result);
        pdLoading.dismiss();

        ArrayList<DataHistorico> data=new ArrayList<>();

        if(result.equals("no rows")) {

            mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo);
            mAdapter = new AdapterHistorico(getActivity(), data, null);
            mRVHistoricoInfo.setAdapter(mAdapter);
            mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity()));
           data.clear();

            Toast.makeText(getActivity(), "Não foram encontrados pedidos pelo nome do cliente informado.", Toast.LENGTH_LONG).show();
        }else{

            try {
                data.clear();
                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataHistorico historicoData = new DataHistorico();
                    historicoData.pNumero= json_data.getString("nid");
                    historicoData.pStatus= json_data.getString("pedido_status");
                    historicoData.pCliente= json_data.getString("pedido_cliente");
                    historicoData.pEndereco= json_data.getString("pedido_endereco");
                    historicoData.pData= json_data.getString("pedido_data");
                    historicoData.pTotal= json_data.getString("pedido_total");
                    data.add(historicoData);
                }

                mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo);
                mAdapter = new AdapterHistorico(getActivity(), data, null);
                mRVHistoricoInfo.setAdapter(mAdapter);
                mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity()));

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(getActivity(),"Não foi possível contatar o servidor.", Toast.LENGTH_LONG).show();
            }

        }

    }

}

[...]
</code>```

This is the error:

java.lang.NullPointerException: Attempt to invoke interface method
  'void
  com.beliasdev.cadjobel.adapter.AdapterHistorico$IProcessFilter.onProcessFilter(com.beliasdev.cadjobel.adapter.DataHistorico)'
  on a null object reference

答:
You are sending null instead of listener as a parameter:

So change

```<code> mAdapter = new AdapterHistorico(getActivity(), data, null);
</code>```

To

```<code> mAdapter = new AdapterHistorico(getActivity(), data, this);
</code>```

Body:
RecyclerView is updated after the search and mCallback returns null but before search works correctly.

AdapterHistorico.java

 package com.beliasdev.cadjobel.adapter;

 import android.content.Context;

 import android.content.DialogInterface;
 import android.support.v7.app.AlertDialog;
 import android.support.v7.widget.RecyclerView;
 import android.text.TextUtils;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.AdapterView;
 import android.widget.ArrayAdapter;
 import android.widget.EditText;
 import android.widget.ImageView;
 import android.widget.LinearLayout;
 import android.widget.Spinner;
 import android.widget.TextView;
 import android.widget.Toast;

 import com.beliasdev.cadjobel.R;
 import com.beliasdev.cadjobel.utility.DrawableHelper;
 import com.bumptech.glide.Glide;

 import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;

 public class AdapterHistorico extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Spinner spinner1;
    private String dateold;
    private String datenew;
    private String compareValue;
    private String concluido;
    private String em_andamento;
    private String cancelado;
    private String concluido1;
    private String em_andamento1;
    private String cancelado1;
    private String status;
    private Context context;
    private LayoutInflater inflater;
    private IProcessFilter mCallback;
    private ArrayList<DataHistorico> data;
    //List<DataHistorico> data= Collections.emptyList();
    DataHistorico current;
    int currentPos=0;

    public AdapterHistorico(Context context, ArrayList<DataHistorico> data, IProcessFilter callback){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
        mCallback = callback;
    }

    public interface IProcessFilter {
        void onProcessFilter(DataHistorico produtos);
    }

   @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view=inflater.inflate(R.layout.container_historico, parent,false);

        MyHolder holder=new MyHolder(view);

        return holder;
    }

   @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
       final DataHistorico pedidos = data.get(position);

        values from list
        MyHolder myHolder= (MyHolder) holder;
        final DataHistorico current = data.get(position);

        dateold = current.pData;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yyyy 'ás' HH:mm:ss");
            datenew = df2.format(format.parse(dateold));

        } catch (ParseException e) {

            e.printStackTrace();
        }

        myHolder.txtPedidoNumero.setText("N° " + current.pNumero);

        myHolder.txtPedidoCliente.setText(current.pCliente);

        myHolder.txtPedidoData.setText(datenew);

        myHolder.txtPedidoTotal.setText("R$ " + current.pTotal);

        myHolder.edtPedido.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mCallback.onProcessFilter(pedidos); //NullPointerException here
            }
        });

        // load image into imageview using glide
        concluido = "concluido";
        cancelado = "cancelado";
        em_andamento= "em_andamento";
        status = current.pStatus;
        if (status.equals(concluido)) {
            Glide.with(context).load(R.drawable.ic_pedido_concluido).into(myHolder.imgPedidoStatus);
        } else if (status.equals(cancelado)) {
            Glide.with(context).load(R.drawable.ic_pedido_cancelado).into(myHolder.imgPedidoStatus);
        }else if (status.equals(em_andamento)) {
            Glide.with(context).load(R.drawable.ic_pedido_em_andamento).into(myHolder.imgPedidoStatus);
        }

    }

    // return total item from List
    @Override
    public int getItemCount() {
        return data.size();
    }

    class MyHolder extends RecyclerView.ViewHolder{

        TextView txtPedidoNumero;
        TextView txtPedidoCliente;
        ImageView imgPedidoStatus;
        TextView txtPedidoData;
        TextView txtPedidoTotal;
        ImageView edtPedido;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            txtPedidoNumero= (TextView) itemView.findViewById(R.id.txtPedidoNumero);
            txtPedidoCliente= (TextView) itemView.findViewById(R.id.txtPedidoCliente);
            imgPedidoStatus= (ImageView) itemView.findViewById(R.id.imgPedidoStatus);
            txtPedidoData = (TextView) itemView.findViewById(R.id.txtPedidoData);
            txtPedidoTotal = (TextView) itemView.findViewById(R.id.txtPedidoTotal);
            edtPedido = (ImageView) itemView.findViewById(R.id.edtPedido);
        }

    }

    }

FragmentoHistorico.java

public class FragmentoHistorico extends Fragment implements AdapterHistorico.IProcessFilter {

[...]

public void onProcessFilter(DataHistorico pedidos) {

            EditarPedidoDialog(pedidos);

    }

private void EditarPedidoDialog(final DataHistorico pedidos){

        LayoutInflater inflater = LayoutInflater.from(getActivity());
        final View subView = inflater.inflate(R.layout.layout_edt_pedido, null);

[...]

 private class ProcurarPedido extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(getActivity());
    HttpURLConnection conn;
    URL url = null;
    private String searchQuery;
    private View rootView;

    public ProcurarPedido(String searchQuery, View rootView){
        this.searchQuery=searchQuery;
        this.rootView=rootView;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tAguarde...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL(ADMIN_PANEL_URL + "public/procurar-pedido-app.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Erro na conexão!");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }

    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        Log.v("result", result);
        pdLoading.dismiss();

        ArrayList<DataHistorico> data=new ArrayList<>();

        if(result.equals("no rows")) {

            mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo);
            mAdapter = new AdapterHistorico(getActivity(), data, null);
            mRVHistoricoInfo.setAdapter(mAdapter);
            mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity()));
           data.clear();

            Toast.makeText(getActivity(), "Não foram encontrados pedidos pelo nome do cliente informado.", Toast.LENGTH_LONG).show();
        }else{

            try {
                data.clear();
                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataHistorico historicoData = new DataHistorico();
                    historicoData.pNumero= json_data.getString("nid");
                    historicoData.pStatus= json_data.getString("pedido_status");
                    historicoData.pCliente= json_data.getString("pedido_cliente");
                    historicoData.pEndereco= json_data.getString("pedido_endereco");
                    historicoData.pData= json_data.getString("pedido_data");
                    historicoData.pTotal= json_data.getString("pedido_total");
                    data.add(historicoData);
                }

                mRVHistoricoInfo = (RecyclerView)rootView.findViewById(R.id.ListaHistoricoInfo);
                mAdapter = new AdapterHistorico(getActivity(), data, null);
                mRVHistoricoInfo.setAdapter(mAdapter);
                mRVHistoricoInfo.setLayoutManager(new LinearLayoutManager(getActivity()));

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(getActivity(),"Não foi possível contatar o servidor.", Toast.LENGTH_LONG).show();
            }

        }

    }

}

[...]

This is the error:

java.lang.NullPointerException: Attempt to invoke interface method
  'void
  com.beliasdev.cadjobel.adapter.AdapterHistorico$IProcessFilter.onProcessFilter(com.beliasdev.cadjobel.adapter.DataHistorico)'
  on a null object reference

Body:
You are sending null instead of listener as a parameter:

So change

 mAdapter = new AdapterHistorico(getActivity(), data, null);

To

 mAdapter = new AdapterHistorico(getActivity(), data, this);


问:
How to make Date object toString via stringify use the regular toString instead of toStringISO in javascript?
In javascript, when I convert a Date object to string via JSON.stringify, it uses toStringISO by default. How can I change the prototype of it so that it uses the basic toString?

I have

```<code>var f = new Date("Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)");
</code>```

then if I do JSON.stringify(f) it gives me "2019-05-28T00:11:13.000Z"

but I want it to give me "Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)" (which I can get from f.toString()), how do I get that?

Looking to override prototype, something like that.

Does anyone know?

Thanks

答:
The documentation for JSON.stringify says this:

If the value has a toJSON() method, it's responsible to define what data will be serialized.

...

The instances of Date implement the toJSON() function by returning a string (the same as date.toISOString()). Thus, they are treated as strings.

If you wanted to change how every date is serialized, you can override Date.toJSON:

```<code>Date.prototype.toJSON = function() { return this.toString() }
</code>```

By replacing that method, now every date will be serialized using Date.toString:

```<code>var f = new Date(2019, 2, 3);
JSON.stringify(f)
</code>```

This will work regardless of how deeply the date is nested inside your JSON structure, will work for every date, and will not require any customization to how you perform serialization.  The JSON.stringify(f) call shown above is probably what you would have used already.

If you wanted to change how a particular date is serialized, just replace that Date object's toJSON method:

```<code>var f = new Date(2019, 2, 3);
g = new Date();
f.toJSON = function() { return this.toString() };
JSON.stringify([f,g])
</code>```

Which gives you this JSON:

```<code>"["Sun Mar 03 2019 00:00:00 GMT-0600 (Central Standard Time)","2019-05-27T20:56:51.335Z"]"
</code>```

Body:
In javascript, when I convert a Date object to string via JSON.stringify, it uses toStringISO by default. How can I change the prototype of it so that it uses the basic toString?

I have

var f = new Date("Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)");

then if I do JSON.stringify(f) it gives me "2019-05-28T00:11:13.000Z"

but I want it to give me "Mon May 27 2019 20:11:13 GMT-0400 (Eastern Daylight Time)" (which I can get from f.toString()), how do I get that?

Looking to override prototype, something like that.

Does anyone know?

Thanks

Body:
The documentation for JSON.stringify says this:

If the value has a toJSON() method, it's responsible to define what data will be serialized.

...

The instances of Date implement the toJSON() function by returning a string (the same as date.toISOString()). Thus, they are treated as strings.

If you wanted to change how every date is serialized, you can override Date.toJSON:

Date.prototype.toJSON = function() { return this.toString() }

By replacing that method, now every date will be serialized using Date.toString:

var f = new Date(2019, 2, 3);
JSON.stringify(f)

This will work regardless of how deeply the date is nested inside your JSON structure, will work for every date, and will not require any customization to how you perform serialization.  The JSON.stringify(f) call shown above is probably what you would have used already.

If you wanted to change how a particular date is serialized, just replace that Date object's toJSON method:

var f = new Date(2019, 2, 3);
g = new Date();
f.toJSON = function() { return this.toString() };
JSON.stringify([f,g])

Which gives you this JSON:

"["Sun Mar 03 2019 00:00:00 GMT-0600 (Central Standard Time)","2019-05-27T20:56:51.335Z"]"


问:
How to have img same size as div
I want to make a nav bar in the footer with images. The footer needs to be 10% of the total screen and the images need to be within those 10% as well. Only I don't get the images scale according to the screen size and are way bigger. What am I doing wrong?

I am using Bootstrap 4 and I intent to make a mobile version of my website but it is not displaying good.

```<code><div class="footer navbar row">
 <div class="col-sm-2 menu_item">
<a href="#home" class="active">
    <img src="<source>" class="menu_img" alt="Logo"/>
</a>
 </div>
 <div class="col-sm-2 menu_item">
<a href="#news">
<img src="<source>" class="menu_img" alt="Logo"/>
    </a>
  </div>
  <div class="col-sm-2 menu_item">
    <a href="#contact">
        <img src="<source>" class="menu_img" alt="Logo"/>
    </a>
  </div>
  <div class="col-sm-2 menu_item">
  <a href="#contact">
    <img src="<source>" class="menu_img" alt="Logo"/>
   </a>
   </div>
   <div class="col-sm-2 menu_item">
   <a href="#contact">
    <img src="<source>" class="menu_img" alt="Logo"/>
   </a>
   </div>
</code>```

```<code>/* Place the navbar at the bottom of the page, and make it stick */
.navbar {
        background-color: var(--primary-color-1);
        overflow: hidden;
        position: fixed;
        bottom: 0;
        width: 100%;
        margin: 0px;
        height: 10vh;
    }
    /* Style the menu blocks */
    .menu_item {
        position: relative;
        padding: 2px 10px;
        margin: 0px;
    }
    /* Style the links inside the navigation bar */
    .navbar a {
        float: left;
        display: block;
        text-align: center;
        text-decoration: none;

    }
   /* Style the images/icons of the links */
    .menu_img {
        height:100%;
        width: 100%;
        object-fit: cover;
      }
</code>```

答:
responsive img's need width: 100%; to be responsive, you can control the image size with his container, for example:

```

<pre class="lang-css prettyprint-override"><code>img{
    width: 100%;
}
.img-container{
    width: 10%;
}
</code>```

Title: How to have img same size as div

Body:
I want to make a nav bar in the footer with images. The footer needs to be 10% of the total screen and the images need to be within those 10% as well. Only I don't get the images scale according to the screen size and are way bigger. What am I doing wrong?

I am using Bootstrap 4 and I intent to make a mobile version of my website but it is not displaying good.

    <img src="<source>" class="menu_img" alt="Logo"/>

<img src="<source>" class="menu_img" alt="Logo"/>

        <img src="<source>" class="menu_img" alt="Logo"/>

    <img src="<source>" class="menu_img" alt="Logo"/>

    <img src="<source>" class="menu_img" alt="Logo"/>

/* Place the navbar at the bottom of the page, and make it stick */
.navbar {
        background-color: var(--primary-color-1);
        overflow: hidden;
        position: fixed;
        bottom: 0;
        width: 100%;
        margin: 0px;
        height: 10vh;
    }
    /* Style the menu blocks */
    .menu_item {
        position: relative;
        padding: 2px 10px;
        margin: 0px;
    }
    /* Style the links inside the navigation bar */
    .navbar a {
        float: left;
        display: block;
        text-align: center;
        text-decoration: none;

    }
   /* Style the images/icons of the links */
    .menu_img {
        height:100%;
        width: 100%;
        object-fit: cover;
      }

Body:
responsive img's need width: 100%; to be responsive, you can control the image size with his container, for example:

<div class="img-container">
    <img src="imgUrl"/>
</div>

img{
    width: 100%;
}
.img-container{
    width: 10%;
}


问:
Returning a zend paginator object in ajax request, getting wrong url
I'm using Zend Paginator here, in an ajax request I am retrieving objects based upon search results and rendering the HTML and passing it along with a rendered Zend Paginator view.

The problem is that the returning paginator doesn't take into account the new url. for example if I were to do it without ajax I would have my page url read:

www.mysite.com/?search=something&page=2

However from and ajax query it doesn't work that way the search variable is not appended to the url in the paginator links. Help please.

答:
I assume you hava pagination links somewhere on your site that point to the different pages that are generated within you pagination.phtml file.

OnClick you need to get that href attribute and load the contents like that:

```<code>function getContents() {
    var url = window.location.protocol + "//" +
              window.location.host + $(this).attr('href');

    var jqxhr = $.post(url, {
        "format" : "json"
    }, function(data) {
        displayContents(data);
    }, 'html');
    return false;
}

$(document).ready(function() {
    $("#paginator a").each(function() {
        $(this).click(getContents);
    });
});
</code>```

This way you get your classic url

```<code>www.mysite.com/?search=something&page=2
</code>```

maybe you need to change the url field. Just alert the url field and look what needs to be changed.

Here is a tutorial on that (without search) : Zend Framework 1.9 tutorial 14: ajax requests part 1

Body:
I assume you hava pagination links somewhere on your site that point to the different pages that are generated within you pagination.phtml file.

OnClick you need to get that href attribute and load the contents like that:

function getContents() {
    var url = window.location.protocol + "//" +
              window.location.host + $(this).attr('href');

    var jqxhr = $.post(url, {
        "format" : "json"
    }, function(data) {
        displayContents(data);
    }, 'html');
    return false;
}

$(document).ready(function() {
    $("#paginator a").each(function() {
        $(this).click(getContents);
    });
});

This way you get your classic url

www.mysite.com/?search=something&page=2

maybe you need to change the url field. Just alert the url field and look what needs to be changed.

Here is a tutorial on that (without search) : Zend Framework 1.9 tutorial 14: ajax requests part 1


问:
mpicc - clang: error: no such file or directory:
Month ago I installed Open MPI 4.0.1 on macOS Mojave following this Stack Overflow answer.

Back then everything worked and I managed to compile and run hello.c and few other programs.

But when I tried today to compile any program using $HOME/opt/usr/local/bin/mpicc -o program_name ./program_name.c I get error clang: error: no such file or directory: './program_name.c', even though these files are in that directory.
It doesn't even work for hello.c.

But when I try to run existing programs, for example hello, using $HOME/opt/usr/local/bin/mpirun -np 4 hello, it works.

So I don't understand how can I get error no such file or directory if mpi can find and run existing programs, but can't compile files that are in the same directory.

I also tried to position in that directory using cd $HOME/opt/usr/local/bin and then execute mpicc -o hello ./hello.c, but then I get error -bash: mpicc: command not found.

Does anyone know where is the problem and how to solve it?

答:
In case of issues like this, it's good to run mpicc with option -v. This way, you can take a look at all the commands that are executed behind your back

```<code>> mpicc -v -o main ./main.c
Apple LLVM version 9.0.0 (clang-900.0.39.2)
Target: x86_64-apple-darwin17.7.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
 "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -cc1 -triple x86_64-apple-macosx10.13.0 -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name main.c -mrelocation-model pic -pic-level 2 -mthread-model posix -mdisable-fp-elim -fno-strict-return -masm-verbose -munwind-tables -target-cpu penryn -target-linker-version 305 -v -dwarf-column-info -debugger-tuning=lldb -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/9.0.0 -I ... -fdebug-compilation-dir /Users/... -ferror-limit 19 -fmessage-length 173 -stack-protector 1 -fblocks -fobjc-runtime=macosx-10.13.0 -fencode-extended-block-signature -fmax-type-align=16 -fdiagnostics-show-option -fcolor-diagnostics -o /var/folders/cx/76hd7pcs41g_vdj4qjfx0d4h0000gn/T/main-29e74d.o -x c ./main.c
clang -cc1 version 9.0.0 (clang-900.0.39.2) default target x86_64-apple-darwin17.7.0
...
...
</code>```

This way, you can spot issues related to compiler. Also, make sure your Toolchain hasn't changed after system/XCode upgrade. If you have compiled MPI from sources, it might be you have some discrepancies between what was used during compilation time and what you have now.

Body:
In case of issues like this, it's good to run mpicc with option -v. This way, you can take a look at all the commands that are executed behind your back

> mpicc -v -o main ./main.c
Apple LLVM version 9.0.0 (clang-900.0.39.2)
Target: x86_64-apple-darwin17.7.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
 "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang" -cc1 -triple x86_64-apple-macosx10.13.0 -Wdeprecated-objc-isa-usage -Werror=deprecated-objc-isa-usage -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name main.c -mrelocation-model pic -pic-level 2 -mthread-model posix -mdisable-fp-elim -fno-strict-return -masm-verbose -munwind-tables -target-cpu penryn -target-linker-version 305 -v -dwarf-column-info -debugger-tuning=lldb -resource-dir /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/clang/9.0.0 -I ... -fdebug-compilation-dir /Users/... -ferror-limit 19 -fmessage-length 173 -stack-protector 1 -fblocks -fobjc-runtime=macosx-10.13.0 -fencode-extended-block-signature -fmax-type-align=16 -fdiagnostics-show-option -fcolor-diagnostics -o /var/folders/cx/76hd7pcs41g_vdj4qjfx0d4h0000gn/T/main-29e74d.o -x c ./main.c
clang -cc1 version 9.0.0 (clang-900.0.39.2) default target x86_64-apple-darwin17.7.0
...
...

This way, you can spot issues related to compiler. Also, make sure your Toolchain hasn't changed after system/XCode upgrade. If you have compiled MPI from sources, it might be you have some discrepancies between what was used during compilation time and what you have now.


问:
Loop through array of arrays containing objects
This is my first time posting and I'm also very new to AngularJs and somewhat new to JavaScript in general. I hope I am providing enough info. I have an array containing arrays of objects [[{},{},{}],[{},{},{}],[{},{},{}]]. Is there a way to loop through this using AngularJs and output something similar to the following?

Group Title 1

01 Item title 1: item description

02 Item title 2: item description

Group Title 2

03 Item title 1: item description

04 Item title 2: item description

==============

```<code>$scope.groups_array = [
    [
        {
            "id": "01 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        },
        {
            "id": "02 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        }
    ],
    [
        {
            "id": "03 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        },
        {
            "id": "04 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        }
    ]
]

$scope.group_title = ["Group Title 1", "Group Title 2"];
</code>```

```<code><div>
    <div ng-repeat="title in group_title">
        <h1>{{title}}</h1>
        <ul>
            <li ng-repeat="item in groups_array">
              {{item.id + ' ' + item[''][0]}}: {{item[''][1]}}
            </li>
        </ul>
    </div>
</div>
</code>```

The output I'm getting instead is simply a list of the :'s with no errors in the console.

The arrays of objects themselves come from a master array containing all the objects, and I tried to group them into arrays by group title. I'm not sure if this is the best solution.

答:
What you should try is to turn groups_array into an object like

```<code>$scope.groups_array = {
    "Group Title 1": [
        {
            "id": "01 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        },
        {
            "id": "02 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        }
    ],
    "Group Title 2": [
        {
            "id": "03 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        },
        {
            "id": "04 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        }
    ]
}
</code>```

And then in your Angular snippet:

```<code><div>
    <div ng-repeat="title in group_title">
        <h1>{{title}}</h1>
        <ul>
            <li ng-repeat="item in groups_array[title]">
              {{item.id + ' ' + item[''][0]}}: {{item[''][1]}}
            </li>
        </ul>
    </div>
</div>
</code>```

Body:
This is my first time posting and I'm also very new to AngularJs and somewhat new to JavaScript in general. I hope I am providing enough info. I have an array containing arrays of objects [[{},{},{}],[{},{},{}],[{},{},{}]]. Is there a way to loop through this using AngularJs and output something similar to the following?

Group Title 1

01 Item title 1: item description

02 Item title 2: item description

Group Title 2

03 Item title 1: item description

04 Item title 2: item description

==============

$scope.groups_array = [
    [
        {
            "id": "01 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        },
        {
            "id": "02 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        }
    ],
    [
        {
            "id": "03 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        },
        {
            "id": "04 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        }
    ]
]

$scope.group_title = ["Group Title 1", "Group Title 2"];

{{title}}

              {{item.id + ' ' + item[''][0]}}: {{item[''][1]}}

The output I'm getting instead is simply a list of the :'s with no errors in the console.

The arrays of objects themselves come from a master array containing all the objects, and I tried to group them into arrays by group title. I'm not sure if this is the best solution.

Body:
What you should try is to turn groups_array into an object like

$scope.groups_array = {
    "Group Title 1": [
        {
            "id": "01 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        },
        {
            "id": "02 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "A",
            "title": "Group Title 1"
        }
    ],
    "Group Title 2": [
        {
            "id": "03 ",
            "": [
                "Item Title 1",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        },
        {
            "id": "04 ",
            "": [
                "Item Title 2",
                "Item description"
            ],
            "group_id": "B",
            "title": "Group Title 2"
        }
    ]
}

And then in your Angular snippet:

<div>
    <div ng-repeat="title in group_title">
        <h1>{{title}}</h1>
        <ul>
            <li ng-repeat="item in groups_array[title]">
              {{item.id + ' ' + item[''][0]}}: {{item[''][1]}}
            </li>
        </ul>
    </div>
</div>