问:
operator new inside namespace
```<code>namespace X
{
  void* operator new (size_t);
}
</code>```

gives error message as:

```<code>error: ‘void* X::operator new(size_t)’ may not be declared within a namespace
</code>```

Is it a gcc compiler bug ? In older gcc version it seems to be working.
Any idea, why it's not allowed ?

Use case:
I wanted to allow only custom operator new/delete for the classes and wanted to disallow global new/operator. Instead of linker error, it was easy to catch compiler error; so I coded:

```<code>namespace X {
  void* operator new (size_t);
}
using namespace X;
</code>```

This worked for older version of gcc but not for the new one.

答:
@Sharptooth's Answer makes more sense if we consider this section from the standard:

3.7.3.1 Allocation functions [basic.stc.dynamic.allocation]

[..] An allocation function shall be a class member function or a global function; a program is ill-formed if an allocation function is declared in a namespace scope other than global scope or declared static in global scope. [..]

The above limitation is probably imposed for the very reason that @sharptooth's answer points out.

Title: operator new inside namespace

Body:
namespace X
{
  void* operator new (size_t);
}

gives error message as:

error: ‘void* X::operator new(size_t)’ may not be declared within a namespace

Is it a gcc compiler bug ? In older gcc version it seems to be working.
Any idea, why it's not allowed ?

Use case:
I wanted to allow only custom operator new/delete for the classes and wanted to disallow global new/operator. Instead of linker error, it was easy to catch compiler error; so I coded:

namespace X {
  void* operator new (size_t);
}
using namespace X;

This worked for older version of gcc but not for the new one.


来源: stackexchange

问:
Which output should I use for prediction with LSTM for sequenced data?
I'm still new to machine learning and deep learning. I am currently trying to predict time series data with LSTM in PyTorch. The problem I am having is that I don't understand which output should I use for my final prediction.
My code is given below:

```<code>class Model(nn.Module):
  def __init__(self, input_size, hidden_size, output_size, seq_len, dropout):
    super(Model, self).__init__()
    self.input_size = input_size
    self.hidden_size = hidden_size
    self.output_size = output_size
    self.dropout = dropout
    self.seq_len = seq_len
    self.lstm = nn.LSTM(
        input_size = self.input_size,
        hidden_size = self.hidden_size,
        dropout = self.dropout
    )
    self.linear = nn.Linear(self.hidden_size, self.output_size)

  def reset_hidden_state(self):
    self.hidden = (
        torch.zeros(1, self.seq_len, self.hidden_size),
        torch.zeros(1, self.seq_len, self.hidden_size)
    )

  def forward(self, sequences):
    lstm_out, self.hidden = self.lstm(sequences, self.hidden)
    y_pred = self.linear(lstm_out[-1, :, :])
    return y_pred

mymodel = Model(5, 10, 1, 3, 0.0)
inps = torch.randn(10, 3, 5)   #input
#print(inps)
mymodel.reset_hidden_state()
out = mymodel.forward(inps)
print(out.shape)
print(out)
</code>```

output:

torch.Size([3, 1])

tensor([[-0.0996],
          [-0.0587],
          [-0.0421]], grad_fn=)

As you can see, this gives me three outputs, but my output size is 1 as I am trying to predict only 1 variable. So, in this case which variable should I use for my final prediction? Or, is it is even possible to predict only 1 value for sequential data like this?

NB: My python version is 3.7.4
and my PyTorch version is 1.4.0

And, sorry if I have made any mistake while asking the question. This is my first time asking question here.

答:
You are already using the correct output of the LSTM, which is the last hidden state. Conveniently that is also the last element in lstm_out, which you are using as lstm_out[-1, :, :].

The input of the model inps are multiple sequences, because their size is [seq_len, batch_size, num_featuers] = [10, 3, 5]. That means you have 3 independent sequences, which have 10 time steps each with 5 features per time step.

Therefore, the out (size: [3, 1]) contains the predictions for each of the 3 sequences. out[0][0] is the prediction of the first sequence, out[1][0] of the second, and out[2][0] of the third. You can also get rid of the singular second sequence with out.unsqueeze(1), so you have a 1D tensor with the 3 predictions.

If you want to predict only a single sequence, you would use a batch size of 1, which means the input would have size [10, 1, 5] instead, then you get a single value back, even though it's in a tensor of size [1, 1].

ContentLicense: CC BY-SA 4.0

Body:
I'm still new to machine learning and deep learning. I am currently trying to predict time series data with LSTM in PyTorch. The problem I am having is that I don't understand which output should I use for my final prediction.
My code is given below:

class Model(nn.Module):
  def __init__(self, input_size, hidden_size, output_size, seq_len, dropout):
    super(Model, self).__init__()
    self.input_size = input_size
    self.hidden_size = hidden_size
    self.output_size = output_size
    self.dropout = dropout
    self.seq_len = seq_len
    self.lstm = nn.LSTM(
        input_size = self.input_size,
        hidden_size = self.hidden_size,
        dropout = self.dropout
    )
    self.linear = nn.Linear(self.hidden_size, self.output_size)

  def reset_hidden_state(self):
    self.hidden = (
        torch.zeros(1, self.seq_len, self.hidden_size),
        torch.zeros(1, self.seq_len, self.hidden_size)
    )

  def forward(self, sequences):
    lstm_out, self.hidden = self.lstm(sequences, self.hidden)
    y_pred = self.linear(lstm_out[-1, :, :])
    return y_pred

mymodel = Model(5, 10, 1, 3, 0.0)
inps = torch.randn(10, 3, 5)   #input
#print(inps)
mymodel.reset_hidden_state()
out = mymodel.forward(inps)
print(out.shape)
print(out)

output:

torch.Size([3, 1])

tensor([[-0.0996],
          [-0.0587],
          [-0.0421]], grad_fn=)

As you can see, this gives me three outputs, but my output size is 1 as I am trying to predict only 1 variable. So, in this case which variable should I use for my final prediction? Or, is it is even possible to predict only 1 value for sequential data like this?

NB: My python version is 3.7.4
and my PyTorch version is 1.4.0

And, sorry if I have made any mistake while asking the question. This is my first time asking question here.


问:
cron (reboot job) and wget (extract files) don't "get" along
I'm trying really hard to get this to work, but I just can't seem to get it right.

I got this Raspberry Pi that I want to download photos from a dropbox link into a specific folder on reboot.

sudo crontab -e

```<code>@reboot /home/pi/path/to/dir/with/photos/scripts.sh
</code>```

scripts.sh

```<code>#!/bin/bash
set -x
cd /home/pi/path/to/dir/with/photos/

# delete all photos and download and convert them again
rm -f /home/pi/crontab.refresh.log || true
sh /home/pi/path/to/dir/with/photos/refreshPhotos.sh > /home/pi/crontab.refresh.log

# convert all photos to bmp (and scale them)
rm -f /home/pi/crontab.convert.log || true
/usr/bin/python2.7 /home/pi/path/to/dir/with/photos/convertPhotos.py > /home/pi/crontab.convert.log

</code>```

refreshPhotos.sh

```<code>#!/bin/bash

# clear the "old" ones
rm -f *.JPG || true
rm -f *.jpg || true

# Get the "fresh" ones
wget -qO- https://www.dropbox.com/sh/AAA/BB -P /home/pi/path/to/dir/with/photos/ | bsdtar -xvf-
</code>```

The wget looks a bit funky with the -qO- and | bsdtar -xvf- - it's in order avoid getting them into folder AAA and BBB.

Running the script from

```<code>/home/pi/path/to/dir$ bash /with/photos/scripts.sh
</code>```

