问:
How to use devise in an other model?
I'm trying to implement devise login into a nav, but I'm facing to an error that I can't solve. When i'm submit my form to run the connection, I have this error :

```<code>No route matches [POST] "/login"
</code>```

So I followed this wiki/devise which deals with the subject. But is not working with the line :

```<code>helper_method :resource_name, :resource, :devise_mapping
</code>```

I have this error :

undefined method `helper_method' for PlainpageHelper:Module

For my last attempt, i'd try to add this lines into my routes file, but it's still not working

```<code>get 'login', to: 'sessions#new', as: 'login'
get 'logout', to: 'sessions#destroy', as: 'logout'
get 'signup', to: 'users#new', as: 'signup'
</code>```

My code :

My app (views/layout/application) =

```<code>  <%- if user_signed_in? %>
    <%= render 'partial/_connected'%>
  <% else %>
    <%= render 'partial/_disconnected'%>
  <% end %>
</code>```

My form (views/partial/_disconnected) =

```<code><li>
   <div class="row">
      <div class="col-md-12">
        Connection via
        <div class="social-buttons">
          <a href="#" class="btn btn-fb"><i class="fa fa-facebook"></i> Facebook</a>
          <a href="#" class="btn btn-tw"><i class="fa fa-twitter"></i> Twitter</a>
        </div>

         <form class="form" role="form" method="post" action="login" accept-charset="UTF-8" id="login-nav">
            <%= simple_form_for(resource, url: session_path(resource_name)) do |f| %>

              <div class="form-group">
                <%= f.input :email, required: false, autofocus: true %>
              </div>
              <div class="form-group">
                <%= f.input :password, required: false %>
              </div>

              <div class="form-group">
                <%= f.submit "Connection", class: "btn btn-success" %>
              </div>
              <div class="checkbox">
                <%= f.input :remember_me, as: :boolean if devise_mapping.rememberable? %>
              </div>
            <% end %>
         </form>
      </div>
      <div class="bottom text-center">
        New here ? <a href="#"><b>Join Us</b></a>
      </div>
   </div>
</li>
</code>```

The plain page helper :

```<code>module PlainpageHelper

  def resource_name
    :user
  end

  def resource
    @resource ||= User.new
  end

  def devise_mapping
    @devise_mapping ||= Devise.mappings[:user]
  end

end
</code>```

And finally my routes :

```<code>devise_for :users

  get 'plainpage/index'

  authenticated :user do
    root to: "plainpage#home", as: :authenticated_root
  end

  unauthenticated do
    root 'plainpage#index'
  end
</code>```

So if you have any idea to solve this error, you'll be my hero !!
Thanks all, and good continuation !!

答:
Remove <form class="form" role="form" method="post" action="login" accept-charset="UTF-8" id="login-nav">, the simple_form_for will generate form tag, so it's duplicated.

And there is no need to add resource_name, resource, devise_mapping in module PlainpageHelper

Title: How to use devise in an other model?

Body:
I'm trying to implement devise login into a nav, but I'm facing to an error that I can't solve. When i'm submit my form to run the connection, I have this error :

No route matches [POST] "/login"

So I followed this wiki/devise which deals with the subject. But is not working with the line :

helper_method :resource_name, :resource, :devise_mapping

I have this error :

undefined method `helper_method' for PlainpageHelper:Module

For my last attempt, i'd try to add this lines into my routes file, but it's still not working

get 'login', to: 'sessions#new', as: 'login'
get 'logout', to: 'sessions#destroy', as: 'logout'
get 'signup', to: 'users#new', as: 'signup'

My code :

My app (views/layout/application) =

  <%- if user_signed_in? %>
    <%= render 'partial/_connected'%>
  <% else %>
    <%= render 'partial/_disconnected'%>
  <% end %>

My form (views/partial/_disconnected) =

        Connection via

           Facebook
           Twitter

         <form class="form" role="form" method="post" action="login" accept-charset="UTF-8" id="login-nav">
            <%= simple_form_for(resource, url: session_path(resource_name)) do |f| %>

                <%= f.input :email, required: false, autofocus: true %>

                <%= f.input :password, required: false %>

                <%= f.submit "Connection", class: "btn btn-success" %>

                <%= f.input :remember_me, as: :boolean if devise_mapping.rememberable? %>

            <% end %>
         </form>

        New here ? Join Us

The plain page helper :

module PlainpageHelper

  def resource_name
    :user
  end

  def resource
    @resource ||= User.new
  end

  def devise_mapping
    @devise_mapping ||= Devise.mappings[:user]
  end

end

And finally my routes :

devise_for :users

  get 'plainpage/index'

  authenticated :user do
    root to: "plainpage#home", as: :authenticated_root
  end

  unauthenticated do
    root 'plainpage#index'
  end

So if you have any idea to solve this error, you'll be my hero !!
Thanks all, and good continuation !!


来源: stackexchange

问:
ng-repeat for json object not working
This is my html and it would create profiles per reponse it gets from the $http.get service.

```<code> <div class="container" ng-controller="profileController" ng-init="loadProfilesData()">
<div ng-repeat="p in profileData">

<div>{{p.company}}</div>
 <div>{{p.country}}</div>

<div gauge-chart class="gauge" id="first-{{p.Id}}" value=p.value*100 min=0 max=100 gauge-width-scale=0.8 title=""
donut=false relative-gauge-size=true symbol='%' hide-min-max=true></div>

<div gauge-chart class="gauge" id="second-{{p.Id}}" value=p.value*100 min=0 max=100 gauge-width-scale=0.8 title=""
donut=false relative-gauge-size=true symbol='%' hide-min-max=true></div>

<span>

{{ p.value | date: "hh:mm:ss" }}

</span>
</div>
  </div>
</code>```

The reponse i get is like below

```<code>     {
                   ID: "1",
                   employeeList: {
                      [{"Value":0.003,"Stat":{"parameter":0,"Name":"test0","Tag":"Devo100"}},
{"Value":0.004,"Stat":{"parameter":0,"Name":"test1","Tag":"Devo101"},
{"Value":0.005,"Stat":{"parameter":0,"Name":"test2","Tag":"Devo102"}]
                   },
                   comapny: "MSDFT",
                   department: "Sales",
                   country: "USA"

                },
                {
                   ID: "2",
                   employeeList: null,
                   comapny: "MSDFT",
                   department: "Sales",
                   country: "USA"

                },
                {
                   ID: "3",
                   employeeList: [{"Value":0.003,"Stat":{"parameter":0,"Name":"test0","Tag":"Devo100"}},
{"Value":0.004,"Stat":{"parameter":0,"Name":"test1","Tag":"Devo101"}],
                   comapny: "MSDFT",
                   department: "Sales",
                   country: "USA"

                }
</code>```

Since im getting inner list for name, value and sometimes i get this list employeeList empty. Do i need to have another ng-repeat for employeeList. Please suggest how can i bind since ordering is also random.

答:
You do not need to have another ng-repeat since employeeList is an object.

You could just access it like,

```<code><div>
    <span>{{p.employeeList.Name }}</span>
    <span>{{p.employeeList.Age}}</span>
    <span>{{p.employeeList.hireDate}}</span>
</div>
</code>```

