问:
How to disable the options in select element based on another select element with same option values?
I have to disable the slect options based on value selected in another select.

```<code><select   ng-model="myval" ng-options="lst as lst.txt  for lst in valuedata track by $index" ></select>

   <select   ng-model="myval" ng-options="lst as lst.txt  for lst in valuedata track by $index" ></select>
</code>```

here I get same data,but my requirement is,if I select two in first dropdown I need to disable the values less than two in second dropdown and If i select two in dropdown two I need to disable the values greater than two in first dropdown.

Any help would be appreciated.

答:
You can achieve this by disable when syntax of angular 1.4+ version. Read Doc.

In your problem, I suggest to have 2 different ng-model properties(though you can achieve this by single prop as well).,  you can do like:

```<code>    <select ng-model="data.first" ng-options="lst.txt as lst.txt disable when lst.txt > data.second for lst in valuedata">
    </select>

    <select ng-model="data.second" ng-options="lst.txt as lst.txt disable when lst.txt < data.first for lst in valuedata">
   </select>
</code>```

Here is working fiddle.

Body:
I have to disable the slect options based on value selected in another select.

<select   ng-model="myval" ng-options="lst as lst.txt  for lst in valuedata track by $index" ></select>

   <select   ng-model="myval" ng-options="lst as lst.txt  for lst in valuedata track by $index" ></select>

here I get same data,but my requirement is,if I select two in first dropdown I need to disable the values less than two in second dropdown and If i select two in dropdown two I need to disable the values greater than two in first dropdown.

Any help would be appreciated.

Body:
You can achieve this by disable when syntax of angular 1.4+ version. Read Doc.

In your problem, I suggest to have 2 different ng-model properties(though you can achieve this by single prop as well).,  you can do like:

    <select ng-model="data.first" ng-options="lst.txt as lst.txt disable when lst.txt > data.second for lst in valuedata">
    </select>

    <select ng-model="data.second" ng-options="lst.txt as lst.txt disable when lst.txt < data.first for lst in valuedata">
   </select>

Here is working fiddle.


来源: stackexchange

问:
CoreNFC debug not working
How programmatically work CoreNFC on xcode-9

```<code>func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
    //What I need to do here
}

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
    //What I need to do here
}

override func viewDidLoad() {
    super.viewDidLoad()

    let sessionReader = NFCNDEFReaderSession.init(delegate: self, queue: nil, invalidateAfterFirstRead: true)
    let nfcSession = NFCReaderSession.self

    let nfcTag = NFCTagCommandConfiguration.init()
    let tagType = NFCTagType(rawValue: 0)

    sessionReader.begin()

}
</code>```

I want to know what I need to do for read some NFC tag.

答:
There are four steps to get it working:

Add the NFC Tag permission to your App Identifier in the Apple developer portal

Add a Code Signing Entitlement file to your project and build settings and add the following raw key and value:

Add the usage description to your Info.plist:

Implement the delegate and pass it to the NFCNDEFReaderSession init like this:

```<code>import UIKit
import CoreNFC

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, NFCNDEFReaderSessionDelegate {

    var window: UIWindow?
    var session: NFCNDEFReaderSession?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)
        self.session?.begin()
        return true
    }

    func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
        print(error)
    }

    func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
        print(messages)
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: CoreNFC debug not working

Body:
How programmatically work CoreNFC on xcode-9

func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
    //What I need to do here
}

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
    //What I need to do here
}

override func viewDidLoad() {
    super.viewDidLoad()

    let sessionReader = NFCNDEFReaderSession.init(delegate: self, queue: nil, invalidateAfterFirstRead: true)
    let nfcSession = NFCReaderSession.self

    let nfcTag = NFCTagCommandConfiguration.init()
    let tagType = NFCTagType(rawValue: 0)

    sessionReader.begin()

}

I want to know what I need to do for read some NFC tag.

Body:
There are four steps to get it working:

Add the NFC Tag permission to your App Identifier in the Apple developer portal

Add a Code Signing Entitlement file to your project and build settings and add the following raw key and value:

Add the usage description to your Info.plist:

Implement the delegate and pass it to the NFCNDEFReaderSession init like this:

import UIKit
import CoreNFC

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, NFCNDEFReaderSessionDelegate {

    var window: UIWindow?
    var session: NFCNDEFReaderSession?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)
        self.session?.begin()
        return true
    }

    func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
        print(error)
    }

    func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
        print(messages)
    }

}

ContentLicense: CC BY-SA 4.0


问:
facebook getting session_key for offline_access in canvas application
Hey everyone,
I am trying to get the session_key and secret for a facebook session (offline_access) in  canvas application.

However, I am unable to get these two particular variables.
When, I am testing the same code locally, I can get the variables above (but this can be because the local app is not a canvas application)

I 'm using the following code, for redirect:

```<code>$facebook->getLoginUrl(array(
   'canvas' => 1,
   'fbconnect' => 0,
   'req_perms' => 'user_status,publish_stream,offline_access'
));
</code>```

Can someone suggest me on how I can grab the session_key and secret, when the user authorizes the application? (for permanent offline access)

Here is an example session dump via Facebook:

```<code>Array (
   [uid] => 100000926583671
   [session_key] =>
   [expires] => 0
   [secret] =>
   [base_domain] =>
   [access_token] => 183043495039366|3ab6ac2asdkhj1bcfdec13d7-100000926583671|jJQaIT-n80YxioAasdwN0cm99U
   [sig] => 2f64sadasc1da31c12927a052752776
)
</code>```

and this is the error:

```<code>Array (
   [error] => Array (
          [type] => OAuthException
          [message] => An active access token must be used to query information about the current user.
          )
   )
</code>```

答:
session_key and secret are now deprecated, and Facebook wants you to use Oauth authentication schema. Then, you will have to use given access_token (that you correctly get in $session) to make your api calls.

Try:

```<code>$session = $facebook->getSession();
$me = $facebook->api('/100000926583671',
                     array('access_token' => $session['access_token'])
      );
var_dump($me);
</code>```

Ref:
http://developers.facebook.com/docs/authentication/

ContentLicense: CC BY-SA 2.5

Body:
Hey everyone,
I am trying to get the session_key and secret for a facebook session (offline_access) in  canvas application.

However, I am unable to get these two particular variables.
When, I am testing the same code locally, I can get the variables above (but this can be because the local app is not a canvas application)

I 'm using the following code, for redirect:

$facebook->getLoginUrl(array(
   'canvas' => 1,
   'fbconnect' => 0,
   'req_perms' => 'user_status,publish_stream,offline_access'
));

Can someone suggest me on how I can grab the session_key and secret, when the user authorizes the application? (for permanent offline access)

Here is an example session dump via Facebook:

Array (
   [uid] => 100000926583671
   [session_key] =>
   [expires] => 0
   [secret] =>
   [base_domain] =>
   [access_token] => 183043495039366|3ab6ac2asdkhj1bcfdec13d7-100000926583671|jJQaIT-n80YxioAasdwN0cm99U
   [sig] => 2f64sadasc1da31c12927a052752776
)

and this is the error:

Array (
   [error] => Array (
          [type] => OAuthException
          [message] => An active access token must be used to query information about the current user.
          )
   )

Body:
session_key and secret are now deprecated, and Facebook wants you to use Oauth authentication schema. Then, you will have to use given access_token (that you correctly get in $session) to make your api calls.

Try:

$session = $facebook->getSession();
$me = $facebook->api('/100000926583671',
                     array('access_token' => $session['access_token'])
      );
var_dump($me);

Ref:
http://developers.facebook.com/docs/authentication/


问:
NoReverseMatch at /music/ 'music' is not a registered namespace
```<code>Error during template rendering

In template
</code>```

C:\Users\Pranay\Desktop\website\music\templates\music\index.html, error at line 5

'music' is not a registered namespace

this is the template code with the error:

```<code>{% if all_albums %}
<h3>here are all my albums</h3>
<ul>
    {% for album in all_albums %}
    <li><a href="{% url 'music:detail' album.id %}">{{ album.album_title }}</a></li>
    {% endfor %}
</ul>

{% else %}
<h3>you dont have any albums</h3>
{% endif %}
</code>```

urls.py

```<code>from django.conf.urls import url
from . import views
urlpatterns = [
# /music/
 url(r'^$',views.index, name='index'),

 # /music/<album_id>/
 url(r'^(?P<album_id>[0-9]+)/$', views.detail,name='detail'),

 # /music/<album_id>/favorite
 url(r'^(?P<album_id>[0-9]+)/favorite/$', views.favorite,name='favorite'),
]
</code>```

i have added my urls.py code

答:
If you use the namespace music in {% url 'music:detail album.id %} then you either need to include the app_name in music/urls.py:

```<code>app_name = 'music'

urlpatterns = [
...
]
</code>```

Or specify the namespace when including the music urls:

```<code>urlpatterns = [
    url('^music/', include('music.urls', namespace='music'),
]
</code>```

Body:
Error during template rendering

In template

C:\Users\Pranay\Desktop\website\music\templates\music\index.html, error at line 5

'music' is not a registered namespace

this is the template code with the error:

{% if all_albums %}

here are all my albums

    {% for album in all_albums %}

{{ album.album_title }}

    {% endfor %}

{% else %}

you dont have any albums

{% endif %}

urls.py

from django.conf.urls import url
from . import views
urlpatterns = [
# /music/
 url(r'^$',views.index, name='index'),

 # /music/<album_id>/
 url(r'^(?P<album_id>[0-9]+)/$', views.detail,name='detail'),

 # /music/<album_id>/favorite
 url(r'^(?P<album_id>[0-9]+)/favorite/$', views.favorite,name='favorite'),
]

i have added my urls.py code

Body:
If you use the namespace music in {% url 'music:detail album.id %} then you either need to include the app_name in music/urls.py:

app_name = 'music'

urlpatterns = [
...
]

Or specify the namespace when including the music urls:

urlpatterns = [
    url('^music/', include('music.urls', namespace='music'),
]


问:
Symfony 3 : Sending the $options argument values from formType to underFormType
I've created a tag system in a bundle using a formType (TagsType) which I include in my main formType (See below).
I'd like to know how I can send the $options argument values from MyFormType to TagsType.

```<code>//...

use EC\TagBundle\Form\Type\TagsType;

class MyFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

    $builder

    //...
        ->add('tags', TagsType::class)
    //...
    ;
    }
}
</code>```

My TagsType

```<code>//...