works just fine. BUT rebooting does not seem to work (it only deletes the old photos and does not download the new ones.

ANY help that will solve my issue will be highly appreciated!

答:
cron often starts a very basic shell with barely any environmental variables.
To make sure it gets the proper environment, follow this and add

$HOME/.profile;

to just before the command on @reboot, so

@reboot $HOME/.profile; /home/pi/path/to/dir/with/photos/scripts.sh

Answer from :How can I run a cron command with existing environmental variables?

Body:
I'm trying really hard to get this to work, but I just can't seem to get it right.

I got this Raspberry Pi that I want to download photos from a dropbox link into a specific folder on reboot.

sudo crontab -e

@reboot /home/pi/path/to/dir/with/photos/scripts.sh

scripts.sh

#!/bin/bash
set -x
cd /home/pi/path/to/dir/with/photos/

# delete all photos and download and convert them again
rm -f /home/pi/crontab.refresh.log || true
sh /home/pi/path/to/dir/with/photos/refreshPhotos.sh > /home/pi/crontab.refresh.log

# convert all photos to bmp (and scale them)
rm -f /home/pi/crontab.convert.log || true
/usr/bin/python2.7 /home/pi/path/to/dir/with/photos/convertPhotos.py > /home/pi/crontab.convert.log

refreshPhotos.sh

#!/bin/bash

# clear the "old" ones
rm -f *.JPG || true
rm -f *.jpg || true

# Get the "fresh" ones
wget -qO- https://www.dropbox.com/sh/AAA/BB -P /home/pi/path/to/dir/with/photos/ | bsdtar -xvf-

The wget looks a bit funky with the -qO- and | bsdtar -xvf- - it's in order avoid getting them into folder AAA and BBB.

Running the script from

/home/pi/path/to/dir$ bash /with/photos/scripts.sh

works just fine. BUT rebooting does not seem to work (it only deletes the old photos and does not download the new ones.

ANY help that will solve my issue will be highly appreciated!


问:
How do you access navbar css property from another component in Angular
I have a navbar with this code:

```<code><mdb-navbar SideClass="navbar fixed-top navbar-toggleable-md navbar-expand-lg scrolling-navbar py-0 navbar-dark lunada-gradient" [containerInside]="false">
</code>```

How can I change the lunada-gradient property from another component in my case it is customizer. This is an example of an available option:

```<code><div class="col">
    <span class="deep-space-gradient d-block rounded-circle" style="width:20px; height:20px;"
        data-bg-color="deep-space-gradient" [ngClass]="{'selected': selectedBgColor === 'deep-space-gradient'}"
        (click)="changeNavbarBgColor('deep-space-gradient')">
  </span>
</div>
</code>```

Component:

```<code> selectedBgColor: string = 'lunada';selectedBgColor: string = 'lunada';

  options = {
    bgColor: 'lunada-gradient',
    layout: 'light'
  };

  constructor(
    private layoutService: LayoutService,
  ) {
    this.layoutSub = layoutService.customizerChangeEmitted$.subscribe(
      options => {
        if (options) {
          if (options.bgColor) {
            this.selectedBgColor = options.bgColor;
          }
        }
      }
    );
  }

  changeNavbarBgColor(color) {
    this.selectedBgColor = color;
    this.options.bgColor = color;

    this.layoutService.emitCustomizerChange(this.options);
  }

  options = {
    bgColor: 'lunada-gradient',
    layout: 'light'
  };

 changeNavbarBgColor(color) {
    this.selectedBgColor = color;
    this.options.bgColor = color;
    this.layoutService.emitCustomizerChange(this.options);
  }
</code>```

答:
If you want to modify the CSS of another component, you cant use ::ng-deep on your component, but need to be careful with this because it is easy to do a mess.

This is a simple example of how to do that

```<code>::ng-deep mdb-navbar {
  background-color: red;
}
</code>```

If need more details about it, you can reed https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep

Body:
I have a navbar with this code:

<mdb-navbar SideClass="navbar fixed-top navbar-toggleable-md navbar-expand-lg scrolling-navbar py-0 navbar-dark lunada-gradient" [containerInside]="false">

How can I change the lunada-gradient property from another component in my case it is customizer. This is an example of an available option:

Component:

 selectedBgColor: string = 'lunada';selectedBgColor: string = 'lunada';

  options = {
    bgColor: 'lunada-gradient',
    layout: 'light'
  };

  constructor(
    private layoutService: LayoutService,
  ) {
    this.layoutSub = layoutService.customizerChangeEmitted$.subscribe(
      options => {
        if (options) {
          if (options.bgColor) {
            this.selectedBgColor = options.bgColor;
          }
        }
      }
    );
  }

  changeNavbarBgColor(color) {
    this.selectedBgColor = color;
    this.options.bgColor = color;

    this.layoutService.emitCustomizerChange(this.options);
  }

  options = {
    bgColor: 'lunada-gradient',
    layout: 'light'
  };

 changeNavbarBgColor(color) {
    this.selectedBgColor = color;
    this.options.bgColor = color;
    this.layoutService.emitCustomizerChange(this.options);
  }

Body:
If you want to modify the CSS of another component, you cant use ::ng-deep on your component, but need to be careful with this because it is easy to do a mess.

This is a simple example of how to do that

::ng-deep mdb-navbar {
  background-color: red;
}

If need more details about it, you can reed https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep


问:
How to create touch events using Angular 2+ version?
How to create angular touch events, because angular does not have in built touch events like (click) etc ?</p>

答:
```<code>import { Component, HostListener } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    defaultTouch = { x: 0, y: 0, time: 0 };

    @HostListener('touchstart', ['$event'])
    //@HostListener('touchmove', ['$event'])
    @HostListener('touchend', ['$event'])
    @HostListener('touchcancel', ['$event'])
    handleTouch(event) {
        let touch = event.touches[0] || event.changedTouches[0];

        // check the events
        if (event.type === 'touchstart') {
            this.defaultTouch.x = touch.pageX;
            this.defaultTouch.y = touch.pageY;
            this.defaultTouch.time = event.timeStamp;
        } else if (event.type === 'touchend') {
            let deltaX = touch.pageX - this.defaultTouch.x;
            let deltaY = touch.pageY - this.defaultTouch.y;
            let deltaTime = event.timeStamp - this.defaultTouch.time;

            // simulte a swipe -> less than 500 ms and more than 60 px
            if (deltaTime < 500) {
                // touch movement lasted less than 500 ms
                if (Math.abs(deltaX) > 60) {
                    // delta x is at least 60 pixels
                    if (deltaX > 0) {
                        this.doSwipeRight(event);
                    } else {
                        this.doSwipeLeft(event);
                    }
                }

                if (Math.abs(deltaY) > 60) {
                    // delta y is at least 60 pixels
                    if (deltaY > 0) {
                        this.doSwipeDown(event);
                    } else {
                        this.doSwipeUp(event);
                    }
                }
            }
        }
    }

    doSwipeLeft(event) {
        console.log('swipe left', event);
    }

    doSwipeRight(event) {
        console.log('swipe right', event);
    }

    doSwipeUp(event) {
        console.log('swipe up', event);
    }

    doSwipeDown(event) {
        console.log('swipe down', event);
    }
}
</code>```


问:
How to select an option from a dropdown menu through partial text using Selenium and Python
I'm using the Selenium Kit in Python and am trying to select an option from a drop-down menu.

For this I'm using python driver.select_by_visible_text() .
My problem is now that the visible text always contains the value I'm looking but with something added afterwards. The select_by_visible_text() just finds the exact option, but I can´t name it exactly.

For example: I'm looking for the option "W33", the website then says "W33 (only 4 left)". I would like to select "W33 (only 4 left)", but don´t know how to achieve this?

答:
As the static part of the visible text i.e. W33 is always followed by a variable text, e.g. (only 4 left), (only 3 left), etc, so  select_by_visible_text() may not be effective. You may have to consider either among:

select_by_value(value)

select_by_index(index)

Alternative

As an alternative you can also use the xpath based Locator Strategy as follows:

```<code>driver.find_element_by_xpath("//select//option[contains(., 'W33')]").click()
</code>```

Note: You may need to expand the <select> element first before clicking on the option.

Ideally, you need to induce WebDriverWait for the element_to_be_clickable() as follows:

```<code>WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select//option[contains(., 'W33')]"))).click()
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Reference

You can find a relevant discussion in:

Message: Element  could not be scrolled into view while trying to click on an option within a dropdown menu through Selenium

Body:
As the static part of the visible text i.e. W33 is always followed by a variable text, e.g. (only 4 left), (only 3 left), etc, so  select_by_visible_text() may not be effective. You may have to consider either among:

select_by_value(value)

select_by_index(index)

Alternative

As an alternative you can also use the xpath based Locator Strategy as follows:

driver.find_element_by_xpath("//select//option[contains(., 'W33')]").click()

Note: You may need to expand the <select> element first before clicking on the option.

Ideally, you need to induce WebDriverWait for the element_to_be_clickable() as follows:

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select//option[contains(., 'W33')]"))).click()

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Reference

You can find a relevant discussion in:

Message: Element  could not be scrolled into view while trying to click on an option within a dropdown menu through Selenium


问:
Npgsql - Using "GENERATED ALWAYS AS IDENTITY"
I'm currently trying to use Npgsql (version 3.1.3) to insert a record into a table with a generated identity using the official documentation (Npgsql.org) . But I always get the error:

```<code>Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
 ---> Npgsql.PostgresException (0x80004005): 428C9: cannot insert into column "mitteilung_id"
</code>```

I have already found several questions about this topic, but they are either outdated (version 2 or lower) or do not work.

My project is structured as follows. The table definition looks like this:

```<code>CREATE TABLE mitteilung
(
    mitteilung_id INTEGER GENERATED ALWAYS AS IDENTITY
        CONSTRAINT mitteilung_pk
            PRIMARY KEY,
    betreff       TEXT
        CONSTRAINT mitteilung_nn_betreff
            CHECK (betreff IS NOT NULL)
        CONSTRAINT mitteilung_ck_length_betreff
            CHECK (length(betreff) <= 100),
    nachricht     TEXT
        CONSTRAINT mitteilung_ck_length_nachricht
            CHECK (length(nachricht) <= 500)
        CONSTRAINT mitteilung_nn_nachricht
            CHECK (nachricht IS NOT NULL),
    erfasst_am    TIMESTAMP WITH TIME ZONE
        CONSTRAINT mitteilung_nn_erfasst_am
            CHECK (erfasst_am IS NOT NULL)
);
</code>```

I have defined the entity as follows:

```<code>public class Mitteilung : ISlongooEntity
    {
        public int MitteilungId { get; set; }

...
</code>```

I have also tried to add the following attributes to the ID property:

```<code>[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
</code>```

In the DB context I have tested the following settings to solve the problem.

```<code>modelBuilder.Entity<Mitteilung>()
                .Property(b => b.MitteilungId)
                .UseIdentityAlwaysColumn();

modelBuilder.Entity<Mitteilung>()
                .Property(b => b.MitteilungId)
 .Metadata.SetValueGenerationStrategy(NpgsqlValueGenerationStrategy.IdentityAlwaysColumn);

modelBuilder.Entity<Mitteilung>()
                .Property(b => b.MitteilungId)
.Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);
</code>```

But no matter in which combination I use the settings, I get the above mentioned error message when trying to save an entity. I also don't quite understand why an attempt is made to update the ID at all when an update is made. What am I doing wrong?

```<code>public Mitteilung Save(Mitteilung obj)
        {
            var addedObj = Context.Mitteilungen.Add(obj);
            // Context.Entry(obj).Property(x => x.MitteilungId).IsModified = false;
            Context.SaveChanges();
            return addedObj.Entity;
        }
</code>```

答:
The code below does work correctly.

Note that EF Core will automatically detect that MitteilungId is the primary key for Mitteilung, and since it's an int, will set it up as GENERATED BY DEFAULT AS IDENTITY. In other words, you don't need any of the fluent API calls - or the [Key] or [DatabaseGenerated] annotations - EF Core will set things up correctly by convention.

If, for some reason, you need to have GENERATED ALWAYS AS IDENTITY (instead of BY DEFAULT), then the fluent API call below can be used.

If you're still having an issue, can you please change the code sample below to produce the error?

class Program
{
    static async Task Main(string[] args)
    {
        await using var ctx = new BlogContext();
        await ctx.Database.EnsureDeletedAsync();
        await ctx.Database.EnsureCreatedAsync();

        ctx.Blogs.Add(new Mitteilung { Name = "foo" });
        await ctx.SaveChangesAsync();
    }
}

public class BlogContext : DbContext
{
    public DbSet<Mitteilung> Blogs { get; set; }

    static ILoggerFactory ContextLoggerFactory
        => LoggerFactory.Create(b => b.AddConsole().AddFilter("", LogLevel.Information));

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseNpgsql("...")
            .EnableSensitiveDataLogging()
            .UseLoggerFactory(ContextLoggerFactory);

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Mitteilung>()
            .Property(b => b.MitteilungId)
            .UseIdentityAlwaysColumn();
    }
}

public class Mitteilung
{
    public int MitteilungId { get; set; }
    public string Name { get; set; }
}
```

Body:
I'm currently trying to use Npgsql (version 3.1.3) to insert a record into a table with a generated identity using the official documentation (Npgsql.org) . But I always get the error:

Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
 ---> Npgsql.PostgresException (0x80004005): 428C9: cannot insert into column "mitteilung_id"

I have already found several questions about this topic, but they are either outdated (version 2 or lower) or do not work.

My project is structured as follows. The table definition looks like this:

CREATE TABLE mitteilung
(
    mitteilung_id INTEGER GENERATED ALWAYS AS IDENTITY
        CONSTRAINT mitteilung_pk
            PRIMARY KEY,
    betreff       TEXT
        CONSTRAINT mitteilung_nn_betreff
            CHECK (betreff IS NOT NULL)
        CONSTRAINT mitteilung_ck_length_betreff
            CHECK (length(betreff) <= 100),
    nachricht     TEXT
        CONSTRAINT mitteilung_ck_length_nachricht
            CHECK (length(nachricht) <= 500)
        CONSTRAINT mitteilung_nn_nachricht
            CHECK (nachricht IS NOT NULL),
    erfasst_am    TIMESTAMP WITH TIME ZONE
        CONSTRAINT mitteilung_nn_erfasst_am
            CHECK (erfasst_am IS NOT NULL)
);

I have defined the entity as follows:

public class Mitteilung : ISlongooEntity
    {
        public int MitteilungId { get; set; }

...

I have also tried to add the following attributes to the ID property:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

In the DB context I have tested the following settings to solve the problem.

modelBuilder.Entity<Mitteilung>()
                .Property(b => b.MitteilungId)
                .UseIdentityAlwaysColumn();

modelBuilder.Entity<Mitteilung>()
                .Property(b => b.MitteilungId)
 .Metadata.SetValueGenerationStrategy(NpgsqlValueGenerationStrategy.IdentityAlwaysColumn);

modelBuilder.Entity<Mitteilung>()
                .Property(b => b.MitteilungId)
.Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);

But no matter in which combination I use the settings, I get the above mentioned error message when trying to save an entity. I also don't quite understand why an attempt is made to update the ID at all when an update is made. What am I doing wrong?

public Mitteilung Save(Mitteilung obj)
        {
            var addedObj = Context.Mitteilungen.Add(obj);
            // Context.Entry(obj).Property(x => x.MitteilungId).IsModified = false;
            Context.SaveChanges();
            return addedObj.Entity;
        }


问:
element showing in design window but not showing in the emulator in Android Studio
I'm designing a screen where the user will be able to click on the plus sign that you will see in the design window, but whenever I run the code it doesn't show on the emulator.
did anyone face this kind of problem, I wanted to upload some of the code but it's too long.

XML file

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DashboardActivity">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/dashboard_toolbar"

        android:layout_width="match_parent"
        android:layout_height="?android:actionBarSize"

        android:background="@color/colorPrimaryDark" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_dashboard"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab_dashboard"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="338dp"
        android:layout_marginLeft="338dp"
        android:layout_marginTop="659dp"
        android:layout_marginEnd="17dp"
        android:layout_marginRight="17dp"
        android:layout_marginBottom="16dp"
        android:src="@drawable/plus"
        app:backgroundTint="@color/colorPrimaryDark" />

</RelativeLayout>

</code>```

答:
Your XML code should look like this in a coordinatorlayout

```<code><androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_marginEnd="16dp"
    android:layout_marginBottom="16dp"
    android:elevation="0dp"
    app:srcCompat="@drawable/ic_fab_chart" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

Your MainActivity.Kt file, if you are using Kotlin should look like this

```<code>import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    fab.setOnClickListener { view ->
        Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
    }
}

}
</code>```

If you are using java your MainActivity.java file should look like this

```<code>import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action",
Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}
</code>```

Body:
I'm designing a screen where the user will be able to click on the plus sign that you will see in the design window, but whenever I run the code it doesn't show on the emulator.
did anyone face this kind of problem, I wanted to upload some of the code but it's too long.

XML file

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DashboardActivity">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/dashboard_toolbar"

        android:layout_width="match_parent"
        android:layout_height="?android:actionBarSize"

        android:background="@color/colorPrimaryDark" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv_dashboard"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab_dashboard"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="338dp"
        android:layout_marginLeft="338dp"
        android:layout_marginTop="659dp"
        android:layout_marginEnd="17dp"
        android:layout_marginRight="17dp"
        android:layout_marginBottom="16dp"
        android:src="@drawable/plus"
        app:backgroundTint="@color/colorPrimaryDark" />

</RelativeLayout>

Body:
Your XML code should look like this in a coordinatorlayout

<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_marginEnd="16dp"
    android:layout_marginBottom="16dp"
    android:elevation="0dp"
    app:srcCompat="@drawable/ic_fab_chart" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Your MainActivity.Kt file, if you are using Kotlin should look like this

import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    fab.setOnClickListener { view ->
        Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
    }
}

}

If you are using java your MainActivity.java file should look like this

import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action",
Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}


