问:
phpMyAdmin can't connect to remote sever on Windows 7 from Linux client
I cannot connect to mysql server on Windows 7 from my phpMyAdmin on Linux machine.

I've configured phpMyAdmin by modifying common.inc.php.
I've added at the bottom of common.inc.php the following lines:

```<code>$i=2;
$cfg['Servers'][$i]['host'] = 'HostName:port'; //provide hostname and port if other than default
$cfg['Servers'][$i]['user'] = 'userName';      //user name for your remote server
$cfg['Servers'][$i]['password'] = 'Password';  //password
$cfg['Servers'][$i]['auth_type'] = 'config';   // keep it as config
$i++;
</code>```

I see a drop down menu with remote server listed, but when I selected a remote server phphMyAdmin returns to localhost and it doesn't connect to remote without error messages.

Using mysql command to connect to the remote database server and using the same user/password, I can successfully connect to the database server.

The versions are:

```<code>PHP 5.4.16 Development Server
phpMyAdmin 4.4.15.10
MySQL 5.6.32 - MySQL Community Server (GPL)
</code>```

The request is initiated from the post
Error from phmpMyAdmin when is configured in order to access remote server with local phpMyAdmin client
where I have entered a request regarding the configuration of phpMyAdmin

答:
You can access the remote server by adding a block of code in your phpmyadmin config file...

```<code>$i++;
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['host'] = '';
$cfg['Servers'][$i]['user'] = '';
$cfg['Servers'][$i]['password'] = '';
</code>```

try this

Body:
I cannot connect to mysql server on Windows 7 from my phpMyAdmin on Linux machine.

I've configured phpMyAdmin by modifying common.inc.php.
I've added at the bottom of common.inc.php the following lines:

$i=2;
$cfg['Servers'][$i]['host'] = 'HostName:port'; //provide hostname and port if other than default
$cfg['Servers'][$i]['user'] = 'userName';      //user name for your remote server
$cfg['Servers'][$i]['password'] = 'Password';  //password
$cfg['Servers'][$i]['auth_type'] = 'config';   // keep it as config
$i++;

I see a drop down menu with remote server listed, but when I selected a remote server phphMyAdmin returns to localhost and it doesn't connect to remote without error messages.

Using mysql command to connect to the remote database server and using the same user/password, I can successfully connect to the database server.

The versions are:

PHP 5.4.16 Development Server
phpMyAdmin 4.4.15.10
MySQL 5.6.32 - MySQL Community Server (GPL)

The request is initiated from the post
Error from phmpMyAdmin when is configured in order to access remote server with local phpMyAdmin client
where I have entered a request regarding the configuration of phpMyAdmin

Body:
You can access the remote server by adding a block of code in your phpmyadmin config file...

$i++;
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['host'] = '';
$cfg['Servers'][$i]['user'] = '';
$cfg['Servers'][$i]['password'] = '';

try this


来源: stackexchange

问:
C# why cant i exit this while loop?
I'm tryig to make a program that can auto press space.
but i can only enable it. after the program crashes.

so i cant turn it off. pleace help

here is my code:

```<code>using System.Windows.Forms;

namespace Auto_Abillty
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    public bool startFlag = false;
    public bool stopFlag = false;
    private void Preiststop_Click(object sender, EventArgs e)
    {
        stopFlag = true;
    }
    private void Preist_Click(object sender, EventArgs e)
    {
        startFlag = true;
        while (startFlag)
        {
            SendKeys.Send(" ");
            Thread.Sleep(5000);
            if (stopFlag)
                startFlag = false;
        }
    }

}
}
</code>```

答:
You must abort the thread as well.</p>

```<code>public bool x = false;
public bool j = false;
private void Preiststop_Click(object sender, EventArgs e)
{
    j = true;
}
private void Preist_Click(object sender, EventArgs e)
{
    x = true;

    Thread newThread = new Thread(delegate ()
    {
        DoPriestWork();
    });

    newThread.Start();

    //loop to wait for the response from DoPriestWork thread
    while (x)
    {
        Thread.Sleep(5000);
        if (j)
            x = false;
    }

    newThread.Abort();
}
public void DoPriestWork()
{
    //x = true;
    //while (x == true)
    //{
    SendKeys.Send(" ");
    //Thread.Sleep(5000);
    //    if (j == true)
    //        x = false;
    //}
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: C# why cant i exit this while loop?

Body:
I'm tryig to make a program that can auto press space.
but i can only enable it. after the program crashes.

so i cant turn it off. pleace help

here is my code:

using System.Windows.Forms;

namespace Auto_Abillty
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

    }

    public bool startFlag = false;
    public bool stopFlag = false;
    private void Preiststop_Click(object sender, EventArgs e)
    {
        stopFlag = true;
    }
    private void Preist_Click(object sender, EventArgs e)
    {
        startFlag = true;
        while (startFlag)
        {
            SendKeys.Send(" ");
            Thread.Sleep(5000);
            if (stopFlag)
                startFlag = false;
        }
    }

}
}

Body:
You must abort the thread as well.

public bool x = false;
public bool j = false;
private void Preiststop_Click(object sender, EventArgs e)
{
    j = true;
}
private void Preist_Click(object sender, EventArgs e)
{
    x = true;

    Thread newThread = new Thread(delegate ()
    {
        DoPriestWork();
    });

    newThread.Start();

    //loop to wait for the response from DoPriestWork thread
    while (x)
    {
        Thread.Sleep(5000);
        if (j)
            x = false;
    }

    newThread.Abort();
}
public void DoPriestWork()
{
    //x = true;
    //while (x == true)
    //{
    SendKeys.Send(" ");
    //Thread.Sleep(5000);
    //    if (j == true)
    //        x = false;
    //}
}


问:
Is it possible to let upstream servers handle SSL certificates behind an Nginx server?
I have a Nginx server handling http request and doing proxy pass to some node servers upstream, if the domain name match one of the enabled sites, all packets are redirected to one node server, only if the channel is SSL, otherwise 301 to the https version:

```<code>server {
    listen         80;
    server_name    something.com
    return 301     https://$host$request_uri;
}

server {
    listen 433;
    server_name something.com;

    ssl_certificate           /etc/nginx/cert.crt;
    ssl_certificate_key       /etc/nginx/cert.key;

    ssl on;
    ssl_session_cache  builtin:1000  shared:SSL:10m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;

    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass http://127.0.0.1:3000/;
      proxy_redirect off;
    }
 }
</code>```

All that works, but the certificates management, the SSL handshake and so are made by Nginx. I will like to have each node server upstream to manage their own SSL preferences so I don't depend on Nginx to do this. My node servers already support https requests but I don't understand if it is possible to tell Nginx:

Listen to 80, if something comes do a 301 to the https version of it.

Listen to 433, don't worry for SSL, just proxy pass everything to localhost:3000

And the node server listening to port 3000 handles SSL

答:
Listen to 433, don't worry for SSL, just proxy pass everything to localhost:3000

No, not with nginx, you will have to use port forwarding for that.

nginx would either have to use some SSL key and possibly proxy the traffic to some Node app using SSL, this will mean that both Node and nginx would have to manage their own SSL keys (nginx for the client-nginx connection and Node app for the nginx-nodeApp connection).

Or nginx could use HTTP without SSL to proxy the request to Node that uses SSL, and this will mean that the client-nginx connection would be insecure and only the nginx-NodeApp connection would be secure. Also it would mean that https://www.example.com/ would not work - though http://www.example.com:443/ would.

If you want Node to handle the SSL keys and not the reverse proxy (as it is usually done) then you would have to use port forwarding on the TCP/IP level to pass the traffic to the Node app, without using a reverse proxy (nginx) at all.

Usually a reverse proxy is used so that the apps wouldn't have to handle the SSL keys used for client connections (among other things). If you want the Node apps to use the SSL keys and not the reverse proxy then you should reconsider using a reverse proxy in the first place.

Body:
I have a Nginx server handling http request and doing proxy pass to some node servers upstream, if the domain name match one of the enabled sites, all packets are redirected to one node server, only if the channel is SSL, otherwise 301 to the https version:

server {
    listen         80;
    server_name    something.com
    return 301     https://$host$request_uri;
}

server {
    listen 433;
    server_name something.com;

    ssl_certificate           /etc/nginx/cert.crt;
    ssl_certificate_key       /etc/nginx/cert.key;

    ssl on;
    ssl_session_cache  builtin:1000  shared:SSL:10m;
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELLIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;

    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass http://127.0.0.1:3000/;
      proxy_redirect off;
    }
 }

All that works, but the certificates management, the SSL handshake and so are made by Nginx. I will like to have each node server upstream to manage their own SSL preferences so I don't depend on Nginx to do this. My node servers already support https requests but I don't understand if it is possible to tell Nginx:

Listen to 80, if something comes do a 301 to the https version of it.

Listen to 433, don't worry for SSL, just proxy pass everything to localhost:3000

And the node server listening to port 3000 handles SSL


问:
Django1.8 and Mongoclient settings.DATABASES is improperly configured.
i am making an application using django 1.8 and mongoengine
But when i am trying to configure Django setting.py file to use a Dummy Database , I receive the following error

```<code>(orahienv) somya@somya-Inspiron-15-3555:/var/www/html/admin_python$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
July 06, 2017 - 16:57:25
Django version 1.8, using settings 'admin_python.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Performing system checks...