use Symfony\Component\Form\Extension\Core\Type\TextType;

class TagsType extends AbstractType
{
    /**
     * @var ObjectManager
     */
    private $manager;

    public function __construct(ObjectManager $manager)
    {
        $this->manager = $manager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->addModelTransformer( new CollectionToArrayTransformer(), true )
            ->addModelTransformer( new TagsTransformer($this->manager), true )
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('attr', [
            'class' => 'tag-input',

        ]);
        $resolver->setDefault('required', false);
    }

    public function getParent()
    {
        // Il retourne un TextType par défaut.
        return TextType::class;
    }
}
</code>```

答:
I found. Just do this :

```<code>->add('tags', TagsType::class, ['empty_data' => $options])
</code>```

TagsType.php

```<code>$options = $options['empty_data'];
</code>```

Body:
I've created a tag system in a bundle using a formType (TagsType) which I include in my main formType (See below).
I'd like to know how I can send the $options argument values from MyFormType to TagsType.

//...

use EC\TagBundle\Form\Type\TagsType;

class MyFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

    $builder

    //...
        ->add('tags', TagsType::class)
    //...
    ;
    }
}

My TagsType

//...

use Symfony\Component\Form\Extension\Core\Type\TextType;

class TagsType extends AbstractType
{
    /**
     * @var ObjectManager
     */
    private $manager;

    public function __construct(ObjectManager $manager)
    {
        $this->manager = $manager;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->addModelTransformer( new CollectionToArrayTransformer(), true )
            ->addModelTransformer( new TagsTransformer($this->manager), true )
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('attr', [
            'class' => 'tag-input',

        ]);
        $resolver->setDefault('required', false);
    }

    public function getParent()
    {
        // Il retourne un TextType par défaut.
        return TextType::class;
    }
}

Body:
I found. Just do this :

->add('tags', TagsType::class, ['empty_data' => $options])

TagsType.php

$options = $options['empty_data'];


问:
how to detect if device is pointing in a certain direction?
I am building a game which requires that the user points their device downwards and then in front of them. How would I detect when the user points their device downwards or in front of them, using the device's gyro and accelerometer sensors?</p>

答:
You can use CoreMotion with Accelerometer. Try this :

```<code>import Foundation
import CoreMotion

class CoreViewController: UIViewController {
let motionManager = CMMotionManager()

override func viewDidLoad() {
    super.viewDidLoad()

    motionManager.deviceMotionUpdateInterval = 0.01
    motionManager.startDeviceMotionUpdates(to: OperationQueue.current!)
    { deviceManager, error in
        print(deviceManager?.userAcceleration.z)
        print("Test") // no print
    }

    print(motionManager.isDeviceMotionActive) // print false
    }
}
</code>```

Check the value that you get in the Z's acceleration. If it is positive it means your phone is face down. I didn't have a device so tested it on simulator. Check the positive or negative value of Z to confirm.
Edit : Updated with Swift code.

Body:
You can use CoreMotion with Accelerometer. Try this :

import Foundation
import CoreMotion

class CoreViewController: UIViewController {
let motionManager = CMMotionManager()

override func viewDidLoad() {
    super.viewDidLoad()

    motionManager.deviceMotionUpdateInterval = 0.01
    motionManager.startDeviceMotionUpdates(to: OperationQueue.current!)
    { deviceManager, error in
        print(deviceManager?.userAcceleration.z)
        print("Test") // no print
    }

    print(motionManager.isDeviceMotionActive) // print false
    }
}

Check the value that you get in the Z's acceleration. If it is positive it means your phone is face down. I didn't have a device so tested it on simulator. Check the positive or negative value of Z to confirm.
Edit : Updated with Swift code.


问:
Cant View Module From Open Cart Admin
Hi Everyone hope all well. I am having a weird issue in Opencart. I have installed three different modules onto my opencart ( seo pro, total import pro and Image manager plus). I have installed them correctly and have added user permissions. The weird thing is that they dont show up in the Admin navigation.

Normally Seo Pro Comes under the catalog menu. The Total Import Pro comes under the systems menu and the Image Manager Plus comes under the Extensions menu. For some weird reason none of them appear. This is the same if i add any extensions. I have done this many times on other sites and never had a problem but for the life of me can not work out why they wont appear.

They are installed because when i call upon them from the url i can view them and use them but they just dont display on the navigation bar

http://www.top4pets.co.uk/admin/index.php?route=tool/total_import&token=#####################

Has anyone ever had this problem or know what it could be?

答:
Total Import Pro adds the menu option with the help of vQmod. You can download and install vqmod by the instructions written here: Installing vQmod on OpenCart

If the extensions have a folder named vqmod or files with .xml extension, then are likely to require vqmod to run properly.

Title: Cant View Module From Open Cart Admin


问:
How to access local files of the filesystem in the Android emulator?
I want to know whether there is a method to access local files (say text files, web pages) of the filesystem in Android emulator.

I'm using Ubuntu 10.04 for Android development.

答:
Update!
You can access the Android filesystem via Android Device Monitor. In Android Studio go to  Tools >> Android >> Android Device Monitor.

Note that you can run your app in the simulator while using the Android Device Monitor. But you cannot debug you app while using the Android Device Monitor.


问:
How to add a white line below every ListView Item in xml?
My Problem is --> I put a white line as a view in the Fragment item xml but it doesn't appear when i debug it. How can i get the changes i make in the fragment item xml file. Because i tried some little changes like alpha property change but it didnt change is it because of this is a listview and has itself design? Please help me about that problem.

The xml code and adapter code are below.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:orientation="vertical"
        android:gravity="center"
        android:paddingTop="5dp"
        >

        <ImageView
            android:id="@+id/menulogo"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@drawable/infoicon"
            android:layout_gravity="center"
            android:paddingTop="5dp"
            />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="vertical"
        android:gravity="center">
        <TextView
            android:id="@+id/txtMenu"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="Company Name"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_weight="1" />
    </LinearLayout>
    <View
        android:id="@+id/line"
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:layout_below="@+id/txtMenu"
        android:background="#FFFFFF"
        />

</LinearLayout>
</code>```

My listview adapter codes right down below.

```<code>    public class MenuListAdapter extends ArrayAdapter<Menu_Item> {
        private final ArrayList<Menu_Item> list;
        private final Activity context;
    private int[] colors = new int[]{0x34a4a4a4, 0x34fafafa};

    public MenuListAdapter(Activity context, ArrayList<Menu_Item> list) {
        super(context, R.layout.menu_item, list);
        this.context = context;
        this.list = list;
    }

    static class ViewHolder {
        public ImageView menulogo;
        public TextView txtMenu;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.menu_item, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.menulogo = (ImageView) view.findViewById(R.id.menulogo);
            viewHolder.txtMenu = (TextView) view.findViewById(R.id.txtMenu);
            view.setTag(viewHolder);
            int colorPos = position % colors.length;
            view.setBackgroundColor(colors[colorPos]);
        } else {
            view = convertView;
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.txtMenu.setText(list.get(position).getMenuName());
        //holder.menulogo.setImageBitmap(list.get(position).getMenuImage());
        String menuName=list.get(position).getMenuName();
        if (menuName.equals("Info")){
            holder.menulogo.setImageResource(R.drawable.infoicon);
        }
        if (menuName.equals("Odalar")){
            holder.menulogo.setImageResource(R.drawable.accomodation);
        }
        if (menuName.equals("Galeri")){
            holder.menulogo.setImageResource(R.drawable.galeryicon);
        }
        if (menuName.equals("Aktiviteler")){
            holder.menulogo.setImageResource(R.drawable.activitiesicon);
        }
        if (menuName.equals("Robin's Kids Club")){
            holder.menulogo.setImageResource(R.drawable.kidsclub);
        }
        if (menuName.equals("Restaurants")){
            holder.menulogo.setImageResource(R.drawable.restaurantsicon);
        }
        view.setId(list.get(position).getMenu_id());
        return view;
    }

    @Override
    public int getViewTypeCount() {
        if (getCount() != 0)
            return getCount();

        return 1;
    }

    }
</code>```

答:
In ListView XML add these two lines

```<code><ListView
    android:divider="@android:color/white"
    android:dividerHeight="5dip"
.
.
 </ListView>
</code>```

Body:
My Problem is --> I put a white line as a view in the Fragment item xml but it doesn't appear when i debug it. How can i get the changes i make in the fragment item xml file. Because i tried some little changes like alpha property change but it didnt change is it because of this is a listview and has itself design? Please help me about that problem.

The xml code and adapter code are below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="center"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:orientation="vertical"
        android:gravity="center"
        android:paddingTop="5dp"
        >

        <ImageView
            android:id="@+id/menulogo"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@drawable/infoicon"
            android:layout_gravity="center"
            android:paddingTop="5dp"
            />

    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="vertical"
        android:gravity="center">
        <TextView
            android:id="@+id/txtMenu"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="Company Name"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:layout_weight="1" />
    </LinearLayout>
    <View
        android:id="@+id/line"
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:layout_below="@+id/txtMenu"
        android:background="#FFFFFF"
        />

</LinearLayout>