问:
EF CodeFirst: Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong
I've a table named EducationTypes and an Entity named EducationType, I renamed one of entity properties, now I'm frequently getting Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong. How can I solve this issue?

The generated SQL Script:

```<code>EXECUTE sp_rename @objname = N'dbo.EducationTypes.nvarchar', @newname = N'EducationTypeTitle', @objtype = N'COLUMN'
</code>```

答: I resolved this error by deleting all the old migrations from My database Migration history table in SQL server and then adding a new one but only for the desired changes and then updated database.It worked fine.</p>

ContentLicense: CC BY-SA 3.0

Body:
I've a table named EducationTypes and an Entity named EducationType, I renamed one of entity properties, now I'm frequently getting Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong. How can I solve this issue?

The generated SQL Script:

EXECUTE sp_rename @objname = N'dbo.EducationTypes.nvarchar', @newname = N'EducationTypeTitle', @objtype = N'COLUMN'


问:
How to write a Javascript function that sorts account numbers in a string?
Write a function that sorts account numbers in a string and returns a string of sorted account numbers. Also remove the duplicates and add the number of duplicates at the end of the original bankNumber
ex:

```<code>12455 1435 5
 12455 1435 5
</code>```

will be:

```<code>12455 1435 52
</code>```

example:

```<code> var input = `2
 5
 12455 1435 5
 12455 1435 5
 23454 3554 5
 12344 1435 30
 12344 1435 30

 2
 41234 5451 9
 13451 5151 5
 `;

output = "2
 5
 12344 1435 302
 12455 1435 52
 23454 3554 5

 2
 13451 5151 5
 41234 5451 9
 "
</code>```

I have split the strings in to a array using split("\n").
    and sorted the array using a for loop and sort().
    Mostly having trouble getting it sort both transactions.

Thanks.

This is what i have so far:

```<code>function sort(a) {
  let totalTests = a.slice(0, 1);
  let newString = a.slice(2);
  let arr = newString.split("\n");
  let tempBankNumbers = 0;

  let multiArr = [];
  let arr2 = [1]
  let tempBankNumberAmount = arr2.splice(0, 1);
  let totalTestsInt = parseInt(totalTests);

    for(let i = 0; i < totalTestsInt -1 ; i++)
  {
    let arrayTemp = arr.splice(0, arr.indexOf(""))
   multiArr[i] = (arrayTemp)
  }
  arr2.sort();

  var tempBankNumber = "";

  let returnArray = [];
  returnArray.push(tempBankNumberAmount[0]);

  for (let i = 0; i < arr2.length; i++) {
    tempBankNumber = arr2[i];
    let numberOfAccounts = 1;

    for (let j = i + 1; j < arr2.length; j++) {
      if (arr2[i] == (arr2[j])) {

        arr2[i] = arr2[i].concat(++numberOfAccounts)
        arr2.splice(j, 1)
      }
    }
  }
  arr2.unshift(tempBankNumberAmount[0])
  return a;
}
</code>```

答:
I've put comments into how it works.  I'm assuming they should be lexical sorted only based on original values, and not based on appended string.

Uses object map to keep track of dupe count, then unwraps object map.

var input = `2
 5
 12455 1435 5
 12455 1435 5
 23454 3554 5
 12344 1435 30
 12344 1435 30

 2
 41234 5451 9
 13451 5151 5
 `;

const [t, ...split] = input.split(/\s*\n+\s*/)

const r = [], rn = []
let n
while (n = split.shift()) {
  rn.push(n)
  r.push(
    Object.entries(
      // sort first
      split.splice(0, +n).sort()
        // increment object map count value
        .reduce((a, x) => (a[x] = (a[x] || 0) + 1, a), {}))
     // append count if > 1
    .map(([k, v]) => `${k}${v>1?v:''}`))
}

