问:
How to use Django url template tag with variable as url path
I encountered a No Reverse Match Error in trying to render a template. Can you explain what this No Reverse Match Error mean for easier understanding and how to solve the error?

models.py

```<code>from django.contrib.sites.models import Site
from django.contrib.gis.db import models
from django.utils.crypto import get_random_string
from django.contrib.gis.geos import GEOSGeometry,Point
from django.contrib.auth.models import AbstractUser
from django.shortcuts import render
# Create your models here.
class User(AbstractUser):
    pass

geos_pnt=Point(4314498.56, 1003834.600,srid=3857)
#pnt=GEOSGeometry('POINT(4314498.56, 1003834.600)').wkt
class Apartment(models.Model):
    SUBCITY_CHOICES = (
    ('ADK', 'Addis Ketema'), ('AKLTY', 'Akaki-Kality'), ('ARD', 'Arada'), ('BL', 'Bole'), ('GL', 'Gulele'),
    ('KLF', 'Kolfe-Keranio'), ('LDTA', 'Ledeta'), ('NFS', 'Nefas Silk'), ('YK', 'Yeka'))
    apt_id = models.CharField(str(SUBCITY_CHOICES)+"-"+get_random_string(length=4), max_length=8,primary_key=True)
    location = models.PointField(default=geos_pnt,extent=(4282586.10,996190.90,4346411.02,1011478.31),
                                    blank=True, null=True, srid=3857, help_text="Point(longitude latitude)")
    no_bedrooms= models.IntegerField(null=True)
    apt_area = models.IntegerField(default=0, null=True)
    apt_cost = models.IntegerField(default=0, null=True)
    apt_subcity = models.CharField(default='Nefas Silk',max_length=100, choices=SUBCITY_CHOICES,null=True)
    register_date = models.DateTimeField('Register Date',auto_now_add=True,null=True)
    slug = models.SlugField(unique=True)
    objects = models.Manager()
    sites =models.ManyToManyField(Site)

    #change points from apt_rent_db to kml
    def pointkml(self):
        points = Apartment.objects.kml()
        return render("placemarks.kml", {'places': points})
    def get_absolute_url(self):
        return reverse('apartment_create', kwargs={'pk': self.pk, 'apt_id': self.apt_id.pk})

    def save(self, *args, **kwargs):
        #self.Latitude = self..y
        #self.Longitude = self.location.x
        self.slug = slugify(self.apt_id)
        super(Apartment, self).save(*args, **kwargs)

    class Meta:
       # order of drop-down list items
       verbose_name = ("Apartment")
       verbose_name_plural = ("Apartments")
       ordering = ('apt_cost',)
       app_label = 'rent_app'

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

urls.py:

```<code>from django.urls import path
from . import views
app_name = 'rent_app'

    urlpatterns = [

            path('', views.IndexView.as_view(), name='index'),
            path('apartment_create/<slug:apt_id>)', views.ApartmentCreate.as_view(), name='apartment_create'),
            path('apartments/<int:pk>/', views.ApartmentUpdate.as_view(), name='apartment_update'),
            path('apartments/<int:pk>/delete/', views.ApartmentDelete.as_view(), name='apartment_delete'),
             ]
</code>```

views.py:

```<code>from django.urls import reverse_lazy
from django.views import generic
from django.views.generic.edit import CreateView, DeleteView, UpdateView
from .models import Apartment
from .forms import ApartmentCreateForm

class IndexView(generic.ListView):

    template_name = 'djnago_leaflet.html'
    context_object_name = 'latest_apartments_list'

    def get_queryset(self):

        """Return the last five published apartments."""

        return Apartment.objects.order_by('-register_date')[:5]

class ApartmentCreate(CreateView):
    template_name = 'rent_app/apartment-create-success.html'
    form_class = ApartmentCreateForm
    fields = ['apt_id','location','apt_area','apt_cost']
    success_url= reverse_lazy('apartment-create')

class ApartmentUpdate(UpdateView):
    model = Apartment
    fields = ['apt_id','location','apt_area', 'apt_cost']
    template_name='index_leaflet.html'
    template_name_suffix='apartments'

class ApartmentDelete(DeleteView):
    model = Apartment
    template_name = 'index_leaflet.html'
    template_name_suffix='apartments'
    success_url = reverse_lazy('apartment-list')
</code>```

the html:

```<code><html>
  <head>
   {% leaflet_js plugins="forms" %}
   {% leaflet_css plugins="forms" %}
  </head>

  <body>

    {% leaflet_map "map" callback="window.map_init_basic" %}
    <h2>Edit Apartment ID {{ Apartment.apt_id }}</h2>
    <h2>Edit Apartment Location {{ Apartment.location }}</h2>
    <form action="{% url 'rent_app:apartment_create' apt_id %}" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit"/>
    </form>
  </body>
</html>
</code>```

答:
I think there are a number of issues in your code.

First regarding the error you are seeing. In your urls you have defined a pattern with the name 'apartment_create' which expects a slug as a parameter. However, apt_id in your template is an empty field. So django cannot find a pattern with the name 'apartment_create' and a valid slug. To solve this change the url pattern to

```<code>path('apartment_create/', views.ApartmentCreate.as_view(), name='apartment_create')
</code>```

And in your template either take out the apt_id from your action in the form (or take out the action all together.

However, in your ApartmenCreate view you are missing the model parameter. In addition the fields and the form parameter are redundant. And are you sure the template_name parameter in that view is correct?

In your model the field apt_id looks strange. You are creating a field with some very obscure verbose_name. If you want to have a choice field you have to set the choices parameter of the field, e.g.:

```<code>apt_id = models.CharField(choices=SUBCITY_CHOICES, max_length=8, primary_key=True)
</code>```

Your get_absolute_url is also not correct: First of all there is no valid url matching that pattern and secondly a field (apt_id) does not have a pk.

In your template you have statements like {{ Apartment.apt_id }}. However, Apartment is a class. So in your views add context_object_name='apartment' so you can access the values in your template like so {{ apartment.apt_id }}.

There are probably some other issues which I have overlooked.

Body:
I encountered a No Reverse Match Error in trying to render a template. Can you explain what this No Reverse Match Error mean for easier understanding and how to solve the error?

models.py

from django.contrib.sites.models import Site
from django.contrib.gis.db import models
from django.utils.crypto import get_random_string
from django.contrib.gis.geos import GEOSGeometry,Point
from django.contrib.auth.models import AbstractUser
from django.shortcuts import render
# Create your models here.
class User(AbstractUser):
    pass

geos_pnt=Point(4314498.56, 1003834.600,srid=3857)
#pnt=GEOSGeometry('POINT(4314498.56, 1003834.600)').wkt
class Apartment(models.Model):
    SUBCITY_CHOICES = (
    ('ADK', 'Addis Ketema'), ('AKLTY', 'Akaki-Kality'), ('ARD', 'Arada'), ('BL', 'Bole'), ('GL', 'Gulele'),
    ('KLF', 'Kolfe-Keranio'), ('LDTA', 'Ledeta'), ('NFS', 'Nefas Silk'), ('YK', 'Yeka'))
    apt_id = models.CharField(str(SUBCITY_CHOICES)+"-"+get_random_string(length=4), max_length=8,primary_key=True)
    location = models.PointField(default=geos_pnt,extent=(4282586.10,996190.90,4346411.02,1011478.31),
                                    blank=True, null=True, srid=3857, help_text="Point(longitude latitude)")
    no_bedrooms= models.IntegerField(null=True)
    apt_area = models.IntegerField(default=0, null=True)
    apt_cost = models.IntegerField(default=0, null=True)
    apt_subcity = models.CharField(default='Nefas Silk',max_length=100, choices=SUBCITY_CHOICES,null=True)
    register_date = models.DateTimeField('Register Date',auto_now_add=True,null=True)
    slug = models.SlugField(unique=True)
    objects = models.Manager()
    sites =models.ManyToManyField(Site)

    #change points from apt_rent_db to kml
    def pointkml(self):
        points = Apartment.objects.kml()
        return render("placemarks.kml", {'places': points})
    def get_absolute_url(self):
        return reverse('apartment_create', kwargs={'pk': self.pk, 'apt_id': self.apt_id.pk})

    def save(self, *args, **kwargs):
        #self.Latitude = self..y
        #self.Longitude = self.location.x
        self.slug = slugify(self.apt_id)
        super(Apartment, self).save(*args, **kwargs)

    class Meta:
       # order of drop-down list items
       verbose_name = ("Apartment")
       verbose_name_plural = ("Apartments")
       ordering = ('apt_cost',)
       app_label = 'rent_app'

    def __unicode__(self):
        return self.apt_id

urls.py:

from django.urls import path
from . import views
app_name = 'rent_app'

    urlpatterns = [

            path('', views.IndexView.as_view(), name='index'),
            path('apartment_create/<slug:apt_id>)', views.ApartmentCreate.as_view(), name='apartment_create'),
            path('apartments/<int:pk>/', views.ApartmentUpdate.as_view(), name='apartment_update'),
            path('apartments/<int:pk>/delete/', views.ApartmentDelete.as_view(), name='apartment_delete'),
             ]

views.py:

from django.urls import reverse_lazy
from django.views import generic
from django.views.generic.edit import CreateView, DeleteView, UpdateView
from .models import Apartment
from .forms import ApartmentCreateForm

class IndexView(generic.ListView):

    template_name = 'djnago_leaflet.html'
    context_object_name = 'latest_apartments_list'

    def get_queryset(self):

        """Return the last five published apartments."""

        return Apartment.objects.order_by('-register_date')[:5]

class ApartmentCreate(CreateView):
    template_name = 'rent_app/apartment-create-success.html'
    form_class = ApartmentCreateForm
    fields = ['apt_id','location','apt_area','apt_cost']
    success_url= reverse_lazy('apartment-create')

class ApartmentUpdate(UpdateView):
    model = Apartment
    fields = ['apt_id','location','apt_area', 'apt_cost']
    template_name='index_leaflet.html'
    template_name_suffix='apartments'

class ApartmentDelete(DeleteView):
    model = Apartment
    template_name = 'index_leaflet.html'
    template_name_suffix='apartments'
    success_url = reverse_lazy('apartment-list')

the html:

   {% leaflet_js plugins="forms" %}
   {% leaflet_css plugins="forms" %}

    {% leaflet_map "map" callback="window.map_init_basic" %}

Edit Apartment ID {{ Apartment.apt_id }}

Edit Apartment Location {{ Apartment.location }}

    <form action="{% url 'rent_app:apartment_create' apt_id %}" method="post">
        {% csrf_token %}
        {{ form }}
        <input type="submit"/>
    </form>

Body:
I think there are a number of issues in your code.

First regarding the error you are seeing. In your urls you have defined a pattern with the name 'apartment_create' which expects a slug as a parameter. However, apt_id in your template is an empty field. So django cannot find a pattern with the name 'apartment_create' and a valid slug. To solve this change the url pattern to

path('apartment_create/', views.ApartmentCreate.as_view(), name='apartment_create')

And in your template either take out the apt_id from your action in the form (or take out the action all together.

However, in your ApartmenCreate view you are missing the model parameter. In addition the fields and the form parameter are redundant. And are you sure the template_name parameter in that view is correct?

In your model the field apt_id looks strange. You are creating a field with some very obscure verbose_name. If you want to have a choice field you have to set the choices parameter of the field, e.g.:

apt_id = models.CharField(choices=SUBCITY_CHOICES, max_length=8, primary_key=True)

Your get_absolute_url is also not correct: First of all there is no valid url matching that pattern and secondly a field (apt_id) does not have a pk.

In your template you have statements like {{ Apartment.apt_id }}. However, Apartment is a class. So in your views add context_object_name='apartment' so you can access the values in your template like so {{ apartment.apt_id }}.

There are probably some other issues which I have overlooked.


来源: stackexchange

问:
PSQLException: ERROR: relation "TABLE_NAME" does not exist
I am trying to run hibernate on a PostgreSQL 8.4.2 DB. Whenever I try to run a simple java code like:

```<code>List<User> users = service.findAllUsers();
</code>```

I get the following error:

```<code>PSQLException: ERROR: relation "TABLE_NAME" does not exist
</code>```

Since I have option hibernate.show_sql option set to true, I can see that hibernate is trying to run the following SQL command:

```<code>    select this_.USERNAME as USERNAME0_0_, this_.PASSWORD as PASSWORD0_0_
from "TABLE_NAME" this_
</code>```

When in reality, it should at least run something like:

```<code>    select this_."USERNAME" as USERNAME0_0_, this_."PASSWORD" as PASSWORD0_0_
from "SCHEMA_NAME"."TABLE_NAME" as this_
</code>```

Does anyone know what changes I need to make for Hibernate to produce the right SQL for PostgreSQL?

I have set up the necessary postgreSQL datasource in applicationContext.xml file:

```<code><!-- Use Spring annotations -->
 <context:annotation-config />
 <!-- postgreSQL datasource -->
 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <property name="driverClassName" value="org.postgresql.Driver" />
  <property name="url"
   value="jdbc:postgresql://localhost/DB_NAME:5432/SCHEMA_NAME" />
  <property name="username" value="postgres" />
  <property name="password" value="password" />
  <property name="defaultAutoCommit" value="false" />
 </bean>