var myApp = angular.module('myApp', [])
myApp.controller('profileController', function ($scope) {
    $scope.profilesData = [{
            ID: "1",
            employeeList: {
                Name: "harry",
                Age: "20",
                hireDate: 236558.189280
            },
            comapny: "MSDFT",
            department: "Sales",
            country: "USA"

        },
        {
            ID: "2",
            employeeList: null,
            comapny: "MSDFT",
            department: "Sales",
            country: "USA"

        },
        {
            ID: "3",
            employeeList: {
                hireDate: "",
                Name: "marry",
                Age: ""

            },
            comapny: "MSDFT",
            department: "Sales",
            country: "USA"

        }
    ];

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app='myApp'>
    <div class="container" ng-controller="profileController">
                    <div ng-repeat="p in profilesData">
                        <span>{{ p.ID }}</span>
                        <div>
                            <div>{{p.Name}}</div>
                            <div>{{p.Age}}</div>
                        </div>
                        <hr />
                        <div>
                            <span>
                            {{ p.hireDate | date: "hh:mm:ss" }}</span>
                        </div>
                        <hr />
                        <div>
                            <span>Company</span>
                            <span>Department</span>
                            <span>Country</span>
                        </div>
                        <div>
                            <span>{{p.company }}</span>
                            <span>{{p.department}}</span>
                            <span>{{p.country}}</span>
                        </div>
                         <div  ng-if="p.employeeList">
                            <span>{{p.employeeList.Name }}</span>
                            <span>{{p.employeeList.Age}}</span>
                            <span>{{p.employeeList.hireDate}}</span>
                        </div>
                    </div>
                </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Title: ng-repeat for json object not working

Body:
This is my html and it would create profiles per reponse it gets from the $http.get service.

{{p.company}}

{{p.country}}

{{ p.value | date: "hh:mm:ss" }}

The reponse i get is like below

     {
                   ID: "1",
                   employeeList: {
                      [{"Value":0.003,"Stat":{"parameter":0,"Name":"test0","Tag":"Devo100"}},
{"Value":0.004,"Stat":{"parameter":0,"Name":"test1","Tag":"Devo101"},
{"Value":0.005,"Stat":{"parameter":0,"Name":"test2","Tag":"Devo102"}]
                   },
                   comapny: "MSDFT",
                   department: "Sales",
                   country: "USA"

                },
                {
                   ID: "2",
                   employeeList: null,
                   comapny: "MSDFT",
                   department: "Sales",
                   country: "USA"

                },
                {
                   ID: "3",
                   employeeList: [{"Value":0.003,"Stat":{"parameter":0,"Name":"test0","Tag":"Devo100"}},
{"Value":0.004,"Stat":{"parameter":0,"Name":"test1","Tag":"Devo101"}],
                   comapny: "MSDFT",
                   department: "Sales",
                   country: "USA"

                }

Since im getting inner list for name, value and sometimes i get this list employeeList empty. Do i need to have another ng-repeat for employeeList. Please suggest how can i bind since ordering is also random.

Body:
You do not need to have another ng-repeat since employeeList is an object.

You could just access it like,

<div>
    <span>{{p.employeeList.Name }}</span>
    <span>{{p.employeeList.Age}}</span>
    <span>{{p.employeeList.hireDate}}</span>
</div>

var myApp = angular.module('myApp', [])
myApp.controller('profileController', function ($scope) {
    $scope.profilesData = [{
            ID: "1",
            employeeList: {
                Name: "harry",
                Age: "20",
                hireDate: 236558.189280
            },
            comapny: "MSDFT",
            department: "Sales",
            country: "USA"

        },
        {
            ID: "2",
            employeeList: null,
            comapny: "MSDFT",
            department: "Sales",
            country: "USA"

        },
        {
            ID: "3",
            employeeList: {
                hireDate: "",
                Name: "marry",
                Age: ""

            },
            comapny: "MSDFT",
            department: "Sales",
            country: "USA"

        }
    ];

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app='myApp'>
    <div class="container" ng-controller="profileController">
                    <div ng-repeat="p in profilesData">
                        <span>{{ p.ID }}</span>
                        <div>
                            <div>{{p.Name}}</div>
                            <div>{{p.Age}}</div>
                        </div>
                        <hr />
                        <div>
                            <span>
                            {{ p.hireDate | date: "hh:mm:ss" }}</span>
                        </div>
                        <hr />
                        <div>
                            <span>Company</span>
                            <span>Department</span>
                            <span>Country</span>
                        </div>
                        <div>
                            <span>{{p.company }}</span>
                            <span>{{p.department}}</span>
                            <span>{{p.country}}</span>
                        </div>
                         <div  ng-if="p.employeeList">
                            <span>{{p.employeeList.Name }}</span>
                            <span>{{p.employeeList.Age}}</span>
                            <span>{{p.employeeList.hireDate}}</span>
                        </div>
                    </div>
                </div>
</div>


问:
git - how to set a remote branch out of a branch in upstream?
Use case - I have a code base on github, which has several branches.
e.g. developer, integration, regression, production, etc.
I usually use this command to add remote branch: git remote add upstream <repo link>.git

So, git remote -v shows as below:

```<code>upstream        <repo link>.git (fetch)
upstream        <repo link>.git (push)
</code>```

but if remote has a branch then what command should I use to set to that branch to?

答:
To make a new remote branch to local, you can use git fetch.

After that, you will find the branch by git branch -a.

If you want to work on the new branch, just use git checkout branchname.

Body:
Use case - I have a code base on github, which has several branches.
e.g. developer, integration, regression, production, etc.
I usually use this command to add remote branch: git remote add upstream <repo link>.git

So, git remote -v shows as below:

upstream        <repo link>.git (fetch)
upstream        <repo link>.git (push)

but if remote has a branch then what command should I use to set to that branch to?


问:
Set max width and max height of image from Picasso. It's not working in Android Studio
I'm trying to set the Set max width and max height of an image from Picasso but for some reason it is not working.

Here is my code:

Picasso.with(this).load(imagePath).transform(new CircleTransform()).into(imageTest);

This is my xml:

```<code> <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:maxWidth="42dp"
    android:maxHeight="42dp"
    android:scaleType="fitCenter"
    android:id="@+id/imageTest"/>
</code>```

答:
use resize </p>

```<code>Picasso.with(this).load(imagePath).resize(42,42).transform(new CircleTransform().into(imageTest);
</code>```

Body:
I'm trying to set the Set max width and max height of an image from Picasso but for some reason it is not working.

Here is my code:

Picasso.with(this).load(imagePath).transform(new CircleTransform()).into(imageTest);

This is my xml:

 <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:maxWidth="42dp"
    android:maxHeight="42dp"
    android:scaleType="fitCenter"
    android:id="@+id/imageTest"/>

Body:
use resize

Picasso.with(this).load(imagePath).resize(42,42).transform(new CircleTransform().into(imageTest);


问:
Django 'AsgiRequest' object has no attribute 'content_type'
I am working on developing a django app named app, which is a part of a django project, but i am getting some problems when try to login admin.

```<code>import os

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

SECRET_KEY = 'something'

DEBUG = True

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'connections',
    'custom_user',
    'chat',
    'channels',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'testpoject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'traego.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'testproject',
        'USER': 'admin_testproject',
        'PASSWORD': 'passw123',
        'HOST': 'localhost',
        'PORT': '',
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_ROOT = os.path.join(BASE_DIR, "static")

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static-temp')]

STATIC_URL = '/static/'

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = '/home'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

AUTH_USER_MODEL = 'custom_user.EmailUser'

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "asgi_redis.RedisChannelLayer",
        "CONFIG": {
            "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
        },
        "ROUTING": "chat.routing.channel_routing",
    },
}

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'INFO'
        },
        'chat': {
            'handlers': ['console'],
            'propagate': False,
            'level': 'DEBUG',
        },
    },
}
</code>```

The error occurs when I try to login a super user create in shell by localhost:8000/admin/login/, it show error:

```<code>Internal Server Error: /admin/login/
</code>```

then show the traceback

```<code>[2017/04/01 23:58:36] HTTP GET /admin/ 302 [0.03, 127.0.0.1:45030]
[2017/04/01 23:58:36] HTTP GET /admin/login/ 200 [0.04, 127.0.0.1:45030]
Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
2017-04-01 23:58:42,380 - ERROR - exception - Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = response_for_exception(request, exc)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 86, in response_for_exception
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception
    return debug.technical_500_response(request, *exc_info)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 84, in technical_500_response
    html = reporter.get_traceback_html()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 328, in get_traceback_html
    c = Context(self.get_traceback_data(), use_l10n=False)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 304, in get_traceback_data
    'filtered_POST': self.filter.get_post_parameters(self.request),
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 167, in get_post_parameters
    return request.POST
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
2017-04-01 23:58:42,388 - ERROR - exception - Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
</code>```

This is my requirements.txt:

```<code>appdirs==1.4.2
Django==1.10.5
django-custom-user==0.7
packaging==16.8
psycopg2==2.6.2
pyparsing==2.1.10
six==1.10.0
Pillow==4.0.0
asgi-redis==0.8.3
asgiref==0.9
autobahn==0.12.1
channels==0.9.3
daphne==0.9.1
haikunator==1.0.1
msgpack-python==0.4.7
redis==2.10.5
six==1.10.0
Twisted==15.5.0
txaio==2.2.1
wheel==0.24.0
zope.interface==4.1.3
</code>```

Is there a good way to solve the problem?
The rarest thing is that until yesterday it worked correctly and today I did not make any changes and it does not work

答: Try upgrading django channels version to 1.1.2, 0.9.3 is a beta.</p>

Body:
I am working on developing a django app named app, which is a part of a django project, but i am getting some problems when try to login admin.

import os

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

SECRET_KEY = 'something'

DEBUG = True

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'connections',
    'custom_user',
    'chat',
    'channels',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'testpoject.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'traego.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'testproject',
        'USER': 'admin_testproject',
        'PASSWORD': 'passw123',
        'HOST': 'localhost',
        'PORT': '',
    }
}

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_ROOT = os.path.join(BASE_DIR, "static")

STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static-temp')]

STATIC_URL = '/static/'

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = '/home'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

AUTH_USER_MODEL = 'custom_user.EmailUser'

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "asgi_redis.RedisChannelLayer",
        "CONFIG": {
            "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
        },
        "ROUTING": "chat.routing.channel_routing",
    },
}

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'INFO'
        },
        'chat': {
            'handlers': ['console'],
            'propagate': False,
            'level': 'DEBUG',
        },
    },
}

The error occurs when I try to login a super user create in shell by localhost:8000/admin/login/, it show error:

Internal Server Error: /admin/login/

then show the traceback

[2017/04/01 23:58:36] HTTP GET /admin/ 302 [0.03, 127.0.0.1:45030]
[2017/04/01 23:58:36] HTTP GET /admin/login/ 200 [0.04, 127.0.0.1:45030]
Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
2017-04-01 23:58:42,380 - ERROR - exception - Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/utils/deprecation.py", line 136, in __call__
    response = self.get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = response_for_exception(request, exc)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 86, in response_for_exception
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception
    return debug.technical_500_response(request, *exc_info)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 84, in technical_500_response
    html = reporter.get_traceback_html()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 328, in get_traceback_html
    c = Context(self.get_traceback_data(), use_l10n=False)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 304, in get_traceback_data
    'filtered_POST': self.filter.get_post_parameters(self.request),
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/views/debug.py", line 167, in get_post_parameters
    return request.POST
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'
2017-04-01 23:58:42,388 - ERROR - exception - Internal Server Error: /admin/login/
Traceback (most recent call last):
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner
    response = get_response(request)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 178, in _get_response
    response = middleware_method(request, callback, callback_args, callback_kwargs)
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/middleware/csrf.py", line 260, in process_view
    request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/channels/handler.py", line 119, in _get_post
    self._load_post_and_files()
  File "/home/mrc/.virtualenvs/djangotest/local/lib/python3.5/site-packages/django/http/request.py", line 292, in _load_post_and_files
    if self.content_type == 'multipart/form-data':
AttributeError: 'AsgiRequest' object has no attribute 'content_type'

This is my requirements.txt:

appdirs==1.4.2
Django==1.10.5
django-custom-user==0.7
packaging==16.8
psycopg2==2.6.2
pyparsing==2.1.10
six==1.10.0
Pillow==4.0.0
asgi-redis==0.8.3
asgiref==0.9
autobahn==0.12.1
channels==0.9.3
daphne==0.9.1
haikunator==1.0.1
msgpack-python==0.4.7
redis==2.10.5
six==1.10.0
Twisted==15.5.0
txaio==2.2.1
wheel==0.24.0
zope.interface==4.1.3

Is there a good way to solve the problem?
The rarest thing is that until yesterday it worked correctly and today I did not make any changes and it does not work


问:
Rails: How to sort/re-order an OrderedHash
I have an OrderedHash, generated from the answer here that looks like this:

```<code><OrderedHash {2=>"534.45",7=>"10",153=>"85.0"}>
</code>```

So, I need to sort the hash by the second value, in descending order.  I tried this:

```<code>var.sort! {|a,b| b[1] <=> a[1]}
NoMethodError: undefined method `sort!' for #<ActiveSupport::OrderedHash:0x127a50848>
</code>```

How can I reorder this OrderedHash?

答:
Well, I think you can simply use :order => 'sum_deal_price ASC' in the sum call of the original answer.

But you can also do it in Ruby, it's just a bit trickier:

```<code># You can't sort a Hash directly, so turn it into an Array.
arr = var.to_a  # => [[2, "534.45"], [7, "10"], [153, "85.0"]]
# Looks like there's a bunch of floats-as-strings in there, fix that.
arr.map! { |pair| [pair.first, pair.second.to_f] }
# Now sort it by the value (which is the second entry of the pair).
arr.sort! { |a, b| a.second <=> b.second }
# Turn it back into an OrderedHash.
sorted_hash = ActiveSupport::OrderedHash[arr]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have an OrderedHash, generated from the answer here that looks like this:

<OrderedHash {2=>"534.45",7=>"10",153=>"85.0"}>

So, I need to sort the hash by the second value, in descending order.  I tried this:

var.sort! {|a,b| b[1] <=> a[1]}
NoMethodError: undefined method `sort!' for #<ActiveSupport::OrderedHash:0x127a50848>

How can I reorder this OrderedHash?

Body:
Well, I think you can simply use :order => 'sum_deal_price ASC' in the sum call of the original answer.

But you can also do it in Ruby, it's just a bit trickier:

# You can't sort a Hash directly, so turn it into an Array.
arr = var.to_a  # => [[2, "534.45"], [7, "10"], [153, "85.0"]]
# Looks like there's a bunch of floats-as-strings in there, fix that.
arr.map! { |pair| [pair.first, pair.second.to_f] }
# Now sort it by the value (which is the second entry of the pair).
arr.sort! { |a, b| a.second <=> b.second }
# Turn it back into an OrderedHash.
sorted_hash = ActiveSupport::OrderedHash[arr]


问:
How can I edit the original array throughout all of my functions C++
I'm trying to create a sodoku program and I need to find a way to edit the same array in all of my functions. I have read that pointers can be used for this but I do not really know how to use pointers very well.</p>

```<code>#include <iostream>
#include <fstream>
using namespace std;

char upperCase(char letter)
{
   int decVal = (int) letter;
   if (decVal >= 97 && decVal <= 122)
      decVal -= 32;
   letter = (char) decVal;
   return letter;
}

void readFile(int board[9][9])
{
   char fileName[256];
   int row = 0;
   int col = 0;
   cout << "Where is your board located? ";
   cin >> fileName;
   ifstream fin(fileName);
   while (fin >> board[row][col])
   {
      col++;
      if (col == 9)
      {
         row++;
         col = 0;
      }
   }

}

void displayOptions()
{
   cout << "Options:" << endl;
   cout << "   ?  Show these instructions" << endl;
   cout << "   D  Display the board" << endl;
   cout << "   E  Edit one square" << endl;
   cout << "   S  Show the possible values for a square" << endl;
   cout << "   Q  Save and quit" << endl;
   cout << endl;
}

void displayBoard(int board[9][9])
{
   int row = 0;
   int col = 0;
   int rowNum = 1;
   bool onSide = true;
   cout << "   A B C D E F G H I" << endl;
   while (row <= 8)
   {
      if ((row == 3 || row == 6) && col == 0)
         cout << "   -----+-----+-----" << endl;

      if (onSide)
      {
         cout << rowNum << " ";
         onSide = false;
      }

      if (col == 3 || col == 6)
         cout << "|";
      else
         cout << " ";

      if (board[row][col] == 0)
         cout << " ";
      else
         cout << board[row][col];
      col++;

      if (col == 9)
      {
         row++;
         col = 0;
         rowNum++;
         onSide = true;
         cout << endl;
      }
   }
}

void editSquare(int board[9][9])
{
   char cord[2];
   int row;
   int col;
   bool run = true;
   bool fail = false;
   while (run)
   {
      run = false;
      fail = false;
      cout << "What are the coordinates of the square: ";
      cin >> cord;

      if (cord[0] == 'A' || cord[0] == 'a')
         row = 0;
      else if (cord[0] == 'B' || cord[0] == 'b')
         row = 1;
      else if (cord[0] == 'C' || cord[0] == 'c')
         row = 2;
      else if (cord[0] == 'D' || cord[0] == 'd')
         row = 3;
      else if (cord[0] == 'E' || cord[0] == 'e')
         row = 4;
      else if (cord[0] == 'F' || cord[0] == 'f')
         row = 5;
      else if (cord[0] == 'G' || cord[0] == 'g')
         row = 6;
      else if (cord[0] == 'H' || cord[0] == 'h')
         row = 7;
      else if (cord[0] == 'I' || cord[0] == 'i')
         row = 8;
      else
      {
         cout << "ERROR: Square '";
         for (int i = 0; i < 2; i++)
            cout << cord[i];
         cout << "' is invalid" << endl;
         run = true;
         fail = true;
      }

      if (!fail)
      {
         if (cord[1] == '1')
            col = 0;
         else if (cord[1] == '2')
            col = 1;
         else if (cord[1] == '3')
            col = 2;
         else if (cord[1] == '4')
            col = 3;
         else if (cord[1] == '5')
            col = 4;
         else if (cord[1] == '6')
            col = 5;
         else if (cord[1] == '7')
            col = 6;
         else if (cord[1] == '8')
            col = 7;
         else if (cord[1] == '9')
            col = 8;
         else
         {
            cout << "ERROR: Square '";
            for (int i = 0; i < 2; i++)
               cout << cord[i];
            cout << "' is invalid" << endl;
            run = true;
         }
      }
   }

   cord[0] = upperCase(cord[0]);

   if (board[row][col] == 0)
   {
      int number;
      cout << "What is the value at '";
      for (int i = 0; i < 2; i++)
         cout << cord[i];
      cout << "': ";
      cin >> number;
      if (number >= 0 && number <= 9)
         board[row][col] = number;
      else
      {
         cout << "ERROR: Value '" << number << "' in square '";
         for (int i = 0; i < 2; i++)
            cout << cord[i];
         cout << "' is invalid" << endl;
      }
   }
   else
   {
      cout << "ERROR: Square '";
      for (int i = 0; i < 2; i++)
         cout << cord[i];
      cout << "' is filled" << endl;
   }
}

bool writeFile(int board[9][9])
{
   int row = 0;
   int col = 0;
   char fileName[256];
   cout << "What file would you like to write your board to: ";
   cin >> fileName;
   ofstream fout(fileName);
   while (row <= 8)
   {
      fout << board[row][col] << " ";
      col++;
      if (col == 9)
      {
         row++;
         col = 0;
         fout << endl;
      }
   }
   cout << "Board written successfully" << endl;
   return false;
}

bool getCommand(int board[9][9])
{
   bool run = true;
   char input;
   cout << endl << "> ";
   cin >> input;

   input = upperCase(input);

   if (input == '?')
      displayOptions();
   else if (input == 'D')
      displayBoard(board);
   else if (input == 'E')
      editSquare(board);
   else if (input == 'S');
   else if (input == 'Q')
   {
      run = writeFile(board);
   }
   else
      cout << "ERROR: Invalid command" << endl;

   return run;
}

int main()
{
   bool run = true;
   int board[9][9];
   readFile(board);
   displayOptions();
   displayBoard(board);
   while (run)
      run = getCommand(board);
   return 0;
}
</code>```

答:
You shouldn't  pass uniform-dimension arrays in this fashion:

```<code>bool writeFile(int board[9][9]);
</code>```

you initialize your array ONCE:

```<code>int board[9][9];
</code>```

Then, you pass it to a method,specifying how long each row is, aka the column count ONLY, in the case of a 2D construct. Such a method signature would look like this:

```<code>bool writeFile(int board[][9]);
</code>```

Within writeFile, board IS the same array you passed in, NOT a copy by value to which you may be accustomed.
If you use c style arrays, you're using pointers whether you like it or not, because all an array variable in fact is IS a pointer to the first array element. For example:

```<code>//given
int array[9];
//array can be passed into a method signed "void DoSomethingWithArray(int* array);
//or a method signed "void DoSomethingWithArray(int array[]);
</code>```

and all changes made in such a method affect array, the original declaration variable.

In the case of passing a 2D array, "board" in your case, the parameter board decays into(is programtically) a pointer to an int array, aka a pointer to the first row of your construct, which in turn is a pointer to the first element(int) of your construct. This fact shouldn't overtly matter, because you can double subscript it to access any elements in the familiar way. Knowing this is important though, as you wouldn't wonder how to manipulate the same array in various functions once you know that the way they get there is by address, not by value.

One additional note that may shed light on some of these points:

```<code>array[1];
//is the same as
*(array + 1);
//take the address of the first array element, move index*sizeof(elementT) addresses forward,
 //and then dereference. [] is just a syntactical abstraction of this behavior.
</code>```

Body:
I'm trying to create a sodoku program and I need to find a way to edit the same array in all of my functions. I have read that pointers can be used for this but I do not really know how to use pointers very well.

#include <iostream>
#include <fstream>
using namespace std;

char upperCase(char letter)
{
   int decVal = (int) letter;
   if (decVal >= 97 && decVal <= 122)
      decVal -= 32;
   letter = (char) decVal;
   return letter;
}

void readFile(int board[9][9])
{
   char fileName[256];
   int row = 0;
   int col = 0;
   cout << "Where is your board located? ";
   cin >> fileName;
   ifstream fin(fileName);
   while (fin >> board[row][col])
   {
      col++;
      if (col == 9)
      {
         row++;
         col = 0;
      }
   }

}

void displayOptions()
{
   cout << "Options:" << endl;
   cout << "   ?  Show these instructions" << endl;
   cout << "   D  Display the board" << endl;
   cout << "   E  Edit one square" << endl;
   cout << "   S  Show the possible values for a square" << endl;
   cout << "   Q  Save and quit" << endl;
   cout << endl;
}

void displayBoard(int board[9][9])
{
   int row = 0;
   int col = 0;
   int rowNum = 1;
   bool onSide = true;
   cout << "   A B C D E F G H I" << endl;
   while (row <= 8)
   {
      if ((row == 3 || row == 6) && col == 0)
         cout << "   -----+-----+-----" << endl;

      if (onSide)
      {
         cout << rowNum << " ";
         onSide = false;
      }

      if (col == 3 || col == 6)
         cout << "|";
      else
         cout << " ";

      if (board[row][col] == 0)
         cout << " ";
      else
         cout << board[row][col];
      col++;

      if (col == 9)
      {
         row++;
         col = 0;
         rowNum++;
         onSide = true;
         cout << endl;
      }
   }
}

void editSquare(int board[9][9])
{
   char cord[2];
   int row;
   int col;
   bool run = true;
   bool fail = false;
   while (run)
   {
      run = false;
      fail = false;
      cout << "What are the coordinates of the square: ";
      cin >> cord;

      if (cord[0] == 'A' || cord[0] == 'a')
         row = 0;
      else if (cord[0] == 'B' || cord[0] == 'b')
         row = 1;
      else if (cord[0] == 'C' || cord[0] == 'c')
         row = 2;
      else if (cord[0] == 'D' || cord[0] == 'd')
         row = 3;
      else if (cord[0] == 'E' || cord[0] == 'e')
         row = 4;
      else if (cord[0] == 'F' || cord[0] == 'f')
         row = 5;
      else if (cord[0] == 'G' || cord[0] == 'g')
         row = 6;
      else if (cord[0] == 'H' || cord[0] == 'h')
         row = 7;
      else if (cord[0] == 'I' || cord[0] == 'i')
         row = 8;
      else
      {
         cout << "ERROR: Square '";
         for (int i = 0; i < 2; i++)
            cout << cord[i];
         cout << "' is invalid" << endl;
         run = true;
         fail = true;
      }

      if (!fail)
      {
         if (cord[1] == '1')
            col = 0;
         else if (cord[1] == '2')
            col = 1;
         else if (cord[1] == '3')
            col = 2;
         else if (cord[1] == '4')
            col = 3;
         else if (cord[1] == '5')
            col = 4;
         else if (cord[1] == '6')
            col = 5;
         else if (cord[1] == '7')
            col = 6;
         else if (cord[1] == '8')
            col = 7;
         else if (cord[1] == '9')
            col = 8;
         else
         {
            cout << "ERROR: Square '";
            for (int i = 0; i < 2; i++)
               cout << cord[i];
            cout << "' is invalid" << endl;
            run = true;
         }
      }
   }

   cord[0] = upperCase(cord[0]);

   if (board[row][col] == 0)
   {
      int number;
      cout << "What is the value at '";
      for (int i = 0; i < 2; i++)
         cout << cord[i];
      cout << "': ";
      cin >> number;
      if (number >= 0 && number <= 9)
         board[row][col] = number;
      else
      {
         cout << "ERROR: Value '" << number << "' in square '";
         for (int i = 0; i < 2; i++)
            cout << cord[i];
         cout << "' is invalid" << endl;
      }
   }
   else
   {
      cout << "ERROR: Square '";
      for (int i = 0; i < 2; i++)
         cout << cord[i];
      cout << "' is filled" << endl;
   }
}

bool writeFile(int board[9][9])
{
   int row = 0;
   int col = 0;
   char fileName[256];
   cout << "What file would you like to write your board to: ";
   cin >> fileName;
   ofstream fout(fileName);
   while (row <= 8)
   {
      fout << board[row][col] << " ";
      col++;
      if (col == 9)
      {
         row++;
         col = 0;
         fout << endl;
      }
   }
   cout << "Board written successfully" << endl;
   return false;
}

bool getCommand(int board[9][9])
{
   bool run = true;
   char input;
   cout << endl << "> ";
   cin >> input;

   input = upperCase(input);

   if (input == '?')
      displayOptions();
   else if (input == 'D')
      displayBoard(board);
   else if (input == 'E')
      editSquare(board);
   else if (input == 'S');
   else if (input == 'Q')
   {
      run = writeFile(board);
   }
   else
      cout << "ERROR: Invalid command" << endl;

   return run;
}

int main()
{
   bool run = true;
   int board[9][9];
   readFile(board);
   displayOptions();
   displayBoard(board);
   while (run)
      run = getCommand(board);
   return 0;
}

Body:
You shouldn't  pass uniform-dimension arrays in this fashion:

bool writeFile(int board[9][9]);

you initialize your array ONCE:

int board[9][9];

Then, you pass it to a method,specifying how long each row is, aka the column count ONLY, in the case of a 2D construct. Such a method signature would look like this:

bool writeFile(int board[][9]);

Within writeFile, board IS the same array you passed in, NOT a copy by value to which you may be accustomed.
If you use c style arrays, you're using pointers whether you like it or not, because all an array variable in fact is IS a pointer to the first array element. For example:

//given
int array[9];
//array can be passed into a method signed "void DoSomethingWithArray(int* array);
//or a method signed "void DoSomethingWithArray(int array[]);

and all changes made in such a method affect array, the original declaration variable.

In the case of passing a 2D array, "board" in your case, the parameter board decays into(is programtically) a pointer to an int array, aka a pointer to the first row of your construct, which in turn is a pointer to the first element(int) of your construct. This fact shouldn't overtly matter, because you can double subscript it to access any elements in the familiar way. Knowing this is important though, as you wouldn't wonder how to manipulate the same array in various functions once you know that the way they get there is by address, not by value.

One additional note that may shed light on some of these points:

array[1];
//is the same as
*(array + 1);
//take the address of the first array element, move index*sizeof(elementT) addresses forward,
 //and then dereference. [] is just a syntactical abstraction of this behavior.


答:
use ng-if to check the property is null or not

```<code><div ng-if="p.employeeList">
     <span>{{p.employeeList.Name }}</span>
     <span>{{p.employeeList.Age}}</span>
     <span>{{p.employeeList.hireDate | date: "hh:mm:ss"}}              </span>
</div>
</code>```

angular.module("app",[])
.controller("ctrl",function($scope){

  $scope.profilesData = [ {
   ID: "1",
   employeeList: {
      Name: "harry",
      Age:   "20",
      hireDate: 236558.189280
   },
   comapny: "MSDFT",
   department: "Sales",
   country: "USA"

},
{
   ID: "2",
   employeeList: null,
   comapny: "MSDFT",
   department: "Sales",
   country: "USA"

},
{
   ID: "3",
   employeeList: {
      hireDate: "",
      Name: "marry",
      Age:   ""

   },
   comapny: "MSDFT",
   department: "Sales",
   country: "USA"

}]

})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div ng-repeat="p in profilesData">
    <span>{{ p.ID }}</span>
    <div>
        <div>{{p.Name}}</div>
        <div>{{p.Age}}</div>
    </div>
    <hr />
    <div>
        <span>
        {{ p.hireDate | date: "hh:mm:ss" }}</span>
    </div>
    <hr />
    <div>
        <span>Company</span>
        <span>Department</span>
        <span>Country</span>
    </div>
    <div>
        <span>{{p.comapny }}</span>
        <span>{{p.department}}</span>
        <span>{{p.country}}</span>
    </div>
    <div ng-if="p.employeeList">
        <span>{{p.employeeList.Name }}</span>
        <span>{{p.employeeList.Age}}</span>
        <span>{{p.employeeList.hireDate | date: "hh:mm:ss"}}              </span>
    </div>
  </div>
</div></code>```

Title: ng-repeat for json object not working

Body:
use ng-if to check the property is null or not

<div ng-if="p.employeeList">
     <span>{{p.employeeList.Name }}</span>
     <span>{{p.employeeList.Age}}</span>
     <span>{{p.employeeList.hireDate | date: "hh:mm:ss"}}              </span>
</div>

angular.module("app",[])
.controller("ctrl",function($scope){

  $scope.profilesData = [ {
   ID: "1",
   employeeList: {
      Name: "harry",
      Age:   "20",
      hireDate: 236558.189280
   },
   comapny: "MSDFT",
   department: "Sales",
   country: "USA"

},
{
   ID: "2",
   employeeList: null,
   comapny: "MSDFT",
   department: "Sales",
   country: "USA"

},
{
   ID: "3",
   employeeList: {
      hireDate: "",
      Name: "marry",
      Age:   ""

   },
   comapny: "MSDFT",
   department: "Sales",
   country: "USA"

}]

})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div ng-repeat="p in profilesData">
    <span>{{ p.ID }}</span>
    <div>
        <div>{{p.Name}}</div>
        <div>{{p.Age}}</div>
    </div>
    <hr />
    <div>
        <span>
        {{ p.hireDate | date: "hh:mm:ss" }}</span>
    </div>
    <hr />
    <div>
        <span>Company</span>
        <span>Department</span>
        <span>Country</span>
    </div>
    <div>
        <span>{{p.comapny }}</span>
        <span>{{p.department}}</span>
        <span>{{p.country}}</span>
    </div>
    <div ng-if="p.employeeList">
        <span>{{p.employeeList.Name }}</span>
        <span>{{p.employeeList.Age}}</span>
        <span>{{p.employeeList.hireDate | date: "hh:mm:ss"}}              </span>
    </div>
  </div>
</div>


问:
How to change 1,000,000 price to 1,XXX,XXX using php or javascript?
This is my source code:

```<code>preg_replace('/[A-Z0-9]/', 'X', number_format('1000000'));
</code>```

Result: x,xxx,xxx

But, I want the result like 1,xxx,xxx, i.e., don't replace the first number.

答:
Please use this code when you are using PHP:</p>

```<code><?php
$number  = '1000000';
$x = number_format($number);
echo $result = str_replace("0", "X", $x);
?>
</code>```

Body:
This is my source code:

preg_replace('/[A-Z0-9]/', 'X', number_format('1000000'));

Result: x,xxx,xxx

But, I want the result like 1,xxx,xxx, i.e., don't replace the first number.

Body:
Please use this code when you are using PHP:

<?php
$number  = '1000000';
$x = number_format($number);
echo $result = str_replace("0", "X", $x);
?>


问:
How to store a function and call it later in QML JavaScript
Here is part of code:

```<code>Repeater{
    model: [["Text A", function(){console.log("hello A")}],
            ["Text B", function(){console.log("hello B")}],
            ["Text C", function(){console.log("hello C")}],
            ["Text D", function(){console.log("hello D")}]]
    delegate: Button{
        text: modelData[0]
        onClicked: modelData[1](); // Type Error
    }
}
</code>```

I want give different behavior for each button. I think it's supposed to be same as native JavaScript.

```<code>var func = function(){
  //...
}
func();
</code>```

How to do this in QML JavaScript?

BTW, now my solution is:

```<code>Repeater{
    model: ["Text A",
            "Text B",
            "Text C",
            "Text D"]
    delegate: Button{
        text: modelData
        onClicked: {
           switch(index)
           {
              cast 0:
                console.log("hello A")
                break;
              cast 1:
                console.log("hello B")
                break;
              cast 2:
                console.log("hello C")
                break;
              cast 3:
                console.log("hello D")
                break;
           }
        }
    }
}
</code>```

答:
This looks like a bug to me, it just won't get to the function through the model interface. Or maybe a design limitation. As far as the function is concerned, it is undefined.

You could work around it like this:

```<code>  property var mod :
   [["Text A", function(){console.log("hello A")}],
    ["Text B", function(){console.log("hello B")}],
    ["Text C", function(){console.log("hello C")}],
    ["Text D", function(){console.log("hello D")}]]

  Column {
    Repeater {
      id: rep
      model: mod
      delegate: Button {
        text: modelData[0]
        onClicked: mod[index][1]()
      }
    }
  }
</code>```

Body:
Here is part of code:

Repeater{
    model: [["Text A", function(){console.log("hello A")}],
            ["Text B", function(){console.log("hello B")}],
            ["Text C", function(){console.log("hello C")}],
            ["Text D", function(){console.log("hello D")}]]
    delegate: Button{
        text: modelData[0]
        onClicked: modelData[1](); // Type Error
    }
}

I want give different behavior for each button. I think it's supposed to be same as native JavaScript.

var func = function(){
  //...
}
func();

How to do this in QML JavaScript?

BTW, now my solution is:

Repeater{
    model: ["Text A",
            "Text B",
            "Text C",
            "Text D"]
    delegate: Button{
        text: modelData
        onClicked: {
           switch(index)
           {
              cast 0:
                console.log("hello A")
                break;
              cast 1:
                console.log("hello B")
                break;
              cast 2:
                console.log("hello C")
                break;
              cast 3:
                console.log("hello D")
                break;
           }
        }
    }
}

Body:
This looks like a bug to me, it just won't get to the function through the model interface. Or maybe a design limitation. As far as the function is concerned, it is undefined.

You could work around it like this:

  property var mod :
   [["Text A", function(){console.log("hello A")}],
    ["Text B", function(){console.log("hello B")}],
    ["Text C", function(){console.log("hello C")}],
    ["Text D", function(){console.log("hello D")}]]

  Column {
    Repeater {
      id: rep
      model: mod
      delegate: Button {
        text: modelData[0]
        onClicked: mod[index][1]()
      }
    }
  }


答:
You don't need another ng-repeat for these fields. You can access the child JSON object like this: p.employeeList.hireDate

If a value might be null you could check using ng-if and choose whether or not you want to display the HTML.

Example:

```<code><div ng-repeat="p in profilesData">
    <div>
        <span ng-if="p.employeeList != null">{{ p.employeeList.hireDate | date: "hh:mm:ss" }}</span>
    </div>
</div>
</code>```

Title: ng-repeat for json object not working

Body:
You don't need another ng-repeat for these fields. You can access the child JSON object like this: p.employeeList.hireDate

If a value might be null you could check using ng-if and choose whether or not you want to display the HTML.

Example:

<div ng-repeat="p in profilesData">
    <div>
        <span ng-if="p.employeeList != null">{{ p.employeeList.hireDate | date: "hh:mm:ss" }}</span>
    </div>
</div>


问:
Is there a way for users of my website to invite their friends via Facebook Connect or the API?
Working with the Facebook API makes my ears bleed, but nonetheless I've got a specific problem here which I'm hoping someone can find a solution for. I'm using the Facebook PHP SDK to allow users of my website to link their FB account with their website account, so they can return later and log in with one click (by storing their OAuth tokens in my database). This is all working fine - what I now want is to be able to provide users with the facility to invite/recommend their friends to my site, using a form on my site.

I've tried FBML examples from many places including here - I've managed to get an invitation form to display but try as I might, all I can get it to generate is an invitation to my application, which isn't relevant. The app exists only so that I have an OAuth ID/secret to use with the Graph API. I want to invite the user's friends to my website, or at the very least to a Facebook Page plugging my website. But seemingly including this FBML on my page will only generate application invites.

My question: is there any way to accomplish this? Can I invite the user's friends to my site (ie. to a specific URL), or invite them to my FB Page? Am I approaching this from the wrong angle?

Any advice would be much appreciated. If you'd benefit from any further info, please let me know. Many thanks,

Biggs

答: Why not go for this open source inviter which can get your work done quick . also if you are using a cms they might have already made the plugin for your cms. http://openinviter.com/</p>


问:
API Management - Response Time
We are working on setting up an API Management portal for one of our Web API. We are using eventhubs for logging the events and we are transferring the event messages to Azure Blob storage using Azure functions.

We would like to know how can we find the Time taken by API Management portal for providing the response for a message (we are capturing the time taken at the back end api layer but not from the API Management layer).

Regards,

John

答:
The simpler solution is to enable Azure Monitor Diagnostic Logs for the Apimanagement service. You will get raw logs for each request including

durationMs - interval between receiving request line and headers from a client and writing last chunk of response body to a client. All writes and reads include network latency.

BackendTime - time spent waiting on backend response

ClientTime - time spent with client for request and response

CacheTime - time spent on fetching from cache

You can also refer this video.

Title: API Management - Response Time


问:
Ruby object oriented inheritance
I am writing a banking program. Already defined Bank class.

```<code>class Checking
    def initialize(initial_deposit)
        @number = Bank.size + 1
        @principal = initial_deposit.to_f
        @@intest_rate = 0.003
    end

    def balance
        principal = principal * (1 + interest_rate / 365 ) ** 365
    end
end

class Savings
    def initialize(initial_deposit)
        @number = Bank.size + 1
        @principal = initial_deposit.to_f
        @@interest_rate = 0.025
    end

    def balance
        principal = principal * (1 + interest_rate / 4) ** 4
    end
 end
</code>```

But keep getting error message.I'm pretty sure the issue is within Saving and Checking; when I press s or c, errors arise. Maybe someone could help find my error. Any help or advice would be appreciated.

答:
Can you post the Bank class code here. I think the issue could be in the Bank class, not sure why are you pressing 's' and 'c'. The above code doesn't take any input.

And I assume that the Bank class asks the user to select the account type  he need to create and in response to the key he presses, the Bank class might call the Saving and Checking class and create the account.

Title: Ruby object oriented inheritance

Body:
I am writing a banking program. Already defined Bank class.

class Checking
    def initialize(initial_deposit)
        @number = Bank.size + 1
        @principal = initial_deposit.to_f
        @@intest_rate = 0.003
    end

    def balance
        principal = principal * (1 + interest_rate / 365 ) ** 365
    end
end

class Savings
    def initialize(initial_deposit)
        @number = Bank.size + 1
        @principal = initial_deposit.to_f
        @@interest_rate = 0.025
    end

    def balance
        principal = principal * (1 + interest_rate / 4) ** 4
    end
 end

But keep getting error message.I'm pretty sure the issue is within Saving and Checking; when I press s or c, errors arise. Maybe someone could help find my error. Any help or advice would be appreciated.


问:
Vectorize add-subtract loop in NumPy using O(1) space?
It's easy to vectorize this code with NumPy using extra buffers:

```<code>import numpy.random

def foo(a, b):
    for k in xrange(n):
        bk = b[k]
        b[k] = a[k] - bk
        a[k] += bk

n = 16
x = numpy.random.randn(n)  # some arbitrary input array, this is just for example
y = numpy.random.randn(n)  # some arbitrary input array, this is just for example
foo(x, y)
</code>```

But is there any way for me to make NumPy do so without allocating extra arrays/buffers?

Edit:

I was intending this do this in only 1 vectorized operation (so that each memory location is written to only once), sorry for not mentioning that earlier.

Body:
It's easy to vectorize this code with NumPy using extra buffers:

import numpy.random

def foo(a, b):
    for k in xrange(n):
        bk = b[k]
        b[k] = a[k] - bk
        a[k] += bk

n = 16
x = numpy.random.randn(n)  # some arbitrary input array, this is just for example
y = numpy.random.randn(n)  # some arbitrary input array, this is just for example
foo(x, y)

But is there any way for me to make NumPy do so without allocating extra arrays/buffers?

Edit:

I was intending this do this in only 1 vectorized operation (so that each memory location is written to only once), sorry for not mentioning that earlier.

Body:
How about:

a += b
b *= -2
b += a


问:
Creating a Partial Class for a Form
I would like to create a partial class for my form. I have a lot of events, and it  gets messy, so I would like to break up sections into their own files.

The problem: When I create a partial class of my form, say:

```<code>Partial Public Class Form1

End Class
</code>```

Visual Studio decides I need another form for this partial class.

Questions:

1. How do I create a partial class for a form?

2. If I cant do that, how can I break up all the events in my form into different files?

答:
While it does not answer the original question, I found using regions made my code a little more manageable/readable.

```<code>#Region "RegionA"

#End Region
</code>```

I orginally called this method a "hack", thus the comment below.

Title: Creating a Partial Class for a Form

Body:
I would like to create a partial class for my form. I have a lot of events, and it  gets messy, so I would like to break up sections into their own files.

The problem: When I create a partial class of my form, say:

Partial Public Class Form1

End Class

Visual Studio decides I need another form for this partial class.

Questions:

1. How do I create a partial class for a form?

2. If I cant do that, how can I break up all the events in my form into different files?

Body:
While it does not answer the original question, I found using regions made my code a little more manageable/readable.

#Region "RegionA"

#End Region

I orginally called this method a "hack", thus the comment below.


问:
Multiple Spark servers in a single JVM
Is there any way to run multiple instances of Sparkjava server in the same JVM? I am using it in a "plugin" software and based on external circumstances multiple instances of my plugin might be started up which then cause

```<code>java.lang.IllegalStateException: This must be done before route mapping has begun
at spark.SparkBase.throwBeforeRouteMappingException(SparkBase.java:256)
at spark.SparkBase.port(SparkBase.java:101)
at com.foo.bar.a(SourceFile:59)
</code>```

It seems to me by looking at the code that it is heavily built around static fields in the code, so I am thinking about a classloader trick or working with SparkServerFactory somehow eliminating SparkBase.

答:
From Spark 2.5 you can use ignite():

http://sparkjava.com/news.html#spark25released

Example:

```<code>public static void main(String[] args) {
    igniteFirstSpark();
    igniteSecondSpark();
}

static void igniteSecondSpark() {
    Service http = ignite();

    http.get("/basicHello", (q, a) -> "Hello from port 4567!");
}

static void igniteFirstSpark() {
    Service http = ignite()
                      .port(8080)
                      .threadPool(20);

    http.get("/configuredHello", (q, a) -> "Hello from port 8080!");
}
</code>```

I personally initialize them something like this:

```<code>import spark.Service

public static void main(String[] args) {
    Service service1 = Service.ignite().port(8080).threadPool(20)
    Service service2 = Service.ignite().port(8081).threadPool(10)
}
</code>```

I recommend to read about how to use those services outside your main method, which I think would be a great use here.

Title: Multiple Spark servers in a single JVM

Body:
Is there any way to run multiple instances of Sparkjava server in the same JVM? I am using it in a "plugin" software and based on external circumstances multiple instances of my plugin might be started up which then cause

java.lang.IllegalStateException: This must be done before route mapping has begun
at spark.SparkBase.throwBeforeRouteMappingException(SparkBase.java:256)
at spark.SparkBase.port(SparkBase.java:101)
at com.foo.bar.a(SourceFile:59)

It seems to me by looking at the code that it is heavily built around static fields in the code, so I am thinking about a classloader trick or working with SparkServerFactory somehow eliminating SparkBase.

Body:
From Spark 2.5 you can use ignite():

http://sparkjava.com/news.html#spark25released

Example:

public static void main(String[] args) {
    igniteFirstSpark();
    igniteSecondSpark();
}

static void igniteSecondSpark() {
    Service http = ignite();

    http.get("/basicHello", (q, a) -> "Hello from port 4567!");
}

static void igniteFirstSpark() {
    Service http = ignite()
                      .port(8080)
                      .threadPool(20);

    http.get("/configuredHello", (q, a) -> "Hello from port 8080!");
}

I personally initialize them something like this:

import spark.Service

public static void main(String[] args) {
    Service service1 = Service.ignite().port(8080).threadPool(20)
    Service service2 = Service.ignite().port(8081).threadPool(10)
}

I recommend to read about how to use those services outside your main method, which I think would be a great use here.


问:
Acumatica customer mailing settings through API
I am trying to get Customer  Mailing Settings created through the Screen API. I am however not succeeding in getting the data saved.

Here is my code:

```<code>public static class CustomerManager
{
    private static Value CreateValue(
        string value,
        Command linkedCommand)
    {
        return new Value()
        {
            Value = value,
            LinkedCommand = linkedCommand
        };
    }

    private static Value CreateValueCommit(
        string value,
        Command linkedCommand)
    {
        return new Value()
        {
            Value = value,
            LinkedCommand = linkedCommand,
            Commit = true
        };
    }

    public static void ManageContact() {
        try {
            using (var context = WebServiceConnector.InitializeScreenWebService()) {
                var customerSchema = context.AR303000GetSchema();

                var commands = new List<Command>() {
                    CreateValueCommit("C00001", customerSchema.CustomerSummary.CustomerID),
                    CreateValueCommit("INVOICE", customerSchema.MailingSettingsMailings.MailingID),
                    CreateValue("mail@mail.com", customerSchema.MailingSettingsMailings.EmailAccountEmailAddress),
                    CreateValueCommit("InvoiceNotification", customerSchema.MailingSettingsMailings.NotificationTemplate),
                    customerSchema.MailingSettingsRecipients.ServiceCommands.NewRow,
                    CreateValueCommit("Contact", customerSchema.MailingSettingsRecipients.ContactType),
                    CreateValueCommit("Doe John, Dr.", customerSchema.MailingSettingsRecipients.ContactID),
                    customerSchema.Actions.Save,
                    customerSchema.CustomerSummary.CustomerID,
                    customerSchema.MailingSettingsMailings.EmailAccountEmailAddress,
                    customerSchema.MailingSettingsRecipients.ContactID
                };

                var customer = context.AR303000Submit(commands.ToArray());

                context.Logout();
            }
        }
        catch (Exception ex) {

            throw ex;
        }
    }
}
</code>```

The only value that gets saved correctly is the Notification Template.

Upon debug, I inspected the Mailing Recipient, and the value is in my customer return object. But there is nothing on the Customer screen:

答:
The Mailing Settings tab is not an easy thing to automate thought Web Services because of the following reasons:

initial mailing settings are defined on the Customer Class level. Users are allowed to either modify the initial settings or create new Branch-specific settings. Only one mailing setting can be defined for every MailingID/Branch pair

the Recipients grid displays only recipients defined for the current mailing setting

DisplayMode set to Text for the Email Account column requires to change originally generated FieldName from EMailAccountID to EMailAccountID!Address. Otherwise the API will ignore values defined for this column:

```<code>Content customerSchema = context.GetSchema();
customerSchema.MailingSettingsMailings.EmailAccount.FieldName += "!Address";
</code>```

Definition of the Mailings grid in Aspx:

```<code><px:PXGrid ID="gridNS" runat="server" SkinID="DetailsInTab" Caption="Mailings" ... >
    ...
    <Levels>
        <px:PXGridLevel DataMember="NotificationSources" DataKeyNames="SourceID,SetupID">
            <RowTemplate>
                ...
            </RowTemplate>
            <Columns>
                ...
                <px:PXGridColumn DataField="EMailAccountID" DisplayMode="Text" Width="200px" />
                ...
            </Columns>
            ...
        </px:PXGridLevel>
    </Levels>
</px:PXGrid>
</code>```

Below are 3 samples showing how to work with the Mailing Settings tab though Screen-Based API:

To insert new recipient for the initial mailing setting defined on the Customer Class level:

```<code>Screen context = new Screen();
context.CookieContainer = new System.Net.CookieContainer();
context.Url = "http://localhost/StackOverflow/Soap/AR303000.asmx";
context.Login(username, password);

try
{
    Content customerSchema = context.GetSchema();
    var commands = new Command[]
    {
        new Value
        {
            Value = "ABCSTUDIOS",
            LinkedCommand = customerSchema.CustomerSummary.CustomerID
        },

        new Key
        {
            Value = "='INVOICE'",
            FieldName = customerSchema.MailingSettingsMailings.MailingID.FieldName,
            ObjectName = customerSchema.MailingSettingsMailings.MailingID.ObjectName
        },
        customerSchema.MailingSettingsMailings.MailingID,

        customerSchema.MailingSettingsRecipients.ServiceCommands.NewRow,
        new Value
        {
            Value = "Contact",
            LinkedCommand = customerSchema.MailingSettingsRecipients.ContactType,
        },
        new Value
        {
            Value = "Harper, Travis",
            LinkedCommand = customerSchema.MailingSettingsRecipients.ContactID,
            Commit = true
        },
        customerSchema.Actions.Save
    };
    context.Submit(commands);
}
finally
{
    context.Logout();
}
</code>```

To update the initial mailing setting defined on the Customer Class level mailing setting and add new recipient for it:

```<code>Screen context = new Screen();
context.CookieContainer = new System.Net.CookieContainer();
context.Url = "http://localhost/StackOverflow/Soap/AR303000.asmx";
context.Login(username, password);

try
{
    Content customerSchema = context.GetSchema();
    customerSchema.MailingSettingsMailings.EmailAccount.FieldName += "!Address";

    var commands = new Command[]
    {
        new Value
        {
            Value = "ACTIVESTAF",
            LinkedCommand = customerSchema.CustomerSummary.CustomerID
        },

        new Key
        {
            Value = "='INVOICE'",
            FieldName = customerSchema.MailingSettingsMailings.MailingID.FieldName,
            ObjectName = customerSchema.MailingSettingsMailings.MailingID.ObjectName
        },
        new Value
        {
            Value = "admin@revisiontwo.com",
            LinkedCommand = customerSchema.MailingSettingsMailings.EmailAccount,
            Commit = true
        },

        customerSchema.MailingSettingsRecipients.ServiceCommands.NewRow,
        new Value
        {
            Value = "Contact",
            LinkedCommand = customerSchema.MailingSettingsRecipients.ContactType,
        },
        new Value
        {
            Value = "Dunnaville, Linda",
            LinkedCommand = customerSchema.MailingSettingsRecipients.ContactID,
            Commit = true
        },
        customerSchema.Actions.Save
    };
    context.Submit(commands);
}
finally
{
    context.Logout();
}
</code>```

To create new Branch-specific mailing setting and add new recipient for it:

```<code>Screen context = new Screen();
context.CookieContainer = new System.Net.CookieContainer();
context.Url = "http://localhost/StackOverflow/Soap/AR303000.asmx";
context.Login(username, password);

try
{
    Content customerSchema = context.GetSchema();

    customerSchema.MailingSettingsMailings.EmailAccount.FieldName += "!Address";
    var commands = new Command[]
    {
        new Value
        {
            Value = "ABCVENTURE",
            LinkedCommand = customerSchema.CustomerSummary.CustomerID
        },

        customerSchema.MailingSettingsMailings.ServiceCommands.NewRow,
        new Value
        {
            Value = "INVOICE",
            LinkedCommand = customerSchema.MailingSettingsMailings.MailingID,
        },
        new Value
        {
            Value = "HQ",
            LinkedCommand = customerSchema.MailingSettingsMailings.Branch,
        },
        new Value
        {
            Value = "admin@revisiontwo.com",
            LinkedCommand = customerSchema.MailingSettingsMailings.EmailAccount,
            Commit = true
        },

        customerSchema.MailingSettingsRecipients.ServiceCommands.NewRow,
        new Value
        {
            Value = "Contact",
            LinkedCommand = customerSchema.MailingSettingsRecipients.ContactType,
        },
        new Value
        {
            Value = "Palmer, Steve",
            LinkedCommand = customerSchema.MailingSettingsRecipients.ContactID,
            Commit = true
        },
        customerSchema.Actions.Save
    };
    context.Submit(commands);
}
finally
{
    context.Logout();
}
</code>```

Body:
I am trying to get Customer  Mailing Settings created through the Screen API. I am however not succeeding in getting the data saved.

Here is my code:

public static class CustomerManager
{
    private static Value CreateValue(
        string value,
        Command linkedCommand)
    {
        return new Value()
        {
            Value = value,
            LinkedCommand = linkedCommand
        };
    }

    private static Value CreateValueCommit(
        string value,
        Command linkedCommand)
    {
        return new Value()
        {
            Value = value,
            LinkedCommand = linkedCommand,
            Commit = true
        };
    }

    public static void ManageContact() {
        try {
            using (var context = WebServiceConnector.InitializeScreenWebService()) {
                var customerSchema = context.AR303000GetSchema();

                var commands = new List<Command>() {
                    CreateValueCommit("C00001", customerSchema.CustomerSummary.CustomerID),
                    CreateValueCommit("INVOICE", customerSchema.MailingSettingsMailings.MailingID),
                    CreateValue("mail@mail.com", customerSchema.MailingSettingsMailings.EmailAccountEmailAddress),
                    CreateValueCommit("InvoiceNotification", customerSchema.MailingSettingsMailings.NotificationTemplate),
                    customerSchema.MailingSettingsRecipients.ServiceCommands.NewRow,
                    CreateValueCommit("Contact", customerSchema.MailingSettingsRecipients.ContactType),
                    CreateValueCommit("Doe John, Dr.", customerSchema.MailingSettingsRecipients.ContactID),
                    customerSchema.Actions.Save,
                    customerSchema.CustomerSummary.CustomerID,
                    customerSchema.MailingSettingsMailings.EmailAccountEmailAddress,
                    customerSchema.MailingSettingsRecipients.ContactID
                };

                var customer = context.AR303000Submit(commands.ToArray());

                context.Logout();
            }
        }
        catch (Exception ex) {

            throw ex;
        }
    }
}

The only value that gets saved correctly is the Notification Template.

Upon debug, I inspected the Mailing Recipient, and the value is in my customer return object. But there is nothing on the Customer screen:

Body:
The Mailing Settings tab is not an easy thing to automate thought Web Services because of the following reasons:

initial mailing settings are defined on the Customer Class level. Users are allowed to either modify the initial settings or create new Branch-specific settings. Only one mailing setting can be defined for every MailingID/Branch pair

the Recipients grid displays only recipients defined for the current mailing setting

DisplayMode set to Text for the Email Account column requires to change originally generated FieldName from EMailAccountID to EMailAccountID!Address. Otherwise the API will ignore values defined for this column:

Content customerSchema = context.GetSchema();
customerSchema.MailingSettingsMailings.EmailAccount.FieldName += "!Address";

Definition of the Mailings grid in Aspx:

<px:PXGrid ID="gridNS" runat="server" SkinID="DetailsInTab" Caption="Mailings" ... >
    ...
    <Levels>
        <px:PXGridLevel DataMember="NotificationSources" DataKeyNames="SourceID,SetupID">
            <RowTemplate>
                ...
            </RowTemplate>
            <Columns>
                ...
                <px:PXGridColumn DataField="EMailAccountID" DisplayMode="Text" Width="200px" />
                ...
            </Columns>
            ...
        </px:PXGridLevel>
    </Levels>
</px:PXGrid>

Below are 3 samples showing how to work with the Mailing Settings tab though Screen-Based API:

To insert new recipient for the initial mailing setting defined on the Customer Class level:

Screen context = new Screen();
context.CookieContainer = new System.Net.CookieContainer();
context.Url = "http://localhost/StackOverflow/Soap/AR303000.asmx";
context.Login(username, password);

try
{
    Content customerSchema = context.GetSchema();
    var commands = new Command[]
    {
        new Value
        {
            Value = "ABCSTUDIOS",
            LinkedCommand = customerSchema.CustomerSummary.CustomerID
        },

        new Key
        {
            Value = "='INVOICE'",
            FieldName = customerSchema.MailingSettingsMailings.MailingID.FieldName,
            ObjectName = customerSchema.MailingSettingsMailings.MailingID.ObjectName
        },
        customerSchema.MailingSettingsMailings.MailingID,

        customerSchema.MailingSettingsRecipients.ServiceCommands.NewRow,
        new Value
        {
            Value = "Contact",
            LinkedCommand = customerSchema.MailingSettingsRecipients.ContactType,
        },
        new Value
        {
            Value = "Harper, Travis",
            LinkedCommand = customerSchema.MailingSettingsRecipients.ContactID,
            Commit = true
        },
        customerSchema.Actions.Save
    };
    context.Submit(commands);
}
finally
{
    context.Logout();
}

To update the initial mailing setting defined on the Customer Class level mailing setting and add new recipient for it:

Screen context = new Screen();
context.CookieContainer = new System.Net.CookieContainer();
context.Url = "http://localhost/StackOverflow/Soap/AR303000.asmx";
context.Login(username, password);

try
{
    Content customerSchema = context.GetSchema();
    customerSchema.MailingSettingsMailings.EmailAccount.FieldName += "!Address";

    var commands = new Command[]
    {
        new Value
        {
            Value = "ACTIVESTAF",
            LinkedCommand = customerSchema.CustomerSummary.CustomerID
        },

        new Key
        {
            Value = "='INVOICE'",
            FieldName = customerSchema.MailingSettingsMailings.MailingID.FieldName,
            ObjectName = customerSchema.MailingSettingsMailings.MailingID.ObjectName
        },
        new Value
        {
            Value = "admin@revisiontwo.com",
            LinkedCommand = customerSchema.MailingSettingsMailings.EmailAccount,
            Commit = true
        },

        customerSchema.MailingSettingsRecipients.ServiceCommands.NewRow,
        new Value
        {
            Value = "Contact",
            LinkedCommand = customerSchema.MailingSettingsRecipients.ContactType,
        },
        new Value
        {
            Value = "Dunnaville, Linda",
            LinkedCommand = customerSchema.MailingSettingsRecipients.ContactID,
            Commit = true
        },
        customerSchema.Actions.Save
    };
    context.Submit(commands);
}
finally
{
    context.Logout();
}

To create new Branch-specific mailing setting and add new recipient for it:

Screen context = new Screen();
context.CookieContainer = new System.Net.CookieContainer();
context.Url = "http://localhost/StackOverflow/Soap/AR303000.asmx";
context.Login(username, password);

try
{
    Content customerSchema = context.GetSchema();

    customerSchema.MailingSettingsMailings.EmailAccount.FieldName += "!Address";
    var commands = new Command[]
    {
        new Value
        {
            Value = "ABCVENTURE",
            LinkedCommand = customerSchema.CustomerSummary.CustomerID
        },

        customerSchema.MailingSettingsMailings.ServiceCommands.NewRow,
        new Value
        {
            Value = "INVOICE",
            LinkedCommand = customerSchema.MailingSettingsMailings.MailingID,
        },
        new Value
        {
            Value = "HQ",
            LinkedCommand = customerSchema.MailingSettingsMailings.Branch,
        },
        new Value
        {
            Value = "admin@revisiontwo.com",
            LinkedCommand = customerSchema.MailingSettingsMailings.EmailAccount,
            Commit = true
        },

        customerSchema.MailingSettingsRecipients.ServiceCommands.NewRow,
        new Value
        {
            Value = "Contact",
            LinkedCommand = customerSchema.MailingSettingsRecipients.ContactType,
        },
        new Value
        {
            Value = "Palmer, Steve",
            LinkedCommand = customerSchema.MailingSettingsRecipients.ContactID,
            Commit = true
        },
        customerSchema.Actions.Save
    };
    context.Submit(commands);
}
finally
{
    context.Logout();
}


问:
Bring back the old password of Gmail
I want to change my Gmail Password with the old one that i used before. Anybody know how i can do it? Because Google doesn't allow me to use the old password. </p>

答: Change your password 5 or 10 times in a row, and then change it back to the one you want. Most password managers only keep a history of the last 5 or 10 changes (particularly banks). As the comment on the question is right, password security policies are there to protect you, the user from unauthorized access.</p>

Title: Bring back the old password of Gmail