// concat the input count numbers in the input and join result array
console.log(t+'\n'+r.map((x,i)=>`${rn[i]}\n${x.join('\n')}`).join('\n'))```

Body:
Write a function that sorts account numbers in a string and returns a string of sorted account numbers. Also remove the duplicates and add the number of duplicates at the end of the original bankNumber
ex:

12455 1435 5
 12455 1435 5

will be:

12455 1435 52

example:

 var input = `2
 5
 12455 1435 5
 12455 1435 5
 23454 3554 5
 12344 1435 30
 12344 1435 30

 2
 41234 5451 9
 13451 5151 5
 `;

output = "2
 5
 12344 1435 302
 12455 1435 52
 23454 3554 5

 2
 13451 5151 5
 41234 5451 9
 "

I have split the strings in to a array using split("\n").
    and sorted the array using a for loop and sort().
    Mostly having trouble getting it sort both transactions.

Thanks.

This is what i have so far:

function sort(a) {
  let totalTests = a.slice(0, 1);
  let newString = a.slice(2);
  let arr = newString.split("\n");
  let tempBankNumbers = 0;

  let multiArr = [];
  let arr2 = [1]
  let tempBankNumberAmount = arr2.splice(0, 1);
  let totalTestsInt = parseInt(totalTests);

    for(let i = 0; i < totalTestsInt -1 ; i++)
  {
    let arrayTemp = arr.splice(0, arr.indexOf(""))
   multiArr[i] = (arrayTemp)
  }
  arr2.sort();

  var tempBankNumber = "";

  let returnArray = [];
  returnArray.push(tempBankNumberAmount[0]);

  for (let i = 0; i < arr2.length; i++) {
    tempBankNumber = arr2[i];
    let numberOfAccounts = 1;

    for (let j = i + 1; j < arr2.length; j++) {
      if (arr2[i] == (arr2[j])) {

        arr2[i] = arr2[i].concat(++numberOfAccounts)
        arr2.splice(j, 1)
      }
    }
  }
  arr2.unshift(tempBankNumberAmount[0])
  return a;
}


问:
Python or NumPy to randomize an array with a specific proportion
This code is to randomize an array with a specific proportion

```<code>a0 = np.full((17),0)
a1 = np.full((30),1)
a2 = np.full((38),2)
a3 = np.full((15),3)
options = np.concatenate((a0,a1,a2,a3))
np.random.shuffle(options)
</code>```

it works as expected generating [a0, a1, a2, a3] with the specific proportion [17%, 30%, 38%, 15%]

However, it becomes ugly when the number of "ax" grow large, like [a0, a1, ... , a999] with [1%, 5%, ... , .2%]

Does Python or NumPy have API to do that work?

答:
You can use a dict where the key is number and the value is the repeats. Then use a list comprehension to build the list to concatenate.

```<code>d = {
0: 17,
1: 30,
2: 38,
3: 15
}

options = no.concatenate([np.full((v), k) for k, v in d.items()])
</code>```

Body:
This code is to randomize an array with a specific proportion

a0 = np.full((17),0)
a1 = np.full((30),1)
a2 = np.full((38),2)
a3 = np.full((15),3)
options = np.concatenate((a0,a1,a2,a3))
np.random.shuffle(options)

it works as expected generating [a0, a1, a2, a3] with the specific proportion [17%, 30%, 38%, 15%]

However, it becomes ugly when the number of "ax" grow large, like [a0, a1, ... , a999] with [1%, 5%, ... , .2%]

Does Python or NumPy have API to do that work?

Body:
You can use a dict where the key is number and the value is the repeats. Then use a list comprehension to build the list to concatenate.

d = {
0: 17,
1: 30,
2: 38,
3: 15
}

options = no.concatenate([np.full((v), k) for k, v in d.items()])


问:
Laravel search results paginate without direct collection
I have a search like:

```<code>$users = User::search($q)
               ->orderBy($sortBy, $orderBy)
               ->paginate($perPage);
</code>```

and I can paginate results in blade with

```<code>{{ $users->render() }}
</code>```

no problem.
However my SearchController continues like

```<code>if($request->loc){
    $users = $users->where('loc',$request->loc);
}
if($request->sz) {
    $users = $users->where('sz',$request->sz);
}
...
return view('search', compact('users'));
</code>```

which means I cant use the {{ $users->render() }} in blade because $users doesnt have the orderBy, paginate of the collection.

How can I solve this? Thanks for answer!

答:
You should not combine pagination and filtering the Collections, it can make the results flakey. If you want filtering with pagination you have to do it on the QueryBuilder.

For your logic you can utilize when($condition, $clojure) on the QueryBuilder that will only execute if the condition is true.

```<code>$users = User::search($q)
           ->orderBy($sortBy, $orderBy)
           ->when($request->loc, function ($query) use ($request) {
               $query->where('loc', $request->loc);
           })
           ->when($request->sz, function ($query) use ($request) {
               $query->where('sz', $request->sz);
           })
           ->paginate($perPage);

return view('search', compact('users'));
</code>```

Body:
I have a search like:

$users = User::search($q)
               ->orderBy($sortBy, $orderBy)
               ->paginate($perPage);

and I can paginate results in blade with

{{ $users->render() }}

no problem.
However my SearchController continues like

if($request->loc){
    $users = $users->where('loc',$request->loc);
}
if($request->sz) {
    $users = $users->where('sz',$request->sz);
}
...
return view('search', compact('users'));

which means I cant use the {{ $users->render() }} in blade because $users doesnt have the orderBy, paginate of the collection.

How can I solve this? Thanks for answer!

Body:
You should not combine pagination and filtering the Collections, it can make the results flakey. If you want filtering with pagination you have to do it on the QueryBuilder.

For your logic you can utilize when($condition, $clojure) on the QueryBuilder that will only execute if the condition is true.

$users = User::search($q)
           ->orderBy($sortBy, $orderBy)
           ->when($request->loc, function ($query) use ($request) {
               $query->where('loc', $request->loc);
           })
           ->when($request->sz, function ($query) use ($request) {
               $query->where('sz', $request->sz);
           })
           ->paginate($perPage);

return view('search', compact('users'));


问:
How to find elements without using the tag attribute?
```<code>image = driver.find_elements_by_xpath("//img[contains(@class,'ui_qtext')]")
copy = driver.find_elements_by_xpath("//p[contains(@class,'ui_qtext')]")
</code>```

I have this two elements with different tag_names. How do i locate them without the tag_name? Or how do i "combine" this two? Both have the same class_name.

答:
To remove the dependency on the tagNames you can use either of the following  Locator Strategies:

Using xpath:

```<code>image_copy = driver.find_elements_by_xpath("//*[contains(@class,'ui_qtext')]")
</code>```

Using css_selector:

```<code>image_copy = driver.find_elements_by_css_selector(".ui_qtext")
</code>```

Body:
image = driver.find_elements_by_xpath("//img[contains(@class,'ui_qtext')]")
copy = driver.find_elements_by_xpath("//p[contains(@class,'ui_qtext')]")

I have this two elements with different tag_names. How do i locate them without the tag_name? Or how do i "combine" this two? Both have the same class_name.

Body:
To remove the dependency on the tagNames you can use either of the following  Locator Strategies:

Using xpath:

image_copy = driver.find_elements_by_xpath("//*[contains(@class,'ui_qtext')]")

Using css_selector:

image_copy = driver.find_elements_by_css_selector(".ui_qtext")


答:
So if you grow the basenumber the individual percentage decreases, if you want to hold the same percentages you have to increment the size of the arrays with the same proportion.
Instead of writing '17' you could try to write 0.17 * len(total array), if this does help</p>

Title: Python or NumPy to randomize an array with a specific proportion


问:
could not stat file - c
I need to stat a file to get the size of it. I also need to provide the name of the file as a command line argument. This is my code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

int main (int argc, char* argv[])
{
    int N = 300;
    int L = 1000;
    char Nseq[N][L];

    FILE *myfile;
    char *token;
    const char s[2] = ",";
    char *line;
    int lenline;
    char filename[100];
    strcpy(filename, "/path/");
    char name[100];
    strcpy(name, argv[1]);
    strcat(filename, name);
    strcat(filename, ".txt");
    printf("%s\n", filename);

    int err;
    struct stat st;
    int n = 0;

    err = stat(filename,&st);
    if (err < 0) {
        printf("could not stat file %s", filename);
        exit(1);
    }
    lenline = st.st_size + 1;

    line = malloc(lenline);

    myfile = fopen(filename, "r");
    if (myfile == NULL) {
        printf("could not open file %s", filename);
        exit(1);
    }

    while (fgets(line, lenline, myfile) != NULL) {
        token = strtok(line, s);
        while (token != NULL && n<N) {
            strcpy(Nseq[n], token);
            printf("%s\t%u\n", token, n);
            token = strtok(NULL, s);
            n++;
        }
    }

    fclose(myfile);

    return 0;
}
</code>```

The output I get is:

```<code>/path/file.txt

could not stat file /path/file.txt
</code>```

Does anyone know why is this happening?
how can I fix it?
thank you!

答:
The underlying problem, most likely, is that you're prepending /path and appending .txt and there is no actual file at the path you're constructing before calling stat.  If you focus only on successfully stating the file, try this:

```<code>#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>

int main (int argc, char** argv) {
  const char* filename = argv[1];

  printf("Calling stat(%s)...", filename);

  int err;
  struct stat st;

  err = stat(filename, &st);
  if (err < 0) {
    printf("failed with error %d (%s)\n", err, strerror(errno));
    return err;
  } else {
    printf("succeeded\n");
    return 0;
  }
}
</code>```

At the very least you'll see exactly why stat is failing and it will help show why you're code isn't working properly.

Title: could not stat file - c

Body:
I need to stat a file to get the size of it. I also need to provide the name of the file as a command line argument. This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>

int main (int argc, char* argv[])
{
    int N = 300;
    int L = 1000;
    char Nseq[N][L];

    FILE *myfile;
    char *token;
    const char s[2] = ",";
    char *line;
    int lenline;
    char filename[100];
    strcpy(filename, "/path/");
    char name[100];
    strcpy(name, argv[1]);
    strcat(filename, name);
    strcat(filename, ".txt");
    printf("%s\n", filename);

    int err;
    struct stat st;
    int n = 0;

    err = stat(filename,&st);
    if (err < 0) {
        printf("could not stat file %s", filename);
        exit(1);
    }
    lenline = st.st_size + 1;

    line = malloc(lenline);

    myfile = fopen(filename, "r");
    if (myfile == NULL) {
        printf("could not open file %s", filename);
        exit(1);
    }

    while (fgets(line, lenline, myfile) != NULL) {
        token = strtok(line, s);
        while (token != NULL && n<N) {
            strcpy(Nseq[n], token);
            printf("%s\t%u\n", token, n);
            token = strtok(NULL, s);
            n++;
        }
    }

    fclose(myfile);

    return 0;
}

The output I get is:

/path/file.txt

could not stat file /path/file.txt

Does anyone know why is this happening?
how can I fix it?
thank you!

Body:
The underlying problem, most likely, is that you're prepending /path and appending .txt and there is no actual file at the path you're constructing before calling stat.  If you focus only on successfully stating the file, try this:

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>

int main (int argc, char** argv) {
  const char* filename = argv[1];

  printf("Calling stat(%s)...", filename);

  int err;
  struct stat st;

  err = stat(filename, &st);
  if (err < 0) {
    printf("failed with error %d (%s)\n", err, strerror(errno));
    return err;
  } else {
    printf("succeeded\n");
    return 0;
  }
}