</code>```

On the same file I have set up the session factory with PostgreSQL dialect:

```<code><!-- Hibernate session factory -->
 <bean id="sessionFactory"   class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>com.myPackage.dbEntities.domain.User</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
    <prop key="hibernate.show_sql">true</prop>
   </props>
  </property>
 </bean>
 <!-- setup transaction manager -->
 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
 </bean>
</code>```

Finally, the way I am mapping the domain class to the table is:

```<code>    @Entity
@Table(name = "`TABLE_NAME`")
public class User {
@Id
@Column(name = "USERNAME")
private String username;
</code>```

Has anyone encountered a similar error?. Any help in solving this issue will be much appreciated.
Please note that question is different to post Cannot simply use PostgreSQL table name (”relation does not exist”)

Apologies for the lengthy post.

答:
Not sure about others but my case if worked only if I wrote my query like this:

```<code>@Query(value = "SELECT tbl.* FROM my_schema.my_table tbl", nativeQuery = true)
</code>```

Always have some reference "tbl" for table and use it in the query.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to run hibernate on a PostgreSQL 8.4.2 DB. Whenever I try to run a simple java code like:

List<User> users = service.findAllUsers();

I get the following error:

PSQLException: ERROR: relation "TABLE_NAME" does not exist

Since I have option hibernate.show_sql option set to true, I can see that hibernate is trying to run the following SQL command:

    select this_.USERNAME as USERNAME0_0_, this_.PASSWORD as PASSWORD0_0_
from "TABLE_NAME" this_

When in reality, it should at least run something like:

    select this_."USERNAME" as USERNAME0_0_, this_."PASSWORD" as PASSWORD0_0_
from "SCHEMA_NAME"."TABLE_NAME" as this_

Does anyone know what changes I need to make for Hibernate to produce the right SQL for PostgreSQL?

I have set up the necessary postgreSQL datasource in applicationContext.xml file:

 <context:annotation-config />

 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
  destroy-method="close">
  <property name="driverClassName" value="org.postgresql.Driver" />
  <property name="url"
   value="jdbc:postgresql://localhost/DB_NAME:5432/SCHEMA_NAME" />
  <property name="username" value="postgres" />
  <property name="password" value="password" />
  <property name="defaultAutoCommit" value="false" />
 </bean>

On the same file I have set up the session factory with PostgreSQL dialect:

 <bean id="sessionFactory"   class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>com.myPackage.dbEntities.domain.User</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
    <prop key="hibernate.show_sql">true</prop>
   </props>
  </property>
 </bean>

 <bean id="transactionManager"
  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
 </bean>

Finally, the way I am mapping the domain class to the table is:

    @Entity
@Table(name = "`TABLE_NAME`")
public class User {
@Id
@Column(name = "USERNAME")
private String username;

Has anyone encountered a similar error?. Any help in solving this issue will be much appreciated.
Please note that question is different to post Cannot simply use PostgreSQL table name (”relation does not exist”)

Apologies for the lengthy post.

Body:
Not sure about others but my case if worked only if I wrote my query like this:

@Query(value = "SELECT tbl.* FROM my_schema.my_table tbl", nativeQuery = true)

Always have some reference "tbl" for table and use it in the query.

ContentLicense: CC BY-SA 4.0


问:
How to get difference of time between two datetime columns pandas?
I have two different columns in my dataset,

```<code>       start    end
0   2015-01-01  2017-01-01
1   2015-01-02  2015-06-02
2   2015-01-03  2015-12-03
3   2015-01-04  2020-11-25
4   2015-01-05  2025-07-27
</code>```

I want the difference between start and end in a specific way, here's my desired output.

```<code>year_diff  month_diff
        2           1
        0           6
        0          12
        5          11
       10           7
</code>```

Here the day is not important to me, only month and year. I've tried to period to get diff but it returns just different in months only. how can I achieve my desired output?

```<code>df['end'].dt.to_period('M') - df['start'].dt.to_period('M'))
</code>```

答:
Try:</p>

```<code>df["year_diff"]=df["end"].dt.year.sub(df["start"].df.year)
df["month_diff"]=df["end"].dt.month.sub(df["start"].df.month)
</code>```

Body:
I have two different columns in my dataset,

       start    end
0   2015-01-01  2017-01-01
1   2015-01-02  2015-06-02
2   2015-01-03  2015-12-03
3   2015-01-04  2020-11-25
4   2015-01-05  2025-07-27

I want the difference between start and end in a specific way, here's my desired output.

year_diff  month_diff
        2           1
        0           6
        0          12
        5          11
       10           7

Here the day is not important to me, only month and year. I've tried to period to get diff but it returns just different in months only. how can I achieve my desired output?

df['end'].dt.to_period('M') - df['start'].dt.to_period('M'))

Body:
Try:

df["year_diff"]=df["end"].dt.year.sub(df["start"].df.year)
df["month_diff"]=df["end"].dt.month.sub(df["start"].df.month)


问:
Is it possible to have DDev automatically launch the site after starting?
Using DDEv I'd like to be able to run the command ddev start and after starting it would automatically open the site in my browser. I know I can run ddev launch separately but I'd like it to happen automacically.

I tried chaining the commands but that failed and I also looked at the post-start hook but couldn't get it to work.

Is this possible?

答:
(edited with full recipe)

Use a post start exec host hook that does ddev launch. Add this to your .ddev/config.yaml:

```<code>hooks:
  post-start:
  - exec-host: ddev launch