My listview adapter codes right down below.

    public class MenuListAdapter extends ArrayAdapter<Menu_Item> {
        private final ArrayList<Menu_Item> list;
        private final Activity context;
    private int[] colors = new int[]{0x34a4a4a4, 0x34fafafa};

    public MenuListAdapter(Activity context, ArrayList<Menu_Item> list) {
        super(context, R.layout.menu_item, list);
        this.context = context;
        this.list = list;
    }

    static class ViewHolder {
        public ImageView menulogo;
        public TextView txtMenu;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.menu_item, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.menulogo = (ImageView) view.findViewById(R.id.menulogo);
            viewHolder.txtMenu = (TextView) view.findViewById(R.id.txtMenu);
            view.setTag(viewHolder);
            int colorPos = position % colors.length;
            view.setBackgroundColor(colors[colorPos]);
        } else {
            view = convertView;
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.txtMenu.setText(list.get(position).getMenuName());
        //holder.menulogo.setImageBitmap(list.get(position).getMenuImage());
        String menuName=list.get(position).getMenuName();
        if (menuName.equals("Info")){
            holder.menulogo.setImageResource(R.drawable.infoicon);
        }
        if (menuName.equals("Odalar")){
            holder.menulogo.setImageResource(R.drawable.accomodation);
        }
        if (menuName.equals("Galeri")){
            holder.menulogo.setImageResource(R.drawable.galeryicon);
        }
        if (menuName.equals("Aktiviteler")){
            holder.menulogo.setImageResource(R.drawable.activitiesicon);
        }
        if (menuName.equals("Robin's Kids Club")){
            holder.menulogo.setImageResource(R.drawable.kidsclub);
        }
        if (menuName.equals("Restaurants")){
            holder.menulogo.setImageResource(R.drawable.restaurantsicon);
        }
        view.setId(list.get(position).getMenu_id());
        return view;
    }

    @Override
    public int getViewTypeCount() {
        if (getCount() != 0)
            return getCount();

        return 1;
    }

    }

Body:
In ListView XML add these two lines

<ListView
    android:divider="@android:color/white"
    android:dividerHeight="5dip"
.
.
 </ListView>


问:
Not getting on Ajax Success from controller JsonResult method
```<code>function GetSort() {
    var url = '@Url.Action("GetSort", "CatMaster")';
    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: null,
        success: function (data) {
            restrctTrans = false;
            $("#Order").data("kendoNumericTextBox").value(data.NxtSort);
        },
        error: function (data) {
            alert('error');
        }
    });
}
</code>```

This calls an controller method which returns JSON value:

```<code>public JsonResult GetSort()
{
    var response = _catMaster.GetNextSort();
    return Json(response.NxtSort, JsonRequestBehavior.AllowGet);
}
</code>```

Problem is the ajax success and error function is not called.
But controller returns a value.
Value of response.NxtSort is 1

答:
"the ajax success and error function is not called. But controller
  returns a value."

This scenario is extremely unlikely to be true. If the controller is returning something, then one of those functions will run. The only way they wouldn't run is if the ajax call fails prior to actually executing, for some other reason. You would see the error displayed in your browser's Developer Tools.

To verify this, you can check your browser's network tab (in the Developer Tools, press F12 on most browsers) and watch for the ajax call to see the HTTP response returned to the browser. If it's "200" then "success" will definitely run. If it's anything else, "error" will run. You could put an "alert" command into start of the "success" function to prove that it runs.

Also check for any errors in your browser's Console as well. I predict that data.NxtSort will not exist in the JavaScript context, because as you mentioned, you only return a single integer value from the controller, not an object which could contain a property with that name. data in the "success" function will simply be an integer with the value 1. This means almost certainly there's an "undefined" error happening and showing in the console when you try to access the non-existent nxtSort property.

This means that, contrary to your statement, "success" is called, but then it crashes without outputting anything.

Simply replacing

```<code>$("#Order").data("kendoNumericTextBox").value(data.NxtSort);
</code>```

with

```<code> $("#Order").data("kendoNumericTextBox").value(data);
</code>```

should solve your problem.

In future if you learn to use your browser's Developer Tools to debug your code, you can avoid simple problems such as this. The tools in Chrome and Firefox in particular are extremely powerful and informative.

Body:
function GetSort() {
    var url = '@Url.Action("GetSort", "CatMaster")';
    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        data: null,
        success: function (data) {
            restrctTrans = false;
            $("#Order").data("kendoNumericTextBox").value(data.NxtSort);
        },
        error: function (data) {
            alert('error');
        }
    });
}

This calls an controller method which returns JSON value:

public JsonResult GetSort()
{
    var response = _catMaster.GetNextSort();
    return Json(response.NxtSort, JsonRequestBehavior.AllowGet);
}

Problem is the ajax success and error function is not called.
But controller returns a value.
Value of response.NxtSort is 1

Body:
"the ajax success and error function is not called. But controller
  returns a value."

This scenario is extremely unlikely to be true. If the controller is returning something, then one of those functions will run. The only way they wouldn't run is if the ajax call fails prior to actually executing, for some other reason. You would see the error displayed in your browser's Developer Tools.

To verify this, you can check your browser's network tab (in the Developer Tools, press F12 on most browsers) and watch for the ajax call to see the HTTP response returned to the browser. If it's "200" then "success" will definitely run. If it's anything else, "error" will run. You could put an "alert" command into start of the "success" function to prove that it runs.

Also check for any errors in your browser's Console as well. I predict that data.NxtSort will not exist in the JavaScript context, because as you mentioned, you only return a single integer value from the controller, not an object which could contain a property with that name. data in the "success" function will simply be an integer with the value 1. This means almost certainly there's an "undefined" error happening and showing in the console when you try to access the non-existent nxtSort property.

This means that, contrary to your statement, "success" is called, but then it crashes without outputting anything.

Simply replacing

$("#Order").data("kendoNumericTextBox").value(data.NxtSort);

with

 $("#Order").data("kendoNumericTextBox").value(data);

should solve your problem.

In future if you learn to use your browser's Developer Tools to debug your code, you can avoid simple problems such as this. The tools in Chrome and Firefox in particular are extremely powerful and informative.


问:
How to fetch all the child nodes of an XML using python?
This is my XML file

```<code><?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdp>141100</gdp>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
</data>
</code>```

How to pull all the child nodes of country?

For Example, I need the output as ['rank','year','gdp','neighbor']

答:
Looks like there are a few APIs that Python can use to parse XML files:

http://python-guide-pt-br.readthedocs.io/en/latest/scenarios/xml/

https://www.tutorialspoint.com/python/python_xml_processing.htm

Body:
This is my XML file

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdp>141100</gdp>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
</data>

How to pull all the child nodes of country?

For Example, I need the output as ['rank','year','gdp','neighbor']


问:
Error Cannot access memory at address in linked list
I'm creating a linked list with some insert functions.

This method work fine :

```<code>void insert_before(){
    struct node *new_node, *ptr, *preptr;
    int pivot;

    new_node = (struct node*)malloc(sizeof(struct node));
    ptr = link;
    preptr = link;

    printf("\n Enter the data : ");
    scanf("%d", &new_node->data);

    printf("\n Enter the value before which the data has to be inserted : ");
    scanf("%d", &pivot);

    while(ptr->data != pivot){
        preptr = ptr;
        ptr = ptr->next;
    }

    preptr->next = new_node;
    new_node->next = ptr;
}
</code>```

However, I got Cannot access memory at address 0x8 in this method :

```<code>void insert_after(){
    struct node *new_node, *ptr, *preptr;
    int pivot;

    new_node = (struct node*)malloc(sizeof(struct node));
    ptr = link;
    preptr = link;

    printf("\n Enter the data : ");
    scanf("%d", &new_node->data);

    printf("\n Enter the value after which the data has to be inserted : ");
    scanf("%d", &pivot);

    while(preptr->data != pivot){
        preptr = ptr;
        ptr = ptr->next;
    }

    preptr->next = new_node;
    new_node->next = ptr;
}
</code>```

Note that both of the method use the same struct* link, and the only difference is on the looping while(preptr->data != pivot).

Why does the first code working fine, but the second one broken?

Thanks for your help

PS : This is my whole project (very short), in case you need it : https://pastebin.com/wsMEicGv

答:
I don't think that even the first method works correctly (simple proof: the code never changes the value of link, hence an insert before the first node cannot work).

Anyway, your code will produce the mentioned error message in both functions when you enter a value for pivot which does not match any data or which matches the last node in the list:

```<code>while(preptr->data != pivot){
    preptr = ptr;
    ptr = ptr->next;
}
</code>```

The reason is that the loop above will reach the end of the list (having preptr = NULL), when condition preptr->data still accesses this null-pointer. I suppose that member data is the second one in your struct (the first one is next), right? Then you access actually (NULL + sizeof(node*)) which is (NULL + 8) which is 0x08.

Body:
I'm creating a linked list with some insert functions.

This method work fine :

void insert_before(){
    struct node *new_node, *ptr, *preptr;
    int pivot;

    new_node = (struct node*)malloc(sizeof(struct node));
    ptr = link;
    preptr = link;

    printf("\n Enter the data : ");
    scanf("%d", &new_node->data);

    printf("\n Enter the value before which the data has to be inserted : ");
    scanf("%d", &pivot);

    while(ptr->data != pivot){
        preptr = ptr;
        ptr = ptr->next;
    }

    preptr->next = new_node;
    new_node->next = ptr;
}

However, I got Cannot access memory at address 0x8 in this method :

void insert_after(){
    struct node *new_node, *ptr, *preptr;
    int pivot;

    new_node = (struct node*)malloc(sizeof(struct node));
    ptr = link;
    preptr = link;

    printf("\n Enter the data : ");
    scanf("%d", &new_node->data);

    printf("\n Enter the value after which the data has to be inserted : ");
    scanf("%d", &pivot);

    while(preptr->data != pivot){
        preptr = ptr;
        ptr = ptr->next;
    }

    preptr->next = new_node;
    new_node->next = ptr;
}

Note that both of the method use the same struct* link, and the only difference is on the looping while(preptr->data != pivot).

Why does the first code working fine, but the second one broken?

Thanks for your help

PS : This is my whole project (very short), in case you need it : https://pastebin.com/wsMEicGv

Body:
I don't think that even the first method works correctly (simple proof: the code never changes the value of link, hence an insert before the first node cannot work).

Anyway, your code will produce the mentioned error message in both functions when you enter a value for pivot which does not match any data or which matches the last node in the list:

while(preptr->data != pivot){
    preptr = ptr;
    ptr = ptr->next;
}

