问:
How do I connect my docker Django instance to my docker mysql instance?
I'm running Docker on Mac High Sierra.  I want to run Docker container to house both my Django instances and MySql instances.  I have the following docker-compose.yml file ...

```<code>version: '3'

services:
  web:
    restart: always
    build: ./web
    ports:           # to access the container from outside
      - "8000:8000"
    env_file: .env
    environment:
      DEBUG: 'true'
    command: /usr/local/bin/gunicorn maps.wsgi:application -w 2 -b :8000

  apache:
    restart: always
    build: ./apache/
    ports:
      - "80:80"
    #volumes:
    #  - web-static:/www/static
    links:
      - web:web

  mysql:
    restart: always
    image: mysql:5.7
    environment:
      MYSQL_DATABASE: 'maps_data'
      # So you don't have to use root, but you can if you like
      MYSQL_USER: 'chicommons'
      # You can use whatever password you like
      MYSQL_PASSWORD: 'password'
      # Password for root access
      MYSQL_ROOT_PASSWORD: 'password'
    ports:
      - "3406:3406"
    volumes:
      - my-db:/var/lib/mysql

volumes:
  my-db:
</code>```

The ".env" file I set up looks like this ...

```<code>DB_NAME=maps_data
DB_USER=chicommons
DB_PASS=password
DB_SERVICE=mysql
DB_PORT=3406
</code>```