At the very least you'll see exactly why stat is failing and it will help show why you're code isn't working properly.


问:
How to call kendra api using reactjs?
i am not able to call the kendra API using reactjs.
i have below details in js only but need help in reactjs:

```<code>var kendra = new AWS.Kendra();
kendra.batchDeleteDocument(params, function (err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});
</code>```

please help me.

答:
I think it's better/safer if you could have a lambda function to deal with the Kendra query and your reactjs can call the lambda function. In this way, you can control more on the query and others.

Since you also need the kendra index id or other information, it's better to hide them in the lambda.

For example, you can add a simple flask lambda/app:

```<code>@app.route('/kendra/<method>', methods=['POST'])
def client(method: str):
    kendra = boto3.client('kendra')
    try:
        data = request.get_json(silent=True) or {}
        return jsonify(getattr(kendra, method)(**data))
    except Exception as e:
        return jsonify({'error': f"{e}"})
</code>```

Title: How to call kendra api using reactjs?

Body:
i am not able to call the kendra API using reactjs.
i have below details in js only but need help in reactjs:

var kendra = new AWS.Kendra();
kendra.batchDeleteDocument(params, function (err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

please help me.

Body:
I think it's better/safer if you could have a lambda function to deal with the Kendra query and your reactjs can call the lambda function. In this way, you can control more on the query and others.

Since you also need the kendra index id or other information, it's better to hide them in the lambda.

For example, you can add a simple flask lambda/app:

@app.route('/kendra/<method>', methods=['POST'])
def client(method: str):
    kendra = boto3.client('kendra')
    try:
        data = request.get_json(silent=True) or {}
        return jsonify(getattr(kendra, method)(**data))
    except Exception as e:
        return jsonify({'error': f"{e}"})


问:
Is there R function for specifying treatment group as indicator in linear regression?
I have original dataset collected for my  thesis survey experiment analyzing effects of various  crisis communication strategies on voter's public approval for politician who committed a political scandal. I have 4 treatment and 2 control groups, wherein T1, T2 and C1 refer to one type of scandal, and T3, T4 and C2 to another type. I need to run regression where

```<code> lm(PoliticalApproval ~ Ideology + Education + Age + Sex + Plaus_1 + Seri_1 + FL_10_DO, data = c(Qualtricsdata))
</code>```

FL_10_DO variable stands for treatment/control group (T1, T2, etc). How do i specify regression that would take C1 as a reference group, and have coefficients for T1 and T2 which represents different types of communication strategies? Is there a code in R to do that? Thank you

答:
The solution provided by @daszlosek should work! You can also use relevel() command to make C1/C2 as your reference group. Here is the link to its R documentation: https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/relevel

If you wish to change the base level for all analyses on your data, you can do this:

```<code># Make C1 as the reference group
Qualtricsdata$FL_10_DO_R <- relevels(Qualtricsdata$FL_10_DO, ref = "C1")

#check the level to make sure we turn C1 into the reference group
levels(Qualtricsdata$FL_10_DO_R)
</code>```

This should return something like this

```<code>> levels(Qualtricsdata$FL_10_DO_R)
[1] "C1" "XXX" "XXX"
</code>```

You can also choose to use relevel inside your formula so it won't affect your original dataset.

```<code>lm(PoliticalApproval ~ Ideology + Education + Age + Sex + Plaus_1 + Seri_1 + relevel(FL_10_DO, ref = "C1"), data = c(Qualtricsdata))
</code>```

Body:
I have original dataset collected for my  thesis survey experiment analyzing effects of various  crisis communication strategies on voter's public approval for politician who committed a political scandal. I have 4 treatment and 2 control groups, wherein T1, T2 and C1 refer to one type of scandal, and T3, T4 and C2 to another type. I need to run regression where

 lm(PoliticalApproval ~ Ideology + Education + Age + Sex + Plaus_1 + Seri_1 + FL_10_DO, data = c(Qualtricsdata))

FL_10_DO variable stands for treatment/control group (T1, T2, etc). How do i specify regression that would take C1 as a reference group, and have coefficients for T1 and T2 which represents different types of communication strategies? Is there a code in R to do that? Thank you

Body:
The solution provided by @daszlosek should work! You can also use relevel() command to make C1/C2 as your reference group. Here is the link to its R documentation: https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/relevel

If you wish to change the base level for all analyses on your data, you can do this:

# Make C1 as the reference group
Qualtricsdata$FL_10_DO_R <- relevels(Qualtricsdata$FL_10_DO, ref = "C1")

#check the level to make sure we turn C1 into the reference group
levels(Qualtricsdata$FL_10_DO_R)

This should return something like this

> levels(Qualtricsdata$FL_10_DO_R)
[1] "C1" "XXX" "XXX"

You can also choose to use relevel inside your formula so it won't affect your original dataset.

lm(PoliticalApproval ~ Ideology + Education + Age + Sex + Plaus_1 + Seri_1 + relevel(FL_10_DO, ref = "C1"), data = c(Qualtricsdata))


问:
Importing Maven project is changing src/test/resource structure
Importing Maven Project is splitting src/test/resource folder

Originally, there are multiple packages under that project structure, if I import the maven project into eclipse as existing maven project,

the project is split into

1) src/test/resource/properties
2) src/test /resource

Please see the before and after screen shot Original Project Structure
Project Structure after import

I have bunch of packages on src/test/resources. If I import project into eclipse as an existing Maven project, the src/test/resources folder gets split into 2 structure, not sure why this is happening enter image description here

答:
Looks like the log4j properties in pom.xml was influencing the structure, </p>

<p>removed the following the pom.xml and updated the maven project, and the project structured went to the original state incase anyone in the future runs into this issue-- </p>

```<code><testResources>
            <testResource>
                <directory>src/test/resources/properties</directory>
                <includes>
                    <include>log4j.properties</include>
                </includes>
            </testResource>
        </testResources>
</code>```

Body:
Looks like the log4j properties in pom.xml was influencing the structure,

removed the following the pom.xml and updated the maven project, and the project structured went to the original state incase anyone in the future runs into this issue--

<testResources>
            <testResource>
                <directory>src/test/resources/properties</directory>
                <includes>
                    <include>log4j.properties</include>
                </includes>
            </testResource>
        </testResources>


问:
Find which version of package is installed with pip
Using pip, is it possible to figure out which version of a package is currently installed?

I know about pip install XYZ --upgrade but I am wondering if there is anything like pip info XYZ.  If not what would be the best way to tell what version I am currently using.

答:
To do this using Python code:

Using importlib.metadata.version

Python ≥3.8

import importlib.metadata
importlib.metadata.version('beautifulsoup4')
'4.9.1'
```

<h3>Python ≤3.7</h3>

<p>(using <code>importlib_metadata.version</code>)</p>

<pre class="lang-py prettyprint-override"><code>!pip install importlib-metadata

import importlib_metadata
importlib_metadata.version('beautifulsoup4')
'4.9.1'
</code>```

Using pkg_resources.Distribution

import pkg_resources
pkg_resources.get_distribution('beautifulsoup4').version
'4.9.1'
pkg_resources.get_distribution('beautifulsoup4').parsed_version
<Version('4.9.1')>
```

Credited to comments by sinoroc and mirekphd.

Body:
To do this using Python code:

Using importlib.metadata.version

Python ≥3.8

import importlib.metadata
importlib.metadata.version('beautifulsoup4')
'4.9.1'

Python ≤3.7

(using importlib_metadata.version)

!pip install importlib-metadata

import importlib_metadata
importlib_metadata.version('beautifulsoup4')
'4.9.1'

Using pkg_resources.Distribution

import pkg_resources
pkg_resources.get_distribution('beautifulsoup4').version
'4.9.1'
pkg_resources.get_distribution('beautifulsoup4').parsed_version
<Version('4.9.1')>

Credited to comments by sinoroc and mirekphd.


问:
Any ideas about how to use CSS to emulate a messy stamp?
I'm interested in ways to render a span that to look something like one of these:

Here are the tricks I plan on using:

@font-face

-{moz/webkit/o}-transform:rotate

It's for a personal project so assuming the most modern CSS support is fine. Maybe border-images could help? I'd like to avoid image splicing all over the place -- if it really comes down to that I'll just skip the border all together and rely on a font for the look.

I'm just curious how the CSS gurus around here would approach this.

UPDATE

There is now a CSS property for this, mask-image. More here.

答:
There is no specific css solution for the grunge look. You'll have to rely on a typeface for that, or an image (such as some sort of 'grungy' splotch pattern that matches the background color on top of the type).

The only other CSS that might be applicable is to use an RGBA color set to perhaps 80 or 90% opacity to allow a bit of whatever background pattern you might use seep through as would be the case with a real ink stamp.

I love doing as much as I can with CSS, but for that specific look, I'd stick with an image. Images still serve a purpose. ;o)


问:
Check that bot is in channel before on_voice_state_update process
I have previously asked a question for the actual process of this and I got it working perfectly but there's just one bug to this.

```<code>async def on_voice_state_update(self, member, before, after):
    def is_connected(member):
        voice_client = get(self.bot.voice_clients, guild=member.guild)
        return voice_client and voice_client.is_connected()

    if is_connected(member):
        await asyncio.sleep(9)
        if member.id == 'id of member' and after.afk and not before.afk:
            prevchannel = int(before.channel.id)
            channel = self.bot.get_channel(prevchannel)
            voice = await channel.connect()
            voice.play(discord.FFmpegPCMAudio('dir of mp3 file'))
            await asyncio.sleep(5)
            await voice.disconnect()
        else:
            pass
    else:
        if member.id == 'id of member' and after.afk and not before.afk:
            prevchannel = int(before.channel.id)
            channel = self.bot.get_channel(prevchannel)
            voice = await channel.connect()
            voice.play(discord.FFmpegPCMAudio('dir of mp3 file'))
            await asyncio.sleep(5)
            await voice.disconnect()
        else:
            pass