The reason is that the loop above will reach the end of the list (having preptr = NULL), when condition preptr->data still accesses this null-pointer. I suppose that member data is the second one in your struct (the first one is next), right? Then you access actually (NULL + sizeof(node*)) which is (NULL + 8) which is 0x08.


问:
PHP - Add value to existing array in cookie on button click
I want to add values to the existing array variable inside my cookie.

Currently I set my cookie using Ajax:

Ajax:

```<code>function setcookie(productid){
     $.ajax({
            type: 'POST',
            url: "setcookies.php",
            data: {
                id: "productid"
            },
            success: function (e) {
                alert(e);
            }
        });
}
</code>```

PHP setcookies.php

```<code><?php
$cookiename = "products";
$cart = array();

$pid = $_POST['id'];
array_push($cart, $pid);

setcookie($cookiename, serialize($cart), time() + 3600, "/");
$_COOKIE[$cookiename] = serialize($cart);
</code>```

When I click addproduct button setcookie() function will be called.
Clicking addproduct button three times I expected that 3 ids of the product should be added to the cookie array but when I access the page that will show the cookies in my page it will just only show the last productid added.

Thank you in advance guys.

EDIT FOR MY WORKING CODE:

Below code works in my end:
Just slightly modified the code answered by Dominique.

```<code>$cookiename = "products";
$cart = null;
$pid = $_POST['id'];
if (!empty($_COOKIE[$cookiename])) {
    $cart = unserialize($_COOKIE[$cookiename]);
    array_push($cart, $pid);
} else {
    $cart = array();
    array_push($cart, $pid);
}
setcookie($cookiename, serialize($cart), time() + 3600, "/");
$_COOKIE[$cookiename] = serialize($cart);
</code>```

答:
In your code, you instantiate $cart as an array containing 0 element and put it in $_COOKIE['products'] so it'll delete existing content.

It would explain why you could only have an array with a simple element.

This code should work

```<code><?php
$cookiename = "products";

$cart = array();

if(!empty($_COOKIE[$cookiename])) {
    $cart = json_decode($_COOKIE[$cookiename], true);
}

$pid = $_POST['id'];
array_push($cart, $pid);

setcookie($cookiename, json_encode($cart), time() + 3600, "/");
$_COOKIE[$cookiename] = json_encode($cart);
</code>```

Body:
I want to add values to the existing array variable inside my cookie.

Currently I set my cookie using Ajax:

Ajax:

function setcookie(productid){
     $.ajax({
            type: 'POST',
            url: "setcookies.php",
            data: {
                id: "productid"
            },
            success: function (e) {
                alert(e);
            }
        });
}

PHP setcookies.php

<?php
$cookiename = "products";
$cart = array();

$pid = $_POST['id'];
array_push($cart, $pid);

setcookie($cookiename, serialize($cart), time() + 3600, "/");
$_COOKIE[$cookiename] = serialize($cart);

When I click addproduct button setcookie() function will be called.
Clicking addproduct button three times I expected that 3 ids of the product should be added to the cookie array but when I access the page that will show the cookies in my page it will just only show the last productid added.

Thank you in advance guys.

EDIT FOR MY WORKING CODE:

Below code works in my end:
Just slightly modified the code answered by Dominique.

$cookiename = "products";
$cart = null;
$pid = $_POST['id'];
if (!empty($_COOKIE[$cookiename])) {
    $cart = unserialize($_COOKIE[$cookiename]);
    array_push($cart, $pid);
} else {
    $cart = array();
    array_push($cart, $pid);
}
setcookie($cookiename, serialize($cart), time() + 3600, "/");
$_COOKIE[$cookiename] = serialize($cart);

Body:
In your code, you instantiate $cart as an array containing 0 element and put it in $_COOKIE['products'] so it'll delete existing content.

It would explain why you could only have an array with a simple element.

This code should work

<?php
$cookiename = "products";

$cart = array();

if(!empty($_COOKIE[$cookiename])) {
    $cart = json_decode($_COOKIE[$cookiename], true);
}

$pid = $_POST['id'];
array_push($cart, $pid);

setcookie($cookiename, json_encode($cart), time() + 3600, "/");
$_COOKIE[$cookiename] = json_encode($cart);


问:
If all my sql server database access is done thru stored procedures
If all my sql server database access is done thru stored procedures, and I plan on continuing that practice, is using linq2sql and/or the entity framework for future projects an unnecessary layer of complexity that doesn't add much value?

Related question: is Microsoft trying to steer developers away from relying on stored procs for data access?

答:
Just to address your related question: The benefits of using stored procedures are not as prominent as they once were. Though I would not go as far as saying stored procedures are evil, as some have said in the past (http://www.tonymarston.net/php-mysql/stored-procedures-are-evil.html - this is a very nice article though), I would say that the use of dynamic sql, as long as it's done in a well defined structured way, is perfectly acceptable these days.

I don't this Microsoft are trying to steer developers away from using stored procs but that dynamic sql should be seen as an acceptable option.

OwnerDisplayName: E.J. Brennan

OwnerDisplayName: Chris Simpson


问:
OpenGL glTranslate and glRotate
I need a function that applies a translation like glTranslate() to a point.
Does someone know of a function like glTranslate() and glRotate() to modify and retrieve a matrix to multiply?

答:
There are thousands of free matrix classes out there.  Have a hunt round google and then you can set up a translation and rotation without using the gl* functions at all ...

edit:  If you really just want to create the matrix without using a more than handy matrix class then you can define glRotatef( angle, x, y, z ) as follows:

```<code>const float cosA = cosf( angle );
const float sinA = sinf( angle );
float m[16] = { cosA + ((x * x) * (1 - cosA)), ((x * y) * (1 - cosA)) - (z * sinA), ((x * z) * (1 - cosA)) + (y * sinA), 0.0f,
                ((y * x) * (1 - cosA)) + (z * sinA), cosA + ((y * y) * (1 - cosA)), ((y * z) * (1 - cosA)) - (x * sinA), 0.0f,
                ((z * x) * (1 - cosA)) - (y * sinA), ((z * y) * (1 - cosA)) + (x * sinA), cosA + ((z * z) * (1 - cosA)), 0.0f,
                0.0f, 0.0f, 0.0f, 1.0f
               };
</code>```

As taken from wikipedia.

A translation matrix is really easy to create:  glTranslatef( x, y, z) is define as follows:

```<code>float m[16] = { 1.0f, 0.0f, 0.0f, 0.0f,
                0.0f, 1.0f, 0.0f, 0.0f,
                0.0f, 0.0f, 1.0f, 0.0f,
                   x,    y,    z, 1.0f
               };
</code>```

You can look up matrix multiplication and matrix-vector multiplication pretty easily.

To make your life simple, though, you could just download a matrix class which does all this for you ...

Title: OpenGL glTranslate and glRotate

Body:
There are thousands of free matrix classes out there.  Have a hunt round google and then you can set up a translation and rotation without using the gl* functions at all ...

edit:  If you really just want to create the matrix without using a more than handy matrix class then you can define glRotatef( angle, x, y, z ) as follows:

const float cosA = cosf( angle );
const float sinA = sinf( angle );
float m[16] = { cosA + ((x * x) * (1 - cosA)), ((x * y) * (1 - cosA)) - (z * sinA), ((x * z) * (1 - cosA)) + (y * sinA), 0.0f,
                ((y * x) * (1 - cosA)) + (z * sinA), cosA + ((y * y) * (1 - cosA)), ((y * z) * (1 - cosA)) - (x * sinA), 0.0f,
                ((z * x) * (1 - cosA)) - (y * sinA), ((z * y) * (1 - cosA)) + (x * sinA), cosA + ((z * z) * (1 - cosA)), 0.0f,
                0.0f, 0.0f, 0.0f, 1.0f
               };

As taken from wikipedia.

A translation matrix is really easy to create:  glTranslatef( x, y, z) is define as follows:

float m[16] = { 1.0f, 0.0f, 0.0f, 0.0f,
                0.0f, 1.0f, 0.0f, 0.0f,
                0.0f, 0.0f, 1.0f, 0.0f,
                   x,    y,    z, 1.0f
               };

You can look up matrix multiplication and matrix-vector multiplication pretty easily.

To make your life simple, though, you could just download a matrix class which does all this for you ...


问:
Round to Highest Factor with Variable Scale?
PHP's floor() and ceil() is useful for rounding floats to their nearest integers.

But what if we need to find the highest multiple of 10 (hundreds, thousands, etc.) for a given number?  For example:

```<code>num_to_scale(538.9)           // 500
num_to_scale(543123654.01234) // 5000000
</code>```

答:
Try this code, check the live demo. You also can refer to this post.</p>

```<code>  $floor = floor($v);
  return str_pad(substr($floor, 0, 1), strlen($floor), '0');
</code>```

Body:
PHP's floor() and ceil() is useful for rounding floats to their nearest integers.

But what if we need to find the highest multiple of 10 (hundreds, thousands, etc.) for a given number?  For example:

num_to_scale(538.9)           // 500
num_to_scale(543123654.01234) // 5000000

Body:
Try this code, check the live demo. You also can refer to this post.

  $floor = floor($v);
  return str_pad(substr($floor, 0, 1), strlen($floor), '0');


问:
Unit testing a controller with automapper mapping in it
I have an asp.net webapi project, in which I have a controller that I want to unit test. In that controller I have a mapping. The controller inherits from a base controller, of which the implementation is:

```<code>public class BaseController : ApiController
{
    /// <summary>
    /// AutoMapper Mapper instance to handle all mapping.
    /// </summary>
    protected IMapper GlobalMapper => AutoMapperConfig.Mapper;
}
</code>```

I now want to unit test the controller. My automapper configuration looks like this:

```<code>    public static class AutoMapperConfig
    {
        /// <summary>
        /// Provides access to the AutoMapper configuration.
        /// </summary>
        public static MapperConfiguration MapperConfiguration { get; private set; }

        /// <summary>
        /// Provides access to the instance of the AutoMapper Mapper object to perform mappings.
        /// </summary>
        public static IMapper Mapper { get; private set; }

        /// <summary>
        /// Starts the configuration of the mapping.
        /// </summary>
        public static void Start()
        {
            MapperConfiguration = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile<MeldingProfiel>();
                cfg.AddProfile<GebouwProfiel>();
                cfg.AddProfile<AdresProfiel>();
            });

            MapperConfiguration.AssertConfigurationIsValid();

            Mapper = MapperConfiguration.CreateMapper();
        }
    }
</code>```

How can I unit test the controller that has this automapper mapping in it?

答:
My recommendation would be to use Dependency Injection.  Each controller would take a dependency on an IMapper instance, which would be provided by your DI container.  This makes unit testing much easier.

```<code>public class MyController : ApiController
{
    private readonly IMapper _mapper;

    public MyController(IMapper mapper)
    {
        _mapper = mapper;
    }
}
</code>```

Don't use the static AutoMapper instance (e.g. Mapper.Map(...) ) at all.

Here's a sample for getting AutoMapper registered in an Autofac container, which just registers any profiles which have been added to the container.  You won't have to look far to find equivalent samples for any other DI container.

```<code>builder.Register<IMapper>(c =>
{
    var profiles = c.Resolve<IEnumerable<Profile>>();
    var config = new MapperConfiguration(cfg =>
    {
        foreach (var profile in profiles)
        {
            cfg.AddProfile(profile);
        }
    });
    return config.CreateMapper();
}).SingleInstance();
</code>```

Body:
I have an asp.net webapi project, in which I have a controller that I want to unit test. In that controller I have a mapping. The controller inherits from a base controller, of which the implementation is:

public class BaseController : ApiController
{
    ///
    /// AutoMapper Mapper instance to handle all mapping.
    ///
    protected IMapper GlobalMapper => AutoMapperConfig.Mapper;
}

I now want to unit test the controller. My automapper configuration looks like this:

    public static class AutoMapperConfig
    {
        ///
        /// Provides access to the AutoMapper configuration.
        ///
        public static MapperConfiguration MapperConfiguration { get; private set; }

        ///
        /// Provides access to the instance of the AutoMapper Mapper object to perform mappings.
        ///
        public static IMapper Mapper { get; private set; }

        ///
        /// Starts the configuration of the mapping.
        ///
        public static void Start()
        {
            MapperConfiguration = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile<MeldingProfiel>();
                cfg.AddProfile<GebouwProfiel>();
                cfg.AddProfile<AdresProfiel>();
            });

            MapperConfiguration.AssertConfigurationIsValid();

            Mapper = MapperConfiguration.CreateMapper();
        }
    }