In my web (Django) instance, I have set my settings.py db thusly ...

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.environ['DB_NAME'],
        'USER': os.environ['DB_USER'],
        'PASSWORD': os.environ['DB_PASS'],
        'HOST': os.environ['DB_SERVICE'],
        'PORT': os.environ['DB_PORT']
    }
}
</code>```

However, when I run "docker-compose up," I get the following errors complaining about not being able to connect to the database ...

```<code>web_1     | Traceback (most recent call last):
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
web_1     |     self.connect()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect
web_1     |     self.connection = self.get_new_connection(conn_params)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 236, in get_new_connection
web_1     |     return Database.connect(**conn_params)
web_1     |   File "/usr/local/lib/python3.7/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1     |     return Connection(*args, **kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1     |     super(Connection, self).__init__(*args, **kwargs2)
web_1     | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on 'mysql' (115)")
web_1     |
web_1     | The above exception was the direct cause of the following exception:
web_1     |
web_1     | Traceback (most recent call last):
web_1     |   File "manage.py", line 21, in <module>
web_1     |     main()
web_1     |   File "manage.py", line 17, in main
web_1     |     execute_from_command_line(sys.argv)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
web_1     |     utility.execute()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute
web_1     |     self.fetch_command(subcommand).run_from_argv(self.argv)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
web_1     |     self.execute(*args, **cmd_options)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 332, in execute
web_1     |     self.check()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in check
web_1     |     include_deployment_checks=include_deployment_checks,
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 351, in _run_checks
web_1     |     return checks.run_checks(**kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 73, in run_checks
web_1     |     new_errors = check(app_configs=app_configs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/checks/model_checks.py", line 27, in check_all_models
web_1     |     errors.extend(model.check(**kwargs))
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 1200, in check
web_1     |     errors.extend(cls._check_fields(**kwargs))
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 1272, in _check_fields
web_1     |     errors.extend(field.check(**kwargs))
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 894, in check
web_1     |     errors = super().check(**kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 206, in check
web_1     |     errors.extend(self._check_backend_specific_checks(**kwargs))
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 303, in _check_backend_specific_checks
web_1     |     return connections[db].validation.check_field(self, **kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/validation.py", line 21, in check_field
web_1     |     field_type = field.db_type(self.connection)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 648, in db_type
web_1     |     return connection.data_types[self.get_internal_type()] % data
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__
web_1     |     res = instance.__dict__[self.name] = self.func(instance)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 133, in data_types
web_1     |     if self.features.supports_microsecond_precision:
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__
web_1     |     res = instance.__dict__[self.name] = self.func(instance)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/features.py", line 65, in supports_microsecond_precision
web_1     |     return self.connection.mysql_version >= (5, 6, 4)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__
web_1     |     res = instance.__dict__[self.name] = self.func(instance)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 345, in mysql_version
web_1     |     with self.temporary_connection() as cursor:
web_1     |   File "/usr/local/lib/python3.7/contextlib.py", line 112, in __enter__
web_1     |     return next(self.gen)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 576, in temporary_connection
web_1     |     cursor = self.cursor()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 255, in cursor
web_1     |     return self._cursor()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 232, in _cursor
web_1     |     self.ensure_connection()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
web_1     |     self.connect()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
web_1     |     raise dj_exc_value.with_traceback(traceback) from exc_value
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
web_1     |     self.connect()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect
web_1     |     self.connection = self.get_new_connection(conn_params)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 236, in get_new_connection
web_1     |     return Database.connect(**conn_params)
web_1     |   File "/usr/local/lib/python3.7/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1     |     return Connection(*args, **kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1     |     super(Connection, self).__init__(*args, **kwargs2)
web_1     | django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'mysql' (115)")
</code>```

What's going on?  How do I get my Django web docker instance to connect to my MySql docker instance?

答:
To use db's and other services, container to container, see links.

You took a mistake: "3406:3406". The first port is the host port and the second port is the service that is running inside the container, so mysql runs on 3306, therefore you have to change to "3406:3306".

If you have different services running like backend/frontend you should create networks between containers.

Body:
I'm running Docker on Mac High Sierra.  I want to run Docker container to house both my Django instances and MySql instances.  I have the following docker-compose.yml file ...

version: '3'

services:
  web:
    restart: always
    build: ./web
    ports:           # to access the container from outside
      - "8000:8000"
    env_file: .env
    environment:
      DEBUG: 'true'
    command: /usr/local/bin/gunicorn maps.wsgi:application -w 2 -b :8000

  apache:
    restart: always
    build: ./apache/
    ports:
      - "80:80"
    #volumes:
    #  - web-static:/www/static
    links:
      - web:web

  mysql:
    restart: always
    image: mysql:5.7
    environment:
      MYSQL_DATABASE: 'maps_data'
      # So you don't have to use root, but you can if you like
      MYSQL_USER: 'chicommons'
      # You can use whatever password you like
      MYSQL_PASSWORD: 'password'
      # Password for root access
      MYSQL_ROOT_PASSWORD: 'password'
    ports:
      - "3406:3406"
    volumes:
      - my-db:/var/lib/mysql

volumes:
  my-db:

The ".env" file I set up looks like this ...

DB_NAME=maps_data
DB_USER=chicommons
DB_PASS=password
DB_SERVICE=mysql
DB_PORT=3406

In my web (Django) instance, I have set my settings.py db thusly ...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.environ['DB_NAME'],
        'USER': os.environ['DB_USER'],
        'PASSWORD': os.environ['DB_PASS'],
        'HOST': os.environ['DB_SERVICE'],
        'PORT': os.environ['DB_PORT']
    }
}

However, when I run "docker-compose up," I get the following errors complaining about not being able to connect to the database ...

web_1     | Traceback (most recent call last):
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
web_1     |     self.connect()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect
web_1     |     self.connection = self.get_new_connection(conn_params)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 236, in get_new_connection
web_1     |     return Database.connect(**conn_params)
web_1     |   File "/usr/local/lib/python3.7/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1     |     return Connection(*args, **kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1     |     super(Connection, self).__init__(*args, **kwargs2)
web_1     | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on 'mysql' (115)")
web_1     |
web_1     | The above exception was the direct cause of the following exception:
web_1     |
web_1     | Traceback (most recent call last):
web_1     |   File "manage.py", line 21, in <module>
web_1     |     main()
web_1     |   File "manage.py", line 17, in main
web_1     |     execute_from_command_line(sys.argv)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
web_1     |     utility.execute()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute
web_1     |     self.fetch_command(subcommand).run_from_argv(self.argv)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
web_1     |     self.execute(*args, **cmd_options)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 332, in execute
web_1     |     self.check()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 364, in check
web_1     |     include_deployment_checks=include_deployment_checks,
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 351, in _run_checks
web_1     |     return checks.run_checks(**kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 73, in run_checks
web_1     |     new_errors = check(app_configs=app_configs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/core/checks/model_checks.py", line 27, in check_all_models
web_1     |     errors.extend(model.check(**kwargs))
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 1200, in check
web_1     |     errors.extend(cls._check_fields(**kwargs))
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 1272, in _check_fields
web_1     |     errors.extend(field.check(**kwargs))
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 894, in check
web_1     |     errors = super().check(**kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 206, in check
web_1     |     errors.extend(self._check_backend_specific_checks(**kwargs))
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 303, in _check_backend_specific_checks
web_1     |     return connections[db].validation.check_field(self, **kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/validation.py", line 21, in check_field
web_1     |     field_type = field.db_type(self.connection)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 648, in db_type
web_1     |     return connection.data_types[self.get_internal_type()] % data
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__
web_1     |     res = instance.__dict__[self.name] = self.func(instance)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 133, in data_types
web_1     |     if self.features.supports_microsecond_precision:
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__
web_1     |     res = instance.__dict__[self.name] = self.func(instance)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/features.py", line 65, in supports_microsecond_precision
web_1     |     return self.connection.mysql_version >= (5, 6, 4)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 36, in __get__
web_1     |     res = instance.__dict__[self.name] = self.func(instance)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 345, in mysql_version
web_1     |     with self.temporary_connection() as cursor:
web_1     |   File "/usr/local/lib/python3.7/contextlib.py", line 112, in __enter__
web_1     |     return next(self.gen)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 576, in temporary_connection
web_1     |     cursor = self.cursor()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 255, in cursor
web_1     |     return self._cursor()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 232, in _cursor
web_1     |     self.ensure_connection()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
web_1     |     self.connect()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
web_1     |     raise dj_exc_value.with_traceback(traceback) from exc_value
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
web_1     |     self.connect()
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 194, in connect
web_1     |     self.connection = self.get_new_connection(conn_params)
web_1     |   File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 236, in get_new_connection
web_1     |     return Database.connect(**conn_params)
web_1     |   File "/usr/local/lib/python3.7/site-packages/MySQLdb/__init__.py", line 84, in Connect
web_1     |     return Connection(*args, **kwargs)
web_1     |   File "/usr/local/lib/python3.7/site-packages/MySQLdb/connections.py", line 179, in __init__
web_1     |     super(Connection, self).__init__(*args, **kwargs2)
web_1     | django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'mysql' (115)")

What's going on?  How do I get my Django web docker instance to connect to my MySql docker instance?


来源: stackexchange

问:
Does Heroku charge any from creadit card for custom domain?
I want to point to custom domain. For account verification, Heroku ask for credit card details.
But I want to ask that for using a custom domain on Heroku does it charged any money from credit card </p>

答:
.. for using a custom domain on Heroku does it charged any money from credit card

It is free.

You can add custom domains to any Heroku app. Adding domains does not incur extra charges. For security purposes, you must verify your Heroku account to add domains to apps.
  https://devcenter.heroku.com/articles/custom-domains

ContentLicense: CC BY-SA 4.0


问:
Nested object destructuring with redux and react
I'm following a tutorial in React Redux. I have created a store variable with Redux store which has two sub variables. One is expenses which is an array of objects and another is filters which is an object itself.

```<code>const store = createStore(
    combineReducers({
        expenses: expensesReducer,
        filters: filtersReducer
    })
);
</code>```

When filled with dummy values the store would look like this:

```<code>const dummyState = {
    expenses: [{
        id: '10-AC-191',
        title: 'January Rent',
        note: 'This was the final payment for that address',
        amount: 545.00,
        createdAt: 0
    }, {
        id: '10-AK-155',
        title: 'Breakfast',
        amount: 545.00,
        createdAt: 2000
    }],
    filters: {
        text: 'rent',
        sortBy: 'amount',
        startDate: 700,
        endDate: 360,
    }
};
</code>```

I'm currently writing a function to display resultant expenses array which looks like this.

```<code>const getVisibleExpenses = (expenses, {text, sortBy, startDate, endDate}) => {
    return expenses.filter(({title, note, createdAt}) => {
        const startDateMatch = typeof startDate !== 'number' || createdAt >= startDate;
        const endDateMatch = typeof endDate !== 'number' || createdAt <= endDate;

        const searchText = text.trim().toLowerCase();
        const textMatch = typeof text !== 'string' || title.toLowerCase().includes(searchText)
            || note.toLowerCase().includes(searchText);

        return startDateMatch && endDateMatch && textMatch;
    }).sort((expense_a, expense_b) => {
        if (sortBy === 'amount') return expense_a.amount - expense_b.amount;
        else if (sortBy === 'date') return expense_a.createdAt - expense_b.createdAt;
    });
};
</code>```

This function takes store.expenses, store.filters as two inputs. So I wanted to pass in store object only and get the output.

Hence I tried to object destructure the input store itself instead of calling store below. But it returns an error.

```<code>const getVisibleExpenses = ({expenses, {text, sortBy, startDate, endDate}})
</code>```

Is there any possible solutions?

答:
Try this:</p>

```<code>const getVisibleExpenses = ({expenses, filters: {text, sortBy, startDate, endDate}}) => {}
</code>```

Body:
I'm following a tutorial in React Redux. I have created a store variable with Redux store which has two sub variables. One is expenses which is an array of objects and another is filters which is an object itself.

const store = createStore(
    combineReducers({
        expenses: expensesReducer,
        filters: filtersReducer
    })
);

When filled with dummy values the store would look like this:

const dummyState = {
    expenses: [{
        id: '10-AC-191',
        title: 'January Rent',
        note: 'This was the final payment for that address',
        amount: 545.00,
        createdAt: 0
    }, {
        id: '10-AK-155',
        title: 'Breakfast',
        amount: 545.00,
        createdAt: 2000
    }],
    filters: {
        text: 'rent',
        sortBy: 'amount',
        startDate: 700,
        endDate: 360,
    }
};

I'm currently writing a function to display resultant expenses array which looks like this.

const getVisibleExpenses = (expenses, {text, sortBy, startDate, endDate}) => {
    return expenses.filter(({title, note, createdAt}) => {
        const startDateMatch = typeof startDate !== 'number' || createdAt >= startDate;
        const endDateMatch = typeof endDate !== 'number' || createdAt <= endDate;

        const searchText = text.trim().toLowerCase();
        const textMatch = typeof text !== 'string' || title.toLowerCase().includes(searchText)
            || note.toLowerCase().includes(searchText);

        return startDateMatch && endDateMatch && textMatch;
    }).sort((expense_a, expense_b) => {
        if (sortBy === 'amount') return expense_a.amount - expense_b.amount;
        else if (sortBy === 'date') return expense_a.createdAt - expense_b.createdAt;
    });
};

This function takes store.expenses, store.filters as two inputs. So I wanted to pass in store object only and get the output.

Hence I tried to object destructure the input store itself instead of calling store below. But it returns an error.

const getVisibleExpenses = ({expenses, {text, sortBy, startDate, endDate}})

Is there any possible solutions?

Body:
Try this:

const getVisibleExpenses = ({expenses, filters: {text, sortBy, startDate, endDate}}) => {}


问:
"infinite" sql statement?
I've got a very strange sql-related problem.

I'm accessing a MSSQL Server 2005 with PHP (odbc), when I profile the sql statement the following is executed:

```<code>declare @p1 int
set @p1=180150003
declare @p3 int
set @p3=2
declare @p4 int
set @p4=1
declare @p5 int
set @p5=-1
exec sp_cursoropen @p1 output,N'SELECT  fieldA,  fieldB, fieldC, fieldD, fieldE FROM mytable WHERE fieldB IS NULL',@p3 output,@p4 output,@p5 output
select @p1, @p3, @p4, @p5

exec sp_cursorfetch 180150003,2,1,1
</code>```

On my own server it's working fine, on the customer-server the sp_cursorfetch reads infinite rows and loads the full cpu.
When I try to execute the statement itself

```<code>SELECT  fieldA,  fieldB, fieldC, fieldD, fieldE FROM mytable WHERE fieldB IS NULL
</code>```

in SQL Server Management Studio it works fine (under 1sec).

Any ideas?

Edit:
the main difference between the servers is that my server is a x86 (Win2003) and the server of the customer is a x64 (Win2008).

Edit2: Added Where-Clause

答: I don't know about SQL server, but Oracle doesn't even index NULL values. Even if it does, field IS NULL is not a selective criterion, so you might get a full table scan, which might take a long time if your customer has a lot of data.</p>

OwnerDisplayName: chris

ContentLicense: CC BY-SA 2.5

Title: "infinite" sql statement?

Body:
I've got a very strange sql-related problem.

I'm accessing a MSSQL Server 2005 with PHP (odbc), when I profile the sql statement the following is executed:

declare @p1 int
set @p1=180150003
declare @p3 int
set @p3=2
declare @p4 int
set @p4=1
declare @p5 int
set @p5=-1
exec sp_cursoropen @p1 output,N'SELECT  fieldA,  fieldB, fieldC, fieldD, fieldE FROM mytable WHERE fieldB IS NULL',@p3 output,@p4 output,@p5 output
select @p1, @p3, @p4, @p5

exec sp_cursorfetch 180150003,2,1,1

On my own server it's working fine, on the customer-server the sp_cursorfetch reads infinite rows and loads the full cpu.
When I try to execute the statement itself

SELECT  fieldA,  fieldB, fieldC, fieldD, fieldE FROM mytable WHERE fieldB IS NULL

in SQL Server Management Studio it works fine (under 1sec).

Any ideas?

Edit:
the main difference between the servers is that my server is a x86 (Win2003) and the server of the customer is a x64 (Win2008).

Edit2: Added Where-Clause

LastEditorDisplayName: DJ


问:
How to do "call by reference" in Java?

How to do "call by reference" in Java?  (Assume that we are using that term in the same way that it has been used in peer-reviewed CS literature since the 1960's; see this Wikipedia page for a simple explanation.)

Since Java doesn't support pointers, how is it possible to call a function by reference in Java like we do in C and C++??

答:
Usually in java this is solved by using interfaces:</p>

```<code>Collections.sort(list, new Comparator() {

  @Override
  public int compareTo(Object o1, Object o2) {
  /// code
  }

});
</code>```

Title: How to do "call by reference" in Java?

Body:
Usually in java this is solved by using interfaces:

Collections.sort(list, new Comparator() {

  @Override
  public int compareTo(Object o1, Object o2) {
  /// code
  }

});

ContentLicense: CC BY-SA 3.0


问:
How to get all cookies with XMLHttpRequest?
For a small project of mine I am trying to get a list of all cookies of a website and analyze them later on which flags they and/or are missing. I look at a website through the inspection tool and I am seeing a lot more cookies than what I get from my code, presumably due to the same-origin-policy? Anyways my question is, if there is a way to request a website in JS and get the entirety of the cookies? I am also open to new ideas if there is another way to test or find out the flags of the cookies of any website.

```<code>var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.withCredentials = true;
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
console.log(headers);
</code>```

EDIT: The answer to the problem was chrome.cookies.getAll().

答:
Have you checked the cookie documentation from Mozilla website ?

I can just use document.cookie to retrieve all cookies stored on your web browser

Body:
For a small project of mine I am trying to get a list of all cookies of a website and analyze them later on which flags they and/or are missing. I look at a website through the inspection tool and I am seeing a lot more cookies than what I get from my code, presumably due to the same-origin-policy? Anyways my question is, if there is a way to request a website in JS and get the entirety of the cookies? I am also open to new ideas if there is another way to test or find out the flags of the cookies of any website.

var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.withCredentials = true;
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
console.log(headers);

EDIT: The answer to the problem was chrome.cookies.getAll().


问:
Get content with RegEx between braces and a keyword
I'm just facing with a problem, what I cannot solve it.
I tried to build up my regex pattern which has to be get the content between braces but if only an exact keyword is stands before the open brace.

```<code>(?<=(?:\testlist\b)|(?:){)((.*?)(?=}))
</code>```

The whole content itself may contains many blocks (which are always beginning with a keyword), like:

```<code>nodelist{
...
...
}
testlist
{
...
...
}
</code>```

With the above pattern I can get each of node contents but I would like to specify in regex that only 'testlist' node's content has to be grabbed.
(Position of braces are different by design because I would like to get the content even if the braces are in the same line as the keyword or no matter, how many line breaks contains after it)

Does anyone any idea, how can I achieve this?

Thank you!

答:
You can use a regex like

```<code>(?s)testlist\s*{(.*?)}
</code>```

This matches testlist literally, followed by spaces and a literal opening brace. (.*?) captures everything until the next closing brace.

Usage:

```<code>PS C:\Users\greg> 'nodelist{
>> ...
>> ...
>> }
>> testlist
>> {
>> ...
>> ...
>> }' -match '(?s)testlist\s*{(.*?)}'
True
PS C:\Users\greg> $Matches.0
testlist
{
...
...
}
PS C:\Users\greg> $Matches.1

...
...

PS C:\Users\greg>
</code>```

If you want a full match instead of a capture group:

```<code>PS C:\Users\greg> 'nodelist{
>> ...
>> ...
>> }
>> testlist
>> {
>> ...
>> ...
>> }' -match '(?s)(?<=testlist\s*{).*?(?=})'
True
PS C:\Users\greg> $Matches.0

...
...

PS C:\Users\greg>
</code>```

Body:
I'm just facing with a problem, what I cannot solve it.
I tried to build up my regex pattern which has to be get the content between braces but if only an exact keyword is stands before the open brace.

(?<=(?:\testlist\b)|(?:){)((.*?)(?=}))

The whole content itself may contains many blocks (which are always beginning with a keyword), like:

nodelist{
...
...
}
testlist
{
...
...
}

With the above pattern I can get each of node contents but I would like to specify in regex that only 'testlist' node's content has to be grabbed.
(Position of braces are different by design because I would like to get the content even if the braces are in the same line as the keyword or no matter, how many line breaks contains after it)

Does anyone any idea, how can I achieve this?

Thank you!

Body:
You can use a regex like

(?s)testlist\s*{(.*?)}

This matches testlist literally, followed by spaces and a literal opening brace. (.*?) captures everything until the next closing brace.

Usage:

PS C:\Users\greg> 'nodelist{
>> ...
>> ...
>> }
>> testlist
>> {
>> ...
>> ...
>> }' -match '(?s)testlist\s*{(.*?)}'
True
PS C:\Users\greg> $Matches.0
testlist
{
...
...
}
PS C:\Users\greg> $Matches.1

...
...

PS C:\Users\greg>

If you want a full match instead of a capture group:

PS C:\Users\greg> 'nodelist{
>> ...
>> ...
>> }
>> testlist
>> {
>> ...
>> ...
>> }' -match '(?s)(?<=testlist\s*{).*?(?=})'
True
PS C:\Users\greg> $Matches.0

...
...

PS C:\Users\greg>


问:
SQL query to find multi level hierarchical data
Imagine I have some data in a relational table like below.

```<code>name           friend_name

Ryan           James
Chin           James
Jack           Charley
Tomy           Ryan
Bill           Chin
</code>```

Now, given friend_name 'James' I want the result as

```<code>name

Ryan
Chin
Tomy
Bill
</code>```

What should my SQL query look like? I'm using SQL Server.

答:
The entry level way to do this would just be a UNION if you don't have duplicates.

```<code>SELECT name
FROM t1
WHERE friend_name = 'James'

UNION

SELECT friend_name name
FROM t2
WHERE name = 'James'
</code>```

Body:
Imagine I have some data in a relational table like below.

name           friend_name

Ryan           James
Chin           James
Jack           Charley
Tomy           Ryan
Bill           Chin

Now, given friend_name 'James' I want the result as

name

Ryan
Chin
Tomy
Bill

What should my SQL query look like? I'm using SQL Server.

Body:
The entry level way to do this would just be a UNION if you don't have duplicates.

SELECT name
FROM t1
WHERE friend_name = 'James'

UNION

SELECT friend_name name
FROM t2
WHERE name = 'James'


问:
How to associate opencv image with dimensions in mm?
I have an image of 2061x2533 which represent an area of 429x349mm. When I open this saved image in Adobe Illustrator I would like the size to be exactly 429x349mm.

So I have a dpi value associated to my opencv image, but when I use cv.imwrite I did not find a way to set the dpi parameter to be considered by Photoshop or Illustrator.

Any idea?

答:
As Micka said in his comment, opencv is for computer vision not for image editing. So you need another library to handle this. </p>

<p>You could for instance use pillow: </p>

```<code>from PIL import Image
dpi = 150

cim = cv.imread(str(filename))

...

im = Image.fromarray(cim)
im.save('foobar.jpg', dpi=(dpi, dpi))
</code>```

Body:
As Micka said in his comment, opencv is for computer vision not for image editing. So you need another library to handle this.

You could for instance use pillow:

from PIL import Image
dpi = 150

cim = cv.imread(str(filename))

...

im = Image.fromarray(cim)
im.save('foobar.jpg', dpi=(dpi, dpi))


问:
Is it possible to get 3 specific randoms in specific order in Python?
The task asks to make a Rock Paper Scissors game where user selects one choice and then random.randint(0,2) generates the random choice for computer.

I have already written a working game (Finnish language in variables, functions and prints) :

```<code>import random

kierrokset = 0
voitot = 0
tasapelit = 0

def arvoTietokone():
    tietokone = random.randint(0,2)
    if tietokone == 0:
        print("tietokone valitsi: Jalka")
        return tietokone
    elif tietokone == 1:
        print("tietokone valitsi: Ydinase")
        return tietokone
    else:
        print("tietokone valitsi: Torakka")
        return tietokone

def arvoVoittaja(pelaaja, tietokone):
    global kierrokset, voitot, tasapelit
    if pelaaja == "Jalka":
        if tietokone == 0:
            print("Tasapeli!")
            tasapelit += 1
            kierrokset += 1

        elif tietokone == 1:
            print("Hävisit!")
            kierrokset += 1

        else:
            print("Voitit!")
            voitot += 1
            kierrokset += 1

    elif pelaaja == "Ydinase":
        if tietokone == 0:
            print("Voitit!")
            voitot += 1
            kierrokset += 1

        elif tietokone == 1:
            print("Tasapeli!")
            tasapelit += 1
            kierrokset += 1

        else:
            print("Hävisit!")
            kierrokset += 1

    elif pelaaja == "Torakka":
        if tietokone == 0:
            print("Hävisit!")
            kierrokset += 1

        elif tietokone == 1:
            print("Voitit!")
            voitot += 1
            kierrokset += 1
        else:
            print("Tasapeli!")
            tasapelit += 1
            kierrokset += 1

while True:

    pelaaja = input("Jalka, Ydinase vai Torakka? (Lopeta lopettaa): ")

    if pelaaja == "Lopeta":
        print("Pelasit",kierrokset,"joista voitit",voitot,"ja pelasit tasan",tasapelit,"peliä.")
        break

    print("Sinä valitsit: ",pelaaja)

    tietokone = arvoTietokone()

    arvoVoittaja(pelaaja, tietokone)
</code>```

I have no problems with code itself, but here's the kicker:

The testing platform that the course uses runs 3 different test runs for the code and each time computer choice has to be exactly different one. On Test1 computer choice has to be Rock, on Test2 computer choice must be Paper, and on Test3 computer choice must be Scissors.

How can you produce the choices exactly in that order (Rock, Paper, Scissors) when the choice is generated on random?

It is as if the task wants 3 specific randoms in specific order.

Is this logically even possible or is the course task invalid/badly designed?

I already have sent feedback to the teacher handling the course, but I have not yet received a response.

答: OK, I've managed to pass the Python course. Turned out that they have a design error in their course platform and thus this task was logically impossible.</p>

Body:
The task asks to make a Rock Paper Scissors game where user selects one choice and then random.randint(0,2) generates the random choice for computer.

I have already written a working game (Finnish language in variables, functions and prints) :

import random

kierrokset = 0
voitot = 0
tasapelit = 0

def arvoTietokone():
    tietokone = random.randint(0,2)
    if tietokone == 0:
        print("tietokone valitsi: Jalka")
        return tietokone
    elif tietokone == 1:
        print("tietokone valitsi: Ydinase")
        return tietokone
    else:
        print("tietokone valitsi: Torakka")
        return tietokone

def arvoVoittaja(pelaaja, tietokone):
    global kierrokset, voitot, tasapelit
    if pelaaja == "Jalka":
        if tietokone == 0:
            print("Tasapeli!")
            tasapelit += 1
            kierrokset += 1

        elif tietokone == 1:
            print("Hävisit!")
            kierrokset += 1

        else:
            print("Voitit!")
            voitot += 1
            kierrokset += 1

    elif pelaaja == "Ydinase":
        if tietokone == 0:
            print("Voitit!")
            voitot += 1
            kierrokset += 1

        elif tietokone == 1:
            print("Tasapeli!")
            tasapelit += 1
            kierrokset += 1

        else:
            print("Hävisit!")
            kierrokset += 1

    elif pelaaja == "Torakka":
        if tietokone == 0:
            print("Hävisit!")
            kierrokset += 1

        elif tietokone == 1:
            print("Voitit!")
            voitot += 1
            kierrokset += 1
        else:
            print("Tasapeli!")
            tasapelit += 1
            kierrokset += 1

while True:

    pelaaja = input("Jalka, Ydinase vai Torakka? (Lopeta lopettaa): ")

    if pelaaja == "Lopeta":
        print("Pelasit",kierrokset,"joista voitit",voitot,"ja pelasit tasan",tasapelit,"peliä.")
        break

    print("Sinä valitsit: ",pelaaja)

    tietokone = arvoTietokone()

    arvoVoittaja(pelaaja, tietokone)

I have no problems with code itself, but here's the kicker:

The testing platform that the course uses runs 3 different test runs for the code and each time computer choice has to be exactly different one. On Test1 computer choice has to be Rock, on Test2 computer choice must be Paper, and on Test3 computer choice must be Scissors.

How can you produce the choices exactly in that order (Rock, Paper, Scissors) when the choice is generated on random?

It is as if the task wants 3 specific randoms in specific order.

Is this logically even possible or is the course task invalid/badly designed?

I already have sent feedback to the teacher handling the course, but I have not yet received a response.


问:
Pandas: Create a table with a “dummy variable” of another table
Let's say I have this dataframes

DataFrame A (Products)

```<code>Cod | Product   | Cost | Date
-------------------------------
18  | Product01 | 3.4  | 21/04
22  | Product02 | 7.2  | 12/08
33  | Product03 | 8.4  | 17/01
55  | Product04 | 0.6  | 13/07
67  | Product05 | 1.1  | 09/09

</code>```

DataFrame B (Operations)

```<code>id | codoper | CodProd  | valor
-------------------------------
1  | 00001   | 55       | 45000
2  | 00001   | 18       | 45000
3  | 00002   | 33       | 53000
1  | 00001   | 55       | 45000

</code>```

The idea is obtain a "dataframe C" with the column product from "Dataframe B":

DataFrame C Result

```<code>id | codoper | Product_18| Product_22| Product_33| Product_55| Product_67 |valor
----------------------------------------------------------------------------------
1  | 00001   | 1         | 0         | 0         | 1         | 0          |45000
2  | 00002   | 0         | 0         | 1         | 0         | 0          |53000
</code>```

So far I only managed to do it from the "DataFrame B":

```<code>pd.get_dummies(df, columns=['CodProd']).groupby(['codoper'], as_index=False).min()
</code>```

Note: I don't have all products from Dataframe A in the Dataframe of Operations

thanks

答:
This is a combination of merge and pivot_table with some tweaks:

```<code>(Products.merge(Operations,
                left_on='Cod',
                right_on='CodProd',
                how='left')
     .pivot_table(index=['codoper','valor'],
                  values='Product',
                  columns='Cod',
                  fill_value=0,
                  aggfunc='any')
     .reindex(Products.Cod.unique(),
              fill_value=False,
              axis=1)
     .astype(int)
     .add_prefix('Product_')
     .reset_index()
)
</code>```

Output:

```<code>Cod codoper    valor  Product_18  Product_22  Product_33  Product_55  \
0     00001  45000.0           1           0           0           1
1     00002  53000.0           0           0           1           0

Cod  Product_67
0             0
1             0
</code>```

Body:
Let's say I have this dataframes

DataFrame A (Products)

Cod | Product   | Cost | Date
-------------------------------
18  | Product01 | 3.4  | 21/04
22  | Product02 | 7.2  | 12/08
33  | Product03 | 8.4  | 17/01
55  | Product04 | 0.6  | 13/07
67  | Product05 | 1.1  | 09/09

DataFrame B (Operations)

id | codoper | CodProd  | valor
-------------------------------
1  | 00001   | 55       | 45000
2  | 00001   | 18       | 45000
3  | 00002   | 33       | 53000
1  | 00001   | 55       | 45000

The idea is obtain a "dataframe C" with the column product from "Dataframe B":

DataFrame C Result

id | codoper | Product_18| Product_22| Product_33| Product_55| Product_67 |valor
----------------------------------------------------------------------------------
1  | 00001   | 1         | 0         | 0         | 1         | 0          |45000
2  | 00002   | 0         | 0         | 1         | 0         | 0          |53000

So far I only managed to do it from the "DataFrame B":

pd.get_dummies(df, columns=['CodProd']).groupby(['codoper'], as_index=False).min()

Note: I don't have all products from Dataframe A in the Dataframe of Operations

thanks

Body:
This is a combination of merge and pivot_table with some tweaks:

(Products.merge(Operations,
                left_on='Cod',
                right_on='CodProd',
                how='left')
     .pivot_table(index=['codoper','valor'],
                  values='Product',
                  columns='Cod',
                  fill_value=0,
                  aggfunc='any')
     .reindex(Products.Cod.unique(),
              fill_value=False,
              axis=1)
     .astype(int)
     .add_prefix('Product_')
     .reset_index()
)

Output:

Cod codoper    valor  Product_18  Product_22  Product_33  Product_55  \
0     00001  45000.0           1           0           0           1
1     00002  53000.0           0           0           1           0

Cod  Product_67
0             0
1             0


问:
Is it possible to get real-time message backup from whatsapp?
I am trying to perform WhatsApp chat analysis and basically want to have the messages instantly transferred into a text file for further processing.

The issue is that WhatsApp does create a local backup daily at around 2:00 am in the msgstore.db, however, I wish to receive the texts and media instantly after every message. In a nutshell, is real-time text and media retrieval of WhatsApp messages possible on every message?

P.S. I did try searching online for the mining methods for WhatsApp, but they usually seem to be based on the local backups that have the lowest backup interval of a day, whereas I want it on every message.

Update: As suggested by @pette, I tried emulator method and it too is able to perform chat analysis on the daily local backup. I came across many research papers and realized that WhatsApp does not allow for third party apps to sniff on its application.

Also, I tried using automation technique wherein, I use whatsapp web and automate to copy text on every message. But, these techniques are limited to computer application.

Is it possible to pipe-out whatsapp texts to another text file or log file?

答: you can install an android emulator, as x86, install the apk of whatsapp, mount the disk of your emulator and open msgstore.db, but you can only retrieve the text files</p>


问:
How can I enable the Virtual Reality Supported project setting from a Unity editor script?
I'm working on a Unity VR framework which I'd like to have enable VR for a project as soon as the package is added. I've done some research on how to change the project settings in an editor script, but I can't find this setting anywhere in the files. This setting is found in the editor as:

Edit->Project Settings->Player->XR Settings->Virtual Reality Supported

I tried finding it in the project settings files by opening all of them in Notepad++, changing the setting in the Unity editor, and checking Notepad++ for which file it said had been changed externally. None of them were, so I'm under the impression that this setting in the editor isn't located in the project settings folder, so I have no idea what that little checkbox actually does. How can I enable VR support for the project from code?

答:
Please try

```<code>PlayerSettings.virtualRealitySupported = true;
</code>```

(While I didn't see this in Unity's PlayerSettings docs, I remembered the Oculus VR plugin did similar, so I dug there.)

Body:
Please try

PlayerSettings.virtualRealitySupported = true;

(While I didn't see this in Unity's PlayerSettings docs, I remembered the Oculus VR plugin did similar, so I dug there.)


问:
Flutter Integration Testing- How to go back to previous screen when no back button available on screen
How to go back to previous screen when no back button available on screen?
Additional Information: I am trying to automate integration testing for flutter app. There is no back button on screen which I can use to go back screen.
Additional information: I am writing integration tests, for same I need to go back to previous screen. And due to design there is no back button on screen, I need to do by scripts only.  </p>

答:
Well, it's maybe a little bit late, however there are two possible ways to achieve this:

```<code>final backButton = find.byTooltip('Back');

await driver.tap(backButton);
</code>```

or:

```<code>await driver.tap(find.pageBack());
</code>```

Body:
Well, it's maybe a little bit late, however there are two possible ways to achieve this:

final backButton = find.byTooltip('Back');

await driver.tap(backButton);

or:

await driver.tap(find.pageBack());


问:
Multiple Bash traps for the same signal
When I use the trap command in Bash, the previous trap for the given signal is replaced.

Is there a way of making more than one trap fire for the same signal?

答:
I add a slightly more robust version of Laurent Simon's trap-add script:

Allows using arbitrary commands as trap, including such with ' characters

Works only in bash; It could be rewritten with sed instead of bash pattern substitution, but that would make it significantly slower.

Still suffers from causing unwanted inheritance of the traps in subshells.

```<code>trap-add () {
    local handler=$(trap -p "$2")
    handler=${handler/trap -- \'/}    # /- Strip `trap '...' SIGNAL` -> ...
    handler=${handler%\'*}            # \-
    handler=${handler//\'\\\'\'/\'}   # <- Unquote quoted quotes ('\'')
    trap "${handler} $1;" "$2"
}
</code>```

Title: Multiple Bash traps for the same signal

Body:
I add a slightly more robust version of Laurent Simon's trap-add script:

Allows using arbitrary commands as trap, including such with ' characters

Works only in bash; It could be rewritten with sed instead of bash pattern substitution, but that would make it significantly slower.

Still suffers from causing unwanted inheritance of the traps in subshells.

trap-add () {
    local handler=$(trap -p "$2")
    handler=${handler/trap -- \'/}    # /- Strip `trap '...' SIGNAL` -> ...
    handler=${handler%\'*}            # \-
    handler=${handler//\'\\\'\'/\'}   # <- Unquote quoted quotes ('\'')
    trap "${handler} $1;" "$2"
}


问:
Table gigpost_category has no column named titled
I'm trying to make a simple blog and I'm facing this problem. When I try to add a model in my admin panel it shows me this error.

Here is the code :

models.py

```<code>from django.db import models
from django.utils import timezone
from django.conf import settings

# Create your models here.
class Category(models.Model):
    titled=models.CharField(max_length=100,default='')

    def __str__(self):
        return self.title
class Gigpost(models.Model):

    title=models.CharField(default='',max_length=100,blank=False)
    user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=False)
    categories=models.OneToOneField(Category,on_delete=models.PROTECT,default='',blank=False)
    published_at=models.DateTimeField(auto_now_add=True)
    description=models.TextField(default='',max_length=None,blank=False)
    mainphoto=models.ImageField(default='')
    photo=models.ImageField()
    def __str__(self):
        return self.title

class Comment_area(models.Model):

    user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=False)
    comment=models.TextField(max_length=None,default='')
    commented_at=models.DateTimeField(auto_now_add=True)
</code>```

admin.py

```<code>from django.contrib import admin
from .models import Gigpost , Category

# Register your models here.
admin.site.register(Gigpost)
admin.site.register(Category)
</code>```

The error message :

```<code>OperationalError at /admin/gigpost/category/add/
table gigpost_category has no column named titled
Request Method: POST
Request URL:    http://127.0.0.1:8000/admin/gigpost/category/add/
Django Version: 2.2.5
Exception Type: OperationalError
Exception Value:
table gigpost_category has no column named titled
</code>```

答:
Fixed ur typoes etc. please try this:

models.py

```<code>from django.db import models
from django.utils import timezone
from django.conf import settings
from django.contrib.auth.models import User

# Create your models here.
class Category(models.Model):
    title = models.CharField(max_length=100, default='')

    def __str__(self):
        return self.title

class Gigpost(models.Model):

    title = models.CharField(default='',max_length=100)
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    categorie=models.ForeignKey(Category,on_delete=models.SET_NULL, null=True)
    published_at = models.DateTimeField(auto_now_add=True)
    description = models.TextField(default='')
    mainphoto = models.ImageField(blank=True)
    photo = models.ImageField(blank=True)

    def __str__(self):
        return self.title

class Comment_area(models.Model):

    user=models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    comment=models.TextField(default='')
    commented_at=models.DateTimeField(auto_now_add=True)
</code>```

After you made any changes on your models.py don't forget to run makemigrations and migrate.

You should also check, whether the migration file was created. And maybe you need to restart your server.

Body:
I'm trying to make a simple blog and I'm facing this problem. When I try to add a model in my admin panel it shows me this error.

Here is the code :

models.py

from django.db import models
from django.utils import timezone
from django.conf import settings

# Create your models here.
class Category(models.Model):
    titled=models.CharField(max_length=100,default='')

    def __str__(self):
        return self.title
class Gigpost(models.Model):

    title=models.CharField(default='',max_length=100,blank=False)
    user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=False)
    categories=models.OneToOneField(Category,on_delete=models.PROTECT,default='',blank=False)
    published_at=models.DateTimeField(auto_now_add=True)
    description=models.TextField(default='',max_length=None,blank=False)
    mainphoto=models.ImageField(default='')
    photo=models.ImageField()
    def __str__(self):
        return self.title

class Comment_area(models.Model):

    user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=False)
    comment=models.TextField(max_length=None,default='')
    commented_at=models.DateTimeField(auto_now_add=True)

admin.py

from django.contrib import admin
from .models import Gigpost , Category

# Register your models here.
admin.site.register(Gigpost)
admin.site.register(Category)

The error message :

OperationalError at /admin/gigpost/category/add/
table gigpost_category has no column named titled
Request Method: POST
Request URL:    http://127.0.0.1:8000/admin/gigpost/category/add/
Django Version: 2.2.5
Exception Type: OperationalError
Exception Value:
table gigpost_category has no column named titled

Body:
Fixed ur typoes etc. please try this:

models.py

from django.db import models
from django.utils import timezone
from django.conf import settings
from django.contrib.auth.models import User

# Create your models here.
class Category(models.Model):
    title = models.CharField(max_length=100, default='')

    def __str__(self):
        return self.title

class Gigpost(models.Model):

    title = models.CharField(default='',max_length=100)
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    categorie=models.ForeignKey(Category,on_delete=models.SET_NULL, null=True)
    published_at = models.DateTimeField(auto_now_add=True)
    description = models.TextField(default='')
    mainphoto = models.ImageField(blank=True)
    photo = models.ImageField(blank=True)

    def __str__(self):
        return self.title

class Comment_area(models.Model):

    user=models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    comment=models.TextField(default='')
    commented_at=models.DateTimeField(auto_now_add=True)

After you made any changes on your models.py don't forget to run makemigrations and migrate.

You should also check, whether the migration file was created. And maybe you need to restart your server.


答:
You need to combine the dummies from Products with the dummies from Operations. Start by defining the output columns by using a prefix:

columns = ['id', 'codoper'] + [f"Product_{cod}" for cod in A['Cod'].unique()] + ['valor']
```

<p>Then, use get dummies as you're doing above, but use the same prefix from defing the columns. Group by <em>all columns which perfectly collinear</em>, i.e. <code>id</code>, <code>codoper</code>, and <code>valor</code>. If these aren't perfectly collinear, than you need to decide how to aggregate them to the level of <code>codoper</code>. Finally, reindex using the output columns you previously defined, filling missing values with zero.</p>

<pre class="lang-py prettyprint-override"><code>pd.get_dummies(B, columns=['CodProd'], prefix='Product').groupby(['id', 'codoper', 'valor'], as_index=False).sum().reindex(columns=columns, fill_value=0)
</code>```

```<code>  id codoper  Product_18  Product_22  Product_33  Product_55  Product_67  valor
0  1   00001           0           0           0           2           0  45000
1  2   00001           1           0           0           0           0  45000
2  3   00002           0           0           1           0           0  53000
</code>```

Title: Pandas: Create a table with a “dummy variable” of another table

Body:
You need to combine the dummies from Products with the dummies from Operations. Start by defining the output columns by using a prefix:

columns = ['id', 'codoper'] + [f"Product_{cod}" for cod in A['Cod'].unique()] + ['valor']

Then, use get dummies as you're doing above, but use the same prefix from defing the columns. Group by all columns which perfectly collinear, i.e. id, codoper, and valor. If these aren't perfectly collinear, than you need to decide how to aggregate them to the level of codoper. Finally, reindex using the output columns you previously defined, filling missing values with zero.

pd.get_dummies(B, columns=['CodProd'], prefix='Product').groupby(['id', 'codoper', 'valor'], as_index=False).sum().reindex(columns=columns, fill_value=0)

  id codoper  Product_18  Product_22  Product_33  Product_55  Product_67  valor
0  1   00001           0           0           0           2           0  45000
1  2   00001           1           0           0           0           0  45000
2  3   00002           0           0           1           0           0  53000


问:
is this the proper way to add multiple text fields at once into mysql?
this works perfect but is this the proper way to do this?</p>

```<code><?
/////////////////add/////////////////////////////////

    for ($i=0; $i<count($_POST['newhour_start']); $i++) {
        if ($_POST['newhour_start'][$i] !="" && $_POST['newhour_end'][$i] !="" ) {
            $inserthour = mysql_query("INSERT INTO hour
            (hour_start,hour_end,hour_day) VALUES
            ('".$_POST['newhour_start'][$i]."','".$_POST['newhour_end'][$i]."','".$_POST['newhour_day'][$i]."')");
        }
    }
?>
Start:<input name="newhour_start[]" type="text" id="newhour_start" > End: <input name="newhour_end[]" type="text" id="newhour_end" ><input name="newhour_day[]" type="hidden" id="newhour_day" value="Monday" >

Start:<input name="newhour_start[]" type="text" id="newhour_start" > End: <input name="newhour_end[]" type="text" id="newhour_end" ><input name="newhour_day[]" type="hidden" id="newhour_day" value="Monday" >

Start:<input name="newhour_start[]" type="text" id="newhour_start" > End: <input name="newhour_end[]" type="text" id="newhour_end" ><input name="newhour_day[]" type="hidden" id="newhour_day" value="Monday" >
</code>```

答:
You can insert multiple rows at once:</p>

```<code>mysql_query("INSERT INTO hour
            (hour_start,hour_end,hour_day) VALUES
            (1, 2, 3),
            (4, 5, 6)
);
</code>```

Body:
this works perfect but is this the proper way to do this?

<?
/////////////////add/////////////////////////////////

    for ($i=0; $i<count($_POST['newhour_start']); $i++) {
        if ($_POST['newhour_start'][$i] !="" && $_POST['newhour_end'][$i] !="" ) {
            $inserthour = mysql_query("INSERT INTO hour
            (hour_start,hour_end,hour_day) VALUES
            ('".$_POST['newhour_start'][$i]."','".$_POST['newhour_end'][$i]."','".$_POST['newhour_day'][$i]."')");
        }
    }
?>
Start:<input name="newhour_start[]" type="text" id="newhour_start" > End: <input name="newhour_end[]" type="text" id="newhour_end" ><input name="newhour_day[]" type="hidden" id="newhour_day" value="Monday" >

Start:<input name="newhour_start[]" type="text" id="newhour_start" > End: <input name="newhour_end[]" type="text" id="newhour_end" ><input name="newhour_day[]" type="hidden" id="newhour_day" value="Monday" >

Start:<input name="newhour_start[]" type="text" id="newhour_start" > End: <input name="newhour_end[]" type="text" id="newhour_end" ><input name="newhour_day[]" type="hidden" id="newhour_day" value="Monday" >

Body:
You can insert multiple rows at once:

mysql_query("INSERT INTO hour
            (hour_start,hour_end,hour_day) VALUES
            (1, 2, 3),
            (4, 5, 6)
);


问:
When removing images the last image removed stays (no re-render)
I have an array of objects, each has a URL that is being loaded in this file:

```<code><template>
  <div>
    <img :key="id" :src="img" alt="" class="image box" @click="cardClicked" />
  </div>
</template>

<script lang="ts">
export default {
  props: ["id", "value", "type", "owner", "imgURL"],
  data() {
    return {
      img: require(`./../assets/${this.imgURL}.png`)
    };
  },
  methods: {
    cardClicked() {
      this.$store.commit("addCardToPlayer", {
        id: this.id,
        type: this.type,
        value: this.value,
        owner: this.owner
      });
    }
  }
};
</script>
</code>```

In the Store mutation I preform filtering and while filtering I add the card to a another player, like so:

```<code> addCardToPlayer(state, clickedCard) {
      const owner = clickedCard.owner;
      const type = clickedCard.type;
      const currPlayer = state.currentPlayerName;
      if (clickedCard.owner === "deck") {
        state.cardOwners[owner].cards[type] = state.cardOwners[owner].cards[
          type
        ].filter(card => {
          if (card.id === clickedCard.id) {
            state.cardOwners[currPlayer].cards[type].push(card);
            return false;
          } else return true;
        });
      }
    },
</code>```

When clicking a card to remove, I see the card being added to the player and displayed correctly, and the number of cards displayed after removal is correct.

But

The card that was removed still shows.

What have I tried:

Forcing to re-render using:

cardClicked() {
  this.$store.commit("addCardToPlayer", {
    id: this.id,
    type: this.type,
    value: this.value,
    owner: this.owner
  });
  this.$forceUpdate();
}

Making different components have key, and trying to change the key to cause a re-render:

data() {
    return {
      componentKey: 0,
    };
  },
  methods: {
    forceRerender() {
      this.componentKey += 1;

    }
  }

Tried changing how I change the array by creating a new state.

EDIT: Tried using computed. i get an error:

TypeError: Cannot read property 'imgURL' of undefined

```<code>computed: {
getImg: () => {
  return require(`./../assets/${this.imgURL}.png`);
}}
</code>```

EDIT: I wrote the computed function as arrow function, which doesn't preserve context.

SOLVED, by using

```<code>     computed: {
    getImg() {
      return require(`./../assets/${this.imgURL}.png`);
    }}
</code>```

How can I make the images update after click (remove).

Thanks.

答:
SOLVED, by using</p>

```<code> computed: {
getImg() {
  return require(`./../assets/${this.imgURL}.png`);
}}
</code>```

Body:
I have an array of objects, each has a URL that is being loaded in this file:

<template>

</template>

In the Store mutation I preform filtering and while filtering I add the card to a another player, like so:

 addCardToPlayer(state, clickedCard) {
      const owner = clickedCard.owner;
      const type = clickedCard.type;
      const currPlayer = state.currentPlayerName;
      if (clickedCard.owner === "deck") {
        state.cardOwners[owner].cards[type] = state.cardOwners[owner].cards[
          type
        ].filter(card => {
          if (card.id === clickedCard.id) {
            state.cardOwners[currPlayer].cards[type].push(card);
            return false;
          } else return true;
        });
      }
    },

When clicking a card to remove, I see the card being added to the player and displayed correctly, and the number of cards displayed after removal is correct.

But

The card that was removed still shows.

What have I tried:

Forcing to re-render using:

cardClicked() {
  this.$store.commit("addCardToPlayer", {
    id: this.id,
    type: this.type,
    value: this.value,
    owner: this.owner
  });
  this.$forceUpdate();
}

Making different components have key, and trying to change the key to cause a re-render:

data() {
    return {
      componentKey: 0,
    };
  },
  methods: {
    forceRerender() {
      this.componentKey += 1;

    }
  }

Tried changing how I change the array by creating a new state.

EDIT: Tried using computed. i get an error:

TypeError: Cannot read property 'imgURL' of undefined

computed: {
getImg: () => {
  return require(`./../assets/${this.imgURL}.png`);
}}

EDIT: I wrote the computed function as arrow function, which doesn't preserve context.

SOLVED, by using

     computed: {
    getImg() {
      return require(`./../assets/${this.imgURL}.png`);
    }}

How can I make the images update after click (remove).

Thanks.


问:
Dependent options caching in cmake via ccmake
Im working on a project with multiple OPTION commands in the cmake hierarchy.

If one option is enabled (OPTION_A=ON), than other options (OPTION_B) are added via newly included subdirectory into the cmake cache:

CMakeLists.txt:

```<code>OPTION(OPTION_A "Do such and such" OFF)
IF(OPTION_A)
    add_subdirectory(subdir)
ENDIF(OPTION_A)
</code>```

subdir/CMakeLists.txt:

```<code>OPTION(OPTION_B "Do this and that" OFF)
IF(OPTION_B)
    add_subdirectory(subsubdir)
ENDIF(OPTION_B)
</code>```

subdir/subsubdir/CMakeLists.txt:

```<code>OPTION(OPTION_C "Do foo then bar" OFF)
IF(OPTION_C)
    <...>
ENDIF(OPTION_C)
</code>```

This is nice, since when working with ccmake for example, I'm not disturbed with OPTION_B/C unless OPTION_A/B was configured ON, thus generating OPTION_B/C in the CMakeCache.txt

The problem is in the reverse direction:

when disabling OPTION_A, OPTION_B & OPTION_C cached variables still show up in ccmake.

I've come up with three solutions:

Unset every option I know isn't going to be used from the external file.

This solution breaks quickly for "deep" projects since ELSE(OPTION_A) now needs to unset(... CACHE) both OPTION_B, OPTION_C, and all other cached variables of their respective subdirectories.

Clean the CMakeCache and start configuring from scratch.

This solution breaks for "wide" projects, since to clean one option field I'm forced to clear his co-directories cache variables.

Modify cmake to have an "opaque" cache, for variables saved but not accessed in generation stage.

Modify ccmake to grey-out/hide the "opaque" cache, presenting only accessed cached variables.

Shouldn't disturb automatic cmake usage, and since ccmake is a GUI I think this is not a breaking change to it either.

Is there a one-for-all solution for both "wide" and "deep" cmake hierarchies that will not require modifying cmake? Is this a common issue worth the entailed effort?

答:
What Tsyvarev mentioned in a comment, you can make options that are dependent on other options using CMakeDependentOption.

Here OPTION_B becomes available and defaults to ON only if OPTION_A is ON, otherwise it'll be set to OFF. You can set its default to OFF too but I made it ON here to make it clear which is which:

```<code>OPTION(OPTION_A "Do such and such" OFF)

CMAKE_DEPENDENT_OPTION(OPTION_B "Do this and that" ON
                       "OPTION_A" OFF)
</code>```

Body:
Im working on a project with multiple OPTION commands in the cmake hierarchy.

If one option is enabled (OPTION_A=ON), than other options (OPTION_B) are added via newly included subdirectory into the cmake cache:

CMakeLists.txt:

OPTION(OPTION_A "Do such and such" OFF)
IF(OPTION_A)
    add_subdirectory(subdir)
ENDIF(OPTION_A)

subdir/CMakeLists.txt:

OPTION(OPTION_B "Do this and that" OFF)
IF(OPTION_B)
    add_subdirectory(subsubdir)
ENDIF(OPTION_B)

subdir/subsubdir/CMakeLists.txt:

OPTION(OPTION_C "Do foo then bar" OFF)
IF(OPTION_C)
    <...>
ENDIF(OPTION_C)

This is nice, since when working with ccmake for example, I'm not disturbed with OPTION_B/C unless OPTION_A/B was configured ON, thus generating OPTION_B/C in the CMakeCache.txt

The problem is in the reverse direction:

when disabling OPTION_A, OPTION_B & OPTION_C cached variables still show up in ccmake.

I've come up with three solutions:

Unset every option I know isn't going to be used from the external file.

This solution breaks quickly for "deep" projects since ELSE(OPTION_A) now needs to unset(... CACHE) both OPTION_B, OPTION_C, and all other cached variables of their respective subdirectories.

Clean the CMakeCache and start configuring from scratch.

This solution breaks for "wide" projects, since to clean one option field I'm forced to clear his co-directories cache variables.

Modify cmake to have an "opaque" cache, for variables saved but not accessed in generation stage.

Modify ccmake to grey-out/hide the "opaque" cache, presenting only accessed cached variables.

Shouldn't disturb automatic cmake usage, and since ccmake is a GUI I think this is not a breaking change to it either.

Is there a one-for-all solution for both "wide" and "deep" cmake hierarchies that will not require modifying cmake? Is this a common issue worth the entailed effort?

Body:
What Tsyvarev mentioned in a comment, you can make options that are dependent on other options using CMakeDependentOption.

Here OPTION_B becomes available and defaults to ON only if OPTION_A is ON, otherwise it'll be set to OFF. You can set its default to OFF too but I made it ON here to make it clear which is which:

OPTION(OPTION_A "Do such and such" OFF)

CMAKE_DEPENDENT_OPTION(OPTION_B "Do this and that" ON
                       "OPTION_A" OFF)


问:
How can I check if a Flutter application is running in debug?
I'm looking for a way to execute code in Flutter when the app is in Debug mode. Is that possible in Flutter? I can't seem to find it anywhere in the documentation.

Something like this

```<code>If(app.inDebugMode) {
   print("Print only in debug mode");
}
</code>```

How can I check if the Flutter application is running in debug or release mode?

答:
Not to be picky, but the foundation package includes a kDebugMode constant.

So:

```<code>import 'package:flutter/foundation.dart' as Foundation;

if(Foundation.kDebugMode) {
   print("App in debug mode");
}
</code>```

Body:
I'm looking for a way to execute code in Flutter when the app is in Debug mode. Is that possible in Flutter? I can't seem to find it anywhere in the documentation.

Something like this

If(app.inDebugMode) {
   print("Print only in debug mode");
}

How can I check if the Flutter application is running in debug or release mode?

Body:
Not to be picky, but the foundation package includes a kDebugMode constant.

So:

import 'package:flutter/foundation.dart' as Foundation;

if(Foundation.kDebugMode) {
   print("App in debug mode");
}


问:
Call dynamic data in Wordpress
I am trying to populate a value depending on the user role.

There are two ways to do this:

Add 600 lines in functions.PHP with then statements, (if user role=1 echo 1..... if user role=600 echo 600)

OR

Add a new meta value in the SQL database for the user upon registration and request this value from the data base.

I think the second option is more logical (unless the first option will bring a faster loading speed?)

Can anyone advice how can I request a parameter from a database in-line with the current user.

答:
Depending on the usage would depend on how you need to hook into that data but if its just in the functions file something like this would work. </p>

<pre class="lang-php prettyprint-override"><code>$user = wp_get_current_user(); // Gives you the current user
$roles = ( array ) $user->roles; // Gives you an array of their roles
</code>```

<p>At this could you could use in_array() to check for a specific user role and then display the meta data.</p>

<pre class="lang-php prettyprint-override"><code>if( in_array( 'role', $roles ) ) {
    echo get_user_meta( $user->ID, 'portal_number', true );
}

</code>```

Title: Call dynamic data in Wordpress

Body:
Depending on the usage would depend on how you need to hook into that data but if its just in the functions file something like this would work.

$user = wp_get_current_user(); // Gives you the current user
$roles = ( array ) $user->roles; // Gives you an array of their roles

At this could you could use in_array() to check for a specific user role and then display the meta data.

if( in_array( 'role', $roles ) ) {
    echo get_user_meta( $user->ID, 'portal_number', true );
}


问:
cannot navigate on the history of iframe content
I am using iframe to load second web site in my program.

I created for this purpose div with iframe inside :

```<code><div id='ktmv-help'>
    <iframe id="contextHelp" allowTransparency="true" scrolling="no"
            frameborder="0">
    </iframe>
</div>
</code>```

I am using $('#contextHelp')[0].contentWindow.location.replace(url); command to change programmatically content of iframe when I navigate between pages of my program.

The problem is I cannot go back on previos page of my iframe after changing content by $('#contextHelp')[0].contentWindow.location.replace(url); command.

I tried history.back(), window.history.back(), history.go(-1) commands but all of them don't work. I see same iframe page.

答:
From the Docs:

Cross-origin script API access

JavaScript APIs like iframe.contentWindow, window.parent, window.open, and window.opener allow documents to directly reference each other. When two documents do not have the same origin, these references provide very limited access to Window and Location objects, as described in the next two sections.

Specification: HTML Living Standard § Cross-origin objects.

For more information, see

MDN Web Security Reference - Same Origin Policy - Cross-origin script API Access

Body:
I am using iframe to load second web site in my program.

I created for this purpose div with iframe inside :

I am using $('#contextHelp')[0].contentWindow.location.replace(url); command to change programmatically content of iframe when I navigate between pages of my program.

The problem is I cannot go back on previos page of my iframe after changing content by $('#contextHelp')[0].contentWindow.location.replace(url); command.

I tried history.back(), window.history.back(), history.go(-1) commands but all of them don't work. I see same iframe page.


问:
SQL Filter based on Case
I have a table as such:

```<code>email | event

e1     a
e1     c
e2     a
e3     b
e4     a
e4     b
e5     c
e6     d

</code>```

I'm trying to create a query that gets only those who have event a exclusively

Desired output:

```<code>email  |  attended

e2       0
</code>```

Here's my SQL:

```<code>SELECT
    tm.email,
    MAX(
    CASE
    WHEN tm.event = 'b' or tm.event = 'c' THEN 1
    ELSE 0
    END)
    as attended,
FROM
    table.events as tm
WHERE
    tm.event IN ('a', 'b', 'c', 'd')
    AND attended = 0
GROUP BY
    tm.email, attended

</code>```

I can't seem to figure out the correct way to go about this.

答:
You could use aggregation:

```<code>select email
from events
group by email
having max(case when event = 'a' then 0 else 1 end) = 0
</code>```

Or, if you want the entire record(s), you can filter with a not exists condition:

```<code>select e.*
from events e
where
    e.event = 'a'
    and not exists (select 1 from events e1 where e1.email = e.email and e1.event <> 'a')
</code>```

Title: SQL Filter based on Case

Body:
I have a table as such:

email | event

e1     a
e1     c
e2     a
e3     b
e4     a
e4     b
e5     c
e6     d

I'm trying to create a query that gets only those who have event a exclusively

Desired output:

email  |  attended

e2       0

Here's my SQL:

SELECT
    tm.email,
    MAX(
    CASE
    WHEN tm.event = 'b' or tm.event = 'c' THEN 1
    ELSE 0
    END)
    as attended,
FROM
    table.events as tm
WHERE
    tm.event IN ('a', 'b', 'c', 'd')
    AND attended = 0
GROUP BY
    tm.email, attended

I can't seem to figure out the correct way to go about this.

Body:
You could use aggregation:

select email
from events
group by email
having max(case when event = 'a' then 0 else 1 end) = 0

Or, if you want the entire record(s), you can filter with a not exists condition:

select e.*
from events e
where
    e.event = 'a'
    and not exists (select 1 from events e1 where e1.email = e.email and e1.event <> 'a')


问:
Javascript Recursive Backtracking Sudoku Solver
I recently wrote this same code in Golang with some help from here.

If you are familiar with go you can see the working code here.

Go Playground

Here is what I am trying to accomplish in python.
Computerphile Video

I am now trying to port this to javascript.

I initialize the gameState.

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

This is the grid taken from the sudoku Wikipedia page.

Sudoku Wiki

I wrote the following helper functions to get the row, column and block units of anywhere on the grid. I've tested them all and they all seem to work fine.

```<code>function isUnitUnique(unit) {
    for (let value = 1; value <= 9; value++) {
        let tally = 0;
        for (let index = 0; index < 9; index++) {
            if (unit[index] == value) {
                tally++;
            }
        }
        if (tally > 1) {
            return false;
        }
    }
    return true;
}
function getColumnUnit(board, column) {
    let unit = [];
    for (let row = 0; row < 9; row++) {
        unit.push(board[row][column]);
    }
    return unit;
}
function getBlockUnit(board, x, y) {
    let unit = []
    if (x >= 0 && x <= 2) { j = 1; }
    else if (x >= 3 && x <= 5) { j = 4; }
    else if (x >= 6 && x <= 8) { j = 7; }
    if (y >= 0 && y <= 2) { i = 1; }
    else if (y >= 3 && y <= 5) { i = 4; }
    else if (y >= 6 && y <= 8) { i = 7; }
    unit.push(board[i - 1][j - 1]);
    unit.push(board[i - 1][j]);
    unit.push(board[i - 1][j + 1]);
    unit.push(board[i][j - 1]);
    unit.push(board[i][j]);
    unit.push(board[i][j + 1]);
    unit.push(board[i + 1][j - 1]);
    unit.push(board[i + 1][j]);
    unit.push(board[i + 1][j + 1]);
    return unit;
}
</code>```

I then use the helper functions with the following code to try and solve the puzzle. This is a recursive backtracking algorithm.

```<code>function solve() {
    for (let row = 0; row < 9; row++) {
        for (let column = 0; column < 9; column++) {
            if (gameState[row][column] == 0) {
                for (let value = 1; value <= 9; value++) {
                    if (possible(row, column, value)) {
                        gameState[row][column] = value;
                        solve();
                        gameState[row][column] = 0;
                    }
                }
                return;
            }
        }
    }
    console.log(gameState);
    return;
}
function possible(y, x, n) {
    let boardCopy = JSON.parse(JSON.stringify(gameState));
    boardCopy[y][x] = n;
    return isUnitUnique(boardCopy[y]) && isUnitUnique(getColumnUnit(boardCopy, x)) && isUnitUnique(getBlockUnit(boardCopy, x, y))
}
</code>```

This console logs the initial game state unchanged. From doing some debugging I can see that the algorithm is going through the grid however it doesn't seem to keep the changes that I make to the grid.

Thanks in advance.

As suggested here is a runnable version of my code. It works when I run it in the snippet. When using chrome it doesn't.

var gameState = [
    [5, 3, 0, 0, 7, 0, 0, 0, 0],
    [6, 0, 0, 1, 9, 5, 0, 0, 0],
    [0, 9, 8, 0, 0, 0, 0, 6, 0],
    [8, 0, 0, 0, 6, 0, 0, 0, 3],
    [4, 0, 0, 8, 0, 3, 0, 0, 1],
    [7, 0, 0, 0, 2, 0, 0, 0, 6],
    [0, 6, 0, 0, 0, 0, 2, 8, 0],
    [0, 0, 0, 4, 1, 9, 0, 0, 5],
    [0, 0, 0, 0, 8, 0, 0, 7, 9]
]
function solve() {
    for (let row = 0; row < 9; row++) {
        for (let column = 0; column < 9; column++) {
            if (gameState[row][column] == 0) {
                for (let value = 1; value <= 9; value++) {
                    if (possible(row, column, value)) {
                        gameState[row][column] = value;
                        solve();
                        gameState[row][column] = 0;
                    }
                }
                return;
            }
        }
    }
    console.log(gameState);
    return;
}
function possible(y, x, n) {
    let boardCopy = JSON.parse(JSON.stringify(gameState));
    boardCopy[y][x] = n;
    return isUnitUnique(boardCopy[y]) && isUnitUnique(getColumnUnit(boardCopy, x)) && isUnitUnique(getBlockUnit(boardCopy, x, y))
}
function isUnitUnique(unit) {
    for (let value = 1; value <= 9; value++) {
        let tally = 0;
        for (let index = 0; index < 9; index++) {
            if (unit[index] == value) {
                tally++;
            }
        }
        if (tally > 1) {
            return false;
        }
    }
    return true;
}
function getColumnUnit(board, column) {
    let unit = [];
    for (let row = 0; row < 9; row++) {
        unit.push(board[row][column]);
    }
    return unit;
}
function getBlockUnit(board, x, y) {
    let unit = []
    if (x >= 0 && x <= 2) { j = 1; }
    else if (x >= 3 && x <= 5) { j = 4; }
    else if (x >= 6 && x <= 8) { j = 7; }
    if (y >= 0 && y <= 2) { i = 1; }
    else if (y >= 3 && y <= 5) { i = 4; }
    else if (y >= 6 && y <= 8) { i = 7; }
    unit.push(board[i - 1][j - 1]);
    unit.push(board[i - 1][j]);
    unit.push(board[i - 1][j + 1]);
    unit.push(board[i][j - 1]);
    unit.push(board[i][j]);
    unit.push(board[i][j + 1]);
    unit.push(board[i + 1][j - 1]);
    unit.push(board[i + 1][j]);
    unit.push(board[i + 1][j + 1]);
    return unit;
}
solve()```

答:
Thanks to @HereticMonkey for suggesting I use stack snippets to share my code. In doing so I realized that it worked in this environment, and that it had to do with running the code in the browser that was causing the issue (Chrome). Also thanks to @bcr666 who also mentioned that potentially the algorithm was zeroing itself out on the way back.

The code listed in the question was all correct. I added one check to prevent the function from continuing to execute after it reached its exit condition.

```<code>let solved = false
function solve() {
    for (let row = 0; row < 9; row++) {
        for (let column = 0; column < 9; column++) {
            if (gameState[row][column] == 0) {
                for (let value = 1; value <= 9; value++) {
                    if (possible(row, column, value)) {
                        gameState[row][column] = value;
                        solve();
                        if (!solved) {
                            gameState[row][column] = 0;
                        }
                    }
                }
                return;
            }
        }
    }
    solved = true;
    console.log(gameState);
    return;
}
</code>```

Checking if the game has been solved before backtracking fixed this issue. Before it would log the results it was attempting to find more solutions.

Body:
I recently wrote this same code in Golang with some help from here.

If you are familiar with go you can see the working code here.

Go Playground

Here is what I am trying to accomplish in python.
Computerphile Video

I am now trying to port this to javascript.

I initialize the gameState.

var gameState = [
    [5, 3, 0, 0, 7, 0, 0, 0, 0],
    [6, 0, 0, 1, 9, 5, 0, 0, 0],
    [0, 9, 8, 0, 0, 0, 0, 6, 0],
    [8, 0, 0, 0, 6, 0, 0, 0, 3],
    [4, 0, 0, 8, 0, 3, 0, 0, 1],
    [7, 0, 0, 0, 2, 0, 0, 0, 6],
    [0, 6, 0, 0, 0, 0, 2, 8, 0],
    [0, 0, 0, 4, 1, 9, 0, 0, 5],
    [0, 0, 0, 0, 8, 0, 0, 7, 9]
]

This is the grid taken from the sudoku Wikipedia page.

Sudoku Wiki

I wrote the following helper functions to get the row, column and block units of anywhere on the grid. I've tested them all and they all seem to work fine.

function isUnitUnique(unit) {
    for (let value = 1; value <= 9; value++) {
        let tally = 0;
        for (let index = 0; index < 9; index++) {
            if (unit[index] == value) {
                tally++;
            }
        }
        if (tally > 1) {
            return false;
        }
    }
    return true;
}
function getColumnUnit(board, column) {
    let unit = [];
    for (let row = 0; row < 9; row++) {
        unit.push(board[row][column]);
    }
    return unit;
}
function getBlockUnit(board, x, y) {
    let unit = []
    if (x >= 0 && x <= 2) { j = 1; }
    else if (x >= 3 && x <= 5) { j = 4; }
    else if (x >= 6 && x <= 8) { j = 7; }
    if (y >= 0 && y <= 2) { i = 1; }
    else if (y >= 3 && y <= 5) { i = 4; }
    else if (y >= 6 && y <= 8) { i = 7; }
    unit.push(board[i - 1][j - 1]);
    unit.push(board[i - 1][j]);
    unit.push(board[i - 1][j + 1]);
    unit.push(board[i][j - 1]);
    unit.push(board[i][j]);
    unit.push(board[i][j + 1]);
    unit.push(board[i + 1][j - 1]);
    unit.push(board[i + 1][j]);
    unit.push(board[i + 1][j + 1]);
    return unit;
}

I then use the helper functions with the following code to try and solve the puzzle. This is a recursive backtracking algorithm.

function solve() {
    for (let row = 0; row < 9; row++) {
        for (let column = 0; column < 9; column++) {
            if (gameState[row][column] == 0) {
                for (let value = 1; value <= 9; value++) {
                    if (possible(row, column, value)) {
                        gameState[row][column] = value;
                        solve();
                        gameState[row][column] = 0;
                    }
                }
                return;
            }
        }
    }
    console.log(gameState);
    return;
}
function possible(y, x, n) {
    let boardCopy = JSON.parse(JSON.stringify(gameState));
    boardCopy[y][x] = n;
    return isUnitUnique(boardCopy[y]) && isUnitUnique(getColumnUnit(boardCopy, x)) && isUnitUnique(getBlockUnit(boardCopy, x, y))
}

This console logs the initial game state unchanged. From doing some debugging I can see that the algorithm is going through the grid however it doesn't seem to keep the changes that I make to the grid.

Thanks in advance.

As suggested here is a runnable version of my code. It works when I run it in the snippet. When using chrome it doesn't.

var gameState = [
    [5, 3, 0, 0, 7, 0, 0, 0, 0],
    [6, 0, 0, 1, 9, 5, 0, 0, 0],
    [0, 9, 8, 0, 0, 0, 0, 6, 0],
    [8, 0, 0, 0, 6, 0, 0, 0, 3],
    [4, 0, 0, 8, 0, 3, 0, 0, 1],
    [7, 0, 0, 0, 2, 0, 0, 0, 6],
    [0, 6, 0, 0, 0, 0, 2, 8, 0],
    [0, 0, 0, 4, 1, 9, 0, 0, 5],
    [0, 0, 0, 0, 8, 0, 0, 7, 9]
]
function solve() {
    for (let row = 0; row < 9; row++) {
        for (let column = 0; column < 9; column++) {
            if (gameState[row][column] == 0) {
                for (let value = 1; value <= 9; value++) {
                    if (possible(row, column, value)) {
                        gameState[row][column] = value;
                        solve();
                        gameState[row][column] = 0;
                    }
                }
                return;
            }
        }
    }
    console.log(gameState);
    return;
}
function possible(y, x, n) {
    let boardCopy = JSON.parse(JSON.stringify(gameState));
    boardCopy[y][x] = n;
    return isUnitUnique(boardCopy[y]) && isUnitUnique(getColumnUnit(boardCopy, x)) && isUnitUnique(getBlockUnit(boardCopy, x, y))
}
function isUnitUnique(unit) {
    for (let value = 1; value <= 9; value++) {
        let tally = 0;
        for (let index = 0; index < 9; index++) {
            if (unit[index] == value) {
                tally++;
            }
        }
        if (tally > 1) {
            return false;
        }
    }
    return true;
}
function getColumnUnit(board, column) {
    let unit = [];
    for (let row = 0; row < 9; row++) {
        unit.push(board[row][column]);
    }
    return unit;
}
function getBlockUnit(board, x, y) {
    let unit = []
    if (x >= 0 && x <= 2) { j = 1; }
    else if (x >= 3 && x <= 5) { j = 4; }
    else if (x >= 6 && x <= 8) { j = 7; }
    if (y >= 0 && y <= 2) { i = 1; }
    else if (y >= 3 && y <= 5) { i = 4; }
    else if (y >= 6 && y <= 8) { i = 7; }
    unit.push(board[i - 1][j - 1]);
    unit.push(board[i - 1][j]);
    unit.push(board[i - 1][j + 1]);
    unit.push(board[i][j - 1]);
    unit.push(board[i][j]);
    unit.push(board[i][j + 1]);
    unit.push(board[i + 1][j - 1]);
    unit.push(board[i + 1][j]);
    unit.push(board[i + 1][j + 1]);
    return unit;
}
solve()

Body:
Thanks to @HereticMonkey for suggesting I use stack snippets to share my code. In doing so I realized that it worked in this environment, and that it had to do with running the code in the browser that was causing the issue (Chrome). Also thanks to @bcr666 who also mentioned that potentially the algorithm was zeroing itself out on the way back.

The code listed in the question was all correct. I added one check to prevent the function from continuing to execute after it reached its exit condition.

let solved = false
function solve() {
    for (let row = 0; row < 9; row++) {
        for (let column = 0; column < 9; column++) {
            if (gameState[row][column] == 0) {
                for (let value = 1; value <= 9; value++) {
                    if (possible(row, column, value)) {
                        gameState[row][column] = value;
                        solve();
                        if (!solved) {
                            gameState[row][column] = 0;
                        }
                    }
                }
                return;
            }
        }
    }
    solved = true;
    console.log(gameState);
    return;
}

Checking if the game has been solved before backtracking fixed this issue. Before it would log the results it was attempting to find more solutions.


问:
MonoTouch Activation/Reactivation
I'm having the most frustrating time with MonoTouch/Mono/Monodevelop. After using the app for nearly six months I, foolishly, decided to get a new computer. I used Apple's Migration Assistant to move everything over, and it went perfectly.

Except I can no longer compile due to a need for reactivation of my license. Well, the folks at MonoTouch got rid of the activation app. I tried uninstalling then reinstalling in hopes that the activation screen would return -- no dice. Can someone point me in the right direction?

1) I need to find the activation application that Mono's own installation instructions allude to here: http://monotouch.net/Releases/MonoTouch_4/MonoTouch_4.0.0 (I know activation is apparently bundled with the app now -- but how would anyone ever reactivate?)

2) How does the reactivation process work?

I'm quite frustrated now considering I've paid 400 dollars for something that I'm not allowed to use if I ever want to upgrade my computer.

答:
This is more a question to Attachmate who stopped supporting the Monotouch. You are not alone there, best answer is, go and ask for a refund from Novell/Attachmate as they do not support you anymore.

You need to wait until the new venture xamarin.com is up and release they successor to the Monotouch solution from Novell.

Title: MonoTouch Activation/Reactivation


问:
Create one nested object with two objects from dictionary
I'm not sure if the title of my question is the right description to the issue I'm facing.

I'm reading the following table of data from a spreadsheet and passing it as a dataframe:

```<code>Name    Description Value
foo     foobar      5
baz     foobaz      4
bar     foofoo      8
</code>```

I need to transform this table of data to json following a specific schema.

I'm trying to get the following output:

```<code>{'global': {'Name': 'bar', 'Description': 'foofoo', 'spec': {'Value': '8'}}
</code>```

So far I'm able to get the global and spec objects but I'm not sure how I should combine them to get the expected output above.

I wrote this:

```<code>for index, row in df.iterrows():
    if row['Description'] == 'foofoo':
            global = row.to_dict()
            spec = row.to_dict()

            del(global['Value'])
            del(spec['Name'])
            del(spec['Description'])
            print("global:", global)
            print("spec:", spec)
</code>```

with the following output:

```<code>global: {'Name': 'bar', 'Description': 'foofoo'}
spec: {'Value': '8'}
</code>```

How can I combine these two objects to get to the desired output?

答:
This should give you that output:</p>

```<code>global['spec'] = spec
combined = {'global': global}
</code>```

Body:
I'm not sure if the title of my question is the right description to the issue I'm facing.

I'm reading the following table of data from a spreadsheet and passing it as a dataframe:

Name    Description Value
foo     foobar      5
baz     foobaz      4
bar     foofoo      8

I need to transform this table of data to json following a specific schema.

I'm trying to get the following output:

{'global': {'Name': 'bar', 'Description': 'foofoo', 'spec': {'Value': '8'}}

So far I'm able to get the global and spec objects but I'm not sure how I should combine them to get the expected output above.

I wrote this:

for index, row in df.iterrows():
    if row['Description'] == 'foofoo':
            global = row.to_dict()
            spec = row.to_dict()

            del(global['Value'])
            del(spec['Name'])
            del(spec['Description'])
            print("global:", global)
            print("spec:", spec)

with the following output:

global: {'Name': 'bar', 'Description': 'foofoo'}
spec: {'Value': '8'}

How can I combine these two objects to get to the desired output?

Body:
This should give you that output:

global['spec'] = spec
combined = {'global': global}