System check identified no issues (0 silenced).
July 06, 2017 - 17:00:15
Django version 1.8, using settings 'admin_python.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
<WSGIRequest: GET '/auth/login/?next=/'>
Internal Server Error: /auth/login/
Traceback (most recent call last):
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 164, in get_response
    response = response.render()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/template/response.py", line 158, in render
    self.content = self.rendered_content
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/template/response.py", line 135, in rendered_content
    content = template.render(context, self._request)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/template/backends/django.py", line 74, in render
    return self.template.render(context)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/template/base.py", line 208, in render
    with context.bind_template(self):
  File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/template/context.py", line 235, in bind_template
    updates.update(processor(self.request))
  File "/var/www/html/admin_python/admin_app/context_processors.py", line 30, in init_menu
    if request.user.is_authenticated():
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/utils/functional.py", line 226, in inner
    self._setup()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/utils/functional.py", line 359, in _setup
    self._wrapped = self._setupfunc()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/contrib/auth/middleware.py", line 22, in <lambda>
    request.user = SimpleLazyObject(lambda: get_user(request))
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/contrib/auth/middleware.py", line 10, in get_user
    request._cached_user = auth.get_user(request)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 174, in get_user
    user = backend.get_user(user_id)
  File "/var/www/html/admin_python/admin_app/backend.py", line 29, in get_user
    return TblAdmin.objects.get(pk=user_id)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/query.py", line 328, in get
    num = len(clone)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/query.py", line 144, in __len__
    self._fetch_all()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/query.py", line 965, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/query.py", line 238, in iterator
    results = compiler.execute_sql()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 818, in execute_sql
    sql, params = self.as_sql()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 367, in as_sql
    extra_select, order_by, group_by = self.pre_sql_setup()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 48, in pre_sql_setup
    self.setup_query()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 39, in setup_query
    self.select, self.klass_info, self.annotation_col_map = self.get_select()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 216, in get_select
    ret.append((col, self.compile(col, select_format=True), alias))
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 346, in compile
    sql, params = node.as_sql(self, self.connection)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/expressions.py", line 611, in as_sql
    return "%s.%s" % (qn(self.alias), qn(self.target.column)), []
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 337, in quote_name_unless_alias
    r = self.connection.ops.quote_name(name)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/backends/dummy/base.py", line 21, in complain
    raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
[06/Jul/2017 17:00:21]"GET /auth/login/?next=/ HTTP/1.1" 500 206077
</code>```

I know people asked similar question before. But it's all about the engine value. does any one know how do I solve this error with the NAME value?

setting.py -

```<code>import os
import admin_app
from django.utils import timezone
import mongoengine
"""from mongoengine import connect
connect('pom')"""

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'uj8$6(ol=!w)b3-luqzb=#6(j19gkbrnp2asq6=xt%5*s2ylz('

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

SPATIALITE_LIBRARY_PATH = 'mod_spatialite'
# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'admin_app',
    'celery', #http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#using-the-django-orm-cache-as-a-result-backend
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'djangoflash.middleware.FlashMiddleware',
    #'django.middleware.cache.CacheMiddleware', #http://stackoverflow.com/a/658583/2546013
)

ROOT_URLCONF = 'admin_python.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'media')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'admin_app.context_processors.init_menu',
                'admin_app.context_processors.server_urls',
                'djangoflash.context_processors.flash',
            ],
        },
    },
]

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
MEDIA_URL = '/media/'
HOST_URL='http://127.0.0.1:8001/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
WSGI_APPLICATION = 'admin_python.wsgi.application'
STATIC_URL = '/static/'
SERVER_URL = 'http://localhost:8001/'
WEBAPP_URL = 'http://localhost/webapp_angular/'
USERAPI_URL = 'http://localhost:8000/'
HOST_URL_NEW='http://localhost:8001/media/'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
"""
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'admin_db',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
    }
}"""

"""DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.dummy',
    }
}
"""
"""
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.dummy',
        'NAME': 'pom',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
    }
}
from mongoengine import connect
connect('pom', username='root', password='root')"""
DATABASES = {
    'default': {
        'ENGINE': '',
    },
}

_MONGODB_USER = 'root'
_MONGODB_PASSWD = 'root'
_MONGODB_HOST = 'localhost'
_MONGODB_NAME = 'pom'
_MONGODB_DATABASE_HOST = \
    'mongodb://%s:%s@%s/%s' \
    % (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME)

mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_L10N = True

USE_TZ = False

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

REST_FRAMEWORK = {
    # other settings...

    'DEFAULT_AUTHENTICATION_CLASSES': [],
    'DEFAULT_PERMISSION_CLASSES': [],
}
LOGIN_URL = '/auth/login/'
LOGIN_REDIRECT_URL = '/'

AUTHENTICATION_BACKENDS = (
    'admin_app.backend.AuthBackend',
    'django.contrib.auth.backends.ModelBackend',

)

AUTH_USER_MODEL = 'admin_app.TblAdmin'

EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'AKIAJB6VACOVZANVTC5A'
EMAIL_HOST_PASSWORD = 'Atu9qbV+X5aiwIlQzVAOVjU/AxkxMDV3X0l0FLWweSn9'
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'support@doctorinsta.com'

#LOGGING SETTING
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format' : "[%(asctime)s] %(levelname)s [%(filename)s:%(funcName)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'applogfile': {
            'level':'DEBUG',
            'class':'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, 'drinsta.log'),
            'formatter': 'verbose'
            },

    },
    'loggers': {
        'django.request': {
            'level': 'ERROR',
            'propagate': True,
            'handlers': ['applogfile',],
        },
        'drinsta': {
            'handlers': ['applogfile',],
            'level': 'DEBUG',
        },
    }
}

#https://docs.djangoproject.com/en/1.8/topics/http/sessions/#configuring-the-session-engine
#https://github.com/dlrust/python-memcached-stats
#We can use the following command to see the keys:
#    python -m memcached_stats 127.0.0.1 11211
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
        'TIMEOUT' : 300 #Default
    }
}
CACHE_BACKEND = 'memcached://127.0.0.1:11211/'

SESSION_ENGINE= 'django.contrib.sessions.backends.cache'

'''
RabbitMQ configurations begins
'''
#OLD FORMAT:
# BROKER_HOST = "127.0.0.1"
# BROKER_PORT = 5672   # default RabbitMQ listening port
# BROKER_USER = "admin"
# BROKER_PASSWORD = "admin"
# BROKER_VHOST = "admin" #Virtual hosts provide a way to segregate applications using the same RabbitMQ instance. Different users can have different access privileges to different vhost and queues and exchanges can be created so they only exists in one vhost.

#NEW FORMAT:
BROKER_URL = 'amqp://admin:admin@localhost:5672/admin'
'''
RabbitMQ configurations ends
'''
'''
Celery configurations begins
'''
#CELERY_BACKEND = "amqp"  # telling Celery to report the results back to RabbitMQ
#'amqp' means Advanced Message Queuing Protocol
# CELERY_RESULT_DBURI = ""
CELERY_TIMEZONE = "Asia/Kolkata"
#CELERY_RESULT_BACKEND='djcelery.backends.cache:CacheBackend'
CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend'