</code>```

Body:
(edited with full recipe)

Use a post start exec host hook that does ddev launch. Add this to your .ddev/config.yaml:

hooks:
  post-start:
  - exec-host: ddev launch


问:
Docker Compose and Rails: Bundler::GemNotFound upon launching. Is bundler not looking at the right gemset?
I'm trying to follow the instructions to setup a Rails and Postgres app with Docker Compose as stated on the documentation here -> https://docs.docker.com/compose/rails/.

However, when I try to launch the app, after having successfully setup the database, I'm stuck with the following error upon running docker-compose up:

```<code>docker-compose up
Creating docker-and-cms_db_1 ... done
Creating docker-and-cms_web_1 ... done
Attaching to docker-and-cms_db_1, docker-and-cms_web_1
web_1  | bundler: failed to load command: rails (/usr/local/bundle/bin/rails)
web_1  | Bundler::GemNotFound: Could not find bindex-0.8.1 in any of the sources
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/spec_set.rb:91:in `block in materialize'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/spec_set.rb:85:in `map!'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/spec_set.rb:85:in `materialize'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/definition.rb:170:in `specs'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/definition.rb:237:in `specs_for'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/definition.rb:226:in `requested_specs'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/runtime.rb:108:in `block in definition_method'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/runtime.rb:20:in `setup'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler.rb:107:in `setup'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/setup.rb:20:in `<top (required)>'
web_1  |   /usr/local/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
web_1  |   /usr/local/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
docker-and-cms_web_1 exited with code 1
</code>```

Some early investigations on my end:

I'm using the ruby:2.6.5 image, and the error message seems to indicate that bundler is trying to look for gems in the /usr/local/lib/ruby/2.6.0 folder and that does look suspicious. I suspect an issue of version, maybe an environment not properly set.

Here is my Dockerfile

```<code># From https://docs.docker.com/compose/rails/
FROM ruby:2.6.5

RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
RUN mkdir /myapp
WORKDIR /myapp

COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock

RUN bundle install --path vendor/cache

COPY . /myapp

# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

# Start the main process.
CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0"]
</code>```

Here is my entrypoind.sh

```<code>#!/bin/bash
set -e

# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid

# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "$@"
</code>```

And finally here is my docker-compose.yml file

```<code>version: '3'
services:
  db:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: password
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db
</code>```

And here is the beginning of my Gemfile (redacted, because only the first lines are relevant I think):

```<code>source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.5'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.4', '>= 5.2.4.1'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# (...)
</code>```

Debug information:
- This is what running bundle env in the docker container returns:

```<code>root@588227887e16:/myapp# bundle env
## Environment

Bundler       1.17.2
  Platforms   ruby, x86_64-linux
Ruby          2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux]
  Full Path   /usr/local/bin/ruby
  Config Dir  /usr/local/etc
RubyGems      3.0.3
  Gem Home    /usr/local/bundle
  Gem Path    /root/.gem/ruby/2.6.0:/usr/local/lib/ruby/gems/2.6.0:/usr/local/bundle
  User Path   /root/.gem/ruby/2.6.0
  Bin Dir     /usr/local/bundle/bin
Tools
  Git         2.20.1
  RVM         not installed
  rbenv       not installed
  chruby      not installed

## Bundler Build Metadata

Built At          2018-12-19
Git SHA           3fc4de72b
Released Version  false

## Bundler settings

path
  Set for your local app (/usr/local/bundle/config): "vendor/cache"
app_config
  Set via BUNDLE_APP_CONFIG: "/usr/local/bundle"
silence_root_warning
  Set via BUNDLE_SILENCE_ROOT_WARNING: true
</code>```

Thank you for your help!

答:
Within the Docker container Bundler is looking for gems in the wrong directory as you say. Either Ruby 2.6.0 is installed and found by Bundler when the container is starting or, something is copied into the container to make Bundler believe Ruby 2.6.0 is installed.

As you're using the Docker image ruby:2.5.6, the second option above is more likely

If you look on lines 8-9 of your Dockerfile you'll see that the Gemfile and Gemfile.lock are copied from your local machine into the container, when building the Docker image.

I think what may be happening here is that the Gemfile.lock generated on your local machine was done using Ruby 2.6.0.

What is your local machine (not in a container) Ruby version? Run ruby -v to see.

Try installing Ruby 2.6.5 on your local machine and running bundle install, to update the Gemfile.lock.

I'm on my mobile, can't test any of this myself currently. But it's somewhere to start!

Body:
I'm trying to follow the instructions to setup a Rails and Postgres app with Docker Compose as stated on the documentation here -> https://docs.docker.com/compose/rails/.

However, when I try to launch the app, after having successfully setup the database, I'm stuck with the following error upon running docker-compose up:

docker-compose up
Creating docker-and-cms_db_1 ... done
Creating docker-and-cms_web_1 ... done
Attaching to docker-and-cms_db_1, docker-and-cms_web_1
web_1  | bundler: failed to load command: rails (/usr/local/bundle/bin/rails)
web_1  | Bundler::GemNotFound: Could not find bindex-0.8.1 in any of the sources
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/spec_set.rb:91:in `block in materialize'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/spec_set.rb:85:in `map!'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/spec_set.rb:85:in `materialize'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/definition.rb:170:in `specs'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/definition.rb:237:in `specs_for'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/definition.rb:226:in `requested_specs'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/runtime.rb:108:in `block in definition_method'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/runtime.rb:20:in `setup'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler.rb:107:in `setup'
web_1  |   /usr/local/lib/ruby/2.6.0/bundler/setup.rb:20:in `<top (required)>'
web_1  |   /usr/local/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
web_1  |   /usr/local/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
docker-and-cms_web_1 exited with code 1

Some early investigations on my end:

I'm using the ruby:2.6.5 image, and the error message seems to indicate that bundler is trying to look for gems in the /usr/local/lib/ruby/2.6.0 folder and that does look suspicious. I suspect an issue of version, maybe an environment not properly set.

Here is my Dockerfile

# From https://docs.docker.com/compose/rails/
FROM ruby:2.6.5

RUN apt-get update -qq && apt-get install -y nodejs postgresql-client
RUN mkdir /myapp
WORKDIR /myapp

COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock

RUN bundle install --path vendor/cache

COPY . /myapp

# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

# Start the main process.
CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0"]

Here is my entrypoind.sh

#!/bin/bash
set -e

# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid

# Then exec the container's main process (what's set as CMD in the Dockerfile).
exec "$@"

And finally here is my docker-compose.yml file

version: '3'
services:
  db:
    image: postgres
    volumes:
      - ./tmp/db:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: password
  web:
    build: .
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db

And here is the beginning of my Gemfile (redacted, because only the first lines are relevant I think):

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.6.5'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.4', '>= 5.2.4.1'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# (...)

Debug information:
- This is what running bundle env in the docker container returns:

root@588227887e16:/myapp# bundle env
## Environment

Bundler       1.17.2
  Platforms   ruby, x86_64-linux
Ruby          2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux]
  Full Path   /usr/local/bin/ruby
  Config Dir  /usr/local/etc
RubyGems      3.0.3
  Gem Home    /usr/local/bundle
  Gem Path    /root/.gem/ruby/2.6.0:/usr/local/lib/ruby/gems/2.6.0:/usr/local/bundle
  User Path   /root/.gem/ruby/2.6.0
  Bin Dir     /usr/local/bundle/bin
Tools
  Git         2.20.1
  RVM         not installed
  rbenv       not installed
  chruby      not installed

## Bundler Build Metadata

Built At          2018-12-19
Git SHA           3fc4de72b
Released Version  false

## Bundler settings

path
  Set for your local app (/usr/local/bundle/config): "vendor/cache"
app_config
  Set via BUNDLE_APP_CONFIG: "/usr/local/bundle"
silence_root_warning
  Set via BUNDLE_SILENCE_ROOT_WARNING: true

Thank you for your help!


问:
How to speed up mysql docker container for tests?
I use docker/docker-compose to run services and tests. One of the services is mysql:

```<code>db:
    image: mysql:5.6
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    expose:
      - "3306"
</code>```

Is there any way I can optimize the container's speed specifically for tests (e.g. keep everything in memory, etc.) ?

答:
Well, you could run your database in RAM if you have enough space to do so. That might speed things up a bit.

```<code>services:
  db:
    image: mysql:5.6
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    expose:
      - "3306"
    tmpfs:
      - /var/lib/mysql
</code>```

Source

https://docs.docker.com/v17.09/engine/admin/volumes/tmpfs/#differences-between---tmpfs-and---mount-behavior

https://docs.docker.com/compose/compose-file/#tmpfs

https://blog.stefanproell.at/2019/02/08/lightning-fast-integration-tests-with-docker-mysql-and-tmpfs/

Body:
I use docker/docker-compose to run services and tests. One of the services is mysql:

db:
    image: mysql:5.6
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    expose:
      - "3306"

Is there any way I can optimize the container's speed specifically for tests (e.g. keep everything in memory, etc.) ?

Body:
Well, you could run your database in RAM if you have enough space to do so. That might speed things up a bit.

services:
  db:
    image: mysql:5.6
    environment:
      - MYSQL_ALLOW_EMPTY_PASSWORD=yes
    expose:
      - "3306"
    tmpfs:
      - /var/lib/mysql

Source

https://docs.docker.com/v17.09/engine/admin/volumes/tmpfs/#differences-between---tmpfs-and---mount-behavior

https://docs.docker.com/compose/compose-file/#tmpfs

https://blog.stefanproell.at/2019/02/08/lightning-fast-integration-tests-with-docker-mysql-and-tmpfs/


问:
Python game,something with wrong answerrs why is this like that?
here is my python game:

```<code>import random

print('H A N G M A N')
hidden_words = ['python', 'java', 'kotlin', 'javascript']
hidden_word = random.choice(hidden_words)
display = '-' * len(hidden_word)
used = []
i = 0
maxshit = 8
while i < maxshit and display != hidden_word:
    print()
    print(display)
    inp = input("Input a letter: ")
    if inp in used:
        print("No improvements")
        i += 1
    elif inp in hidden_word:
        new = ""
        used.append(inp)
        for i in range(len(hidden_word)):
            if inp == hidden_word[i]:
                new += inp
            else:
                new += display[i]
        display = new
    else:
        print("No such letter in the word")
        i += 1