How can I unit test the controller that has this automapper mapping in it?

Body:
My recommendation would be to use Dependency Injection.  Each controller would take a dependency on an IMapper instance, which would be provided by your DI container.  This makes unit testing much easier.

public class MyController : ApiController
{
    private readonly IMapper _mapper;

    public MyController(IMapper mapper)
    {
        _mapper = mapper;
    }
}

Don't use the static AutoMapper instance (e.g. Mapper.Map(...) ) at all.

Here's a sample for getting AutoMapper registered in an Autofac container, which just registers any profiles which have been added to the container.  You won't have to look far to find equivalent samples for any other DI container.

builder.Register<IMapper>(c =>
{
    var profiles = c.Resolve<IEnumerable<Profile>>();
    var config = new MapperConfiguration(cfg =>
    {
        foreach (var profile in profiles)
        {
            cfg.AddProfile(profile);
        }
    });
    return config.CreateMapper();
}).SingleInstance();


问:
How to remove an inherited ValidationAttribute?
I have a controller which take a model as parameter. This model is a specialized version of a generic model. I want my specialized model to hide a required base field to make it not required.

Here is what I did :

Controller

```<code>public class TestController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(new SpecializedModel());
    }

    [HttpPost]
    public ActionResult Index(SpecializedModel model)
    {
        if(ModelState.IsValid)
        {
            //Do some stuff, eventually redirect elsewhere
        }

        return View(model);
    }
}
</code>```

GenericModel

```<code>public class GenericModel
{
    [Required(ErrorMessage = "The field is required.")]
    public string SomeValue { get; set; }
}
</code>```

SpecializedModel

```<code>public class SpecializedModel : GenericModel
{
    new public string SomeValue { get; set; }
}
</code>```

View

```<code>    <form method="post">
        @Html.TextBoxFor(model => model.SomeValue)<br />
        @Html.ValidationMessageFor(model => model.SomeValue)<br />
        <input type="submit" />
    </form>
</code>```

When I validate the form, the error message

The field is required.

is shown. I gather the RequiredAttribute is kept... is there a way to get rid of it ?

Edit : I also tried to make the SomeValue a virtual field to override it, but the problem is the same.

答:
So is your underlying problem that you have attributes/properties/fields on a domain object that you don't want on a domain object elsewhere in your code?

This is why libraries such as AutoMapper or other mappers exist (or even writing it yourself, but that is time consuming and repetitive).

You should have a domain object per domain layer (UI, business logic, data store) and each domain layer should have no references to each others domain object. Instead, you'd use a Data Transfer Object (DTO) to map values between the layers.

Body:
I have a controller which take a model as parameter. This model is a specialized version of a generic model. I want my specialized model to hide a required base field to make it not required.

Here is what I did :

Controller

public class TestController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(new SpecializedModel());
    }

    [HttpPost]
    public ActionResult Index(SpecializedModel model)
    {
        if(ModelState.IsValid)
        {
            //Do some stuff, eventually redirect elsewhere
        }

        return View(model);
    }
}

GenericModel

public class GenericModel
{
    [Required(ErrorMessage = "The field is required.")]
    public string SomeValue { get; set; }
}

SpecializedModel

public class SpecializedModel : GenericModel
{
    new public string SomeValue { get; set; }
}

View

    <form method="post">
        @Html.TextBoxFor(model => model.SomeValue)

        @Html.ValidationMessageFor(model => model.SomeValue)

        <input type="submit" />
    </form>

When I validate the form, the error message

The field is required.

is shown. I gather the RequiredAttribute is kept... is there a way to get rid of it ?

Edit : I also tried to make the SomeValue a virtual field to override it, but the problem is the same.


问:
Retrieving JSON array with $.get but can't set retrieved array value outside function
If I do the following it gives me, in console.log, the values I want.

```<code>        var q;

        $.get('/ajax_subscribers', { code: 'qyhskkcnd'},
            function(returnedData){
                q = returnedData;
                console.log(q);
            });
</code>```

But if I do this

```<code>        var q;

        $.get('/ajax_subscribers', { code: 'qyhskkcnd'},
            function(returnedData){
                q = returnedData;
            });

        console.log(q);
</code>```

q has no value and is an undefined value? Why can't I set returnedData as public?

答:
Your $.get() is asynchronous.

To get around that, try setting a Promise.

Body:
If I do the following it gives me, in console.log, the values I want.

        var q;

        $.get('/ajax_subscribers', { code: 'qyhskkcnd'},
            function(returnedData){
                q = returnedData;
                console.log(q);
            });

But if I do this

        var q;

        $.get('/ajax_subscribers', { code: 'qyhskkcnd'},
            function(returnedData){
                q = returnedData;
            });

        console.log(q);

q has no value and is an undefined value? Why can't I set returnedData as public?


问:
Setting up the MKReverseGeocoderDelegate?
I am a little confused about setting up the MKReverseGeocoderDelegate, I noted from Apples example that they are assigning the MKReverseGeocoder to a property iVar, in the end I decided to alloc the MKReverseGeocoder when a position is found and release the MKReverseGeocoders as they either report back success or failure, does this seem right?</p>

```<code>// ------------------------------------------------------------------- **
// DELEGATE: CLLocationManager
// ------------------------------------------------------------------- **

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {

    MKReverseGeocoder *myGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:[newLocation coordinate]];
    [myGeocoder setDelegate:self];
    [myGeocoder start];
}

// ------------------------------------------------------------------- **
// DELEGATE: MKReverseGeocoderDelegate
// ------------------------------------------------------------------- **

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
    NSLog(@"%@", [placemark locality]);
    [geocoder release];
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
    [geocoder release];
}
@end
</code>```

答:
In the MKReverseGeocoder Class Reference, Apple says that

Each Map Kit application has a limited amount of reverse geocoding capacity, so it is to your advantage to use reverse geocode requests sparingly. Here are some rules of thumb for using this class most effectively:

Send at most one reverse-geocoding request for any one user action.

(...)

In your case, If there is a slow network connection (i.e. position changes are faster then location lookups), multiple requests can be instantiated.

Your code will probably work fine in most cases, however it is not the suggested way to implement it. And implementing anything that only works "in most cases" is not a goot idea at all.

Body:
I am a little confused about setting up the MKReverseGeocoderDelegate, I noted from Apples example that they are assigning the MKReverseGeocoder to a property iVar, in the end I decided to alloc the MKReverseGeocoder when a position is found and release the MKReverseGeocoders as they either report back success or failure, does this seem right?

// ------------------------------------------------------------------- **
// DELEGATE: CLLocationManager
// ------------------------------------------------------------------- **

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {

    MKReverseGeocoder *myGeocoder = [[MKReverseGeocoder alloc] initWithCoordinate:[newLocation coordinate]];
    [myGeocoder setDelegate:self];
    [myGeocoder start];
}

// ------------------------------------------------------------------- **
// DELEGATE: MKReverseGeocoderDelegate
// ------------------------------------------------------------------- **

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
    NSLog(@"%@", [placemark locality]);
    [geocoder release];
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error {
    [geocoder release];
}
@end


问:
How to activate linking to JIRA issues
I've seed in some JIRA projects that from the board or even the backlog, each issue created, you can click directly on it (link) to go to the actual issue.

In my case, when I see the board or backlog, I'm obligated to click on the issue then, in the appearing div on the right which shows the issue in more detail, you can see a link at the top to go to the issue, where can i configure this ?