</code>```

I am trying to check if the bot is already connected to a voice channel so that if more than one person joins the afk at a similar time (like 2 seconds later) it waits until the next iteration of the program is executed: await asyncio.sleep(10)

The Problem

I can't seem to get the is_connected function to work, although I believe I am heading in the right direction. I have thought of trying to get the user id of the bot and checking if it's connected to a voice channel. It would be something like this:

```<code>def is_botconnected(member):
    botid = self.bot.get_user('id of bot')
    channel = (all the channels)
if botid in channel.members:
    await asyncio.sleep(9)
    #execute program
else:
    #execute program
</code>```

答:
The solution

I managed to get it to work by using bot.voice_clients.

```<code>async def on_voice_state_update(self, member, before, after):
    def is_connected(self):
        bot_client = get(self.bot.voice_clients)
        return bot_client and bot_client.is_connected()

    if is_connected(self):
        await asyncio.sleep(9)
        #execute program
    else:
        #execute program
</code>```

self is used as it is a cog.

Body:
I have previously asked a question for the actual process of this and I got it working perfectly but there's just one bug to this.

async def on_voice_state_update(self, member, before, after):
    def is_connected(member):
        voice_client = get(self.bot.voice_clients, guild=member.guild)
        return voice_client and voice_client.is_connected()

    if is_connected(member):
        await asyncio.sleep(9)
        if member.id == 'id of member' and after.afk and not before.afk:
            prevchannel = int(before.channel.id)
            channel = self.bot.get_channel(prevchannel)
            voice = await channel.connect()
            voice.play(discord.FFmpegPCMAudio('dir of mp3 file'))
            await asyncio.sleep(5)
            await voice.disconnect()
        else:
            pass
    else:
        if member.id == 'id of member' and after.afk and not before.afk:
            prevchannel = int(before.channel.id)
            channel = self.bot.get_channel(prevchannel)
            voice = await channel.connect()
            voice.play(discord.FFmpegPCMAudio('dir of mp3 file'))
            await asyncio.sleep(5)
            await voice.disconnect()
        else:
            pass

I am trying to check if the bot is already connected to a voice channel so that if more than one person joins the afk at a similar time (like 2 seconds later) it waits until the next iteration of the program is executed: await asyncio.sleep(10)

The Problem

I can't seem to get the is_connected function to work, although I believe I am heading in the right direction. I have thought of trying to get the user id of the bot and checking if it's connected to a voice channel. It would be something like this:

def is_botconnected(member):
    botid = self.bot.get_user('id of bot')
    channel = (all the channels)
if botid in channel.members:
    await asyncio.sleep(9)
    #execute program
else:
    #execute program

Body:
The solution

I managed to get it to work by using bot.voice_clients.

async def on_voice_state_update(self, member, before, after):
    def is_connected(self):
        bot_client = get(self.bot.voice_clients)
        return bot_client and bot_client.is_connected()

    if is_connected(self):
        await asyncio.sleep(9)
        #execute program
    else:
        #execute program

self is used as it is a cog.


问:
Question R string manipulation, remove duplicates and merge/aggregate
I have a question regarding to R and changing strings. I want for the column taste, that every row has only one name and that duplicates are removed. Then I also want the sweets of duplicated tastes merged.I included before and after pictures as well.
How can I change that not manually but with something like aggregate or splitstring?
The before and after pictures show how it should look like.

```<code>    taste=c("Smarties, Strawberry","Smarties")
    sweets=c("IceCream","Chocolate")
    Dessert=data.frame(taste,sweets)
</code>```

Before:

After:

答:
We can use separate_rows on the 'taste' column to split the elements by the delimiter ,, then grouped by 'taste', paste the 'sweets' in summarise

```<code>library(dplyr)
library(tidyr)
Dessert %>%
    separate_rows(taste) %>%
    group_by(taste) %>%
    summarise(sweets = toString(sweets))
# A tibble: 2 x 2
#  taste      sweets
#* <chr>      <chr>
#1 Smarties   IceCream, Chocolate
#2 Strawberry IceCream
</code>```

Or in base R, use strsplit to split the 'taste' into a list of vectors, set the names of the list with the 'sweets' column, convert to a two column data.frame with stack and use aggregate to do a group by paste (toString - paste(., collapse=', '))

```<code>aggregate(ind ~ values, stack(setNames(strsplit(as.character(Dessert$taste),
         ",\\s*"), Dessert$sweets)), FUN = toString)
</code>```

Body:
I have a question regarding to R and changing strings. I want for the column taste, that every row has only one name and that duplicates are removed. Then I also want the sweets of duplicated tastes merged.I included before and after pictures as well.
How can I change that not manually but with something like aggregate or splitstring?
The before and after pictures show how it should look like.

    taste=c("Smarties, Strawberry","Smarties")
    sweets=c("IceCream","Chocolate")
    Dessert=data.frame(taste,sweets)

Before:

After:

Body:
We can use separate_rows on the 'taste' column to split the elements by the delimiter ,, then grouped by 'taste', paste the 'sweets' in summarise

library(dplyr)
library(tidyr)
Dessert %>%
    separate_rows(taste) %>%
    group_by(taste) %>%
    summarise(sweets = toString(sweets))
# A tibble: 2 x 2
#  taste      sweets
#* <chr>      <chr>
#1 Smarties   IceCream, Chocolate
#2 Strawberry IceCream

Or in base R, use strsplit to split the 'taste' into a list of vectors, set the names of the list with the 'sweets' column, convert to a two column data.frame with stack and use aggregate to do a group by paste (toString - paste(., collapse=', '))

aggregate(ind ~ values, stack(setNames(strsplit(as.character(Dessert$taste),
         ",\\s*"), Dessert$sweets)), FUN = toString)


问:
Is there a way to check if a collection.find returns false using PyMongo?
I am using PyMongo to make a basic currency bot with discord.py, however, the user can register multiple times into the db.

```<code>async def register(ctx):
    insert = {"userid":ctx.message.author.id,"cash":0}
    collection.insert_one(insert)
    await ctx.send('okie dokie you are registered')
</code>```

This is the code for the register command, but I'm not sure how to check if a collection.find query returns true or false. Does anybody know how to use it as a check, or any way to check if they are already registered?

答:
You can use find_one(), which will either return the obj, or None.

async def register(ctx):
    existing = collection.find_one({"userid": ctx.author.id})
    if not existing:
        # register the user
    else:
        await ctx.send("Sorry, you're already registered.")
```

References:

collection.find_one() - It states "Returns a single document, or None if no matching document is found."

Body:
I am using PyMongo to make a basic currency bot with discord.py, however, the user can register multiple times into the db.

async def register(ctx):
    insert = {"userid":ctx.message.author.id,"cash":0}
    collection.insert_one(insert)
    await ctx.send('okie dokie you are registered')

This is the code for the register command, but I'm not sure how to check if a collection.find query returns true or false. Does anybody know how to use it as a check, or any way to check if they are already registered?

Body:
You can use find_one(), which will either return the obj, or None.

async def register(ctx):
    existing = collection.find_one({"userid": ctx.author.id})
    if not existing:
        # register the user
    else:
        await ctx.send("Sorry, you're already registered.")

References:

collection.find_one() - It states "Returns a single document, or None if no matching document is found."


问:
Why is it guaranteed that the highest post number in the reverse graph will be in the sink SCC?
I think I understand now why we can't guarantee that the lowest post number in the original graph is a sink (it may have outgoing edges to vertices that have already been visited before it).

But why is the case different for reversing the graph and looking at the highest post number? Why is this a foolproof way to find a vertex in the sink SCC of the original graph?

答:
I think we reverse the graph for the following reason:
this is a stack operation.when we reverse the graph,we get the sink SCC for the reversed graph firstly and we push it to the top of the stack...we repeat the operation and finally the graph is null.then we pull the point set from the bottom of the stack,which is the sink SCC for the original graph. </p>


问:
for loop is not being executed python
When I run my program, a certain part of the code is not being executed:

```<code>for d in range(0, n+m-1, -1):
    cur = ""
    print("a")
for x in range(max(0, d-m+1),min(n, d+1),-1):
    cur = letras[x][d-x] + cur
    print(cur)
</code>```

The print() instructions are never being executed.

答:
Assuming n+m-1 is greater than 0, a step value of -1 will create an empty range. For example, print(list(range(0, 2, -1))) outputs [].

So check your input or wherever n and m are coming from.

Of course, same is true for the second range. Make sure that min(n, d+1) is not greater than max(0, d-m+1).

Consult range documentation.

Title: for loop is not being executed python

Body:
When I run my program, a certain part of the code is not being executed:

for d in range(0, n+m-1, -1):
    cur = ""
    print("a")
for x in range(max(0, d-m+1),min(n, d+1),-1):
    cur = letras[x][d-x] + cur
    print(cur)

The print() instructions are never being executed.


问:
Approval step on gitlab CI
I want to discuss and to know more approaches about how to add a approval step on Gitlab CI
Everybody knows that gitlab doesn't has a approval feature on the pipeline

I did a small template to add a kind of approval step in any step

this is the content of the template

```<code>.approval_template:
  image: node:buster
  before_script:
    - |
      cat <<'EOF' >> approval.js
      var users = process.env.USERS.split(',');

      if (users.includes(process.env.GITLAB_USER_LOGIN)) {
          console.log(process.env.GITLAB_USER_LOGIN + " allowed to run this job")
          process.exit(0)
      } else {
        console.log(process.env.GITLAB_USER_LOGIN + " cannot trigger this job")
        console.log("List of users allowed to run this job")
        for (user in users)
        {
          console.log(users[user])
        }
        process.exit(1)
      }
      EOF
    - node approval.js
    - rm approval.js
  when: manual
</code>```

how does it work?

This template checks if the user who triggered the job is inside the USERS variable (array)
The check happens on before_script block and it works in any step (without overwrite the before_script)

It works very well but I want to know if there is a better approach to do it.

答:
Anyone with write access to the repository can change that file and add themselves to the list. But my concern with the scripted approach is a different one, as you may end up confusing your future self or your successor(s) with a block of code to maintain. The person who triggers a job may be a different person than the one who would review the code, also I'm not sure if you want to assume that triggering equals approval.

Let me explain what I've been doing: Imagine having a development and a master branch - only master gets deployed automatically. Nobody can push directly to master when you protect the branch. Everything has to be merged into masterby using merge requests. Permission-wise it still comes down to having write access (developer or a higher role). This keeps the step of approval in the GUI (where you would expect an approval feature to appear once it's added). Additionally, accepting a merge request will trigger a dedicated e-mail notification.