if i == maxshit:
    print("You are hanged!")
else:
    print("You survived!")

print()
print('Thanks for playing!')
print("We'll see how well you did in the next stage")
</code>```

It works well when there is 8 wrong answers you lose and game print "You are hanged !",but if you answer is well you win and it prints "You survived" and if you print allredy printed word it prints "No improvments!" or if there is no word what you inputed it prints "No such letter in the world !".
But when you input looks like

```<code>$ python govno.py
H A N G M A N

------
Input a letter: j
No such letter in the word

------
Input a letter: i

----i-
Input a letter: g
No such letter in the word

----i-
Input a letter: g
No such letter in the word

----i-
Input a letter: k

k---i-
Input a letter: g
No such letter in the word

k---i-
Input a letter: g
No such letter in the word

k---i-
Input a letter: g
No such letter in the word
You are hanged!

</code>```

In this input you lose only after 6 mistakes. Why is this like that?
P.S sorry for comon mistakes I am only begining

答:
The problem is in your second loop (the for loop) you reused the variable i. When the input is in the hidden word and after the loop the variable i will be set to one less than the length of the hidden word ("kotlin"), which in this case is 5. After that, the i was incremented 3 times, ending at the value of 8, which is equal to maxshit. So the loop ended and the message was displayed.

Change that variable to another name (e.g. j).
The loop should look something like this:

```<code>        for j in range(len(hidden_word)):
            if inp == hidden_word[j]:
                new += inp
            else:
                new += display[j]
</code>```

Body:
here is my python game:

import random

print('H A N G M A N')
hidden_words = ['python', 'java', 'kotlin', 'javascript']
hidden_word = random.choice(hidden_words)
display = '-' * len(hidden_word)
used = []
i = 0
maxshit = 8
while i < maxshit and display != hidden_word:
    print()
    print(display)
    inp = input("Input a letter: ")
    if inp in used:
        print("No improvements")
        i += 1
    elif inp in hidden_word:
        new = ""
        used.append(inp)
        for i in range(len(hidden_word)):
            if inp == hidden_word[i]:
                new += inp
            else:
                new += display[i]
        display = new
    else:
        print("No such letter in the word")
        i += 1
if i == maxshit:
    print("You are hanged!")
else:
    print("You survived!")

print()
print('Thanks for playing!')
print("We'll see how well you did in the next stage")

It works well when there is 8 wrong answers you lose and game print "You are hanged !",but if you answer is well you win and it prints "You survived" and if you print allredy printed word it prints "No improvments!" or if there is no word what you inputed it prints "No such letter in the world !".
But when you input looks like

$ python govno.py
H A N G M A N

------
Input a letter: j
No such letter in the word

------
Input a letter: i

----i-
Input a letter: g
No such letter in the word

----i-
Input a letter: g
No such letter in the word

----i-
Input a letter: k

k---i-
Input a letter: g
No such letter in the word

k---i-
Input a letter: g
No such letter in the word

k---i-
Input a letter: g
No such letter in the word
You are hanged!

In this input you lose only after 6 mistakes. Why is this like that?
P.S sorry for comon mistakes I am only begining

Body:
The problem is in your second loop (the for loop) you reused the variable i. When the input is in the hidden word and after the loop the variable i will be set to one less than the length of the hidden word ("kotlin"), which in this case is 5. After that, the i was incremented 3 times, ending at the value of 8, which is equal to maxshit. So the loop ended and the message was displayed.

Change that variable to another name (e.g. j).
The loop should look something like this:

        for j in range(len(hidden_word)):
            if inp == hidden_word[j]:
                new += inp
            else:
                new += display[j]


问:
Is there a tensorflow keras that is a wrapper for a stack of Dense layers?
For example, this is trivial but is there a layer for this? Is not really a convolution ... there is one "Dense layer" (weights) per data point.</p>

```<code>In [266]: X = np.random.randn(10, 3); W = np.random.randn(10, 3, 4); (X[:, :, None] * W).sum(axis=1).shape
Out[266]: (10, 4)
</code>```

答:
Create your own layer:

Warning: works only with fixed batch size, you need to define batch_shape or batch_input_shape in your models!!!!

```<code>class SampleDense(Layer):
    def __init__(self, units, **kwargs):
        self.units = units
        super(SampleDense, self).__init__(**kwargs)

    def build(self, input_shape):
        weight_shape = input_shape + (self.units,)

        self.kernel = self.add_weight(name='kernel',
                                      shape=weight_shape,
                                      initializer='uniform',
                                      trainable=True)
        self.built = True

    def call(self, inputs):
        inputs = K.expand_dims(inputs, axis=-1)
        outputs = inputs * self.kernel
        outputs = K.sum(outputs, axis=-2)

        return outputs

    def compute_output_shape(self, input_shape):
        return input_shape[:-1] + (self.units,)
</code>```

Body:
For example, this is trivial but is there a layer for this? Is not really a convolution ... there is one "Dense layer" (weights) per data point.

In [266]: X = np.random.randn(10, 3); W = np.random.randn(10, 3, 4); (X[:, :, None] * W).sum(axis=1).shape
Out[266]: (10, 4)

Body:
Create your own layer:

Warning: works only with fixed batch size, you need to define batch_shape or batch_input_shape in your models!!!!

class SampleDense(Layer):
    def __init__(self, units, **kwargs):
        self.units = units
        super(SampleDense, self).__init__(**kwargs)

    def build(self, input_shape):
        weight_shape = input_shape + (self.units,)

        self.kernel = self.add_weight(name='kernel',
                                      shape=weight_shape,
                                      initializer='uniform',
                                      trainable=True)
        self.built = True

    def call(self, inputs):
        inputs = K.expand_dims(inputs, axis=-1)
        outputs = inputs * self.kernel
        outputs = K.sum(outputs, axis=-2)

        return outputs

    def compute_output_shape(self, input_shape):
        return input_shape[:-1] + (self.units,)


问:
Supress output from function
there is a thing I want to eliminate, it is when the function print to output, I know about overriding sys.stdout.write which print() function uses. but I think this isn't an ideal fix for this. I'm looking for the ideal pythonic way for doing this?

```<code>from timeit import Timer
from functools import partial

def timing_decorator(function):
    def wrapper(*args, **kwargs):
        # print(function)
        callable_f = partial(function, *args, **kwargs)
        # print(dir(Timer))
        total = Timer(callable_f).timeit(1)
        print(total)
        return total
    return wrapper

# example function
@timing_decorator
def hello(arg):
    print(arg)
    return

hello('hi')
</code>```

This outputs:

```<code>hi
0.00036
</code>```

My expected output would be:

```<code>0.00036
</code>```

答:
You can create a file-like object that has a write() method that does nothing, and have your decorator substitute that for sys.stdout (and restore the original stdout after calling the function).

```<code>import sys

class NoOutput:
    def write(text):
        pass

no_output = NoOutput()

def timing_decorator(function):
    def wrapper(*args, **kwargs):
        callable_f = partial(function, *args, **kwargs)
        old_stdout, sys.stdout = sys.stdout, no_output
        try:
            total = Timer(callable_f).timeit(1)
        finally:
            sys.stdout = old_stdout
        print(f"{function.__name__}: {total:.5f}ms")
        return total
    return wrapper
</code>```

Note use of try/finally to make sure stdout gets restored even if an exception is raised in the function.

Title: Supress output from function

Body:
there is a thing I want to eliminate, it is when the function print to output, I know about overriding sys.stdout.write which print() function uses. but I think this isn't an ideal fix for this. I'm looking for the ideal pythonic way for doing this?

from timeit import Timer
from functools import partial

def timing_decorator(function):
    def wrapper(*args, **kwargs):
        # print(function)
        callable_f = partial(function, *args, **kwargs)
        # print(dir(Timer))
        total = Timer(callable_f).timeit(1)
        print(total)
        return total
    return wrapper

# example function
@timing_decorator
def hello(arg):
    print(arg)
    return

hello('hi')

This outputs:

hi
0.00036

My expected output would be:

0.00036

Body:
You can create a file-like object that has a write() method that does nothing, and have your decorator substitute that for sys.stdout (and restore the original stdout after calling the function).

import sys

class NoOutput:
    def write(text):
        pass

no_output = NoOutput()

def timing_decorator(function):
    def wrapper(*args, **kwargs):
        callable_f = partial(function, *args, **kwargs)
        old_stdout, sys.stdout = sys.stdout, no_output
        try:
            total = Timer(callable_f).timeit(1)
        finally:
            sys.stdout = old_stdout
        print(f"{function.__name__}: {total:.5f}ms")
        return total
    return wrapper

Note use of try/finally to make sure stdout gets restored even if an exception is raised in the function.


问:
Declaring a TypeScript function with properties
I'm writing a library and I want to port it to TypeScript.

Currently it looks something like this:

File index.js

```<code>const is = value => {
    // ... Do some returns here
}

is.number = x => typeof x === 'number'
is.bla = x => typeof x === 'bla'
</code>```

And so on.

I have wrote an interface describing is and all its methods.

```<code>type TypeQueryMethod = (val: any) => boolean;

interface Is {
    (val: any): string;
    undefined: TypeQueryMethod;
    null: TypeQueryMethod;
    // ...
}
</code>```

When I try to mark is with the type: const is: Is = value => ...

It throws an error:

Type '(value: any) => string' is not assignable to type 'Is'.
Property 'undefined' is missing in type '(value: any) => string'.
```

Which makes sense because the declaration of the object is split.

How do you construct such an object that is both a method, and has methods?