CELERY_IMPORTS = ("tasks", )
CELERY_RESULT_PERSISTENT = True #If set to True, result messages will be persistent. This means the messages will not be lost after a broker restart. The default is for the results to be transient.
CELERY_TASK_RESULT_EXPIRES = None #Never delete the SUCCESSFUL tasks from the database. http://docs.celeryproject.org/en/latest/configuration.html#celery-task-result-expires
# CELERY_RESULT_BACKEND = 'cache+memcached://127.0.0.1:11211/'
# CELERY_CACHE_BACKEND = 'memory'
#http://www.hiddentao.com/archives/2012/01/27/processing-long-running-django-tasks-using-celery-rabbitmq-supervisord-monit/
'''
Celery configurations ends
'''
</code>```

答:
```<code>connect(
    db='test',
    username='user',
    password='12345',
    host='mongodb://admin:qwerty@localhost/production'
)
</code>```

and change the DATABASES to DATABASES = {} section in the settings.py

Body:
i am making an application using django 1.8 and mongoengine
But when i am trying to configure Django setting.py file to use a Dummy Database , I receive the following error

(orahienv) somya@somya-Inspiron-15-3555:/var/www/html/admin_python$ python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
July 06, 2017 - 16:57:25
Django version 1.8, using settings 'admin_python.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Performing system checks...

System check identified no issues (0 silenced).
July 06, 2017 - 17:00:15
Django version 1.8, using settings 'admin_python.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
<WSGIRequest: GET '/auth/login/?next=/'>
Internal Server Error: /auth/login/
Traceback (most recent call last):
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 164, in get_response
    response = response.render()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/template/response.py", line 158, in render
    self.content = self.rendered_content
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/template/response.py", line 135, in rendered_content
    content = template.render(context, self._request)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/template/backends/django.py", line 74, in render
    return self.template.render(context)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/template/base.py", line 208, in render
    with context.bind_template(self):
  File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
    return self.gen.next()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/template/context.py", line 235, in bind_template
    updates.update(processor(self.request))
  File "/var/www/html/admin_python/admin_app/context_processors.py", line 30, in init_menu
    if request.user.is_authenticated():
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/utils/functional.py", line 226, in inner
    self._setup()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/utils/functional.py", line 359, in _setup
    self._wrapped = self._setupfunc()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/contrib/auth/middleware.py", line 22, in <lambda>
    request.user = SimpleLazyObject(lambda: get_user(request))
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/contrib/auth/middleware.py", line 10, in get_user
    request._cached_user = auth.get_user(request)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 174, in get_user
    user = backend.get_user(user_id)
  File "/var/www/html/admin_python/admin_app/backend.py", line 29, in get_user
    return TblAdmin.objects.get(pk=user_id)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/manager.py", line 127, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/query.py", line 328, in get
    num = len(clone)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/query.py", line 144, in __len__
    self._fetch_all()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/query.py", line 965, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/query.py", line 238, in iterator
    results = compiler.execute_sql()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 818, in execute_sql
    sql, params = self.as_sql()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 367, in as_sql
    extra_select, order_by, group_by = self.pre_sql_setup()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 48, in pre_sql_setup
    self.setup_query()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 39, in setup_query
    self.select, self.klass_info, self.annotation_col_map = self.get_select()
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 216, in get_select
    ret.append((col, self.compile(col, select_format=True), alias))
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 346, in compile
    sql, params = node.as_sql(self, self.connection)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/expressions.py", line 611, in as_sql
    return "%s.%s" % (qn(self.alias), qn(self.target.column)), []
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 337, in quote_name_unless_alias
    r = self.connection.ops.quote_name(name)
  File "/var/www/html/admin_python/orahienv/local/lib/python2.7/site-packages/django/db/backends/dummy/base.py", line 21, in complain
    raise ImproperlyConfigured("settings.DATABASES is improperly configured. "
ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.
[06/Jul/2017 17:00:21]"GET /auth/login/?next=/ HTTP/1.1" 500 206077

I know people asked similar question before. But it's all about the engine value. does any one know how do I solve this error with the NAME value?

setting.py -

import os
import admin_app
from django.utils import timezone
import mongoengine
"""from mongoengine import connect
connect('pom')"""

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'uj8$6(ol=!w)b3-luqzb=#6(j19gkbrnp2asq6=xt%5*s2ylz('

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

SPATIALITE_LIBRARY_PATH = 'mod_spatialite'
# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'admin_app',
    'celery', #http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#using-the-django-orm-cache-as-a-result-backend
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'djangoflash.middleware.FlashMiddleware',
    #'django.middleware.cache.CacheMiddleware', #http://stackoverflow.com/a/658583/2546013
)

ROOT_URLCONF = 'admin_python.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'media')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'admin_app.context_processors.init_menu',
                'admin_app.context_processors.server_urls',
                'djangoflash.context_processors.flash',
            ],
        },
    },
]

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
MEDIA_URL = '/media/'
HOST_URL='http://127.0.0.1:8001/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
WSGI_APPLICATION = 'admin_python.wsgi.application'
STATIC_URL = '/static/'
SERVER_URL = 'http://localhost:8001/'
WEBAPP_URL = 'http://localhost/webapp_angular/'
USERAPI_URL = 'http://localhost:8000/'
HOST_URL_NEW='http://localhost:8001/media/'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
"""
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'admin_db',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
    }
}"""

"""DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.dummy',
    }
}
"""
"""
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.dummy',
        'NAME': 'pom',
        'USER': 'root',
        'PASSWORD': 'root',
        'HOST': 'localhost',
    }
}
from mongoengine import connect
connect('pom', username='root', password='root')"""
DATABASES = {
    'default': {
        'ENGINE': '',
    },
}

_MONGODB_USER = 'root'
_MONGODB_PASSWD = 'root'
_MONGODB_HOST = 'localhost'
_MONGODB_NAME = 'pom'
_MONGODB_DATABASE_HOST = \
    'mongodb://%s:%s@%s/%s' \
    % (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME)

mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_L10N = True

USE_TZ = False

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

REST_FRAMEWORK = {
    # other settings...

    'DEFAULT_AUTHENTICATION_CLASSES': [],
    'DEFAULT_PERMISSION_CLASSES': [],
}
LOGIN_URL = '/auth/login/'
LOGIN_REDIRECT_URL = '/'

AUTHENTICATION_BACKENDS = (
    'admin_app.backend.AuthBackend',
    'django.contrib.auth.backends.ModelBackend',

)

AUTH_USER_MODEL = 'admin_app.TblAdmin'

EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'AKIAJB6VACOVZANVTC5A'
EMAIL_HOST_PASSWORD = 'Atu9qbV+X5aiwIlQzVAOVjU/AxkxMDV3X0l0FLWweSn9'
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'support@doctorinsta.com'

#LOGGING SETTING
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format' : "[%(asctime)s] %(levelname)s [%(filename)s:%(funcName)s:%(lineno)s] %(message)s",
            'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'applogfile': {
            'level':'DEBUG',
            'class':'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, 'drinsta.log'),
            'formatter': 'verbose'
            },

    },
    'loggers': {
        'django.request': {
            'level': 'ERROR',
            'propagate': True,
            'handlers': ['applogfile',],
        },
        'drinsta': {
            'handlers': ['applogfile',],
            'level': 'DEBUG',
        },
    }
}

#https://docs.djangoproject.com/en/1.8/topics/http/sessions/#configuring-the-session-engine
#https://github.com/dlrust/python-memcached-stats
#We can use the following command to see the keys:
#    python -m memcached_stats 127.0.0.1 11211
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
        'TIMEOUT' : 300 #Default
    }
}
CACHE_BACKEND = 'memcached://127.0.0.1:11211/'

SESSION_ENGINE= 'django.contrib.sessions.backends.cache'

'''
RabbitMQ configurations begins
'''
#OLD FORMAT:
# BROKER_HOST = "127.0.0.1"
# BROKER_PORT = 5672   # default RabbitMQ listening port
# BROKER_USER = "admin"
# BROKER_PASSWORD = "admin"
# BROKER_VHOST = "admin" #Virtual hosts provide a way to segregate applications using the same RabbitMQ instance. Different users can have different access privileges to different vhost and queues and exchanges can be created so they only exists in one vhost.

#NEW FORMAT:
BROKER_URL = 'amqp://admin:admin@localhost:5672/admin'
'''
RabbitMQ configurations ends
'''
'''
Celery configurations begins
'''
#CELERY_BACKEND = "amqp"  # telling Celery to report the results back to RabbitMQ
#'amqp' means Advanced Message Queuing Protocol
# CELERY_RESULT_DBURI = ""
CELERY_TIMEZONE = "Asia/Kolkata"
#CELERY_RESULT_BACKEND='djcelery.backends.cache:CacheBackend'
CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend'

CELERY_IMPORTS = ("tasks", )
CELERY_RESULT_PERSISTENT = True #If set to True, result messages will be persistent. This means the messages will not be lost after a broker restart. The default is for the results to be transient.
CELERY_TASK_RESULT_EXPIRES = None #Never delete the SUCCESSFUL tasks from the database. http://docs.celeryproject.org/en/latest/configuration.html#celery-task-result-expires
# CELERY_RESULT_BACKEND = 'cache+memcached://127.0.0.1:11211/'
# CELERY_CACHE_BACKEND = 'memory'
#http://www.hiddentao.com/archives/2012/01/27/processing-long-running-django-tasks-using-celery-rabbitmq-supervisord-monit/
'''
Celery configurations ends
'''

Body:
connect(
    db='test',
    username='user',
    password='12345',
    host='mongodb://admin:qwerty@localhost/production'
)

and change the DATABASES to DATABASES = {} section in the settings.py


答:
If you do not want to configure a database because you are using mongoengine instead, then remove DATABASES from your settings entirely, or change it to an empty dictionary.

```<code>DATABASES = {}
</code>```

If you do include any items in your DATABASES dictionary, then they must include the ENGINE, otherwise you'll get the ImproperlyConfigured error.

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        ...
    },
}
</code>```

Title: Django1.8 and Mongoclient settings.DATABASES is improperly configured.

Body:
If you do not want to configure a database because you are using mongoengine instead, then remove DATABASES from your settings entirely, or change it to an empty dictionary.

DATABASES = {}

If you do include any items in your DATABASES dictionary, then they must include the ENGINE, otherwise you'll get the ImproperlyConfigured error.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        ...
    },
}


问:
How to check a radio button based on some other value?
I have a bootstrap radio button which needs to get selected based on what value the user gives. Suppose the user enters 'male', male radio button should be selected. Consider the user enters the value in lower case.

    function check(){
    var val = document.getElementById("inp").value;
    if( val == "male"){
        //select male radio button
        }
    if(val == "female"){
         //select female radio button
        }
    }

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <div class="btn-group" data-toggle="buttons">
                  <p>Gender <span>*</span></p>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" style="width: 0px;" value="M" type="radio" name="gender" />M</label>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" style="width: 0px;" type="radio" value="F" name="gender" />F</label>

                </div><br><br>
    <input id="inp" type="text" onblur="check()"/>

    </code>```

答:
You can use jquery builtin function Click() for this task.

    function check(){
    var val = document.getElementById("inp").value;
    if( val == "male"){
      $('#male').click();
      console.log(val);
    }
    if(val == "female"){
      $('#female').click();
     console.log(val);
     }
    }
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <div class="btn-group" data-toggle="buttons">
                  <p>Gender <span>*</span></p>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" style="width: 10px;" value="M" type="radio" name="gender" id="male" />M</label>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" type="radio" value="F" name="gender" id="female" />F</label>

                </div><br><br>
    <input id="inp" type="text" onblur="check()"/>

    </code>```

Body:
I have a bootstrap radio button which needs to get selected based on what value the user gives. Suppose the user enters 'male', male radio button should be selected. Consider the user enters the value in lower case.

    function check(){
    var val = document.getElementById("inp").value;
    if( val == "male"){
        //select male radio button
        }
    if(val == "female"){
         //select female radio button
        }
    }

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Gender *

                    <input class="form-control input-sm" style="width: 0px;" value="M" type="radio" name="gender" />M

                    <input class="form-control input-sm" style="width: 0px;" type="radio" value="F" name="gender" />F

    <input id="inp" type="text" onblur="check()"/>

Body:
You can use jquery builtin function Click() for this task.

    function check(){
    var val = document.getElementById("inp").value;
    if( val == "male"){
      $('#male').click();
      console.log(val);
    }
    if(val == "female"){
      $('#female').click();
     console.log(val);
     }
    }

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <div class="btn-group" data-toggle="buttons">
                  <p>Gender <span>*</span></p>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" style="width: 10px;" value="M" type="radio" name="gender" id="male" />M</label>
                  <label class="btn btn-default">
                    <input class="form-control input-sm" type="radio" value="F" name="gender" id="female" />F</label>

                </div><br><br>
    <input id="inp" type="text" onblur="check()"/>


问:
JQuery '.css' not functioning properly on Firefox - works perfectly on Google Chrome
I have a sort of abstract art piece on the main page of my portfolio that moves about depending on where the mouse cursor is.