As you can see, the issue key is not visible in each card, thus, no direct link to the issue. I first have to click on card, then in opening panel I see the issue key/link which I can then click. This is really annoying and time consuming.

The is the possibility to add 3 more fields to the cards; I tried in board settings >> card layout  but no issue key is available.

Edit

Expected result:

答:
Your links are there, it's just that they're shy and thus greyed-out:

You can Ctrl-click or middle-click the issue ID on the right, and the issue will open in a new tab.

Title: How to activate linking to JIRA issues


问:
I cant sort my Collection
This is my Code and I can't sort my LinkedList.

```<code>import java.util.Collections;
import java.util.LinkedList;

import org.omg.CosNaming.NameComponent;

public class Zug implements Comparable<Zug> {

    private String abfahrtzeit;
    private String zuggattung;
    private int zugnummer;
    private int fahrtzeit;

    public Zug(String zeile) {

        String[] teile = zeile.split(";");
        this.abfahrtzeit = teile[0];
        this.zuggattung = teile[1];
        this.zugnummer = Integer.parseInt(teile[2]);
        this.fahrtzeit = Integer.parseInt(teile[3]);

    }

    public String getAbfahrtzeit() {
        return abfahrtzeit;
    }

    public String getZuggattung() {
        return zuggattung;
    }

    public int getZugnummer() {
        return zugnummer;
    }

    public int getFahrtzeit() {
        return fahrtzeit;
    }

    public String toString() {
        return this.abfahrtzeit + ";" + this.zuggattung + ";" + this.zugnummer + ";" + this.fahrtzeit;
    }

  //                          This is the Problem Block

     @Override
    public int compareTo (Zug z) {

        String datei = "Zuege.dat";
        LinkedList<Zug> ll = new LinkedList<Zug>();

        Collections.sort( ll, new NameComponent() );

        ll = getDaten(datei);

        return this.fahrtzeit - z.getFahrtzeit();
    }
// End Of Problem Block

    private LinkedList<Zug> getDaten(String datei) {
        return null;
    }
}
</code>```

答:
As RealSkeptic and matoni write, you must not do anything other in the compareTo(Zug z) method than compare this to z - as the method name implies. compareTo(Zug z) is called by methods sorting a collection whenever they need to compare two elements of that collection. Loading lists of objects in that method doesn't make any sense.

The most simple implementation would be

```<code>@Override
public int compareTo(Zug z) {
    return this.fahrtzeit - z.getFahrtzeit();
}
</code>```

You may want to test your code with that implementation. Generate a few example Zug objects, add them to a List, sort that list using Collecitons.sort() and enjoy the result (or give us a meaningful error message).

Java Practices has an elaborate example on how to write a compareTo()-method.

Please note that this implementation is not consistent with equals() (as detailed in the javadoc).

Sorting by fahrzeit might not be the only way to sort your objects and probably should not be the natural order. You probably should implement a Comparator (e.g. FahrzeitComparator, AbfahrtzeitComparator ...) to be able to sort by different criteria. See this example.

Oh, and:

Rewriting your code with English variable names would allow more people to understand what your objects should represent...

Title: I cant sort my Collection

Body:
This is my Code and I can't sort my LinkedList.

import java.util.Collections;
import java.util.LinkedList;

import org.omg.CosNaming.NameComponent;

public class Zug implements Comparable<Zug> {

    private String abfahrtzeit;
    private String zuggattung;
    private int zugnummer;
    private int fahrtzeit;

    public Zug(String zeile) {

        String[] teile = zeile.split(";");
        this.abfahrtzeit = teile[0];
        this.zuggattung = teile[1];
        this.zugnummer = Integer.parseInt(teile[2]);
        this.fahrtzeit = Integer.parseInt(teile[3]);

    }

    public String getAbfahrtzeit() {
        return abfahrtzeit;
    }

    public String getZuggattung() {
        return zuggattung;
    }

    public int getZugnummer() {
        return zugnummer;
    }

    public int getFahrtzeit() {
        return fahrtzeit;
    }

    public String toString() {
        return this.abfahrtzeit + ";" + this.zuggattung + ";" + this.zugnummer + ";" + this.fahrtzeit;
    }

  //                          This is the Problem Block

     @Override
    public int compareTo (Zug z) {

        String datei = "Zuege.dat";
        LinkedList<Zug> ll = new LinkedList<Zug>();

        Collections.sort( ll, new NameComponent() );

        ll = getDaten(datei);

        return this.fahrtzeit - z.getFahrtzeit();
    }
// End Of Problem Block

    private LinkedList<Zug> getDaten(String datei) {
        return null;
    }
}

Body:
As RealSkeptic and matoni write, you must not do anything other in the compareTo(Zug z) method than compare this to z - as the method name implies. compareTo(Zug z) is called by methods sorting a collection whenever they need to compare two elements of that collection. Loading lists of objects in that method doesn't make any sense.

The most simple implementation would be

@Override
public int compareTo(Zug z) {
    return this.fahrtzeit - z.getFahrtzeit();
}

You may want to test your code with that implementation. Generate a few example Zug objects, add them to a List, sort that list using Collecitons.sort() and enjoy the result (or give us a meaningful error message).

Java Practices has an elaborate example on how to write a compareTo()-method.

Please note that this implementation is not consistent with equals() (as detailed in the javadoc).

Sorting by fahrzeit might not be the only way to sort your objects and probably should not be the natural order. You probably should implement a Comparator (e.g. FahrzeitComparator, AbfahrtzeitComparator ...) to be able to sort by different criteria. See this example.

Oh, and:

Rewriting your code with English variable names would allow more people to understand what your objects should represent...


问:
Building dynamic shared library (.so, .dylib) using Makefile and gcc
I would like to build shared library (.so, .dylib) with Makefile gcc.
My library has references (symbols) from other shared library (other C project compiled to shared library).

I have such directory structure:

```<code>/c/
  /Project1/...
  /Project2/...
  ...
  /unit_tests/...
  /comparers/...
</code>```

Inside my /comparers directory I have such directory structure:

I have tried in order to compile unit_test shared library that depends on comparers shared library make something like this:

```<code>$(SHARED_LIBRARY): assertion.o
    $(CC) $(CFLAGS) -shared -o $(OUTPUT_LIB_DIR)/$(SHARED_LIBRARY) $(OUTPUT_DIR)/assertion.o $(COMPARERS_SHARED_LIB_PATH)
</code>```

where:

```<code>COMPARERS_SHARED_LIB_PATH= ../comparers/output/debug/lib/libcomparers.so
</code>```

But It doesn't work if I use static library path instead it compiles correctly. Why this doesn't work and how to make it working correctly?

UPDATE: error message

Above is building correctly but I assume it cause error at runtime! When I link the same way my executable target it also builds, but when running it gives such error message:

```<code>dyld: Library not loaded: output/debug/lib/libcomparers.so
  Referenced from: /Users/michzio/Developer/MyProjects/BachelorDegree/c/unit_tests/./output/debug/bin/unit_tests
  Reason: image not found
Abort trap: 6
</code>```

答:
Although you did not post the error messages, there are a few errors that are immediately apparent.

One error is that you mix and match filenames with and without paths. E.g. $(SHARED_LIBRARY) is different from $(OUTPUT_LIB_DIR)/$(SHARED_LIBRARY) and assertion.o is different from $(OUTPUT_DIR)/assertion.o. You need to learn how to use GNU make's automatic variables to prevent such mistakes.

Another error is that the way you link to another shared library: the runtime linker searches for ../comparers/output/debug/lib/libcomparers.so and that path is valid only when the current directory is something specific.

And linking normally uses LDFLAGS, not CFLAGS.

One fix could be:

```<code>COMPARERS_SHARED_LIB_PATH := $(abspath ../comparers/output/debug/lib/libcomparers.so)

$(OUTPUT_LIB_DIR)/(SHARED_LIBRARY): $(OUTPUT_DIR)/assertion.o $(COMPARERS_SHARED_LIB_PATH)
    $(CC) -shared -o $@ $(LDFLAGS) $^
</code>```

For a production build though, it needs to specify -rpath to other shared libraries using $ORIGIN relative paths, so that the runtime linker finds the required shared libraries relative to its user. And link to that shared library using -L<path> -l<lib> rather than the full path.

Body:
I would like to build shared library (.so, .dylib) with Makefile gcc.
My library has references (symbols) from other shared library (other C project compiled to shared library).

I have such directory structure:

/c/
  /Project1/...
  /Project2/...
  ...
  /unit_tests/...
  /comparers/...

Inside my /comparers directory I have such directory structure:

I have tried in order to compile unit_test shared library that depends on comparers shared library make something like this:

$(SHARED_LIBRARY): assertion.o
    $(CC) $(CFLAGS) -shared -o $(OUTPUT_LIB_DIR)/$(SHARED_LIBRARY) $(OUTPUT_DIR)/assertion.o $(COMPARERS_SHARED_LIB_PATH)

where:

COMPARERS_SHARED_LIB_PATH= ../comparers/output/debug/lib/libcomparers.so

But It doesn't work if I use static library path instead it compiles correctly. Why this doesn't work and how to make it working correctly?

UPDATE: error message

Above is building correctly but I assume it cause error at runtime! When I link the same way my executable target it also builds, but when running it gives such error message:

dyld: Library not loaded: output/debug/lib/libcomparers.so
  Referenced from: /Users/michzio/Developer/MyProjects/BachelorDegree/c/unit_tests/./output/debug/bin/unit_tests
  Reason: image not found
Abort trap: 6

Body:
Although you did not post the error messages, there are a few errors that are immediately apparent.

One error is that you mix and match filenames with and without paths. E.g. $(SHARED_LIBRARY) is different from $(OUTPUT_LIB_DIR)/$(SHARED_LIBRARY) and assertion.o is different from $(OUTPUT_DIR)/assertion.o. You need to learn how to use GNU make's automatic variables to prevent such mistakes.

Another error is that the way you link to another shared library: the runtime linker searches for ../comparers/output/debug/lib/libcomparers.so and that path is valid only when the current directory is something specific.

And linking normally uses LDFLAGS, not CFLAGS.