答:
All you need to do, is to provide the properties as optional:

```<code>type TypeQueryMethod = (val: any) => boolean;

interface Is {
    (val: any): string;
    undefined?: TypeQueryMethod;
    null?: TypeQueryMethod;
    ...
}
</code>```

And now you can safely define it as Is:

```<code>const is: Is = value => ...
</code>```

Body:
I'm writing a library and I want to port it to TypeScript.

Currently it looks something like this:

File index.js

const is = value => {
    // ... Do some returns here
}

is.number = x => typeof x === 'number'
is.bla = x => typeof x === 'bla'

And so on.

I have wrote an interface describing is and all its methods.

type TypeQueryMethod = (val: any) => boolean;

interface Is {
    (val: any): string;
    undefined: TypeQueryMethod;
    null: TypeQueryMethod;
    // ...
}

When I try to mark is with the type: const is: Is = value => ...

It throws an error:

Type '(value: any) => string' is not assignable to type 'Is'.
Property 'undefined' is missing in type '(value: any) => string'.

Which makes sense because the declaration of the object is split.

How do you construct such an object that is both a method, and has methods?

Body:
All you need to do, is to provide the properties as optional:

type TypeQueryMethod = (val: any) => boolean;

interface Is {
    (val: any): string;
    undefined?: TypeQueryMethod;
    null?: TypeQueryMethod;
    ...
}

And now you can safely define it as Is:

const is: Is = value => ...


问:
You can't specify target table 'Employee' for update in FROM clause
```<code>delete from Employee where Salary=(select max(Salary) from Employee)
</code>```

why is error is showing. can someone help me how to solve it with logic.

答:
```<code>DELETE t1.*
FROM Employee t1
JOIN (SELECT MAX(Salary) Salary FROM Employee) t2
where t1.Salary = t2.Salary
</code>```

Body:
delete from Employee where Salary=(select max(Salary) from Employee)

why is error is showing. can someone help me how to solve it with logic.


问:
Converting String array to java.util.List
How do I convert a String array to a java.util.List?

答: Use the static List list = Arrays.asList(stringArray) or you could just iterate over the array and add the strings to the list.

ContentLicense: CC BY-SA 3.0


问:
Have different
 tag value show up in a separate div when you click each separate section
long time listener, first time caller. I am trying my hand at making an NHL draft chart, as I do some player evaluation and want a fancy looking place to put it all/I'm having a bit of fun while I learn SASS for the first time (it rocks, btw).

Codepen: https://codepen.io/trjwaugh/pen/abONgLm

$desktop: 1000px;
$padding: 15px;
$borders: 15px;
$margin: 20px;
$logo-clip: polygon(70% 0, 100% 0%, 75% 100%, 40% 100%);
$colors: ( ggold: #FFB81C, gold-light: lighten(#FFB81C, 40%), //buf, cbj, edm, fla, nsh
bblue: #002654, blue-light: lighten(#002654, 40%), ragsblue: #0038A8, ragsblue-light: lighten(#0038A8, 40%), leafblue: #00205B, leafblue-light: lighten(#00205B, 40%), rred: #C8102E, red-light: lighten(#C8102E, 40%), oorange: #F74902, orange-light: lighten(#F74902, 40%), starsgreen: #006847, starsgreen-light: lighten(#006847, 40%), yotesred: #8C2633, yotesred-light: lighten(#8C2633, 40%), burg: #6F263D, burg-light: ligthen(#6F263D, 40%), black: black);
@function color($color-name) {
  @return map-get($map: $colors, $key: $color-name);
}

@mixin desktop {
  @media (max-width: #{$desktop}) {
    @content;
  }
}

body,
html {
  height: 100%;
  font-family: 'Montserrat', sans-serif;
}

img {
  margin: 0;
  display: block;
  width: 78px;
  height: 80px;
  float: right;
}

body {
  margin: 0;
  #bg {
    clip-path: polygon(30% 0, 100% 0, 70% 100%, 0 100%);
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: -1;
    @include desktop {
      //suff to change re: responsiveness
    }
  }
}

main {
  #container {
    white-space: nowrap;
    text-align: center;
  }
  section#sticky-main {
    position: -webkit-sticky;
    /* Safari */
    position: sticky;
    top: 0;
    width: 100%;
    margin: 1em auto;
    padding: $padding;
    border-radius: $borders;
    background-size: 100% 100%, 0% 100%;
    box-shadow: 0 10px 30px rgba(0, 0, 0, $alpha: 0.2);
  }
  section#card {
    margin: 1em auto;
    float: right;
    padding: $padding;
    border-radius: $borders;
    width: 100%;
    background-size: 100% 100%, 0% 100%;
    box-shadow: 0 10px 30px rgba(0, 0, 0, $alpha: 0.2);
    -webkit-transition: .5s ease-in;
    -moz-transition: .5s ease-in;
    -o-transition: .5s ease-in;
    transition: .5s ease-in;
    ul {
      list-style-type: none;
      margin: 0;
      padding: 0;
      margin-bottom: 20px;
      li {
        strong {
          display: inline-block;
          margin-left: max(40px);
          margin-top: 10px;
        }
        img {
          display: block;
          width: 138px;
          height: 130px;
          float: right;
          @include desktop {
            //suff to change re: responsiveness
            width: 100px;
            height: 92px;
          }
        }
      }
    }
    #report.one {
      margin: 1em auto;
      float: right;
      padding: $padding;
      margin-right: 20px;
      border-radius: $borders;
      background-size: 100% 100%, 0% 100%;
      box-shadow: 0 10px 30px rgba(0, 0, 0, $alpha: 0.2);
      width: 90%;
      background-color: white !important;
      color: black !important;
    }
    #report.one:hover {
      display: block;
    }
  }
  section#card.gold:hover {
    background-color: color(ggold);
    color: white;
    background-size: 80.1% 10%, 20% 10%;
    box-shadow: 0 10px 30px rgba(100, 0, 0, $alpha: 0.2);
  }
  section#card.blue:hover {
    background-color: color(bblue);
    color: white;
    background-size: 80.1% 10%, 20% 10%;
    box-shadow: 0 10px 30px rgba(100, 0, 0, $alpha: 0.2);
  }
  section#card.red:hover {
    background-color: color(rred);
    color: white;
    background-size: 80.1% 10%, 20% 10%;
    box-shadow: 0 10px 30px rgba(100, 0, 0, $alpha: 0.2);
  }
}
```

<pre class="lang-html prettyprint-override"><code><!doctype html>
<html lang="en">

<head>
  <link rel="stylesheet" href="css/main.css">
  <script src="https://kit.fontawesome.com/9969435508.js" crossorigin="anonymous"></script>
  <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
  <title>Title</title>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>

<body>
  <main>
    <div class="container">
      <div class="row">
        <div class="col-sm-4">
          <section id="sticky-main">
            <div id="content"></div>
          </section>
        </div>
        <div class="col-sm-8">

          <section onmouseover="hover()" id="card" class="gold">
            <ul>
              <li>
                <img src="logos/anaheim-ducks.png">
              </li>
              <br>
              <li>
                <strong>Bigname McLongnamington III <i style ="color: green;" class="far fa-arrow-alt-circle-up"></i></strong>
              </li>
              <li>
                <strong>Kitchener Rangers (OHL)</strong>
              </li>
              <li>
                <strong>height weight</strong>
              </li>
            </ul>
          </section>

          <section onclick="showReport()" id="card" class="red">
            <ul>
              <li>
                <img src="logos/chicago-blackhawks-logo.png">
              </li>
              <br>
              <li>
                <strong>Bigname McLongnamington III <i style ="color: green;" class="far fa-arrow-alt-circle-up"></i></strong>
              </li>
              <li>
                <strong>Kitchener Rangers (OHL)</strong>
              </li>
              <li>
                <strong>height weight</strong>
              </li>
            </ul>
            <div id="report-two" style="display: none;">
              <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer accumsan est massa, quis hendrerit augue volutpat sed. Nam sit amet bibendum enim, eget suscipit odio. Donec risus odio, bibendum eget ipsum eget, bibendum congue est. Sed
                maximus lorem sit amet nibh condimentum viverra. Vestibulum sed quam fringilla, rhoncus eros et, imperdiet tellus. In nec nibh sollicitudin, pharetra purus vitae, consectetur mi. Curabitur laoreet finibus placerat.</p>
            </div>
          </section>

          <section onclick="showReport()" id="card" class="blue">
            <ul>
              <li>
                <img src="logos/columbus -bluejackets-logo.png">
              </li>
              <br>
              <li>
                <strong>Bigname McLongnamington III <i style ="color: green;" class="far fa-arrow-alt-circle-up"></i></strong>
              </li>
              <li>
                <strong>Kitchener Rangers (OHL)</strong>
              </li>
              <li>
                <strong>height weight</strong>
              </li>
            </ul>
            <div id="report" style="display: none;">
              <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer accumsan est massa, quis hendrerit augue volutpat sed. Nam sit amet bibendum enim, eget suscipit odio. Donec risus odio, bibendum eget ipsum eget, bibendum congue est. Sed
                maximus lorem sit amet nibh condimentum viverra. Vestibulum sed quam fringilla, rhoncus eros et, imperdiet tellus. In nec nibh sollicitudin, pharetra purus vitae, consectetur mi. Curabitur laoreet finibus placerat.</p>
            </div>
          </section>
          <section onclick="showReport()" id="card" class="blue">
            <ul>
              <li>
                <img src="logos/columbus -bluejackets-logo.png">
              </li>
              <br>
              <li>
                <strong>Bigname McLongnamington III <i style ="color: green;" class="far fa-arrow-alt-circle-up"></i></strong>
              </li>
              <li>
                <strong>Kitchener Rangers (OHL)</strong>
              </li>
              <li>
                <strong>height weight</strong>
              </li>
            </ul>
            <div id="report" style="display: none;">
              <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer accumsan est massa, quis hendrerit augue volutpat sed. Nam sit amet bibendum enim, eget suscipit odio. Donec risus odio, bibendum eget ipsum eget, bibendum congue est. Sed
                maximus lorem sit amet nibh condimentum viverra. Vestibulum sed quam fringilla, rhoncus eros et, imperdiet tellus. In nec nibh sollicitudin, pharetra purus vitae, consectetur mi. Curabitur laoreet finibus placerat.</p>
            </div>
          </section>

        </div>
      </div>
    </div>
  </main>

  <!-- Optional JavaScript -->
  <script src="script.js"></script>
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>

</html>
</code>```