This works very well when you make sure merging into master is a taboo except for the lead developers. Maybe this is not applicable for your situation but a different approach; and even this one needed my successor to be educated on where to click in order to approve a merge request.

If you want to fast-track the deployment of some developers you can assign them a higher role and use my suggested approach to let them push to the master branch directly. That way they skip the step of awaiting approval.

Title: Approval step on gitlab CI

Body:
I want to discuss and to know more approaches about how to add a approval step on Gitlab CI
Everybody knows that gitlab doesn't has a approval feature on the pipeline

I did a small template to add a kind of approval step in any step

this is the content of the template

.approval_template:
  image: node:buster
  before_script:
    - |
      cat <<'EOF' >> approval.js
      var users = process.env.USERS.split(',');

      if (users.includes(process.env.GITLAB_USER_LOGIN)) {
          console.log(process.env.GITLAB_USER_LOGIN + " allowed to run this job")
          process.exit(0)
      } else {
        console.log(process.env.GITLAB_USER_LOGIN + " cannot trigger this job")
        console.log("List of users allowed to run this job")
        for (user in users)
        {
          console.log(users[user])
        }
        process.exit(1)
      }
      EOF
    - node approval.js
    - rm approval.js
  when: manual

how does it work?

This template checks if the user who triggered the job is inside the USERS variable (array)
The check happens on before_script block and it works in any step (without overwrite the before_script)

It works very well but I want to know if there is a better approach to do it.


问:
Can't access property from object in Javascript
EDIT: Re-structured question, cleaer, and cleaner:

I have a data object from Sequelize that is sent by node-express:

```<code>{
    "page": 0,
    "limit": 10,
    "total": 4,
    "data": [
        {
            "id": 1,
            "title": "movies",
            "isActive": true,
            "createdAt": "2020-05-30T19:26:04.000Z",
            "updatedAt": "2020-05-30T19:26:04.000Z",
            "questions": [
                {
                    "questionsCount": 4
                }
            ]
        }
    ]
}
</code>```

The BIG question is, how do I get the value of questionsCount?
The PROBLEM is, I just can't extract it, these two methods give me undefined result:

category.questions[0].questionsCount

category.questions[0]['questionsCount']

I WAS ABLE to get it using toJSON() (From Sequelize lib I think), like so:

```<code>category.questions[0].toJSON().questionsCount
</code>```

But I'd like to know the answer to the question, or at least a clear explanation of why do I have to use toJSON() just to get the questionsCount?

More context:

I have this GET in my controller:

```<code>exports.getCategories = (req, res) => {
  const page = myUtil.parser.tryParseInt(req.query.page, 0)
  const limit = myUtil.parser.tryParseInt(req.query.limit, 10)

  db.Category.findAndCountAll({
    where: {},
    include: [
      {
        model: db.Question,
        as: "questions",
        attributes: [[db.Sequelize.fn('COUNT', 'id'), 'questionsCount']]
      }
    ],
    offset: limit * page,
    limit: limit,
    order: [["id", "ASC"]],
  })
    .then(data => {

      data.rows.forEach(function(category) {
        console.log("------ May 31 ----> " + JSON.stringify(category.questions[0]) + " -->" + category.questions[0].hasOwnProperty('questionsCount'))
        console.log(JSON.stringify(category))
        console.log(category.questions[0].toJSON().questionsCount)
      })

      res.json(myUtil.response.paging(data, page, limit))
    })
    .catch(err => {
      console.log("Error get categories: " + err.message)
      res.status(500).send({
        message: "An error has occured while retrieving data."
      })
    })
}
</code>```

I loop through the data.rows to get each category object.

The console.log outputs are:

```<code>------ May 31 ----> {"questionsCount":4} -->false

{"id":1,"title":"movies","isActive":true,"createdAt":"2020-05-30T19:26:04.000Z","updatedAt":"2020-05-30T19:26:04.000Z","questions":[{"questionsCount":4}]}

4
</code>```

答:
As mentioned by others already, you need category.data[0].questions[0].questionCount.

Let me add to that by showing you why. Look at your object, I annotated it with how each part would be accessed:

category = { // category
    "page": 0,
    "limit": 10,
    "total": 2,
    "data": [ // category.data
        { // category.data[0]
            "id": 1,
            "title": "movies",
            "createdAt": "2020-05-30T19:26:04.000Z",
            "updatedAt": "2020-05-30T19:26:04.000Z",
            "questions": [ // category.data[0].questions
                { // category.data[0].questions[0]
                    "questionCount": 2 // category.data[0].questions[0].questionCount
                }
            ],
            "questionsCount": "newValue here!"
        }
    ]
}
```

Body:
EDIT: Re-structured question, cleaer, and cleaner:

I have a data object from Sequelize that is sent by node-express:

{
    "page": 0,
    "limit": 10,
    "total": 4,
    "data": [
        {
            "id": 1,
            "title": "movies",
            "isActive": true,
            "createdAt": "2020-05-30T19:26:04.000Z",
            "updatedAt": "2020-05-30T19:26:04.000Z",
            "questions": [
                {
                    "questionsCount": 4
                }
            ]
        }
    ]
}

The BIG question is, how do I get the value of questionsCount?
The PROBLEM is, I just can't extract it, these two methods give me undefined result:

category.questions[0].questionsCount

category.questions[0]['questionsCount']

I WAS ABLE to get it using toJSON() (From Sequelize lib I think), like so:

category.questions[0].toJSON().questionsCount

But I'd like to know the answer to the question, or at least a clear explanation of why do I have to use toJSON() just to get the questionsCount?

More context:

I have this GET in my controller:

exports.getCategories = (req, res) => {
  const page = myUtil.parser.tryParseInt(req.query.page, 0)
  const limit = myUtil.parser.tryParseInt(req.query.limit, 10)

  db.Category.findAndCountAll({
    where: {},
    include: [
      {
        model: db.Question,
        as: "questions",
        attributes: [[db.Sequelize.fn('COUNT', 'id'), 'questionsCount']]
      }
    ],
    offset: limit * page,
    limit: limit,
    order: [["id", "ASC"]],
  })
    .then(data => {

      data.rows.forEach(function(category) {
        console.log("------ May 31 ----> " + JSON.stringify(category.questions[0]) + " -->" + category.questions[0].hasOwnProperty('questionsCount'))
        console.log(JSON.stringify(category))
        console.log(category.questions[0].toJSON().questionsCount)
      })

      res.json(myUtil.response.paging(data, page, limit))
    })
    .catch(err => {
      console.log("Error get categories: " + err.message)
      res.status(500).send({
        message: "An error has occured while retrieving data."
      })
    })
}

I loop through the data.rows to get each category object.

The console.log outputs are:

------ May 31 ----> {"questionsCount":4} -->false

{"id":1,"title":"movies","isActive":true,"createdAt":"2020-05-30T19:26:04.000Z","updatedAt":"2020-05-30T19:26:04.000Z","questions":[{"questionsCount":4}]}

4


问:
Is Ruby really an interpreted language if all of its implementations are compiled into bytecode?
In the chosen answer for this question about Blue Ruby, Chuck says:

All of the current Ruby
  implementations are compiled to
  bytecode. Contrary to SAP's claims, as
  of Ruby 1.9, MRI itself includes a
  bytecode compiler, though the ability
  to save the compiled bytecode to disk
  disappeared somewhere in the process
  of merging the YARV virtual machine.
  JRuby is compiled into Java .class
  files. I don't have a lot of details
  on MagLev, but it seems safe to say it
  will take that road as well.

I'm confused about this compilation/interpretation issue with respect to Ruby.

I learned that Ruby is an interpreted language and that's why when I save changes to my Ruby files I don't need to re-build the project.

But if all of the Ruby implementations now are compiled, is it still fair to say that Ruby is an interpreted language? Or am I misunderstanding something?

答:
A subtle question indeed...
It used to be that "interpreted" languages were parsed and transformed into an intermediate form which was faster to execute, but the "machine" executing them was a pretty language specific program.   "Compiled" languages were translated instead into the machine code instructions supported by the computer on which it was run.  An early distinction was very basic--static vs. dynamic scope.   In a statically typed language, a variable reference could pretty much be resolved to a memory address in a few machine instructions--you knew exactly where in the calling frame the variable referred.   In dynamically typed languages you had to search (up an A-list or up a calling frame) for the reference.  With the advent of object oriented programming, the non-immediate nature of a reference expanded to many more concepts--classes(types), methods(functions),even syntactical interpretation (embedded DSLs like regex).

The distinction, in fact, going back to maybe the late 70's was not so much between compiled and interpreted languages, but whether they were run in a compiled or interpreted environment.
For example, Pascal (the first high-level language I studied) ran at UC Berkeley first on Bill Joy's pxp interpreter, and later on the compiler he wrote pcc.  Same language, available in both compiled and interpreted environments.

Some languages are more dynamic than others, the meaning of something--a type, a method, a variable--is dependent on the run-time environment.   This means that compiled or not there is substantial run-time mechanism associated with executing a program.  Forth, Smalltalk, NeWs, Lisp, all were examples of this.  Initially, these languages required so much mechanism to execute (versus a C or a Fortran) that they were a natural for interpretation.

Even before Java, there were attempts to speed up execution of complex, dynamic languages with tricks, techniques which became threaded compilation, just-in-time compilation, and so on.

I think it was Java, though, which was the first wide-spread language that really muddied the compiler/interpreter gap, ironically not so that it would run faster (though, that too) but so that it would run everywhere.   By defining their own machine language and "machine" the java bytecode and VM, Java attempted to become a language compiled into something close to any basic machine, but not actually any real machine.

Modern languages marry all these innovations.  Some have the dynamic, open-ended, you-don't-know-what-you-get-until-runtime nature of traditional "interpreted languages (ruby, lisp, smalltalk, python, perl(!)), some try to have the rigor of specification allowing deep type-based static error detection of traditional compiled languages (java, scala).  All compile to actual machine-independent representations (JVM) to get write once-run anywhere semantics.

So, compiled vs. interpreted?  Best of both, I'd say.   All the code's around in source (with documentation), change anything and the effect is immediate, simple operations run almost as fast as the hardware can do them, complex ones are supported and fast enough, hardware and memory models are consistent across platforms.

The bigger polemic in languages today is probably whether they are statically or dynamically typed, which is to say not how fast will they run, but will the errors be found by the compiler beforehand (at the cost of the programmer having to specify pretty complex typing information) or will the errors come up in testing and production.

OwnerDisplayName: Paul Dexter


问:
Keras vs Pytorch NN code small differences, need clarification
I have the Keras and Pytorch code for the same neural network. Some of the lines are switched around between the two.
I am wondering why for the Pytorch version max pooling comes before batch normalization and reel activation. In Keras it comes after those two lines. And for flattening, I'm also confused on how Pytorch used 64 * 7 * 7 (where do the 7s come from?).

Here's the Keras version of the Shallow net Alex net:

```<code>def shallownet(nb_classes):
    global img_size
    model = Sequential()
    model.add(Conv2D(64, (5, 5), input_shape=img_size, data_format='channels_first'))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='same', data_format='channels_first'))

    model.add(Conv2D(64, (5, 5), padding='same', data_format='channels_first'))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='same', data_format='channels_first'))

    model.add(Flatten())
    model.add(Dense(384))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(192))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(nb_classes, activation='softmax'))
    return model