This animation works perfectly on Safari, Google Chrome and Opera.

The issue on Firefox is seems to be only when the middle block attempts to move down

Here's a link to my portfolio: http://benjaminthomasgibbs.co.uk/

Okay I know my css code is not properly formatted, I like it this way - could that be the problem:

JS:

```<code>// MIDDLE SLATE ANIMATION

$(document).ready(function() {
    $('#slateMid').mouseenter(function() {
        $('#slateMid').css('top', '160vh');
       // LEFT SLATE
        $('#slate').css('height', '20vh');
        $('#slate').css('top', '45vh');
        $('#slate').css('left', '24vw');
        $('#slate').css('width', '46.5vw')
        $('#slate').css('box-shadow', '0px 0px 0px');
        $('#slate').css('background-color', '#FEBD45');
        // RIGHT SLATE
        $('#slateEnd').css('height', '23.5vh');
        $('#slateEnd').css('top', '19vh');
        $('#slateEnd').css('left', '24vw');
        $('#slateEnd').css('width', '46.5vw');
        $('#slateEnd').css('box-shadow', '0px 0px 0px');
        $('#slateEnd').css('background-color', '#DF4655');
    })
    $('#slateMid').mouseleave(function() {
        $('#slateMid').css('height', '68.5vh');
        $('#slateMid').css('top', '11vh');
        $('#slateMid').css('box-shadow', '10px 10px 10px #888888');
        $('#slateMid').css('border-left', '4px solid #000');
         $('#slateMid').css('border-right', '4px solid #000');
        // LEFT SLATE
        $('#slate').css('height', '34.5vh');
        $('#slate').css('top', '34vh');
        $('#slate').css('left', '26vw');
        $('#slate').css('width', '14vw');
        $('#slate').css('box-shadow', '10px 10px 10px #888888');
        $('#slate').css('background-color', '#DF4655');
        // RIGHT SLATE
        $('#slateEnd').css('height', '45.5vh');
        $('#slateEnd').css('top', '17vh');
        $('#slateEnd').css('left', '56vw');
        $('#slateEnd').css('width', '14vw');
        $('#slateEnd').css('box-shadow', '5px 5px 5px #888888');
        $('#slateEnd').css('background-color', '#FEBD45');
        $('#slateEnd').css('border-left', '4px solid #000');
    })
})
</code>```

HTML:

```<code><div id="changeBottomLeft">
</div>
<div id="changeBottomRight">
</div>
<div id="slate">
</div>
<div id="slateMid">
</div>
<div id="slateEnd">
</div>
</code>```

答:
Your animation moves the middle element out of screen, that means the "mouseleave" callback is sort of automatically called by your animation.

For me, it seems that the behavior on Firefox is the normal one. Maybe Webkit based engines only evaluate "mouse*" events when cursor is moving.

To answer, i think you should divide screen in three parts to trigger animations.

here is a simple snippet to demonstrate this :