If you look at the Codepen, you can see i have a bunch of sections, all will act as a card that a players draft info will appear, minus a paragraph blurb about them. There are a few things ive tried in terms of accomplishing my goal but essentially I want to be able to click on a players <section onclick="showReport()" id="card"... and have that players paragraph blurb appear in the sticky div on the left, changing based on which section card you click on. right now I have the players paragraph in a p tag within the section just for now, but im open to anything. I have a JS function on click in there for now but what I have tried so far required me to write a seperate hide() for each section (will be 31 total). Im looking for a method that will also allow me to only change the bio info and never have to adjust any code when I want to make edits to my draft chart. I hope I explained myself well enough, please tell me if I need to clarify.

Any help would be highly appreciated!

答:
First, add this to each onclick on sections to get the element itself anytime you click on them.

```<code>...
<section onclick="showReport(this)" id="card" class="blue">
...
</code>```

Then, you can use this (now turned into el variable) to find the text and put into the #content element.

```<code>function showReport(el) {
  $('#content').text($(el).find('p').text());
}
</code>```

Title: Have different <p> tag value show up in a separate div when you click each separate section

Body:
long time listener, first time caller. I am trying my hand at making an NHL draft chart, as I do some player evaluation and want a fancy looking place to put it all/I'm having a bit of fun while I learn SASS for the first time (it rocks, btw).

Codepen: https://codepen.io/trjwaugh/pen/abONgLm

$desktop: 1000px;
$padding: 15px;
$borders: 15px;
$margin: 20px;
$logo-clip: polygon(70% 0, 100% 0%, 75% 100%, 40% 100%);
$colors: ( ggold: #FFB81C, gold-light: lighten(#FFB81C, 40%), //buf, cbj, edm, fla, nsh
bblue: #002654, blue-light: lighten(#002654, 40%), ragsblue: #0038A8, ragsblue-light: lighten(#0038A8, 40%), leafblue: #00205B, leafblue-light: lighten(#00205B, 40%), rred: #C8102E, red-light: lighten(#C8102E, 40%), oorange: #F74902, orange-light: lighten(#F74902, 40%), starsgreen: #006847, starsgreen-light: lighten(#006847, 40%), yotesred: #8C2633, yotesred-light: lighten(#8C2633, 40%), burg: #6F263D, burg-light: ligthen(#6F263D, 40%), black: black);
@function color($color-name) {
  @return map-get($map: $colors, $key: $color-name);
}

@mixin desktop {
  @media (max-width: #{$desktop}) {
    @content;
  }
}

body,
html {
  height: 100%;
  font-family: 'Montserrat', sans-serif;
}

img {
  margin: 0;
  display: block;
  width: 78px;
  height: 80px;
  float: right;
}

body {
  margin: 0;
  #bg {
    clip-path: polygon(30% 0, 100% 0, 70% 100%, 0 100%);
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: -1;
    @include desktop {
      //suff to change re: responsiveness
    }
  }
}

main {
  #container {
    white-space: nowrap;
    text-align: center;
  }
  section#sticky-main {
    position: -webkit-sticky;
    /* Safari */
    position: sticky;
    top: 0;
    width: 100%;
    margin: 1em auto;
    padding: $padding;
    border-radius: $borders;
    background-size: 100% 100%, 0% 100%;
    box-shadow: 0 10px 30px rgba(0, 0, 0, $alpha: 0.2);
  }
  section#card {
    margin: 1em auto;
    float: right;
    padding: $padding;
    border-radius: $borders;
    width: 100%;
    background-size: 100% 100%, 0% 100%;
    box-shadow: 0 10px 30px rgba(0, 0, 0, $alpha: 0.2);
    -webkit-transition: .5s ease-in;
    -moz-transition: .5s ease-in;
    -o-transition: .5s ease-in;
    transition: .5s ease-in;
    ul {
      list-style-type: none;
      margin: 0;
      padding: 0;
      margin-bottom: 20px;
      li {
        strong {
          display: inline-block;
          margin-left: max(40px);
          margin-top: 10px;
        }
        img {
          display: block;
          width: 138px;
          height: 130px;
          float: right;
          @include desktop {
            //suff to change re: responsiveness
            width: 100px;
            height: 92px;
          }
        }
      }
    }
    #report.one {
      margin: 1em auto;
      float: right;
      padding: $padding;
      margin-right: 20px;
      border-radius: $borders;
      background-size: 100% 100%, 0% 100%;
      box-shadow: 0 10px 30px rgba(0, 0, 0, $alpha: 0.2);
      width: 90%;
      background-color: white !important;
      color: black !important;
    }
    #report.one:hover {
      display: block;
    }
  }
  section#card.gold:hover {
    background-color: color(ggold);
    color: white;
    background-size: 80.1% 10%, 20% 10%;
    box-shadow: 0 10px 30px rgba(100, 0, 0, $alpha: 0.2);
  }
  section#card.blue:hover {
    background-color: color(bblue);
    color: white;
    background-size: 80.1% 10%, 20% 10%;
    box-shadow: 0 10px 30px rgba(100, 0, 0, $alpha: 0.2);
  }
  section#card.red:hover {
    background-color: color(rred);
    color: white;
    background-size: 80.1% 10%, 20% 10%;
    box-shadow: 0 10px 30px rgba(100, 0, 0, $alpha: 0.2);
  }
}

<!doctype html>

  <link rel="stylesheet" href="css/main.css">

  <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
  <title>Title</title>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

                Bigname McLongnamington III

                Kitchener Rangers (OHL)

                height weight

                Bigname McLongnamington III

                Kitchener Rangers (OHL)

                height weight

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer accumsan est massa, quis hendrerit augue volutpat sed. Nam sit amet bibendum enim, eget suscipit odio. Donec risus odio, bibendum eget ipsum eget, bibendum congue est. Sed
                maximus lorem sit amet nibh condimentum viverra. Vestibulum sed quam fringilla, rhoncus eros et, imperdiet tellus. In nec nibh sollicitudin, pharetra purus vitae, consectetur mi. Curabitur laoreet finibus placerat.

                Bigname McLongnamington III

                Kitchener Rangers (OHL)

                height weight

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer accumsan est massa, quis hendrerit augue volutpat sed. Nam sit amet bibendum enim, eget suscipit odio. Donec risus odio, bibendum eget ipsum eget, bibendum congue est. Sed
                maximus lorem sit amet nibh condimentum viverra. Vestibulum sed quam fringilla, rhoncus eros et, imperdiet tellus. In nec nibh sollicitudin, pharetra purus vitae, consectetur mi. Curabitur laoreet finibus placerat.

                Bigname McLongnamington III

                Kitchener Rangers (OHL)

                height weight

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer accumsan est massa, quis hendrerit augue volutpat sed. Nam sit amet bibendum enim, eget suscipit odio. Donec risus odio, bibendum eget ipsum eget, bibendum congue est. Sed
                maximus lorem sit amet nibh condimentum viverra. Vestibulum sed quam fringilla, rhoncus eros et, imperdiet tellus. In nec nibh sollicitudin, pharetra purus vitae, consectetur mi. Curabitur laoreet finibus placerat.

If you look at the Codepen, you can see i have a bunch of sections, all will act as a card that a players draft info will appear, minus a paragraph blurb about them. There are a few things ive tried in terms of accomplishing my goal but essentially I want to be able to click on a players <section onclick="showReport()" id="card"... and have that players paragraph blurb appear in the sticky div on the left, changing based on which section card you click on. right now I have the players paragraph in a p tag within the section just for now, but im open to anything. I have a JS function on click in there for now but what I have tried so far required me to write a seperate hide() for each section (will be 31 total). Im looking for a method that will also allow me to only change the bio info and never have to adjust any code when I want to make edits to my draft chart. I hope I explained myself well enough, please tell me if I need to clarify.

Any help would be highly appreciated!

Body:
First, add this to each onclick on sections to get the element itself anytime you click on them.

...
<section onclick="showReport(this)" id="card" class="blue">
...

Then, you can use this (now turned into el variable) to find the text and put into the #content element.

function showReport(el) {
  $('#content').text($(el).find('p').text());
}


问:
Is there a way to add an empty element to an array in Javascript?
I've seen posts where you use a variation of .push() .push(undefined) and .push(null) but none seem to work.. my issue might be that when I am joining the list into a string, it gets rid of the empty ones.

The ultimate goal is to iterate through an array of arrays, then for each item in a "row", remove commas from the item if it is a string, and has a comma. My code is messy, I apologize.

Due to a lot of comments I shortened the code as much as I could.. I wanted to include my .join() because I think that might be part of my issue, thanks.