One fix could be:

COMPARERS_SHARED_LIB_PATH := $(abspath ../comparers/output/debug/lib/libcomparers.so)

$(OUTPUT_LIB_DIR)/(SHARED_LIBRARY): $(OUTPUT_DIR)/assertion.o $(COMPARERS_SHARED_LIB_PATH)
    $(CC) -shared -o $@ $(LDFLAGS) $^

For a production build though, it needs to specify -rpath to other shared libraries using $ORIGIN relative paths, so that the runtime linker finds the required shared libraries relative to its user. And link to that shared library using -L<path> -l<lib> rather than the full path.


问:
c++ algorithm to select two random numbers from a range, with minimal distance
I have an std::vector initialized with numbers from 1 to 100

```<code>std::vector<int> vec;
for(int i = 1; i < 101; i++)
  vec.push_back(i);
</code>```

I want to select two random integers that have a minimal distance (for example minimal distance can be 10).

If num1, num2 are the numbers:

num2 - num1 > distance

I am using the following method to select a random integer between ranges:

```<code>int getRandomValue(int from, int to)
        {
                std::random_device seeder;
                std::mt19937 engine(seeder());
                std::uniform_int_distribution<int> dist(from, to);
                return dist(engine);
        }
</code>```

How can I generate num2 and num1?

答:
you can randomize num1 per example and sum the distance, then you have num2.

But you have to be careful cause num1 must be below or equal 100-distance

or the oposite randomize num2 from 10 to 100 and num1 = num2-distance

Body:
I have an std::vector initialized with numbers from 1 to 100

std::vector<int> vec;
for(int i = 1; i < 101; i++)
  vec.push_back(i);

I want to select two random integers that have a minimal distance (for example minimal distance can be 10).

If num1, num2 are the numbers:

num2 - num1 > distance

I am using the following method to select a random integer between ranges:

int getRandomValue(int from, int to)
        {
                std::random_device seeder;
                std::mt19937 engine(seeder());
                std::uniform_int_distribution<int> dist(from, to);
                return dist(engine);
        }

How can I generate num2 and num1?


问:
Is there documentation for the Rails column types?
I'm looking for more than the simple type listing that is found on this page:

:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean

But is there any documentation that actually defines these fields?

Specifically:

What's the difference between :string and :text?

Between :float and :decimal?

What are the distinguishing features of :time, :timestamp, and :datetime?

Are the nuances of these types documented anywhere?

EDIT: Points of DB-platform implementations are irrelevant to the question I'm trying to ask.  If, say, :datetime does not have a defined intended meaning in Rails documentation, then what do db-adapter-writers go by when choosing a corresponding column type?

答:
From Rails master branch source code I found:

abstract mysql_adapter

```<code>#activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb

  NATIVE_DATABASE_TYPES = {
    primary_key: "bigint auto_increment PRIMARY KEY",
    string:      { name: "varchar", limit: 255 },
    text:        { name: "text", limit: 65535 },
    integer:     { name: "int", limit: 4 },
    float:       { name: "float" },
    decimal:     { name: "decimal" },
    datetime:    { name: "datetime" },
    timestamp:   { name: "timestamp" },
    time:        { name: "time" },
    date:        { name: "date" },
    binary:      { name: "blob", limit: 65535 },
    boolean:     { name: "tinyint", limit: 1 },
    json:        { name: "json" },
  }

  # Maps logical Rails types to MySQL-specific data types.
  def type_to_sql(type, limit = nil, precision = nil, scale = nil, unsigned = nil)
    sql = case type.to_s
    when 'integer'
      integer_to_sql(limit)
    when 'text'
      text_to_sql(limit)
    when 'blob'
      binary_to_sql(limit)
    when 'binary'
      if (0..0xfff) === limit
        "varbinary(#{limit})"
      else
        binary_to_sql(limit)
      end
    else
      super(type, limit, precision, scale)
    end

    sql << ' unsigned' if unsigned && type != :primary_key
    sql
  end

# and integer ...

  def integer_to_sql(limit) # :nodoc:
    case limit
    when 1; 'tinyint'
    when 2; 'smallint'
    when 3; 'mediumint'
    when nil, 4; 'int'
    when 5..8; 'bigint'
    else raise(ActiveRecordError, "No integer type has byte size #{limit}")
    end
  end

 # and text ..

  def text_to_sql(limit) # :nodoc:
    case limit
    when 0..0xff;               'tinytext'
    when nil, 0x100..0xffff;    'text'
    when 0x10000..0xffffff;     'mediumtext'
    when 0x1000000..0xffffffff; 'longtext'
    else raise(ActiveRecordError, "No text type has byte length #{limit}")
    end
  end

# and binary ...

    def binary_to_sql(limit) # :nodoc:
      case limit
      when 0..0xff;               "tinyblob"
      when nil, 0x100..0xffff;    "blob"
      when 0x10000..0xffffff;     "mediumblob"
      when 0x1000000..0xffffffff; "longblob"
      else raise(ActiveRecordError, "No binary type has byte length #{limit}")
      end
    end
</code>```

the super in type_to_sql method

```<code>#activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
  def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
    type = type.to_sym if type
    if native = native_database_types[type]
      column_type_sql = (native.is_a?(Hash) ? native[:name] : native).dup

      if type == :decimal # ignore limit, use precision and scale
        scale ||= native[:scale]

        if precision ||= native[:precision]
          if scale
            column_type_sql << "(#{precision},#{scale})"
          else
            column_type_sql << "(#{precision})"
          end
        elsif scale
          raise ArgumentError, "Error adding decimal column: precision cannot be empty if scale is specified"
        end

      elsif [:datetime, :time].include?(type) && precision ||= native[:precision]
        if (0..6) === precision
          column_type_sql << "(#{precision})"
        else
          raise(ActiveRecordError, "No #{native[:name]} type has precision of #{precision}. The allowed range of precision is from 0 to 6")
        end
      elsif (type != :primary_key) && (limit ||= native.is_a?(Hash) && native[:limit])
        column_type_sql << "(#{limit})"
      end

      column_type_sql
    else
      type.to_s
    end
  end
</code>```

Body:
From Rails master branch source code I found:

abstract mysql_adapter

#activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb

  NATIVE_DATABASE_TYPES = {
    primary_key: "bigint auto_increment PRIMARY KEY",
    string:      { name: "varchar", limit: 255 },
    text:        { name: "text", limit: 65535 },
    integer:     { name: "int", limit: 4 },
    float:       { name: "float" },
    decimal:     { name: "decimal" },
    datetime:    { name: "datetime" },
    timestamp:   { name: "timestamp" },
    time:        { name: "time" },
    date:        { name: "date" },
    binary:      { name: "blob", limit: 65535 },
    boolean:     { name: "tinyint", limit: 1 },
    json:        { name: "json" },
  }

  # Maps logical Rails types to MySQL-specific data types.
  def type_to_sql(type, limit = nil, precision = nil, scale = nil, unsigned = nil)
    sql = case type.to_s
    when 'integer'
      integer_to_sql(limit)
    when 'text'
      text_to_sql(limit)
    when 'blob'
      binary_to_sql(limit)
    when 'binary'
      if (0..0xfff) === limit
        "varbinary(#{limit})"
      else
        binary_to_sql(limit)
      end
    else
      super(type, limit, precision, scale)
    end

    sql << ' unsigned' if unsigned && type != :primary_key
    sql
  end

# and integer ...

  def integer_to_sql(limit) # :nodoc:
    case limit
    when 1; 'tinyint'
    when 2; 'smallint'
    when 3; 'mediumint'
    when nil, 4; 'int'
    when 5..8; 'bigint'
    else raise(ActiveRecordError, "No integer type has byte size #{limit}")
    end
  end

 # and text ..

  def text_to_sql(limit) # :nodoc:
    case limit
    when 0..0xff;               'tinytext'
    when nil, 0x100..0xffff;    'text'
    when 0x10000..0xffffff;     'mediumtext'
    when 0x1000000..0xffffffff; 'longtext'
    else raise(ActiveRecordError, "No text type has byte length #{limit}")
    end
  end

# and binary ...

    def binary_to_sql(limit) # :nodoc:
      case limit
      when 0..0xff;               "tinyblob"
      when nil, 0x100..0xffff;    "blob"
      when 0x10000..0xffffff;     "mediumblob"
      when 0x1000000..0xffffffff; "longblob"
      else raise(ActiveRecordError, "No binary type has byte length #{limit}")
      end
    end

the super in type_to_sql method

#activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
  def type_to_sql(type, limit = nil, precision = nil, scale = nil) #:nodoc:
    type = type.to_sym if type
    if native = native_database_types[type]
      column_type_sql = (native.is_a?(Hash) ? native[:name] : native).dup

      if type == :decimal # ignore limit, use precision and scale
        scale ||= native[:scale]

        if precision ||= native[:precision]
          if scale
            column_type_sql << "(#{precision},#{scale})"
          else
            column_type_sql << "(#{precision})"
          end
        elsif scale
          raise ArgumentError, "Error adding decimal column: precision cannot be empty if scale is specified"
        end

      elsif [:datetime, :time].include?(type) && precision ||= native[:precision]
        if (0..6) === precision
          column_type_sql << "(#{precision})"
        else
          raise(ActiveRecordError, "No #{native[:name]} type has precision of #{precision}. The allowed range of precision is from 0 to 6")
        end
      elsif (type != :primary_key) && (limit ||= native.is_a?(Hash) && native[:limit])
        column_type_sql << "(#{limit})"
      end

      column_type_sql
    else
      type.to_s
    end
  end


问:
Getting 3D image from 2D image
I am doing a project in Matlab on Image processing

Is there any possibility of getting 3d image from 2d image?

答: If you have multiple images of the same object and the position of the camera when the picure was taken, then it is possible, but still not easy. You can find two such datasets and links to relevant articles here:  http://vision.middlebury.edu/mview/</p>

Title: Getting 3D image from 2D image