$(document).ready( function () {
  $('.animated').mouseenter(function () {
    $(this).addClass('slided');
  });

  $('.animated').mouseleave(function () {
    $(this).removeClass('slided');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  position: relative;
  background-color: lemonchiffon;
  min-height: 100px;
}

.animated {
  position: absolute;
  background-color: red;
  top: 0;
  left: 0;
  height: 50px;
  width: 100px;
  transition: all .3s ease-in-out;
}

.animated.slided {
  background-color: blue;
  top: 50px;
  left: 200px;
}</code>```

```

Body:
I have a sort of abstract art piece on the main page of my portfolio that moves about depending on where the mouse cursor is.

This animation works perfectly on Safari, Google Chrome and Opera.

The issue on Firefox is seems to be only when the middle block attempts to move down

Here's a link to my portfolio: http://benjaminthomasgibbs.co.uk/

Okay I know my css code is not properly formatted, I like it this way - could that be the problem:

JS:

// MIDDLE SLATE ANIMATION

$(document).ready(function() {
    $('#slateMid').mouseenter(function() {
        $('#slateMid').css('top', '160vh');
       // LEFT SLATE
        $('#slate').css('height', '20vh');
        $('#slate').css('top', '45vh');
        $('#slate').css('left', '24vw');
        $('#slate').css('width', '46.5vw')
        $('#slate').css('box-shadow', '0px 0px 0px');
        $('#slate').css('background-color', '#FEBD45');
        // RIGHT SLATE
        $('#slateEnd').css('height', '23.5vh');
        $('#slateEnd').css('top', '19vh');
        $('#slateEnd').css('left', '24vw');
        $('#slateEnd').css('width', '46.5vw');
        $('#slateEnd').css('box-shadow', '0px 0px 0px');
        $('#slateEnd').css('background-color', '#DF4655');
    })
    $('#slateMid').mouseleave(function() {
        $('#slateMid').css('height', '68.5vh');
        $('#slateMid').css('top', '11vh');
        $('#slateMid').css('box-shadow', '10px 10px 10px #888888');
        $('#slateMid').css('border-left', '4px solid #000');
         $('#slateMid').css('border-right', '4px solid #000');
        // LEFT SLATE
        $('#slate').css('height', '34.5vh');
        $('#slate').css('top', '34vh');
        $('#slate').css('left', '26vw');
        $('#slate').css('width', '14vw');
        $('#slate').css('box-shadow', '10px 10px 10px #888888');
        $('#slate').css('background-color', '#DF4655');
        // RIGHT SLATE
        $('#slateEnd').css('height', '45.5vh');
        $('#slateEnd').css('top', '17vh');
        $('#slateEnd').css('left', '56vw');
        $('#slateEnd').css('width', '14vw');
        $('#slateEnd').css('box-shadow', '5px 5px 5px #888888');
        $('#slateEnd').css('background-color', '#FEBD45');
        $('#slateEnd').css('border-left', '4px solid #000');
    })
})

HTML:

Body:
Your animation moves the middle element out of screen, that means the "mouseleave" callback is sort of automatically called by your animation.

For me, it seems that the behavior on Firefox is the normal one. Maybe Webkit based engines only evaluate "mouse*" events when cursor is moving.

To answer, i think you should divide screen in three parts to trigger animations.

here is a simple snippet to demonstrate this :

$(document).ready( function () {
  $('.animated').mouseenter(function () {
    $(this).addClass('slided');
  });

  $('.animated').mouseleave(function () {
    $(this).removeClass('slided');
  });
});

.container {
  position: relative;
  background-color: lemonchiffon;
  min-height: 100px;
}

.animated {
  position: absolute;
  background-color: red;
  top: 0;
  left: 0;
  height: 50px;
  width: 100px;
  transition: all .3s ease-in-out;
}

.animated.slided {
  background-color: blue;
  top: 50px;
  left: 200px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="animated"></div>
</div>


问:
Using getItem with primary and sort keys
So i have a dynamodb table called tableX with the fields:

```<code>random_fld1, random_fld2, primary_key1, and sort_key1
all fields are Strings.
</code>```

What would be a getItem example with those keys and fields. I haven't been able to get the Keys: portion working with getItem.

答:
Here is the get item code for above table structure.

The below code uses local Dynamodb table.

```<code>var AWS = require("aws-sdk");

var creds = new AWS.Credentials('akid', 'secret', 'session');

AWS.config.update({
  region: "us-west-2",
  endpoint: "http://localhost:8000",
  credentials: creds
});

var docClient = new AWS.DynamoDB.DocumentClient();

var table = "tablex";

var params = {
    TableName: table,
    Key:{
        "primary_key1": "p1",
        "sort_key1": "s1"
    },

};

docClient.get(params, function(err, data) {
    if (err) {
        console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
        console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
});
</code>```

Body:
So i have a dynamodb table called tableX with the fields:

random_fld1, random_fld2, primary_key1, and sort_key1
all fields are Strings.

What would be a getItem example with those keys and fields. I haven't been able to get the Keys: portion working with getItem.

Body:
Here is the get item code for above table structure.

The below code uses local Dynamodb table.

var AWS = require("aws-sdk");

var creds = new AWS.Credentials('akid', 'secret', 'session');

AWS.config.update({
  region: "us-west-2",
  endpoint: "http://localhost:8000",
  credentials: creds
});

var docClient = new AWS.DynamoDB.DocumentClient();

var table = "tablex";

var params = {
    TableName: table,
    Key:{
        "primary_key1": "p1",
        "sort_key1": "s1"
    },

};

docClient.get(params, function(err, data) {
    if (err) {
        console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
        console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
});


问:
How to show data into list in Android
In my application I want show some data in recyclerView and i get this data from server.

I use Retrofit for send or get requests from android to server.

When run the application, it's showing response.body().getData().size() is 0, but in PostMan I see the following data:

I write below code for get data :

```<code>private void getComments() {
    CommentSendData sendData = new CommentSendData();
    sendData.setEntityID(7);
    sendData.setReviewType(5);
    sendData.setReviewUserType(0);
    sendData.setEntityID(newsID);
    sendData.setCelebrityID(0);
    sendData.setPageIndex(0);
    sendData.setPageSize(10);

    InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
    Call<CommentResponse> call = api.getComments(sendData);

    call.enqueue(new Callback<CommentResponse>() {
        @Override
        public void onResponse(Call<CommentResponse> call, Response<CommentResponse> response) {
            Toast.makeText(NewsDetailActivity.this, "" + response.body().getData().size(), Toast.LENGTH_SHORT).show();
            Toast.makeText(NewsDetailActivity.this, "" + call.isExecuted(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<CommentResponse> call, Throwable t) {

        }
    });
}
</code>```

When show this Toast :Toast.makeText(NewsDetailActivity.this, "" + call.isExecuted(), Toast.LENGTH_SHORT).show(); show me true in toast.

and when show this Toast : Toast.makeText(NewsDetailActivity.this, "" + response.body().getData().size(), Toast.LENGTH_SHORT).show(); , show me 0 in toast .

My Adapter codes:

```<code>public class CommentsListAdapter extends RecyclerView.Adapter<CommentsListAdapter.ViewHolder> {

    private Context context;
    private List<CommentData> model;

    public CommentsListAdapter(Context context, List<CommentData> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public CommentsListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_comment, parent, false);

        return new CommentsListAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final CommentsListAdapter.ViewHolder holder, final int position) {

        holder.row_commentNameTxt.setText(Html.fromHtml(model.get(position).getOwner().getName()));
        holder.row_commentCommentTxt.setText(Html.fromHtml(model.get(position).getText()));
        Glide.with(context)
                .load(model.get(position).getOwner().getImageUrl())
                .placeholder(R.drawable.default_image)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.row_commentProfileImage);
        holder.row_commentLikeTxt.setText(model.get(position).getLikeCount() + "");
        holder.row_commentReplayTxt.setText(model.get(position).getRepliesCount() + "");
        holder.row_commentDateTxt.setText(model.get(position).getSubmitDate() + " " + model.get(position).getSubmitTime());
    }

    @Override
    public int getItemCount() {
        return model.size();
    }

    public void addNewItem(List<CommentData> newContent) {
        int start = this.model.size();
        int end = newContent.size();
        model.addAll(newContent);
        notifyDataSetChanged();
    }

    public void clear() {
        model.clear();
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private CircleImageView row_commentProfileImage;
        private TextView row_commentNameTxt, row_commentCommentTxt, row_commentLikeTxt, row_commentReplayTxt, row_commentDateTxt;

        public ViewHolder(View itemView) {
            super(itemView);

            row_commentProfileImage = (CircleImageView) itemView.findViewById(R.id.row_commentProfileImage);
            row_commentNameTxt = (TextView) itemView.findViewById(R.id.row_commentNameTxt);
            row_commentCommentTxt = (TextView) itemView.findViewById(R.id.row_commentCommentTxt);
            row_commentLikeTxt = (TextView) itemView.findViewById(R.id.row_commentLikeTxt);
            row_commentReplayTxt = (TextView) itemView.findViewById(R.id.row_commentReplayTxt);
            row_commentDateTxt = (TextView) itemView.findViewById(R.id.row_commentDateTxt);

        }
    }
}
</code>```

CommentResponse code:

```<code>public class CommentResponse {
    @SerializedName("statusCode")
    @Expose
    private Integer statusCode;
    @SerializedName("statusMessage")
    @Expose
    private String statusMessage;
    @SerializedName("data")
    @Expose
    private List<CommentData> data = null;

    public Integer getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(Integer statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusMessage() {
        return statusMessage;
    }

    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    public List<CommentData> getData() {
        return data;
    }

    public void setData(List<CommentData> data) {
        this.data = data;
    }
}
</code>```

CommentData model :

```<code>public class CommentData {
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("text")
    @Expose
    private String text;
    @SerializedName("likeCount")
    @Expose
    private Integer likeCount;
    @SerializedName("repliesCount")
    @Expose
    private Integer repliesCount;
    @SerializedName("submitDate")
    @Expose
    private String submitDate;
    @SerializedName("submitTime")
    @Expose
    private String submitTime;
    @SerializedName("owner")
    @Expose
    private CommentOwner owner;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Integer getLikeCount() {
        return likeCount;
    }

    public void setLikeCount(Integer likeCount) {
        this.likeCount = likeCount;
    }

    public Integer getRepliesCount() {
        return repliesCount;
    }

    public void setRepliesCount(Integer repliesCount) {
        this.repliesCount = repliesCount;
    }

    public String getSubmitDate() {
        return submitDate;
    }

    public void setSubmitDate(String submitDate) {
        this.submitDate = submitDate;
    }

    public String getSubmitTime() {
        return submitTime;
    }

    public void setSubmitTime(String submitTime) {
        this.submitTime = submitTime;
    }

    public CommentOwner getOwner() {
        return owner;
    }

    public void setOwner(CommentOwner owner) {
        this.owner = owner;
    }
}
</code>```

Why when run application show me 0 data but in PostMan show data ?!

答:
It looks like you are passing some data to the server in the wrong way. Are you sure that the data sent from POSTMAN are the same sent from Retrofit?

Could you post your implementation of api.getComments(sendData) method?

Title: How to show data into list in Android

Body:
In my application I want show some data in recyclerView and i get this data from server.

I use Retrofit for send or get requests from android to server.

When run the application, it's showing response.body().getData().size() is 0, but in PostMan I see the following data:

I write below code for get data :

private void getComments() {
    CommentSendData sendData = new CommentSendData();
    sendData.setEntityID(7);
    sendData.setReviewType(5);
    sendData.setReviewUserType(0);
    sendData.setEntityID(newsID);
    sendData.setCelebrityID(0);
    sendData.setPageIndex(0);
    sendData.setPageSize(10);

    InterfaceApi api = ApiClient.getClient().create(InterfaceApi.class);
    Call<CommentResponse> call = api.getComments(sendData);

    call.enqueue(new Callback<CommentResponse>() {
        @Override
        public void onResponse(Call<CommentResponse> call, Response<CommentResponse> response) {
            Toast.makeText(NewsDetailActivity.this, "" + response.body().getData().size(), Toast.LENGTH_SHORT).show();
            Toast.makeText(NewsDetailActivity.this, "" + call.isExecuted(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailure(Call<CommentResponse> call, Throwable t) {

        }
    });
}

When show this Toast :Toast.makeText(NewsDetailActivity.this, "" + call.isExecuted(), Toast.LENGTH_SHORT).show(); show me true in toast.

and when show this Toast : Toast.makeText(NewsDetailActivity.this, "" + response.body().getData().size(), Toast.LENGTH_SHORT).show(); , show me 0 in toast .

My Adapter codes:

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

    private Context context;
    private List<CommentData> model;

    public CommentsListAdapter(Context context, List<CommentData> model) {
        this.context = context;
        this.model = model;
    }

    @Override
    public CommentsListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_comment, parent, false);

        return new CommentsListAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final CommentsListAdapter.ViewHolder holder, final int position) {

        holder.row_commentNameTxt.setText(Html.fromHtml(model.get(position).getOwner().getName()));
        holder.row_commentCommentTxt.setText(Html.fromHtml(model.get(position).getText()));
        Glide.with(context)
                .load(model.get(position).getOwner().getImageUrl())
                .placeholder(R.drawable.default_image)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(holder.row_commentProfileImage);
        holder.row_commentLikeTxt.setText(model.get(position).getLikeCount() + "");
        holder.row_commentReplayTxt.setText(model.get(position).getRepliesCount() + "");
        holder.row_commentDateTxt.setText(model.get(position).getSubmitDate() + " " + model.get(position).getSubmitTime());
    }

    @Override
    public int getItemCount() {
        return model.size();
    }

    public void addNewItem(List<CommentData> newContent) {
        int start = this.model.size();
        int end = newContent.size();
        model.addAll(newContent);
        notifyDataSetChanged();
    }

    public void clear() {
        model.clear();
        notifyDataSetChanged();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private CircleImageView row_commentProfileImage;
        private TextView row_commentNameTxt, row_commentCommentTxt, row_commentLikeTxt, row_commentReplayTxt, row_commentDateTxt;

        public ViewHolder(View itemView) {
            super(itemView);

            row_commentProfileImage = (CircleImageView) itemView.findViewById(R.id.row_commentProfileImage);
            row_commentNameTxt = (TextView) itemView.findViewById(R.id.row_commentNameTxt);
            row_commentCommentTxt = (TextView) itemView.findViewById(R.id.row_commentCommentTxt);
            row_commentLikeTxt = (TextView) itemView.findViewById(R.id.row_commentLikeTxt);
            row_commentReplayTxt = (TextView) itemView.findViewById(R.id.row_commentReplayTxt);
            row_commentDateTxt = (TextView) itemView.findViewById(R.id.row_commentDateTxt);

        }
    }
}

CommentResponse code:

public class CommentResponse {
    @SerializedName("statusCode")
    @Expose
    private Integer statusCode;
    @SerializedName("statusMessage")
    @Expose
    private String statusMessage;
    @SerializedName("data")
    @Expose
    private List<CommentData> data = null;

    public Integer getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(Integer statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusMessage() {
        return statusMessage;
    }

    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    public List<CommentData> getData() {
        return data;
    }

    public void setData(List<CommentData> data) {
        this.data = data;
    }
}

CommentData model :

public class CommentData {
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("text")
    @Expose
    private String text;
    @SerializedName("likeCount")
    @Expose
    private Integer likeCount;
    @SerializedName("repliesCount")
    @Expose
    private Integer repliesCount;
    @SerializedName("submitDate")
    @Expose
    private String submitDate;
    @SerializedName("submitTime")
    @Expose
    private String submitTime;
    @SerializedName("owner")
    @Expose
    private CommentOwner owner;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Integer getLikeCount() {
        return likeCount;
    }

    public void setLikeCount(Integer likeCount) {
        this.likeCount = likeCount;
    }

    public Integer getRepliesCount() {
        return repliesCount;
    }

    public void setRepliesCount(Integer repliesCount) {
        this.repliesCount = repliesCount;
    }

    public String getSubmitDate() {
        return submitDate;
    }

    public void setSubmitDate(String submitDate) {
        this.submitDate = submitDate;
    }

    public String getSubmitTime() {
        return submitTime;
    }

    public void setSubmitTime(String submitTime) {
        this.submitTime = submitTime;
    }

    public CommentOwner getOwner() {
        return owner;
    }

    public void setOwner(CommentOwner owner) {
        this.owner = owner;
    }
}

Why when run application show me 0 data but in PostMan show data ?!


问:
Microsoft Access Query
I have one settings table that is storing different setting keys for a app built using Microsoft Access
One of the settings key drives how many records should be seen in a dropdown list
The query behind the list is similar to the one below:

```<code>Select Top 3 id, name FROM tblRegular
</code>```

Now, I want to achieve something like this:

```<code>Select Top (Select keyValue FROM tblSettings WHERE key="rowNumber") id, name FROM tblRegular
</code>```

But, using it like this does not work as it fires errors
Could someone tell me if it can be done?

EDIT: The table structure looks similar to the one below:
tblRegular:

```<code>id  | name
1     'A'
2     'B'
3     'C'
</code>```

tblSettings:

```<code>id  | key          | keyValue
1     'rowNumber'    2
</code>```

Thank you!

答:
This syntax does fail in Access SQL, barking at "Select" with the (localised) message like:

The SELECT sentence contains a reserved word or argument, that is
  misspelled or missing, or the punctuation is not correct.

Title: Microsoft Access Query

Body:
I have one settings table that is storing different setting keys for a app built using Microsoft Access
One of the settings key drives how many records should be seen in a dropdown list
The query behind the list is similar to the one below:

Select Top 3 id, name FROM tblRegular

Now, I want to achieve something like this:

Select Top (Select keyValue FROM tblSettings WHERE key="rowNumber") id, name FROM tblRegular

But, using it like this does not work as it fires errors
Could someone tell me if it can be done?

EDIT: The table structure looks similar to the one below:
tblRegular:

id  | name
1     'A'
2     'B'
3     'C'

tblSettings:

id  | key          | keyValue
1     'rowNumber'    2

Thank you!


问:
How to close geckodriver with selenium 3.0.0 beta
Environment: Win 7, Selenium 3.0.0 beta, FireFox- 49.0.1

```<code>System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");

WebDriver driver=new FirefoxDriver();
</code>```

Issue 1:

Command: driver.close();  or  ((FirefoxDriver) driver).kill();

Expected Result: Browser should close.

Actual Result: Browser is not closing.

Issue 2:

Command: driver.quit();

Expected Result: Browser should close.

Actual Result: Firefox crashed.

Getting Error: "Plugin container for FireFox has stopped working."

Any suggestions...

答:
Simple solution I tried for running tests on windows machine was to add this code before driver.quit() or driver.close() for firefox browser using geckodriver</p>

```<code>try {
            Runtime.getRuntime().exec("taskkill /F /IM geckodriver.exe");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
</code>```

Body:
Environment: Win 7, Selenium 3.0.0 beta, FireFox- 49.0.1

System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");

WebDriver driver=new FirefoxDriver();

Issue 1:

Command: driver.close();  or  ((FirefoxDriver) driver).kill();

Expected Result: Browser should close.

Actual Result: Browser is not closing.

Issue 2:

Command: driver.quit();

Expected Result: Browser should close.

Actual Result: Firefox crashed.

Getting Error: "Plugin container for FireFox has stopped working."

Any suggestions...

Body:
Simple solution I tried for running tests on windows machine was to add this code before driver.quit() or driver.close() for firefox browser using geckodriver

try {
            Runtime.getRuntime().exec("taskkill /F /IM geckodriver.exe");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


问:
Cant seem to find the Syntax error
Can somebody tell me what I am doing wrong here, I am getting incorrect syntax near where. Whats wrong with the statement?    </p>

```<code>INSERT INTO dbo.a1
    select x1 as id, x2 as enc_id, x3 as dev,x4 as mang, x4 as sre, x5 as phase,x6, x7, x8
    from
    (select *,
    row_number() over(partition by x2 order by x8)  as rank
    from ccsm.n9 where xx=1 and xx_pat=1 and xx_encz='Tesz')
     where rank=1;
</code>```

答:
You never told us what version of SQL you are using, but one possibility is that your derived table needs an alias:

```<code>INSERT INTO dbo.a1
SELECT t.x1, t.x2, t.x3, t.x4, t.x4, t.x5, t.x6, t.x7, t.x8
FROM
(
    SELECT *,
        ROW_NUMBER() OVER (PARTITION BY x2 ORDER BY x8) AS rank
    FROM ccsm.n9
    WHERE xx = 1 and xx_pat = 1 and xx_encz = 'Tesz'
) t
WHERE t.rank = 1;
</code>```

I know that Oracle enforces the derived table alias rule, and possibly other databases as well.  Note that the aliases you had in the SELECT statement serve no purpose because the values are just being inserted.  If you wish to insert x4 twice then just repeat it twice.

Title: Cant seem to find the Syntax error

Body:
Can somebody tell me what I am doing wrong here, I am getting incorrect syntax near where. Whats wrong with the statement?

INSERT INTO dbo.a1
    select x1 as id, x2 as enc_id, x3 as dev,x4 as mang, x4 as sre, x5 as phase,x6, x7, x8
    from
    (select *,
    row_number() over(partition by x2 order by x8)  as rank
    from ccsm.n9 where xx=1 and xx_pat=1 and xx_encz='Tesz')
     where rank=1;

Body:
You never told us what version of SQL you are using, but one possibility is that your derived table needs an alias:

INSERT INTO dbo.a1
SELECT t.x1, t.x2, t.x3, t.x4, t.x4, t.x5, t.x6, t.x7, t.x8
FROM
(
    SELECT *,
        ROW_NUMBER() OVER (PARTITION BY x2 ORDER BY x8) AS rank
    FROM ccsm.n9
    WHERE xx = 1 and xx_pat = 1 and xx_encz = 'Tesz'
) t
WHERE t.rank = 1;

I know that Oracle enforces the derived table alias rule, and possibly other databases as well.  Note that the aliases you had in the SELECT statement serve no purpose because the values are just being inserted.  If you wish to insert x4 twice then just repeat it twice.


问:
PostgreSQL Config File and Query Design for Calculations
I'm new to PG and trying to run this simple query and it's crashing Postgres. The query works in a few seconds if I only try to calculate r1, but says "Out of memory" if I try to calculate r2 through r6 in addition to r1 as below. Poor query design? I'm going to reference the calculated fields r1...r6 in other calculations, so was thinking about making this query a view. My key config file parameters are below. Windows 10, PG 9.6, 40GB RAM, 64-bit. Any ideas on what to do? Thanks!

Edited: I tried adding LIMIT 500 to the end and that worked, but if I run a query on this query, i.e. to use the calculated r1,r2,r3... in another query, will the new query see all the records or will it be limited to just the 500?

```<code>SELECT
public.psda.price_y1,
public.psda.price_y2,
public.psda.price_y3,
public.psda.price_y4,
public.psda.price_y5,
public.psda.price_y6,
public.psda.price_y7,
(price_y1 - price_y2) / nullif(price_y2, 0) AS r1,
(price_y2 - price_y3) / nullif(price_y3, 0) AS r2,
(price_y3 - price_y4) / nullif(price_y4, 0) AS r3,
(price_y4 - price_y5) / nullif(price_y5, 0) AS r4,
(price_y5 - price_y6) / nullif(price_y6, 0) AS r5,
(price_y6 - price_y7) / nullif(price_y7, 0) AS r6
FROM
public.psda
</code>```

My config file parameters:

```<code>max_connections = 50
shared_buffers = 1GB
effective_cache_size = 20GB
work_mem = 400MB
maintenance_work_mem = 1GB
wal_buffers = 16MB
max_wal_size = 2GB
min_wal_size = 1GB
checkpoint_completion_target = 0.7
default_statistics_target = 100
</code>```

答:
use this service http://pgtune.leopard.in.ua/

when calc total RAM for PostgreSQL = total RAM - RAM for OS

PGTune calculate configuration for PostgreSQL based on the maximum performance for a given hardware configuration.

It isn't a silver bullet for the optimization settings of PostgreSQL.

Many settings depend not only on the hardware configuration, but also on the size of the database, the number of clients and the complexity of queries, so that optimally configure the database can only be given all these parameters.

Body:
I'm new to PG and trying to run this simple query and it's crashing Postgres. The query works in a few seconds if I only try to calculate r1, but says "Out of memory" if I try to calculate r2 through r6 in addition to r1 as below. Poor query design? I'm going to reference the calculated fields r1...r6 in other calculations, so was thinking about making this query a view. My key config file parameters are below. Windows 10, PG 9.6, 40GB RAM, 64-bit. Any ideas on what to do? Thanks!

Edited: I tried adding LIMIT 500 to the end and that worked, but if I run a query on this query, i.e. to use the calculated r1,r2,r3... in another query, will the new query see all the records or will it be limited to just the 500?

SELECT
public.psda.price_y1,
public.psda.price_y2,
public.psda.price_y3,
public.psda.price_y4,
public.psda.price_y5,
public.psda.price_y6,
public.psda.price_y7,
(price_y1 - price_y2) / nullif(price_y2, 0) AS r1,
(price_y2 - price_y3) / nullif(price_y3, 0) AS r2,
(price_y3 - price_y4) / nullif(price_y4, 0) AS r3,
(price_y4 - price_y5) / nullif(price_y5, 0) AS r4,
(price_y5 - price_y6) / nullif(price_y6, 0) AS r5,
(price_y6 - price_y7) / nullif(price_y7, 0) AS r6
FROM
public.psda

My config file parameters:

max_connections = 50
shared_buffers = 1GB
effective_cache_size = 20GB
work_mem = 400MB
maintenance_work_mem = 1GB
wal_buffers = 16MB
max_wal_size = 2GB
min_wal_size = 1GB
checkpoint_completion_target = 0.7
default_statistics_target = 100


问:
Is there a training example of using Tensorflow C++ API?
To be clear, I do not want to load a pretrained model in C++. I want to do the training in C++ and then use the model. </p>

答:
I've been trying to do training using the C++ API for a few days now, as far as I've found there is no full example to be found using the 1.2 release. I've yet to give up, if I do manage to make a working example (I'm trying to recognize digits from MNIST) I will post it here. In 1.2, the way sessions are run was changed and the documentation is very scarce.

If you're willing to use an older version of the C++ API, this example in the source code should suffice:

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/cc/tutorials/example_trainer.cc.


问:
Animate marker in Google Maps SDK in iOS
I have an image over a map and I want to give it some linear and rotational motion over the google maps.

How can I do it in GMS? Please help me.

答:
It's an easy process. First rotate the marker to get the right heading using this function:

```<code>+(float)getBearing:(CLLocationCoordinate2D)locations1 andSecond:(CLLocationCoordinate2D)locattion2{
    float fLat = degreesToRadians(locations1.latitude);
    float fLng = degreesToRadians(locations1.longitude);
    float tLat = degreesToRadians(locattion2.latitude);
    float tLng = degreesToRadians(locattion2.longitude);

    float degree = radiansToDegrees(atan2(sin(tLng-fLng)*cos(tLat), cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng)));

    if (degree >= 0) {
        return degree;
    } else {
        return 360+degree;
    }
}
</code>```

Then rotate your marker to the new heading:

```<code>YOUR_MARKER.rotation = CALCULATED_HEADING - 180;
</code>```

Now, the final step is to animate your driver smoothly

```<code>[CATransaction begin];
[CATransaction setAnimationDuration:3.1];
[YOUR_MARKER setPosition:NEW_LOCATION_COORDINATES];
[CATransaction commit];
</code>```

Body:
It's an easy process. First rotate the marker to get the right heading using this function:

+(float)getBearing:(CLLocationCoordinate2D)locations1 andSecond:(CLLocationCoordinate2D)locattion2{
    float fLat = degreesToRadians(locations1.latitude);
    float fLng = degreesToRadians(locations1.longitude);
    float tLat = degreesToRadians(locattion2.latitude);
    float tLng = degreesToRadians(locattion2.longitude);

    float degree = radiansToDegrees(atan2(sin(tLng-fLng)*cos(tLat), cos(fLat)*sin(tLat)-sin(fLat)*cos(tLat)*cos(tLng-fLng)));

    if (degree >= 0) {
        return degree;
    } else {
        return 360+degree;
    }
}

Then rotate your marker to the new heading:

YOUR_MARKER.rotation = CALCULATED_HEADING - 180;

Now, the final step is to animate your driver smoothly

[CATransaction begin];
[CATransaction setAnimationDuration:3.1];
[YOUR_MARKER setPosition:NEW_LOCATION_COORDINATES];
[CATransaction commit];


问:
Generating a very large matrix of string combinations using combn() and bigmemory package
I have a vector x of 1,344 unique strings. I want to generate a matrix that gives me all possible groups of three values, regardless of order, and export that to a csv.

I'm running R on EC2 on a m1.large instance w 64bit Ubuntu. When using combn(x, 3) I get an out of memory error:

```<code>Error: cannot allocate vector of size 9.0 Gb
</code>```

The size of the resulting matrix is C1344,3 = 403,716,544 rows and three columns - which is the transpose of the result of combn() function.

I thought of using the bigmemory package to create a file backed big.matrix so I can then assign the results of the combn() function. I can create a preallocated big matrix:

```<code>library(bigmemory)
x <- as.character(1:1344)
combos <- 403716544
test <- filebacked.big.matrix(nrow = combos, ncol = 3,
        init = 0, backingfile = "test.matrix")
</code>```

But when I try to allocate the values test <- combn(x, 3) I still get the same: Error: cannot allocate vector of size 9.0 Gb

I even tried coercing the result of combn(x,3) but I think that because the combn() function is returning an error, the big.matrix function doesn't work either.

```<code>test <- as.big.matrix(matrix(combn(x, 3)), backingfile = "abc")
Error: cannot allocate vector of size 9.0 Gb
Error in as.big.matrix(matrix(combn(x, 3)), backingfile = "abc") :
  error in evaluating the argument 'x' in selecting a method for function 'as.big.matrix'
</code>```

Is there a way to combine these two functions together to get what I need? Are there any other ways of achieving this? Thanks.

答:
You could first find all 2-way combinations, and then just combine them with the 3d value while saving them every time. This takes a lot less memory:

```<code>combn.mod <- function(x,fname){
  tmp <- combn(x,2,simplify=F)
  n <- length(x)
  for ( i in x[-c(n,n-1)]){
    # Drop all combinations that contain value i
    id <- which(!unlist(lapply(tmp,function(t) i %in% t)))
    tmp <- tmp[id]
    # add i to all other combinations and write to file
    out <- do.call(rbind,lapply(tmp,c,i))
    write(t(out),file=fname,ncolumns=3,append=T,sep=",")
  }
}

combn.mod(x,"F:/Tmp/Test.txt")
</code>```

This is not as general as Joshua's answer though, it is specifically for your case. I guess it is faster -again, for this particular case-, but I didn't make the comparison. Function works on my computer using little over 50 Mb (roughly estimated) when applied to your x.

EDIT

On a sidenote: If this is for simulation purposes, I find it hard to believe that any scientific application needs 400+ million simulation runs. You might be asking the correct answer to the wrong question here...

PROOF OF CONCEPT :

I changed the write line by tt[[i]]<-out, added tt <- list() before the loop and return(tt) after it. Then:

```<code>> do.call(rbind,combn.mod(letters[1:5]))
      [,1] [,2] [,3]
 [1,] "b"  "c"  "a"
 [2,] "b"  "d"  "a"
 [3,] "b"  "e"  "a"
 [4,] "c"  "d"  "a"
 [5,] "c"  "e"  "a"
 [6,] "d"  "e"  "a"
 [7,] "c"  "d"  "b"
 [8,] "c"  "e"  "b"
 [9,] "d"  "e"  "b"
[10,] "d"  "e"  "c"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a vector x of 1,344 unique strings. I want to generate a matrix that gives me all possible groups of three values, regardless of order, and export that to a csv.

I'm running R on EC2 on a m1.large instance w 64bit Ubuntu. When using combn(x, 3) I get an out of memory error:

Error: cannot allocate vector of size 9.0 Gb

The size of the resulting matrix is C1344,3 = 403,716,544 rows and three columns - which is the transpose of the result of combn() function.

I thought of using the bigmemory package to create a file backed big.matrix so I can then assign the results of the combn() function. I can create a preallocated big matrix:

library(bigmemory)
x <- as.character(1:1344)
combos <- 403716544
test <- filebacked.big.matrix(nrow = combos, ncol = 3,
        init = 0, backingfile = "test.matrix")

But when I try to allocate the values test <- combn(x, 3) I still get the same: Error: cannot allocate vector of size 9.0 Gb

I even tried coercing the result of combn(x,3) but I think that because the combn() function is returning an error, the big.matrix function doesn't work either.

test <- as.big.matrix(matrix(combn(x, 3)), backingfile = "abc")
Error: cannot allocate vector of size 9.0 Gb
Error in as.big.matrix(matrix(combn(x, 3)), backingfile = "abc") :
  error in evaluating the argument 'x' in selecting a method for function 'as.big.matrix'

Is there a way to combine these two functions together to get what I need? Are there any other ways of achieving this? Thanks.

Body:
You could first find all 2-way combinations, and then just combine them with the 3d value while saving them every time. This takes a lot less memory:

combn.mod <- function(x,fname){
  tmp <- combn(x,2,simplify=F)
  n <- length(x)
  for ( i in x[-c(n,n-1)]){
    # Drop all combinations that contain value i
    id <- which(!unlist(lapply(tmp,function(t) i %in% t)))
    tmp <- tmp[id]
    # add i to all other combinations and write to file
    out <- do.call(rbind,lapply(tmp,c,i))
    write(t(out),file=fname,ncolumns=3,append=T,sep=",")
  }
}

combn.mod(x,"F:/Tmp/Test.txt")

This is not as general as Joshua's answer though, it is specifically for your case. I guess it is faster -again, for this particular case-, but I didn't make the comparison. Function works on my computer using little over 50 Mb (roughly estimated) when applied to your x.

EDIT

On a sidenote: If this is for simulation purposes, I find it hard to believe that any scientific application needs 400+ million simulation runs. You might be asking the correct answer to the wrong question here...

PROOF OF CONCEPT :

I changed the write line by tt[[i]]<-out, added tt <- list() before the loop and return(tt) after it. Then:

> do.call(rbind,combn.mod(letters[1:5]))
      [,1] [,2] [,3]
 [1,] "b"  "c"  "a"
 [2,] "b"  "d"  "a"
 [3,] "b"  "e"  "a"
 [4,] "c"  "d"  "a"
 [5,] "c"  "e"  "a"
 [6,] "d"  "e"  "a"
 [7,] "c"  "d"  "b"
 [8,] "c"  "e"  "b"
 [9,] "d"  "e"  "b"
[10,] "d"  "e"  "c"


问:
Find certain characters in cell with Excel
I have a cell where a link can be pasted. For example:
https://stackoverflow.com/questions/ask

I want the cell next to it say "wrong" IF the text contains "/" or ":" or "=". It should say "Correct" is none of these 3 characters are found in the text.

```<code>For example:
test/
Would give "Wrong" because it contains at least 1 "/"

/test:
Would give "Wrong" because it contains at least 1 ":" and at least 1 "/"

test///////
Would give "Wrong" because it contains at least 1 "/"

test/:=
Would give "Wrong" because it contains at least 1 "/", at least 1 ":" and at least 1 "/"

test123{}+_)
Would give "Correct" because it does not contain any "/", ":" or "="
</code>```

I tried to work with nested IF, but I couldn't get it to work. I kept getting errors when adding the third character to the formula.

答:
Try this

```<code>=IF(OR(ISNUMBER(SEARCH("/",A1)),ISNUMBER(SEARCH(":",A1)),ISNUMBER(SEARCH("=",A1))),"Wrong","Correct")
</code>```

or prefereably this one

```<code>=IF(OR(ISNUMBER(SEARCH({"/",":","="},A1))),"Wrong","Correct")
</code>```

See image for reference.

Body:
I have a cell where a link can be pasted. For example:
https://stackoverflow.com/questions/ask

I want the cell next to it say "wrong" IF the text contains "/" or ":" or "=". It should say "Correct" is none of these 3 characters are found in the text.

For example:
test/
Would give "Wrong" because it contains at least 1 "/"

/test:
Would give "Wrong" because it contains at least 1 ":" and at least 1 "/"

test///////
Would give "Wrong" because it contains at least 1 "/"

test/:=
Would give "Wrong" because it contains at least 1 "/", at least 1 ":" and at least 1 "/"

test123{}+_)
Would give "Correct" because it does not contain any "/", ":" or "="

I tried to work with nested IF, but I couldn't get it to work. I kept getting errors when adding the third character to the formula.

Body:
Try this

=IF(OR(ISNUMBER(SEARCH("/",A1)),ISNUMBER(SEARCH(":",A1)),ISNUMBER(SEARCH("=",A1))),"Wrong","Correct")

or prefereably this one

=IF(OR(ISNUMBER(SEARCH({"/",":","="},A1))),"Wrong","Correct")

See image for reference.


问:
How can I fill the space between values(geom_line) and an intercept with ggplot2? Different Colors for values over and under intercept
I want to do a graph with ggplot2, where I need the space/area between the intercept (=1) and the values (which I connected through geom_line) to be red (if the values are lower than 1) or green (if the values are bigger than 1). The data is from microsoft (price performance since 1999).

Data:

```<code>require(quantmod)
require(dplyr)
require(ggplot2)

getSymbols("MSFT", from ="1999-01-01")
microsoft <- data.frame(time(MSFT), MSFT[,6])
microsoft$time <- as.Date(microsoft$time.MSFT., "%Y-%m-%d")

microsoft <- microsoft %>%
mutate(change = MSFT.Adjusted - first(MSFT.Adjusted),
     change.pc = change/first(MSFT.Adjusted)+1)
</code>```

that is the ggplot I have so far:

```<code>ggplot(microsoft, aes(x = time, y = change.pc)) +
  geom_line(stat = "identity") +
  geom_hline(aes(yintercept=1), color="black") +
  theme_bw() +
  xlab("Jahr") + ylab("") +
  ggtitle("Microsoft Kursentwicklung seit Januar 1999")
</code>```

I want to fill the space between y = 1 and the values above in green, and the space between y = 1 and the values under in red. I tried geom_ribbon, geom_area, geom_polynom, but nothing worked. The biggest problem is, that it fills the space green, but not online above y = 1 but also under. and the red you can't even see...

here what I tried:

```<code>geom_area(data = subset(microsoft, change.pc > 1), fill = "green", alpha =0.5)
geom_area(data = subset(microsoft, change.pc < 1), fill = "red", alpha = 0.5)
</code>```

I put these to lines in my plot, and then the problem I described above appeared.

Among other things I also tried this (found here on stackoverflow.com):

```<code>microsoft$grp <- "orig"
microsoft <- microsoft[order(microsoft$time),]
microsoft_new <- do.call("rbind",
             sapply(1:(nrow(microsoft) -1), function(i){
               f <- lm(time ~ change.pc, microsoft[i:(i+1), ])
               if (f$qr$rank < 2) return(NULL)
               r <- predict(f, newdata = data.frame(change.pc = 0))
               if(microsoft[i, ]$time < r & r < microsoft[i+1, ]$time)
                 return(data.frame(time = r, change.pc = 0))
               else return(NULL)
             })
)
microsoft_2 <- rbind(microsoft, microsoft_new)
ggplot(microsoft_2, aes(x = time, y = change.pc)) +
  geom_area(data = subset(microsoft_2, change.pc <= 1), fill = "red") +
  geom_area(data = subset(microsoft_2, change.pc >= 1), fill = "blue") +
  scale_x_continuous("", expand = c(0,0), breaks = seq(1999, 2017, 3)) +
  theme_bw()
</code>```

That didn't work either.
Does anyone has an idea how I could achieve what I need?
This is how it should look

答:
I couldn't get your data to work, but using some made up data, the following approach looks like your example:

```<code>library(ggplot2)
set.seed(0)
microsoft <- data.frame(date=1:1000, y=cumsum(runif(1000)-0.5))

ggplot(microsoft, aes(x=date,y=y)) +
geom_ribbon(aes(ymin=pmin(microsoft$y,0), ymax=0), fill="red", col="red", alpha=0.5) +
geom_ribbon(aes(ymin=0, ymax=pmax(microsoft$y,0)), fill="green", col="green", alpha=0.5) +
geom_line(aes(y=0))
</code>```

Body:
I want to do a graph with ggplot2, where I need the space/area between the intercept (=1) and the values (which I connected through geom_line) to be red (if the values are lower than 1) or green (if the values are bigger than 1). The data is from microsoft (price performance since 1999).

Data:

require(quantmod)
require(dplyr)
require(ggplot2)

getSymbols("MSFT", from ="1999-01-01")
microsoft <- data.frame(time(MSFT), MSFT[,6])
microsoft$time <- as.Date(microsoft$time.MSFT., "%Y-%m-%d")

microsoft <- microsoft %>%
mutate(change = MSFT.Adjusted - first(MSFT.Adjusted),
     change.pc = change/first(MSFT.Adjusted)+1)

that is the ggplot I have so far:

ggplot(microsoft, aes(x = time, y = change.pc)) +
  geom_line(stat = "identity") +
  geom_hline(aes(yintercept=1), color="black") +
  theme_bw() +
  xlab("Jahr") + ylab("") +
  ggtitle("Microsoft Kursentwicklung seit Januar 1999")

I want to fill the space between y = 1 and the values above in green, and the space between y = 1 and the values under in red. I tried geom_ribbon, geom_area, geom_polynom, but nothing worked. The biggest problem is, that it fills the space green, but not online above y = 1 but also under. and the red you can't even see...

here what I tried:

geom_area(data = subset(microsoft, change.pc > 1), fill = "green", alpha =0.5)
geom_area(data = subset(microsoft, change.pc < 1), fill = "red", alpha = 0.5)

I put these to lines in my plot, and then the problem I described above appeared.

Among other things I also tried this (found here on stackoverflow.com):

microsoft$grp <- "orig"
microsoft <- microsoft[order(microsoft$time),]
microsoft_new <- do.call("rbind",
             sapply(1:(nrow(microsoft) -1), function(i){
               f <- lm(time ~ change.pc, microsoft[i:(i+1), ])
               if (f$qr$rank < 2) return(NULL)
               r <- predict(f, newdata = data.frame(change.pc = 0))
               if(microsoft[i, ]$time < r & r < microsoft[i+1, ]$time)
                 return(data.frame(time = r, change.pc = 0))
               else return(NULL)
             })
)
microsoft_2 <- rbind(microsoft, microsoft_new)
ggplot(microsoft_2, aes(x = time, y = change.pc)) +
  geom_area(data = subset(microsoft_2, change.pc <= 1), fill = "red") +
  geom_area(data = subset(microsoft_2, change.pc >= 1), fill = "blue") +
  scale_x_continuous("", expand = c(0,0), breaks = seq(1999, 2017, 3)) +
  theme_bw()

That didn't work either.
Does anyone has an idea how I could achieve what I need?
This is how it should look

Body:
I couldn't get your data to work, but using some made up data, the following approach looks like your example:

library(ggplot2)
set.seed(0)
microsoft <- data.frame(date=1:1000, y=cumsum(runif(1000)-0.5))

ggplot(microsoft, aes(x=date,y=y)) +
geom_ribbon(aes(ymin=pmin(microsoft$y,0), ymax=0), fill="red", col="red", alpha=0.5) +
geom_ribbon(aes(ymin=0, ymax=pmax(microsoft$y,0)), fill="green", col="green", alpha=0.5) +
geom_line(aes(y=0))

ContentLicense: CC BY-SA 4.0


问:
component props destructuring error
I am trying to use the flowing code in my component, I keep getting the error:

Unexpected token (9:8), which if the return statement.

Can anyone help?

```<code>export class Flexible extends React.Component {

  const { style, children, ...rest } = this.props;
  return <View {...rest} style={styles.flexible}>{children}</View>;
}
</code>```

答:
You're creating a class, which only accepts properties and functions.

It looks like you are trying to create the render method - let's do that then:

```<code>export class Flexible extends React.Component {
  render() {
    const { style, children, ...rest } = this.props;
    return <View {...rest} style={styles.flexible}>{children}</View>;
  }
}
</code>```

If you don't need state or any of the life cycle functions (componentWillMount etc), you can get away with just creating a functional component:

```<code>export const Flexible = (props) => {
  const { style, children, ...rest } = props;
  return <View {...rest} style={styles.flexible}>{children}</View>;
};
</code>```

It's understandable to get the two mixed up - they do look kind of similar to the untrained eye :)

Hope this fixed your issue!

Title: component props destructuring error

Body:
I am trying to use the flowing code in my component, I keep getting the error:

Unexpected token (9:8), which if the return statement.

Can anyone help?

export class Flexible extends React.Component {

  const { style, children, ...rest } = this.props;
  return <View {...rest} style={styles.flexible}>{children}</View>;
}

Body:
You're creating a class, which only accepts properties and functions.

It looks like you are trying to create the render method - let's do that then:

export class Flexible extends React.Component {
  render() {
    const { style, children, ...rest } = this.props;
    return <View {...rest} style={styles.flexible}>{children}</View>;
  }
}

If you don't need state or any of the life cycle functions (componentWillMount etc), you can get away with just creating a functional component:

export const Flexible = (props) => {
  const { style, children, ...rest } = props;
  return <View {...rest} style={styles.flexible}>{children}</View>;
};

It's understandable to get the two mixed up - they do look kind of similar to the untrained eye :)

Hope this fixed your issue!