```<code>
    let someRow = [6, "Gaston,OH", "Brumm", "Male", , , , 2554];
    function remCommas(row) {
      let newRow = [];
      for (let item in row) {
        if (typeof row[item] === "string") {
          let Str = row[item].split();
          console.log(Str);
          let newStr = [];
          for (let char in Str) {
            if (Str[char] !== ",") {
              newStr.push(Str[char]);
            }
          }
          newRow.push(newStr.join());
        } else {
          newRow.push(row[item]);
        }
      }
      console.log(newRow);
      return newRow;
    }
    remCommas(someRow);

//          input: [6, "Gaston, OH", "Brumm", "Male", , , , 2554]
//expected output: [6, "Gaston OH", "Brumm", "Male", , , , 2554]
//  current ouput: [6, "Gaston, OH", "Brumm", "Male", 2554]
</code>```

答:
The hardest part was to understand the question, well if I understood correctly?

const input_Row = [6, "Gaston, OH", "Brumm", "Male", , , , 2554];

let output_Row = input_Row.map(row=>(typeof row==='string') ?row.replace(/,/g,'') :row)

console.log ('input_Row', input_Row)
console.log ('output_Row', output_Row)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I've seen posts where you use a variation of .push() .push(undefined) and .push(null) but none seem to work.. my issue might be that when I am joining the list into a string, it gets rid of the empty ones.

The ultimate goal is to iterate through an array of arrays, then for each item in a "row", remove commas from the item if it is a string, and has a comma. My code is messy, I apologize.

Due to a lot of comments I shortened the code as much as I could.. I wanted to include my .join() because I think that might be part of my issue, thanks.

    let someRow = [6, "Gaston,OH", "Brumm", "Male", , , , 2554];
    function remCommas(row) {
      let newRow = [];
      for (let item in row) {
        if (typeof row[item] === "string") {
          let Str = row[item].split();
          console.log(Str);
          let newStr = [];
          for (let char in Str) {
            if (Str[char] !== ",") {
              newStr.push(Str[char]);
            }
          }
          newRow.push(newStr.join());
        } else {
          newRow.push(row[item]);
        }
      }
      console.log(newRow);
      return newRow;
    }
    remCommas(someRow);

//          input: [6, "Gaston, OH", "Brumm", "Male", , , , 2554]
//expected output: [6, "Gaston OH", "Brumm", "Male", , , , 2554]
//  current ouput: [6, "Gaston, OH", "Brumm", "Male", 2554]

Body:
The hardest part was to understand the question, well if I understood correctly?

const input_Row = [6, "Gaston, OH", "Brumm", "Male", , , , 2554];

let output_Row = input_Row.map(row=>(typeof row==='string') ?row.replace(/,/g,'') :row)

console.log ('input_Row', input_Row)
console.log ('output_Row', output_Row)

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
jsonschema: validate list of dictionaries with specifc keys
I'm trying to write a jsonschema for a list of dictionaries (aka an array of objects) where I validate the keys in the dictionary. The labels in this example are what I'm interested in. I'd like to allow an arbitrary number of labels and like to validate that the name and value fields always exist in the label dictionary.  Here is an example input represented as yaml.

```<code>some_field1: "value_a"
some_field2: "value_b"
labels:
- name: "bar"
  value: "foo"
- name: "baz"
  value: "blah"
</code>```

Here is what I've pieced together so far, but it doesn't validate the keys in the dictionaries. I'm not sure exactly how the additionalProperites works in this case, but I found an example online.

```<code>properties:
  some_field1:
    type: string
    default: 'value_a'
  some_field2:
    type: string
    default: 'value_b'
  labels:
    type: array
    items:
      type: object
      additionalProperties:
        type: string
</code>```

My use case is that I'm trying to create a Custom Resource Definition (CRD) for Kubernetes where I validate the input, and my understanding is that the CRDs use openapi3/jsonschema validation to define their fields.

I'm having trouble finding an information about how to validate a list of dictionaries with specific keys. I'd appreciate any help that you have to offer.

答:
Known/fixed keys of a dictionary can be defined in properties and included in the required list:

  labels:
    type: array
    items:
      type: object
      required: [name, value]
      properties:
        name:
          type: string
        value:
          type: string
      additionalProperties:
        type: string
```

Body:
I'm trying to write a jsonschema for a list of dictionaries (aka an array of objects) where I validate the keys in the dictionary. The labels in this example are what I'm interested in. I'd like to allow an arbitrary number of labels and like to validate that the name and value fields always exist in the label dictionary.  Here is an example input represented as yaml.

some_field1: "value_a"
some_field2: "value_b"
labels:
- name: "bar"
  value: "foo"
- name: "baz"
  value: "blah"

Here is what I've pieced together so far, but it doesn't validate the keys in the dictionaries. I'm not sure exactly how the additionalProperites works in this case, but I found an example online.

properties:
  some_field1:
    type: string
    default: 'value_a'
  some_field2:
    type: string
    default: 'value_b'
  labels:
    type: array
    items:
      type: object
      additionalProperties:
        type: string

My use case is that I'm trying to create a Custom Resource Definition (CRD) for Kubernetes where I validate the input, and my understanding is that the CRDs use openapi3/jsonschema validation to define their fields.

I'm having trouble finding an information about how to validate a list of dictionaries with specific keys. I'd appreciate any help that you have to offer.


问:
React MaterialTable editable row validation - how to show and hide error?
I have a material-table and I want to run field validations on row editing only when the user clicks in save button.

I have this function to set the error:

```<code>const [nameError, setNameError] = useState({
        error: false,
        label: '',
        helperText: '',
    });
</code>```

And the onRowUpdate:

```<code>onRowUpdate: (newData, oldData) =>
                    new Promise((resolve, reject) => {
                        setTimeout(() => {

                            if (newData.name === '') {
                                setNameError({
                                    error: true,
                                    label: 'required',
                                    helperText: 'Required helper text'
                                });
                                reject();
                                return;
                            }

                            resolve();
                            if (oldData) {
                                setState(prevState => {
                                    const data = [...prevState.data];
                                    data[data.indexOf(oldData)] = newData;
                                    return { ...prevState, data };
                                });
                            }
                        }, 600);
                    })
</code>```

I can set the error, the problem is if I click on cancel button, next time I click on edit the error continues visible.

Here is a gif:

I tried to look for an event something like onCancelEdit but I didn't find anything, do you know how to solve this?

You can try this in

Complete React component code:

```<code>const tableIcons = {
    Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
    Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
    Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
    DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
    Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
    Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
    FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
    LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
    NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />),
    ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
    SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />),
    ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
    ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />)
};

export default function MaterialTableDemo() {

    const [nameError, setNameError] = useState({
        error: false,
        label: '',
        helperText: '',
    });

    const [state, setState] = React.useState({
        data: [
            {
                name: 'Mehmet',
                surname: 'Baran'
            },
            {
                name: 'Zerya Betül',
                surname: 'Baran'
            },
        ],
    });

    return (
        <MaterialTable
            title="Editable Example"
            columns={
                [
                    {
                        title: 'Name', field: 'name',
                        editComponent: (props) => (
                            <TextField
                                type="text"
                                error={nameError.error}
                                helperText={nameError.helperText}
                                value={props.value ? props.value : ''}
                                onChange={e => props.onChange(e.target.value)}
                            />
                        )
                    },
                    { title: 'Surname', field: 'surname' }
                ]}
            data={state.data}
            icons={tableIcons}
            editable={{
                onRowUpdate: (newData, oldData) =>
                    new Promise((resolve, reject) => {
                        setTimeout(() => {

                            if (newData.name === '') {
                                setNameError({
                                    error: true,
                                    label: 'required',
                                    helperText: 'Required helper text'
                                });
                                reject();
                                return;
                            }

                            resolve();
                            if (oldData) {
                                setState(prevState => {
                                    const data = [...prevState.data];
                                    data[data.indexOf(oldData)] = newData;
                                    return { ...prevState, data };
                                });
                            }
                        }, 600);
                    })
            }}
        />
    );
}

</code>```

答:
Check if the value exists in editComponent.

```<code>const [nameError, setNameError] = useState({
    error: false,
    label: "",
    helperText: "",
    validateInput: false
});