</code>```

and the Pytorch version:

```<code>class AlexNet(nn.Module):

    def __init__(self, num_classes=10):
        super(AlexNet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=5, padding=2,
                      bias=False),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.Conv2d(64, 64, kernel_size=5, padding=2, bias=False),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
        )
        self.classifier = nn.Sequential(
            nn.Linear(64 * 7 * 7, 384, bias=False),
            nn.BatchNorm1d(384),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(384, 192, bias=False),
            nn.BatchNorm1d(192),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(192, num_classes)
        )
        self.regime = {
            0: {'optimizer': 'SGD', 'lr': 1e-3,
                'weight_decay': 5e-4, 'momentum': 0.9},
            60: {'lr': 1e-2},
            120: {'lr': 1e-3},
            180: {'lr': 1e-4}
        }

    def forward(self, x):
        x = self.features(x)
        x = x.view(-1, 64 * 7 * 7)
        x = self.classifier(x)
        return F.log_softmax(x)

def cifar10_shallow(**kwargs):
    num_classes = getattr(kwargs, 'num_classes', 10)
    return AlexNet(num_classes)

def cifar100_shallow(**kwargs):
    num_classes = getattr(kwargs, 'num_classes', 100)
    return AlexNet(num_classes)
</code>```

答:
Max pooling downsamples the data by picking the maximum of a certain pool of values. Comparisons between data will not be affected by batch normalization and ReLU activation because both are one-to-one monotonically increasing functions.

relu(x) = max(0, x)
bn(x) = (x - mu) / sigma
```

Therefore, it doesn't really matter if max pool comes after or before those two layers (it might be more efficient to have it before).

Regarding the flattening, I believe the 7s are the spatial dimensions of the layer before Flatten() i.e. H = W = 7. Thus, the total number of values is equal to the spatial dimensions times the channel size which is 64 * 7 * 7.

Body:
I have the Keras and Pytorch code for the same neural network. Some of the lines are switched around between the two.
I am wondering why for the Pytorch version max pooling comes before batch normalization and reel activation. In Keras it comes after those two lines. And for flattening, I'm also confused on how Pytorch used 64 * 7 * 7 (where do the 7s come from?).

Here's the Keras version of the Shallow net Alex net:

def shallownet(nb_classes):
    global img_size
    model = Sequential()
    model.add(Conv2D(64, (5, 5), input_shape=img_size, data_format='channels_first'))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='same', data_format='channels_first'))

    model.add(Conv2D(64, (5, 5), padding='same', data_format='channels_first'))
    model.add(BatchNormalization(axis=1))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='same', data_format='channels_first'))

    model.add(Flatten())
    model.add(Dense(384))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(192))
    model.add(BatchNormalization())
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(nb_classes, activation='softmax'))
    return model

and the Pytorch version:

class AlexNet(nn.Module):

    def __init__(self, num_classes=10):
        super(AlexNet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=5, padding=2,
                      bias=False),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.Conv2d(64, 64, kernel_size=5, padding=2, bias=False),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
        )
        self.classifier = nn.Sequential(
            nn.Linear(64 * 7 * 7, 384, bias=False),
            nn.BatchNorm1d(384),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(384, 192, bias=False),
            nn.BatchNorm1d(192),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(192, num_classes)
        )
        self.regime = {
            0: {'optimizer': 'SGD', 'lr': 1e-3,
                'weight_decay': 5e-4, 'momentum': 0.9},
            60: {'lr': 1e-2},
            120: {'lr': 1e-3},
            180: {'lr': 1e-4}
        }

    def forward(self, x):
        x = self.features(x)
        x = x.view(-1, 64 * 7 * 7)
        x = self.classifier(x)
        return F.log_softmax(x)

def cifar10_shallow(**kwargs):
    num_classes = getattr(kwargs, 'num_classes', 10)
    return AlexNet(num_classes)

def cifar100_shallow(**kwargs):
    num_classes = getattr(kwargs, 'num_classes', 100)
    return AlexNet(num_classes)

Body:
Max pooling downsamples the data by picking the maximum of a certain pool of values. Comparisons between data will not be affected by batch normalization and ReLU activation because both are one-to-one monotonically increasing functions.

relu(x) = max(0, x)
bn(x) = (x - mu) / sigma

Therefore, it doesn't really matter if max pool comes after or before those two layers (it might be more efficient to have it before).

Regarding the flattening, I believe the 7s are the spatial dimensions of the layer before Flatten() i.e. H = W = 7. Thus, the total number of values is equal to the spatial dimensions times the channel size which is 64 * 7 * 7.


问:
How do I clip a variable sized widget in flutter?
I'm building a chat app where audio messages can accompany the text. The widget that displays this is a very standard looking chat bubble (think iMessage) with one twist - the bubble becomes a progress bar when the audio is playing. The progress bar is essentially just a gradual change in the background color. You can see the layout in this dartpad (hit run). A screenshot of the mock is here:

Because the chat bubble is rounded, I need the progress bar to round only at the end. In other words, it should always be rounded on the left as it is flush with the left side of the message but it should be flat on the right until it hits the end of the message. I think ClipRRect is the right widget to do this.

However, because the message bubble width is variable, I use a FractionallySizedBox as the progress bar. 1/10th the way through the audio, it should be 1/10th the width of the chat bubble. Then I use Positioned.fill to wrap the progress bar so that the fraction is taken out of the full message bubble width. ClipRRect does not seem to play nicely wrapping Positioned.fill I believe it expects the child to have a set size:

```<code>RenderBox was not laid out: RenderClipRRect#3b019 relayoutBoundary=up13
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1694 pos 12: 'hasSize'
</code>```

This is a dartpad to the version with the not-working ClipRRect. Is there some other widget I can wrap Position.fill in to make it clippable? Or maybe a better way to lay this out?

答:
Please try the following code.

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: ChatAudioTextBubble("Test message"),
        ),
      ),
    );
  }
}

class ChatAudioTextBubble extends StatefulWidget {
  final String text;

  ChatAudioTextBubble(this.text);

  @override
  _ChatAudioTextBubbleState createState() => _ChatAudioTextBubbleState();
}

class _ChatAudioTextBubbleState extends State<ChatAudioTextBubble>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;

  @override
  void initState() {
    _controller = AnimationController(
      lowerBound: 0.0,
      upperBound: 1.0,
      value: 0.0,
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    )..addListener(() {
        this.setState(() {});
      });
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void _onTapHandler() {
    _controller.reset();
    _controller.forward(from: 0.0);
  }

  Widget build(BuildContext context) {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          _onTapHandler();
          print(
              "Plays the audio and starts the animation which takes _controller.value from 0-1");
        },
        child: Stack(children: [
          Positioned.fill(
              child: Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                color: Color(0xFFE6E6E6)),
          )),
          Container(
              constraints: BoxConstraints(
                  minWidth: 40,
                  maxWidth: MediaQuery.of(context).size.width * 0.70),
              child: _buildTextChild()),
          Positioned.fill(
            child: ClipRRect(
              borderRadius: BorderRadius.only(
                topRight: Radius.circular(10.0),
                bottomRight: Radius.circular(10.0),
              ),
              child: FractionallySizedBox(
                alignment: Alignment.centerLeft,
                heightFactor: 1,
                widthFactor: _controller == null ? 0 : _controller.value,
                child: Container(
                  decoration: BoxDecoration(
                    shape: BoxShape.rectangle,
                    color: Colors.blue.withOpacity(0.3),
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(10.0),
                      topRight: Radius.zero,
                      bottomLeft: Radius.circular(10.0),
                      bottomRight: Radius.zero,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ]));
  }

  Widget _buildTextChild() {
    final color = Colors.black;
    return Padding(
        padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
        child: Text(widget.text, style: TextStyle(color: color, fontSize: 18)));
  }
}

```

Body:
I'm building a chat app where audio messages can accompany the text. The widget that displays this is a very standard looking chat bubble (think iMessage) with one twist - the bubble becomes a progress bar when the audio is playing. The progress bar is essentially just a gradual change in the background color. You can see the layout in this dartpad (hit run). A screenshot of the mock is here:

Because the chat bubble is rounded, I need the progress bar to round only at the end. In other words, it should always be rounded on the left as it is flush with the left side of the message but it should be flat on the right until it hits the end of the message. I think ClipRRect is the right widget to do this.

However, because the message bubble width is variable, I use a FractionallySizedBox as the progress bar. 1/10th the way through the audio, it should be 1/10th the width of the chat bubble. Then I use Positioned.fill to wrap the progress bar so that the fraction is taken out of the full message bubble width. ClipRRect does not seem to play nicely wrapping Positioned.fill I believe it expects the child to have a set size:

RenderBox was not laid out: RenderClipRRect#3b019 relayoutBoundary=up13
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1694 pos 12: 'hasSize'

This is a dartpad to the version with the not-working ClipRRect. Is there some other widget I can wrap Position.fill in to make it clippable? Or maybe a better way to lay this out?