问:
How to get first and last day of the current week in JavaScript
I have today = new Date(); object. I need to get first and last day of the current week. I need both variants for Sunday and Monday as a start and end day of the week. I am little bit confuse now with a code. Can your help me?

答:
The excellent (and immutable) date-fns library handles this most concisely:

```<code>const start = startOfWeek(date);
const end = endOfWeek(date);
</code>```

Default start day of the week is Sunday (0), but it can be changed to Monday (1) like this:

```<code>const start = startOfWeek(date, {weekStartsOn: 1});
const end = endOfWeek(date, {weekStartsOn: 1});
</code>```

Body:
The excellent (and immutable) date-fns library handles this most concisely:

const start = startOfWeek(date);
const end = endOfWeek(date);

Default start day of the week is Sunday (0), but it can be changed to Monday (1) like this:

const start = startOfWeek(date, {weekStartsOn: 1});
const end = endOfWeek(date, {weekStartsOn: 1});


问:
How to Access Mono<T> While Handling Exception with onErrorMap()?
In data class I defined the 'name' must be unique across whole mongo collection:

```<code>@Document
data class Inn(@Indexed(unique = true) val name: String,
               val description: String) {
  @Id
  var id: String = UUID.randomUUID().toString()

  var intro: String = ""
}
</code>```

So in service I have to capture the unexpected exception if someone pass the same name again.

```<code>@Service
class InnService(val repository: InnRepository) {
  fun create(inn: Mono<Inn>): Mono<Inn> =
      repository
          .create(inn)
          .onErrorMap(
              DuplicateKeyException::class.java,
              { err -> InnAlreadyExistedException("The inn already existed", err) }
          )
}
</code>```

This is OK, but what if I want to add more info to the exceptional message like "The inn named '$it.name' already existed", what should I do for transforming exception with enriched message.

Clearly, assign Mono<Inn> to a local variable at the beginning is not a good idea...

Similar situation in handler,  I'd like to give client more info which derived from the customized exception, but no proper way can be found.

```<code>@Component
class InnHandler(val innService: InnService) {
  fun create(req: ServerRequest): Mono<ServerResponse> {
    return innService
        .create(req.bodyToMono<Inn>())
        .flatMap {
          created(URI.create("/api/inns/${it.id}"))
              .contentType(MediaType.APPLICATION_JSON_UTF8).body(it.toMono())
        }
        .onErrorReturn(
            InnAlreadyExistedException::class.java,
            badRequest().body(mapOf("code" to "SF400", "message" to t.message).toMono()).block()
        )
  }
}
</code>```

答:
In reactor, you aren't going to have the value you want handed to you in onErrorMap as an argument, you just get the Throwable. However, in Kotlin you can reach outside the scope of the error handler and just refer to inn directly. You don't need to change much:

```<code>fun create(inn: Mono<Inn>): Mono<Inn> =
    repository
      .create(inn)
      .onErrorMap(
          DuplicateKeyException::class.java,
          { InnAlreadyExistedException("The inn ${inn.name} already existed", it) }
      )
}
</code>```

Body:
In data class I defined the 'name' must be unique across whole mongo collection:

@Document
data class Inn(@Indexed(unique = true) val name: String,
               val description: String) {
  @Id
  var id: String = UUID.randomUUID().toString()

  var intro: String = ""
}

So in service I have to capture the unexpected exception if someone pass the same name again.

@Service
class InnService(val repository: InnRepository) {
  fun create(inn: Mono<Inn>): Mono<Inn> =
      repository
          .create(inn)
          .onErrorMap(
              DuplicateKeyException::class.java,
              { err -> InnAlreadyExistedException("The inn already existed", err) }
          )
}

This is OK, but what if I want to add more info to the exceptional message like "The inn named '$it.name' already existed", what should I do for transforming exception with enriched message.

Clearly, assign Mono<Inn> to a local variable at the beginning is not a good idea...

Similar situation in handler,  I'd like to give client more info which derived from the customized exception, but no proper way can be found.

@Component
class InnHandler(val innService: InnService) {
  fun create(req: ServerRequest): Mono<ServerResponse> {
    return innService
        .create(req.bodyToMono<Inn>())
        .flatMap {
          created(URI.create("/api/inns/${it.id}"))
              .contentType(MediaType.APPLICATION_JSON_UTF8).body(it.toMono())
        }
        .onErrorReturn(
            InnAlreadyExistedException::class.java,
            badRequest().body(mapOf("code" to "SF400", "message" to t.message).toMono()).block()
        )
  }
}

Body:
In reactor, you aren't going to have the value you want handed to you in onErrorMap as an argument, you just get the Throwable. However, in Kotlin you can reach outside the scope of the error handler and just refer to inn directly. You don't need to change much:

fun create(inn: Mono<Inn>): Mono<Inn> =
    repository
      .create(inn)
      .onErrorMap(
          DuplicateKeyException::class.java,
          { InnAlreadyExistedException("The inn ${inn.name} already existed", it) }
      )
}


问:
Start an application after build in Visual Studio?
I want to start an application after I built my solution in visual studio.
I'm running a batch file on the postbuild event, but I can't start the application, it opens an empty console.</p>

答:
If the application you are starting from you batch files forces the batch to wait till the application completes running it will cause the application you are building to never complete building.

Basically your build task does not complete so the build does not complete.


问:
NgModule vs Component
So I'm learning angular2 now and reading ngbook2 about the modules.
Modules contain components, but also can import different modules with their public components.

And the question is: What is the scope of the module component (in this meaning scope as parts of an application, not the reach of variables inside). Is module the whole application or just some part like header, containing its components?

What is the typicaly used convention?

答:
In one whole application, there can be one main Module.
But your application can be divided into multiple modules and can be injected into the Main Module.
Let's say you have a big application library which contains movies, trailer, songs etc.
You gave the main app Module name 'MyApp'.
but further you divided your app into multiple components say.

MovieComponent

SongComponent (further divided into AudioComponent and VideoComponent)

TrailerComponent

All these Component developed and tested individually and integrated to our MyAppModule.

In case anything happens in our Trailer part we can discard/test our TrailerComponent.

So It is easy to maintain a large Applications.

I hope this will help you to understand. any suggestions most welcomed

Title: NgModule vs Component


问:
onchange="" doesn't work in select tag
I have two tags of select. Their IDs is "study-phase" and "study-year".
I want when the value of study phase to process a CSS code.

HTML:

```<code><select name="study-phase" onchange="myFunction()" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>
<style type="text/css">
    #a , #b , #c , #d , #f , #g , #h , #j , #k , #e , #i {
        display: none;
    }
</style>
</code>```

JS:

```<code>$(function(myFunction()){
   if (document.getElementById("study-phase").value == "pri") {
       document.getElementById("a").style.display = "block";
   }
});
</code>```

And after run the code the css code which I  want don't launch.
What's the problem here ?

答:
You can do something like this instead:

$(document).ready(function() {
  $("#study-phase").on("change", function() {
    if (document.getElementById("study-phase").value === "pri") {
      $('option#a').show();
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#a,
#b,
#c,
#d,
#f,
#g,
#h,
#j,
#k,
#e,
#i {
  display: none;
}</code>```

<select name="study-phase" id="study-phase" class="sp-input">
  <option value=""></option>
  <option id="pri" value="pri">Primary</option>
  <option id="pre" value="pre">Prep</option>
  <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
  <option value=""></option>
  <option id="a" value="aa">Grade 1</option>
  <option id="b" value="">Grade 2</option>
  <option id="c" value="">Grade 3</option>
  <option id="d" value="">Grade 4</option>
  <option id="e" value="">Grade 5</option>
  <option id="f" value="">Grade 6</option>
  <option id="g" value="">Grade 7</option>
  <option id="h" value="">Grade 8</option>
  <option id="i" value="">Grade 9</option>
  <option id="j" value="">Grade 10</option>
</select>```

Title: onchange="" doesn't work in select tag

Body:
I have two tags of select. Their IDs is "study-phase" and "study-year".
I want when the value of study phase to process a CSS code.

HTML:

<select name="study-phase" onchange="myFunction()" id="study-phase" class="sp-input">
    <option value=""></option>
    <option id="pri" value="pri">Primary</option>
    <option id="pre" value="pre">Prep</option>
    <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
    <option value=""></option>
    <option id="a" value="aa">Grade 1</option>
    <option id="b" value="">Grade 2</option>
    <option id="c" value="">Grade 3</option>
    <option id="d" value="">Grade 4</option>
    <option id="e" value="">Grade 5</option>
    <option id="f" value="">Grade 6</option>
    <option id="g" value="">Grade 7</option>
    <option id="h" value="">Grade 8</option>
    <option id="i" value="">Grade 9</option>
    <option id="j" value="">Grade 10</option>
</select>

JS:

$(function(myFunction()){
   if (document.getElementById("study-phase").value == "pri") {
       document.getElementById("a").style.display = "block";
   }
});

And after run the code the css code which I  want don't launch.
What's the problem here ?

Body:
You can do something like this instead:

$(document).ready(function() {
  $("#study-phase").on("change", function() {
    if (document.getElementById("study-phase").value === "pri") {
      $('option#a').show();
    }
  });
});

#a,
#b,
#c,
#d,
#f,
#g,
#h,
#j,
#k,
#e,
#i {
  display: none;
}

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

<select name="study-phase" id="study-phase" class="sp-input">
  <option value=""></option>
  <option id="pri" value="pri">Primary</option>
  <option id="pre" value="pre">Prep</option>
  <option id="sec" value="sec">Secondary</option>
</select>
<select name="study-year" id="study-year" class="sp-input">
  <option value=""></option>
  <option id="a" value="aa">Grade 1</option>
  <option id="b" value="">Grade 2</option>
  <option id="c" value="">Grade 3</option>
  <option id="d" value="">Grade 4</option>
  <option id="e" value="">Grade 5</option>
  <option id="f" value="">Grade 6</option>
  <option id="g" value="">Grade 7</option>
  <option id="h" value="">Grade 8</option>
  <option id="i" value="">Grade 9</option>
  <option id="j" value="">Grade 10</option>
</select>