columns={[
  {
    title: "Name",
    field: "name",
    editComponent: props => (
    <TextField
        type="text"
        error={
        !props.value && nameError.validateInput
            ? nameError.error
            : false
        }
        helperText={
        !props.value && nameError.validateInput
            ? nameError.helperText
            : ""
        }
        value={props.value ? props.value : ""}
        onChange={e => {
        if (nameError.validateInput) {
            setNameError({
            ...nameError,
            validateInput: false
            });
        }

        props.onChange(e.target.value);
        }}
    />
    )
  },
  { title: "Surname", field: "surname" }
]}
</code>```

codesandbox

Body:
I have a material-table and I want to run field validations on row editing only when the user clicks in save button.

I have this function to set the error:

const [nameError, setNameError] = useState({
        error: false,
        label: '',
        helperText: '',
    });

And the onRowUpdate:

onRowUpdate: (newData, oldData) =>
                    new Promise((resolve, reject) => {
                        setTimeout(() => {

                            if (newData.name === '') {
                                setNameError({
                                    error: true,
                                    label: 'required',
                                    helperText: 'Required helper text'
                                });
                                reject();
                                return;
                            }

                            resolve();
                            if (oldData) {
                                setState(prevState => {
                                    const data = [...prevState.data];
                                    data[data.indexOf(oldData)] = newData;
                                    return { ...prevState, data };
                                });
                            }
                        }, 600);
                    })

I can set the error, the problem is if I click on cancel button, next time I click on edit the error continues visible.

Here is a gif:

I tried to look for an event something like onCancelEdit but I didn't find anything, do you know how to solve this?

You can try this in

Complete React component code:

const tableIcons = {
    Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
    Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
    Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
    DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
    Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
    Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
    FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
    LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
    NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    PreviousPage: forwardRef((props, ref) => <ChevronLeft {...props} ref={ref} />),
    ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
    SortArrow: forwardRef((props, ref) => <ArrowDownward {...props} ref={ref} />),
    ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
    ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />)
};

export default function MaterialTableDemo() {

    const [nameError, setNameError] = useState({
        error: false,
        label: '',
        helperText: '',
    });

    const [state, setState] = React.useState({
        data: [
            {
                name: 'Mehmet',
                surname: 'Baran'
            },
            {
                name: 'Zerya Betül',
                surname: 'Baran'
            },
        ],
    });

    return (
        <MaterialTable
            title="Editable Example"
            columns={
                [
                    {
                        title: 'Name', field: 'name',
                        editComponent: (props) => (
                            <TextField
                                type="text"
                                error={nameError.error}
                                helperText={nameError.helperText}
                                value={props.value ? props.value : ''}
                                onChange={e => props.onChange(e.target.value)}
                            />
                        )
                    },
                    { title: 'Surname', field: 'surname' }
                ]}
            data={state.data}
            icons={tableIcons}
            editable={{
                onRowUpdate: (newData, oldData) =>
                    new Promise((resolve, reject) => {
                        setTimeout(() => {

                            if (newData.name === '') {
                                setNameError({
                                    error: true,
                                    label: 'required',
                                    helperText: 'Required helper text'
                                });
                                reject();
                                return;
                            }

                            resolve();
                            if (oldData) {
                                setState(prevState => {
                                    const data = [...prevState.data];
                                    data[data.indexOf(oldData)] = newData;
                                    return { ...prevState, data };
                                });
                            }
                        }, 600);
                    })
            }}
        />
    );
}

Body:
Check if the value exists in editComponent.

const [nameError, setNameError] = useState({
    error: false,
    label: "",
    helperText: "",
    validateInput: false
});

columns={[
  {
    title: "Name",
    field: "name",
    editComponent: props => (
    <TextField
        type="text"
        error={
        !props.value && nameError.validateInput
            ? nameError.error
            : false
        }
        helperText={
        !props.value && nameError.validateInput
            ? nameError.helperText
            : ""
        }
        value={props.value ? props.value : ""}
        onChange={e => {
        if (nameError.validateInput) {
            setNameError({
            ...nameError,
            validateInput: false
            });
        }

        props.onChange(e.target.value);
        }}
    />
    )
  },
  { title: "Surname", field: "surname" }
]}

codesandbox


问:
How do I make modifications to the root window from a sub window in tkinter?
I'm trying to make a sub-window which allows you to alter certain parameters within the main window. I created a function which, when called by a button, will pop up, have an option menu to choose which option you want to alter, then some entry boxes to enter in what you want to alter.

My first thought was to alter the data in the function then just return it, but I didn't think that would work since the function is being called at the touch of a button. Anyone have any recommendations?

答:
Below is a simple example of how one could update the root window directly and any variables in the global namespace. Its just a matter of what you do in the functions you call from you buttons.

Let me know if you have any questions.

```<code>import tkinter as tk

root = tk.Tk()
root.config(background='white')
root.geometry('250x100')

label_1 = tk.Label(root, text=0)
label_1.pack()
label_2 = tk.Label(root, text='test')
label_2.pack()

def toggle_root_bg():
    # check the color of the root window and toggle accordingly.
    if root['background'] == 'black':
        root.config(background='white')
    else:
        root.config(background='black')

def update_root_labels(one, two):
    # Apply argument values to the text fields of the labels defined in the global namespace.
    label_1.config(text=one)
    label_2.config(text=two)

def sub_window():
    # setting sub window variable name to be used with other widgets.
    top = tk.Toplevel(root)
    tk.Label(top, text='Provide a number: ').grid(row=0, column=0)
    tk.Label(top, text='Provide a string: ').grid(row=1, column=0)
    entry_1 = tk.Entry(top)
    entry_2 = tk.Entry(top)
    entry_1.grid(row=0, column=1)
    entry_2.grid(row=1, column=1)

    # create a sub function to get the current entry field values
    # then pass these values on to our update function.
    def submit_update():
        update_root_labels(entry_1.get(), entry_2.get())

    tk.Button(top, text='Update root labels', command=submit_update).grid(row=2, column=0)
    tk.Button(top, text='Toggle Root Background', command=toggle_root_bg).grid(row=3, column=0)

tk.Button(root, text='Open sub window', command=sub_window).pack()
root.mainloop()
</code>```

Before:

After:

Body:
Below is a simple example of how one could update the root window directly and any variables in the global namespace. Its just a matter of what you do in the functions you call from you buttons.

Let me know if you have any questions.

import tkinter as tk

root = tk.Tk()
root.config(background='white')
root.geometry('250x100')

label_1 = tk.Label(root, text=0)
label_1.pack()
label_2 = tk.Label(root, text='test')
label_2.pack()

def toggle_root_bg():
    # check the color of the root window and toggle accordingly.
    if root['background'] == 'black':
        root.config(background='white')
    else:
        root.config(background='black')

def update_root_labels(one, two):
    # Apply argument values to the text fields of the labels defined in the global namespace.
    label_1.config(text=one)
    label_2.config(text=two)

def sub_window():
    # setting sub window variable name to be used with other widgets.
    top = tk.Toplevel(root)
    tk.Label(top, text='Provide a number: ').grid(row=0, column=0)
    tk.Label(top, text='Provide a string: ').grid(row=1, column=0)
    entry_1 = tk.Entry(top)
    entry_2 = tk.Entry(top)
    entry_1.grid(row=0, column=1)
    entry_2.grid(row=1, column=1)

    # create a sub function to get the current entry field values
    # then pass these values on to our update function.
    def submit_update():
        update_root_labels(entry_1.get(), entry_2.get())

    tk.Button(top, text='Update root labels', command=submit_update).grid(row=2, column=0)
    tk.Button(top, text='Toggle Root Background', command=toggle_root_bg).grid(row=3, column=0)

tk.Button(root, text='Open sub window', command=sub_window).pack()
root.mainloop()

Before:

After:


问:
How do I add an integer to every element of an array
I'm doing a method called adversary that takes two parameters: an array of ints and a number int and it adds that number to each element of the array</p>

答:
Try this

```<code>public static void add(int[] a, int n ) {
    for (int i=0; i<a.length;i++){
         a[i]=a[i]+n;
}}

</code>```

Let me know if it helps

Body:
Try this

public static void add(int[] a, int n ) {
    for (int i=0; i<a.length;i++){
         a[i]=a[i]+n;
}}

Let me know if it helps


问:
IE 7 CSS problem
CSS CODE:

```<code>.search {
float: left;
width: 100%;
display: block;
}

.search ul.tabs {
height: 23px;
margin: 50px 0 0 0;
padding: 0px;
}

/* FF ONLY */
.search ul.tabs, x:-moz-any-link {
height: 26px;
margin: 50px 0 0 0;
padding: 0px;
}

.search ul.tabs li {
float: left;
display: inline;
margin: 0;
padding: 0;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
-moz-border-top-left-radius: 3px;
-moz-border-top-right-radius: 3px;
-webkit-border-top-left-radius: 3px;
-webkit-border-top-right-radius: 3px;
}

.search ul.tabs li.second {
padding: 0 0 0 2px;
}

.search ul.tabs li a {
padding: 7px 10px 7px 10px;
background: #ffa63c;
font: normal normal bold 12px/1.5 "Arial", Helvetica, sans;
text-decoration: none;
color: #fdf9f1;
font-weight: bold;
}

.search ul.tabs li a:hover {
color: #fff;
}
</code>```

HTML CODE:

```<code><div style="float:left">
            <ul class="tabs">
                 <li id="ctl00_ctl00_cplMPBody_liRestaurnat" class="first">
                <a title="Poišči po imenu" class="activeRestaurant" href="x">Poišči restavracijo</a>
            </li>
            <li id="ctl00_ctl00_cplMPBody_liAddress" class="second">
                <a title="Poišči po imenu kraja" href="x">Poišči po krajih</a>
            </li>
            </ul>
        </div>
</code>```

And i have problem with IE:

FF

IE 7

what to do in IE 7?

答:
IE7 doesn't support rounded corners (they're a feature of CSS3). Consider using the css3pie, jquery ui, or the jquery rounded corner plugin:

http://css3pie.com/

http://jqueryui.com/

http://jquery.malsup.com/corner/

Title: IE 7 CSS problem

Body:
CSS CODE:

.search {
float: left;
width: 100%;
display: block;
}

.search ul.tabs {
height: 23px;
margin: 50px 0 0 0;
padding: 0px;
}

/* FF ONLY */
.search ul.tabs, x:-moz-any-link {
height: 26px;
margin: 50px 0 0 0;
padding: 0px;
}

.search ul.tabs li {
float: left;
display: inline;
margin: 0;
padding: 0;
border-top-left-radius: 3px;
border-top-right-radius: 3px;
-moz-border-top-left-radius: 3px;
-moz-border-top-right-radius: 3px;
-webkit-border-top-left-radius: 3px;
-webkit-border-top-right-radius: 3px;
}

.search ul.tabs li.second {
padding: 0 0 0 2px;
}

.search ul.tabs li a {
padding: 7px 10px 7px 10px;
background: #ffa63c;
font: normal normal bold 12px/1.5 "Arial", Helvetica, sans;
text-decoration: none;
color: #fdf9f1;
font-weight: bold;
}

.search ul.tabs li a:hover {
color: #fff;
}

HTML CODE:

                Poišči restavracijo

                Poišči po krajih

And i have problem with IE:

FF

IE 7

what to do in IE 7?