问:
When creating a multiple project template for visual studio is there a way to use parameters in the root template file?
I am trying to create a multi project template.  I wish the sub projects names to contain the solution name.  I have tried the following however $safeprojectName$ doesn't work in the root template for some reason.  It tries to create the folders with $safeprojectName$ in the name rather than the actual project name.

<VSTemplate Version="2.0.0" Type="ProjectGroup"
  xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
  <TemplateData>
    <Name>Default Solution</Name>
    <Description>An example of a multi-project template</Description>
    <Icon>Icon.ico</Icon>
    <ProjectType>CSharp</ProjectType>
  </TemplateData>
  <TemplateContent>
    <ProjectCollection>
      <SolutionFolder Name="$safeprojectName$.Web">
        <ProjectTemplateLink ProjectName="$safeprojectName$.Web">
          Src\Web\MyTemplate.vstemplate
        </ProjectTemplateLink>
      </SolutionFolder>
    </ProjectCollection>
  </TemplateContent>
</VSTemplate>
```

<p>I have done a lot of reading on this and have and have created an assembly using the IWizard interface that creates a parameter $solutionName$.  I then used the following template.</p>

<pre class="lang-xml prettyprint-override"><code><VSTemplate Version="2.0.0" Type="ProjectGroup"
  xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
  <TemplateData>
    <Name>Default Solution</Name>
    <Description>An example of a multi-project template</Description>
    <Icon>Icon.ico</Icon>
    <ProjectType>CSharp</ProjectType>
  </TemplateData>
  <TemplateContent>
    <ProjectCollection>
      <SolutionFolder Name="$solutionName$.Web">
        <ProjectTemplateLink ProjectName="$solutionName$.Web">
          Src\Web\MyTemplate.vstemplate
        </ProjectTemplateLink>
      </SolutionFolder>
    </ProjectCollection>
  </TemplateContent>
  <WizardExtension>
    <Assembly>DefaultSoloutionWizard, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=f753ddb61a28cb36, processorArchitecture=MSIL</Assembly>
    <FullClassName>DefaultSoloutionWizard.WizardImplementation</FullClassName>
  </WizardExtension>
</VSTemplate>
</code>```

This however also fails with the same problem.  I'm I trying to do the impossible? Any help on this would be most welcome.

答:
Yes, you need to use a static dictionary in the wizard of root template, which will be used by the wizard implementation of child templates:

IWizard implementation in root template

public void RunStarted(object automationObject,
        Dictionary<string, string> replacementsDictionary,
        WizardRunKind runKind, object[] customParams)
    {
        try
        {
            // Display a form to the user. The form collects
            // input for the custom message.
            inputForm = new UserInputForm();
            inputForm.ShowDialog();

            customMessage = inputForm.get_CustomMessage();

            // Add custom parameters.
            replacementsDictionary.Add("$custommessage$",
                customMessage);
            globalDictionary = new Dictionary<string, string>();
            globalDictionary.Add("$custommessage$",
                customMessage);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    public static Dictionary<string, string> globalDictionary;
```

You can get the complete example implemented here: Multi-Project Templates with Wizard: Visual Studio 2010 Sample

Body:
I am trying to create a multi project template.  I wish the sub projects names to contain the solution name.  I have tried the following however $safeprojectName$ doesn't work in the root template for some reason.  It tries to create the folders with $safeprojectName$ in the name rather than the actual project name.

<VSTemplate Version="2.0.0" Type="ProjectGroup"
  xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
  <TemplateData>
    <Name>Default Solution</Name>
    <Description>An example of a multi-project template</Description>
    <Icon>Icon.ico</Icon>
    <ProjectType>CSharp</ProjectType>
  </TemplateData>
  <TemplateContent>
    <ProjectCollection>
      <SolutionFolder Name="$safeprojectName$.Web">
        <ProjectTemplateLink ProjectName="$safeprojectName$.Web">
          Src\Web\MyTemplate.vstemplate
        </ProjectTemplateLink>
      </SolutionFolder>
    </ProjectCollection>
  </TemplateContent>
</VSTemplate>

I have done a lot of reading on this and have and have created an assembly using the IWizard interface that creates a parameter $solutionName$.  I then used the following template.

<VSTemplate Version="2.0.0" Type="ProjectGroup"
  xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
  <TemplateData>
    <Name>Default Solution</Name>
    <Description>An example of a multi-project template</Description>
    <Icon>Icon.ico</Icon>
    <ProjectType>CSharp</ProjectType>
  </TemplateData>
  <TemplateContent>
    <ProjectCollection>
      <SolutionFolder Name="$solutionName$.Web">
        <ProjectTemplateLink ProjectName="$solutionName$.Web">
          Src\Web\MyTemplate.vstemplate
        </ProjectTemplateLink>
      </SolutionFolder>
    </ProjectCollection>
  </TemplateContent>
  <WizardExtension>
    <Assembly>DefaultSoloutionWizard, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=f753ddb61a28cb36, processorArchitecture=MSIL</Assembly>
    <FullClassName>DefaultSoloutionWizard.WizardImplementation</FullClassName>
  </WizardExtension>
</VSTemplate>

This however also fails with the same problem.  I'm I trying to do the impossible? Any help on this would be most welcome.

Body:
Yes, you need to use a static dictionary in the wizard of root template, which will be used by the wizard implementation of child templates:

IWizard implementation in root template

public void RunStarted(object automationObject,
        Dictionary<string, string> replacementsDictionary,
        WizardRunKind runKind, object[] customParams)
    {
        try
        {
            // Display a form to the user. The form collects
            // input for the custom message.
            inputForm = new UserInputForm();
            inputForm.ShowDialog();

            customMessage = inputForm.get_CustomMessage();

            // Add custom parameters.
            replacementsDictionary.Add("$custommessage$",
                customMessage);
            globalDictionary = new Dictionary<string, string>();
            globalDictionary.Add("$custommessage$",
                customMessage);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    public static Dictionary<string, string> globalDictionary;

You can get the complete example implemented here: Multi-Project Templates with Wizard: Visual Studio 2010 Sample


来源: stackexchange

问:
BroadCast Intent WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION not calling and hence not getting list of peers
Hey I am making an android app based on training samples from developer.android.com Here is my MainActivity Code :

```<code>    package com.example.hellowifi;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    import android.app.Activity;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.IntentFilter;
    import android.net.wifi.WpsInfo;
    import android.net.wifi.p2p.WifiP2pConfig;
    import android.net.wifi.p2p.WifiP2pDevice;
    import android.net.wifi.p2p.WifiP2pDeviceList;
    import android.net.wifi.p2p.WifiP2pInfo;
    import android.net.wifi.p2p.WifiP2pManager;
    import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceInfo;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ListView;
    import android.widget.Toast;

 public class MainActivity extends Activity {

private final IntentFilter mIntentFilter = new IntentFilter();
private WifiP2pManager mManager = null;
private WifiP2pManager.Channel mChannel = null;
private BroadcastReceiver mReciever;
private ListView mListView;
public static final String TAG = "wifidirectdemo";

// TXT RECORD properties
public static final String TXTRECORD_PROP_AVAILABLE = "available";
public static final String SERVICE_INSTANCE = "_wifidemotest";
public static final String SERVICE_REG_TYPE = "_presence._tcp";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mListView = (ListView) findViewById(R.id.listView);

    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    mChannel = mManager.initialize(this, getMainLooper(), null);
    mReciever = new WiFiBroadCastReciever(mManager, mChannel, this);
    startRegistration();
}

@Override
protected void onResume() {
    super.onResume();
    mReciever = new WiFiBroadCastReciever(mManager, mChannel, this);
    registerReceiver(mReciever, mIntentFilter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mReciever);
}

public void OnDiscoverButtonClicked(View view) {
    mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
        @Override
        public void onSuccess() {
            Toast.makeText(MainActivity.this, "Discovery Process Succeded", Toast.LENGTH_SHORT).show();
            System.out.println("changed");
        }

        @Override
        public void onFailure(int reason) {
            Toast.makeText(MainActivity.this, "Discovery Process Failed", Toast.LENGTH_SHORT).show();
        }
    });
}

private static List peers = new ArrayList();/*
private ArrayAdapter listAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,peers);*/

static WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
    @Override
    public void onPeersAvailable(WifiP2pDeviceList peerList) {
        peers.clear();
        peers.addAll(peerList.getDeviceList());
    }
};

private void startRegistration() {
    //  Create a string map containing information about your service.
    Map record = new HashMap();
    record.put(TXTRECORD_PROP_AVAILABLE, "visible");

    // Service information.  Pass it an instance name, service type
    // _protocol._transportlayer , and the map containing
    // information other devices will want once they connect to this one.
    WifiP2pDnsSdServiceInfo serviceInfo =
            WifiP2pDnsSdServiceInfo.newInstance("_test", "_presence._tcp", record);

    // Add the local service, sending the service info, network channel,
    // and listener that will be used to indicate success or failure of
    // the request.
    mManager.addLocalService(mChannel, serviceInfo, new WifiP2pManager.ActionListener() {
        @Override
        public void onSuccess() {
            Toast.makeText(MainActivity.this, "Added Local Service", Toast.LENGTH_SHORT);
        }

        @Override
        public void onFailure(int arg0) {
            Toast.makeText(MainActivity.this,"Failed to add a service",Toast.LENGTH_SHORT);
        }
    });
}
</code>```

}

and my Broadcastreciever class is this :

```<code>package com.example.hellowifi;

import java.util.HashMap;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.util.Log;
import android.widget.Toast;

public class WiFiBroadCastReciever extends BroadcastReceiver {

private MainActivity activity;
private WifiP2pManager mManager=null;
private WifiP2pManager.Channel mChannel=null;
PeerListListener myPeerListListener = null;

public WiFiBroadCastReciever(WifiP2pManager manager, WifiP2pManager.Channel channel,
                                   Activity activity) {
    super();
    this.mManager = manager;
    this.mChannel = channel;
    this.activity = (MainActivity) activity;
}

@Override
public void onReceive(Context context, Intent intent) {
    String action=intent.getAction();

    if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){

        int state=intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
        if (WifiP2pManager.WIFI_P2P_STATE_ENABLED==state)
            Log.d("WiFiBroadCastReciever", "WiFi enabled");
        else
            Log.d("WiFiBroadCastReciever", "WiFi disabled");
    }
    else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
        Toast.makeText(activity, "in intent", Toast.LENGTH_LONG).show();
        if (mManager != null) {
            mManager.requestPeers(mChannel, myPeerListListener);
        }
    }
    else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
        if (mManager == null) {
            return;
        }

        NetworkInfo networkInfo = (NetworkInfo) intent
                .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

        if (networkInfo.isConnected()) {
            // We are connected with the other device, request connection
            // info to find group owner IP
            /*mManager.requestConnectionInfo(mChannel, connectionListener);*/
        }

    }
    else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){

    }
}

final HashMap<String, String> buddies = new HashMap<String, String>();
</code>```

}

I am getting successful calls to Broadcasting Intents WIFI_P2P_STATE_CHANGED_ACTION,WIFI_P2P_CONNECTION_CHANGED_ACTION,WIFI_P2P_THIS_DEVICE_CHANGED_ACTION but not to WIFI_P2P_PEERS_CHANGED_ACTION
when I am making tethering and portable hotspot to other device and trying to discovering on my device.

Note that: WiFi is enabled and I am also getting Toast of Discovery successful. After that WIFI_P2P_PEERS_CHANGED_ACTION intent is not calling.
I tried searching on each and every thread.
Please try to help me someone. Thanks in advance.

答:
I had the same problem before. Please check below scenario how I have fixed the issue.

First I have implemented the same code in server and client android device with minor changes. I have placed a button in server app to invoke the discoverPeers() method. At the same time my client app is running and connected to the same WI-FI network. Then it triggers the WIFI_P2P_PEERS_CHANGED_ACTION event from broadcast in server app. There I have got the list of nearby peers.

ContentLicense: CC BY-SA 3.0

Body:
Hey I am making an android app based on training samples from developer.android.com Here is my MainActivity Code :

    package com.example.hellowifi;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    import android.app.Activity;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.IntentFilter;
    import android.net.wifi.WpsInfo;
    import android.net.wifi.p2p.WifiP2pConfig;
    import android.net.wifi.p2p.WifiP2pDevice;
    import android.net.wifi.p2p.WifiP2pDeviceList;
    import android.net.wifi.p2p.WifiP2pInfo;
    import android.net.wifi.p2p.WifiP2pManager;
    import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceInfo;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ListView;
    import android.widget.Toast;

 public class MainActivity extends Activity {

private final IntentFilter mIntentFilter = new IntentFilter();
private WifiP2pManager mManager = null;
private WifiP2pManager.Channel mChannel = null;
private BroadcastReceiver mReciever;
private ListView mListView;
public static final String TAG = "wifidirectdemo";

// TXT RECORD properties
public static final String TXTRECORD_PROP_AVAILABLE = "available";
public static final String SERVICE_INSTANCE = "_wifidemotest";
public static final String SERVICE_REG_TYPE = "_presence._tcp";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mListView = (ListView) findViewById(R.id.listView);

    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    mChannel = mManager.initialize(this, getMainLooper(), null);
    mReciever = new WiFiBroadCastReciever(mManager, mChannel, this);
    startRegistration();
}

@Override
protected void onResume() {
    super.onResume();
    mReciever = new WiFiBroadCastReciever(mManager, mChannel, this);
    registerReceiver(mReciever, mIntentFilter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mReciever);
}

public void OnDiscoverButtonClicked(View view) {
    mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
        @Override
        public void onSuccess() {
            Toast.makeText(MainActivity.this, "Discovery Process Succeded", Toast.LENGTH_SHORT).show();
            System.out.println("changed");
        }

        @Override
        public void onFailure(int reason) {
            Toast.makeText(MainActivity.this, "Discovery Process Failed", Toast.LENGTH_SHORT).show();
        }
    });
}

private static List peers = new ArrayList();/*
private ArrayAdapter listAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,peers);*/

static WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
    @Override
    public void onPeersAvailable(WifiP2pDeviceList peerList) {
        peers.clear();
        peers.addAll(peerList.getDeviceList());
    }
};

private void startRegistration() {
    //  Create a string map containing information about your service.
    Map record = new HashMap();
    record.put(TXTRECORD_PROP_AVAILABLE, "visible");

    // Service information.  Pass it an instance name, service type
    // _protocol._transportlayer , and the map containing
    // information other devices will want once they connect to this one.
    WifiP2pDnsSdServiceInfo serviceInfo =
            WifiP2pDnsSdServiceInfo.newInstance("_test", "_presence._tcp", record);

    // Add the local service, sending the service info, network channel,
    // and listener that will be used to indicate success or failure of
    // the request.
    mManager.addLocalService(mChannel, serviceInfo, new WifiP2pManager.ActionListener() {
        @Override
        public void onSuccess() {
            Toast.makeText(MainActivity.this, "Added Local Service", Toast.LENGTH_SHORT);
        }

        @Override
        public void onFailure(int arg0) {
            Toast.makeText(MainActivity.this,"Failed to add a service",Toast.LENGTH_SHORT);
        }
    });
}

}

and my Broadcastreciever class is this :

package com.example.hellowifi;

import java.util.HashMap;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.util.Log;
import android.widget.Toast;

public class WiFiBroadCastReciever extends BroadcastReceiver {

private MainActivity activity;
private WifiP2pManager mManager=null;
private WifiP2pManager.Channel mChannel=null;
PeerListListener myPeerListListener = null;

public WiFiBroadCastReciever(WifiP2pManager manager, WifiP2pManager.Channel channel,
                                   Activity activity) {
    super();
    this.mManager = manager;
    this.mChannel = channel;
    this.activity = (MainActivity) activity;
}

@Override
public void onReceive(Context context, Intent intent) {
    String action=intent.getAction();

    if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){

        int state=intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
        if (WifiP2pManager.WIFI_P2P_STATE_ENABLED==state)
            Log.d("WiFiBroadCastReciever", "WiFi enabled");
        else
            Log.d("WiFiBroadCastReciever", "WiFi disabled");
    }
    else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
        Toast.makeText(activity, "in intent", Toast.LENGTH_LONG).show();
        if (mManager != null) {
            mManager.requestPeers(mChannel, myPeerListListener);
        }
    }
    else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
        if (mManager == null) {
            return;
        }

        NetworkInfo networkInfo = (NetworkInfo) intent
                .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

        if (networkInfo.isConnected()) {
            // We are connected with the other device, request connection
            // info to find group owner IP
            /*mManager.requestConnectionInfo(mChannel, connectionListener);*/
        }

    }
    else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){

    }
}

final HashMap<String, String> buddies = new HashMap<String, String>();

}

I am getting successful calls to Broadcasting Intents WIFI_P2P_STATE_CHANGED_ACTION,WIFI_P2P_CONNECTION_CHANGED_ACTION,WIFI_P2P_THIS_DEVICE_CHANGED_ACTION but not to WIFI_P2P_PEERS_CHANGED_ACTION
when I am making tethering and portable hotspot to other device and trying to discovering on my device.

Note that: WiFi is enabled and I am also getting Toast of Discovery successful. After that WIFI_P2P_PEERS_CHANGED_ACTION intent is not calling.
I tried searching on each and every thread.
Please try to help me someone. Thanks in advance.


问:
How to adjust audio balance in iOS
In iOS system settings, To adjust the volume balance, head to Settings > General > Accessibility. Here, you can adjust the left/right volume balance or set the audio to mono.

But can we do it in our app with our code ? objective-c or swift.

My app need play audio,video and virtual midi audio by 'Audio Unit', And I have try follow things:

When I play audio,I can use pan property with AVAudioPlayer. It's work.

When I play video with AVPlayer, Sorry. Here haven't pan property with AVPlayer. And I'm refused how to implement this.

When I play midi virtual audio by Audio Unit. I found related question in How to set pan in IOS Audio Unit Framework

AudioUnitParameterValue panValue = -1; // panned almost dead-right. possible values are between -1 and 1
int result = AudioUnitSetParameter(mixerUnit, kMultiChannelMixerParam_Pan, kAudioUnitScope_Input, 0, panValue, 0);
if (result == 0)
{
   NSLog("success");
}

I get success result,but right channel steal have audio output.

So I'm stuck in video and midi virtual audio part. How to set pan with the audio output? Any advice to me I'm so appreciate.

答:
I have the same problem when using the AudioToolbox library.
However, I found the following code "AudioBalanceFade", but I don't know what "UnsafePointer " parameter is.
This code works, but I can't find an example. Maybe you can solve this part, and I'm glad you told me how you did it.
here Apple developer code Structure

Sorry for my English!

Title: How to adjust audio balance in iOS

ContentLicense: CC BY-SA 4.0


问:
TabLayout+ViewPager+Fragment the first tab didn't display the data?
I use TabLayout+ViewPager+Fragment in my Activity,when I enter the Activity,the first fragment didn't display the data,but I scrolled to the second fragment then scrolled to the third fragment,and I scrolled to the first fragment again,the first fragment display the data. I didn't know why this is.And I try to changedFragmentPagerAdapter to FragmentStatePagerAdapter,it didn't work. The following is my code:

```<code>titles = new ArrayList<>();
 titles.add("未使用");
 titles.add("已使用");
 titles.add("已失效");
 fragments = new ArrayList<>();
 fragments.add(new TicketUnuseFragment());
 fragments.add(new TicketUseFragment());
 fragments.add(new TicketInvalidFragment());

tabLayout = (TabLayout) findViewById(R.id.award_tablayout);
viewPager = (ViewPager) findViewById(R.id.award_view_pager);
viewPager.setAdapter(new FragmentAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
</code>```

FragmentStatePagerAdapter

```<code>public class FragmentAdapter extends FragmentStatePagerAdapter {

    public FragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }

}
</code>```

The TicketUnuseFragment code:

```<code>ublic class TicketUnuseFragment extends AbsFragment {

private RecyclerView recyclerView;
private AwardCenterRecyclerViewAdapter recyclerAdapter;

@Override
public void onServerMessage(Message msg) {
    if (msg.obj != null) {
        IResponseVO iResponseVO = (IResponseVO) msg.obj;
        if (iResponseVO.getServerCode().equals(ServerCode.PatientCouponList)) {
            if (HttpClient.RESULT_OK == iResponseVO.getStatus()) {
                AwardCenterListResponse mpRespBean = (AwardCenterListResponse) iResponseVO;
                recyclerAdapter.setData(mpRespBean.getList());
                recyclerAdapter.notifyDataSetChanged();
            }
        }
    }
}

@Override
protected View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_ticket_unused, container, false);
    recyclerView = (RecyclerView) view.findViewById(R.id.unuse_ticket_recyclerview);
    recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
    recyclerAdapter = new AwardCenterRecyclerViewAdapter(mActivity);
    recyclerView.setAdapter(recyclerAdapter);
    return view;
}

@Override
protected void initVariables() {
}

@Override
protected void loadData() {
    try {
        RwardCenterRequest requestBean = new RwardCenterRequest();
        requestBean.setTabType(1);
        requestBean.setPage(0);
        HttpClient.getInstance(mActivity).requestTextByPost(mActivity, requestHandler, ServerCode.PatientCouponList, requestBean);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
</code>```

}

Thanks, advanced!

答:
Population of the tabs to display is done through TabLayout.Tab instances.
So in your main code just after getting the reference of the TabLayout add these lines.</p>

```<code> tabLayout.addTab(tabLayout.newTab().setText("未使用""));
 tabLayout.addTab(tabLayout.newTab().setText("已使用"));
 tabLayout.addTab(tabLayout.newTab().setText("已失效"));
</code>```

Body:
I use TabLayout+ViewPager+Fragment in my Activity,when I enter the Activity,the first fragment didn't display the data,but I scrolled to the second fragment then scrolled to the third fragment,and I scrolled to the first fragment again,the first fragment display the data. I didn't know why this is.And I try to changedFragmentPagerAdapter to FragmentStatePagerAdapter,it didn't work. The following is my code:

titles = new ArrayList<>();
 titles.add("未使用");
 titles.add("已使用");
 titles.add("已失效");
 fragments = new ArrayList<>();
 fragments.add(new TicketUnuseFragment());
 fragments.add(new TicketUseFragment());
 fragments.add(new TicketInvalidFragment());

tabLayout = (TabLayout) findViewById(R.id.award_tablayout);
viewPager = (ViewPager) findViewById(R.id.award_view_pager);
viewPager.setAdapter(new FragmentAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);

FragmentStatePagerAdapter

public class FragmentAdapter extends FragmentStatePagerAdapter {

    public FragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }

}

The TicketUnuseFragment code:

ublic class TicketUnuseFragment extends AbsFragment {

private RecyclerView recyclerView;
private AwardCenterRecyclerViewAdapter recyclerAdapter;

@Override
public void onServerMessage(Message msg) {
    if (msg.obj != null) {
        IResponseVO iResponseVO = (IResponseVO) msg.obj;
        if (iResponseVO.getServerCode().equals(ServerCode.PatientCouponList)) {
            if (HttpClient.RESULT_OK == iResponseVO.getStatus()) {
                AwardCenterListResponse mpRespBean = (AwardCenterListResponse) iResponseVO;
                recyclerAdapter.setData(mpRespBean.getList());
                recyclerAdapter.notifyDataSetChanged();
            }
        }
    }
}

@Override
protected View initViews(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_ticket_unused, container, false);
    recyclerView = (RecyclerView) view.findViewById(R.id.unuse_ticket_recyclerview);
    recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
    recyclerAdapter = new AwardCenterRecyclerViewAdapter(mActivity);
    recyclerView.setAdapter(recyclerAdapter);
    return view;
}

@Override
protected void initVariables() {
}

@Override
protected void loadData() {
    try {
        RwardCenterRequest requestBean = new RwardCenterRequest();
        requestBean.setTabType(1);
        requestBean.setPage(0);
        HttpClient.getInstance(mActivity).requestTextByPost(mActivity, requestHandler, ServerCode.PatientCouponList, requestBean);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Thanks, advanced!

Body:
Population of the tabs to display is done through TabLayout.Tab instances.
So in your main code just after getting the reference of the TabLayout add these lines.

 tabLayout.addTab(tabLayout.newTab().setText("未使用""));
 tabLayout.addTab(tabLayout.newTab().setText("已使用"));
 tabLayout.addTab(tabLayout.newTab().setText("已失效"));


问:
Asp.NET - Identity 2 - Invalid Token Error - Php
I'm using Asp.Net-Identity-2 and I developed the verification email flow.

Everything is working well on my local environment but as soon as I deploy the code to my server and I test the same scenario (that is working on my local) on my server, it says "Invalid Token".

Scenario

Change email

Receive e-mail

Click on the link "Verify email"

Redirected to webpage

A message pop up saying "Invalid Token"

I already check all the possible mistakes that are in this question and I have everything right, that's why is working perfectly on my local. Has to be something with the server. I thought the date of the server could affect but I put on sync the date of my Database Server and my Web server and it's still failing.

I am using GenerateEmailConfirmationTokenAsync to generate the token and using ConfirmEmailAsync to confirm the token. I am really executing this methods because I put logs for this so I can be sure of it (When you don't know what happens you have to be sure of everything right?)

I already encode/decode the url so the token doesn't get corrupted. I am sure of this because I put logs and run the code in the server and checked couple of times.

The user has a security stamp in the database, so it's not that

The TokenLifeSpan is 8 days. So it's not that.

I even tried the AllowOnlyAlphanumericUserNames property = false in UserValidator and even the UniqueEmail = false

```<code>userManager.UserValidator = new UserValidator<User>(userManager) { AllowOnlyAlphanumericUserNames = false, UniqueEmail = false };
</code>```

Code to generate the token

```<code>ApplicationUserManager.GenerateEmailConfirmationTokenAsync(userId);
</code>```

Code to confirm the token

```<code>ApplicationUserManager.ConfirmEmailAsync(subject, token);
</code>```

Any idea?

Update

It was working on the server/local with all the clients but not with the Php client and the Php client was doing extra work which was changing the Security stamp hence the problem.

As the only client on the server was in Php, I thought that something was wrong with the server and not with my local environment. After installing the whole environment (with php client) in my local and debug, I found out the problem. Please read the answer below.

答:
Well, the error was caused by a code that was being execute after the token generation. This code was changing the SecurityStamp of the user in the database.

As the Asp.Net Identity 2 uses the the Security Stamp to generate and validate the token and it was changed after the generation of the token, the token was always invalid.

Thanks!

Body:
I'm using Asp.Net-Identity-2 and I developed the verification email flow.

Everything is working well on my local environment but as soon as I deploy the code to my server and I test the same scenario (that is working on my local) on my server, it says "Invalid Token".

Scenario

Change email

Receive e-mail

Click on the link "Verify email"

Redirected to webpage

A message pop up saying "Invalid Token"

I already check all the possible mistakes that are in this question and I have everything right, that's why is working perfectly on my local. Has to be something with the server. I thought the date of the server could affect but I put on sync the date of my Database Server and my Web server and it's still failing.

I am using GenerateEmailConfirmationTokenAsync to generate the token and using ConfirmEmailAsync to confirm the token. I am really executing this methods because I put logs for this so I can be sure of it (When you don't know what happens you have to be sure of everything right?)

I already encode/decode the url so the token doesn't get corrupted. I am sure of this because I put logs and run the code in the server and checked couple of times.

The user has a security stamp in the database, so it's not that

The TokenLifeSpan is 8 days. So it's not that.

I even tried the AllowOnlyAlphanumericUserNames property = false in UserValidator and even the UniqueEmail = false

userManager.UserValidator = new UserValidator<User>(userManager) { AllowOnlyAlphanumericUserNames = false, UniqueEmail = false };

Code to generate the token

ApplicationUserManager.GenerateEmailConfirmationTokenAsync(userId);

Code to confirm the token

ApplicationUserManager.ConfirmEmailAsync(subject, token);

Any idea?

Update

It was working on the server/local with all the clients but not with the Php client and the Php client was doing extra work which was changing the Security stamp hence the problem.

As the only client on the server was in Php, I thought that something was wrong with the server and not with my local environment. After installing the whole environment (with php client) in my local and debug, I found out the problem. Please read the answer below.


问:
Saving plot with high resolution image
Since, i'm a newbie to python. I was trying to save a plot using matplotlib in python with the command plt.savefig().
The problem is that the image being save is low in resolution. Unable to read data points.

I was wondering if there is a way to save such figures in a very high resolution?

答:
Use a resolution that uses specific sizing that is large :

```<code> fig = plt.figure(figsize=(19.20,10.80))
</code>```

produces 1080p for example and you can go much higher than this.

Title: Saving plot with high resolution image

Body:
Use a resolution that uses specific sizing that is large :

 fig = plt.figure(figsize=(19.20,10.80))

produces 1080p for example and you can go much higher than this.


问:
Ansible: How to get service status by Ansible?
I want to get service like redis-server running status by Ansible.

I know how to use Ansible service module to stop or start system service.  But how can I get the current service status?

答:
Personally, I like to have some kind of support Playbooks for getting the status of my services across my environments and to be able to restart them etc.

I'll therefore use on the one side the command module as recommended by Konstantin Suvorov but additionally i'll also check the expected port(s) to ensure that all required ports are up and my service is working as expected.
This would look like the following in your case:

```<code>- name: verify redis-server service
  command: /usr/sbin/sservice redis-server status
  changed_when: false

- name: verify redis-server is listening on 6379
  wait_for: port=6379 timeout=1
</code>```

The changed_when is just used because the command module will always set changed to true, although it is just a read-only command.

Body:
Personally, I like to have some kind of support Playbooks for getting the status of my services across my environments and to be able to restart them etc.

I'll therefore use on the one side the command module as recommended by Konstantin Suvorov but additionally i'll also check the expected port(s) to ensure that all required ports are up and my service is working as expected.
This would look like the following in your case:

- name: verify redis-server service
  command: /usr/sbin/sservice redis-server status
  changed_when: false

- name: verify redis-server is listening on 6379
  wait_for: port=6379 timeout=1

The changed_when is just used because the command module will always set changed to true, although it is just a read-only command.


问:
Synchronize database of Firebase with Swift 4 language
I am new at swift 4 programming. I try to show some data(actually they are child names) from database of firebase. When view did load, I can take them and show on tableView but it is not working real time. When I delete some data from firebase, I need to refresh(go back and load again) the viewController. If I refresh the tableView with timer, all data append from its end. If I, firstly, delete after append new data to tableView. It is jittering. Is there anyway to synchronize this tableView with firebase, without these problems? </p>

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        ref = Database.database().reference()
        ref.keepSynced(true)

        let userRef = self.ref.child("Users").child(Username).child("Schedule")
        userRef.observeSingleEvent(of: .value, with: { snapshot in
            for child in snapshot.children {
                let snap = child as! DataSnapshot
                let key = snap.key
                self.myList.append(key)
                self.CourseList.append(key)
                self.LessonsTableView.reloadData()
            }
            // Lessons are taking and after, they are locating under phone's memory!
            UserDefaults.standard.set(self.CourseList, forKey: "LessonsArray")
            UserDefaults.standard.synchronize()
        })
}

//Setting up our table
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myList.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = LessonsTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LessonsTableViewCell
        cell.myLabell.text = myList[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let Dummy:String = myList[indexPath.row] as Any as! String
        let Selected:String = (Dummy as NSString) as Any as! String
        UserDefaults.standard.set(Selected, forKey: "Selected")
        self.performSegue(withIdentifier: "NextPage", sender: self)
    }
</code>```

答:
Firebase's task is a network task which normally runs on a background (lower priority) thread. But tableView.reloadData() is an UI task. So you probably need to execute UI related codes by following codes.</p>

```<code>DispatchQueue.main.sync {
            let snap = child as! DataSnapshot
            let key = snap.key
            self.myList.append(key)
            self.CourseList.append(key)
            self.LessonsTableView.reloadData()
}
</code>```

Body:
I am new at swift 4 programming. I try to show some data(actually they are child names) from database of firebase. When view did load, I can take them and show on tableView but it is not working real time. When I delete some data from firebase, I need to refresh(go back and load again) the viewController. If I refresh the tableView with timer, all data append from its end. If I, firstly, delete after append new data to tableView. It is jittering. Is there anyway to synchronize this tableView with firebase, without these problems?

override func viewDidLoad() {
        super.viewDidLoad()

        ref = Database.database().reference()
        ref.keepSynced(true)

        let userRef = self.ref.child("Users").child(Username).child("Schedule")
        userRef.observeSingleEvent(of: .value, with: { snapshot in
            for child in snapshot.children {
                let snap = child as! DataSnapshot
                let key = snap.key
                self.myList.append(key)
                self.CourseList.append(key)
                self.LessonsTableView.reloadData()
            }
            // Lessons are taking and after, they are locating under phone's memory!
            UserDefaults.standard.set(self.CourseList, forKey: "LessonsArray")
            UserDefaults.standard.synchronize()
        })
}

//Setting up our table
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myList.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = LessonsTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LessonsTableViewCell
        cell.myLabell.text = myList[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let Dummy:String = myList[indexPath.row] as Any as! String
        let Selected:String = (Dummy as NSString) as Any as! String
        UserDefaults.standard.set(Selected, forKey: "Selected")
        self.performSegue(withIdentifier: "NextPage", sender: self)
    }

Body:
Firebase's task is a network task which normally runs on a background (lower priority) thread. But tableView.reloadData() is an UI task. So you probably need to execute UI related codes by following codes.

DispatchQueue.main.sync {
            let snap = child as! DataSnapshot
            let key = snap.key
            self.myList.append(key)
            self.CourseList.append(key)
            self.LessonsTableView.reloadData()
}


问:
How to make secure route in Laravel 5.2?
I have a application with Laravel 5.2. I have some route. Now i want to make few routes secure so that anyone can not guessing and insert any value.Now i want to add some character before {id} and after {id} So that anyone can't reach it by guessing.

```<code>Route::get('/prize/{id}','PrizeCalculateController@showPrizePage');
</code>```

Now user can go to localhost/laravel/public/prize/1 or replace 1 by anything and can go to that url. I want make it secure so that anyone can't go by guessing.

I have tried with:

```<code>$parameter = $qrcode->id;
$encryption= Crypt::encrypt($parameter);
</code>```

What will be the best approach to make a route secure?

答:
Encrypt the ID will generate a very long (188+ chatacters) string, not so friendly.

You can generate an UUID (32 characters) to represent your model. There's many packages that generates and validate UUID, for example this one.

To use the UUID, you should create a column on your table to represent it, and load the model by the uuid field instead of id.

Since the UUID represents a very large number (128 bits one), is very hard to guess it (virtually impossible, one chance in 3.402823669×10³⁸).

Also do difficult guessing (the probability increases as your table size increase), you can expire the UUID periodically (or invalidate it if used for example). There are many ways to secure it, but all depends on your application design.

Since you do not need the universally unique part of UUID, you can also just generate a big random string using str_random() helper from Laravel. A 16 alphanumeric characters string is also very strong (4.767240171×10²⁸ combinations).

Consider add a rate limiting to this route also make it very hard to guess.

Body:
I have a application with Laravel 5.2. I have some route. Now i want to make few routes secure so that anyone can not guessing and insert any value.Now i want to add some character before {id} and after {id} So that anyone can't reach it by guessing.

Route::get('/prize/{id}','PrizeCalculateController@showPrizePage');

Now user can go to localhost/laravel/public/prize/1 or replace 1 by anything and can go to that url. I want make it secure so that anyone can't go by guessing.

I have tried with:

$parameter = $qrcode->id;
$encryption= Crypt::encrypt($parameter);

What will be the best approach to make a route secure?


问:
Using sd as a generic function in R
If I a have a class called foo, then it is straightforward to overload the summary function

```<code>summary.foo = function(x, ...) print("bar")
</code>```

However this technique does not work with the sd function, that is

```<code>> bar = createFooClass()
> sd.foo = function(x, ...) print("Hi")
> sd(bar)
  error: is.atomic(x) is not TRUE
</code>```

What is the correct way of overloading this function?

答:
Look at the code of sd()---it effectively dispatches internally.  In other words, it is not a generic function but a plain old regular function.

The easiest may just be to modify sd() to branch on class foo.

ContentLicense: CC BY-SA 2.5

Title: Using sd as a generic function in R

Body:
If I a have a class called foo, then it is straightforward to overload the summary function

summary.foo = function(x, ...) print("bar")

However this technique does not work with the sd function, that is

> bar = createFooClass()
> sd.foo = function(x, ...) print("Hi")
> sd(bar)
  error: is.atomic(x) is not TRUE

What is the correct way of overloading this function?


问:
clear cache of clients browsers when making changes
When developing a website using HTML/CSS, during the development phase it makes sense to prevent caching as people viewing the website would otherwise see old versions. Ive seen threads on this before using meta tags ie:

```<code><meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />enter code here
</code>```

However this dosent seem to work with HTML5 and similarly I only want to clear clients cache to empty once Ive made an update.

For example if I have an image in index.html and update this image (same filename different content) then clients would see the previous image

Is there a way I can version html pages such that the clients browser would cache version 1 then on reloading If I change the html to version 2 the cache would be emptied and the new website with all changes would be loaded?

Seems this would need to be the case in most web developments otherwise clients would never see changes

答:
Add the following in your head content -</p>

```<code><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
</code>```

Body:
When developing a website using HTML/CSS, during the development phase it makes sense to prevent caching as people viewing the website would otherwise see old versions. Ive seen threads on this before using meta tags ie:

<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />enter code here

However this dosent seem to work with HTML5 and similarly I only want to clear clients cache to empty once Ive made an update.

For example if I have an image in index.html and update this image (same filename different content) then clients would see the previous image

Is there a way I can version html pages such that the clients browser would cache version 1 then on reloading If I change the html to version 2 the cache would be emptied and the new website with all changes would be loaded?

Seems this would need to be the case in most web developments otherwise clients would never see changes

Body:
Add the following in your head content -

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />


问:
How to place image in tkinter(background) and place button on the image using python 3.6?
Need to place buttons on image but image always stays on center and buttons stays on sides.</p>

答:
Why not place an image on a button instead? It's much easier :)

getting the buttons to have an image can be kind of tricky (you kind of need a 2 layered approach), but changing the image is easy.

```<code>x_image = 'x.png'

o_image = 'o.png'
</code>```

then...

```<code>x_image_for_button = PhotoImage(file=x_image)
o_image_for_button = PhotoImage(file=o_image)
</code>```

then.....

```<code>button = tk.Button(self.controller, image=o_image_for_button, command=lambda: command_or_something)
button.config(width="40", height="40")
button.place(x=5, y=5)
</code>```

(add in self. or root. etc)

now all you do to change the image is:

```<code>button.set(image=o_image_for_button)
#on second thought... maybe use `button.config(image=o_image_for_button)` insted
</code>```

easy :)

Body:
Why not place an image on a button instead? It's much easier :)

getting the buttons to have an image can be kind of tricky (you kind of need a 2 layered approach), but changing the image is easy.

x_image = 'x.png'

o_image = 'o.png'

then...

x_image_for_button = PhotoImage(file=x_image)
o_image_for_button = PhotoImage(file=o_image)

then.....

button = tk.Button(self.controller, image=o_image_for_button, command=lambda: command_or_something)
button.config(width="40", height="40")
button.place(x=5, y=5)

(add in self. or root. etc)

now all you do to change the image is:

button.set(image=o_image_for_button)
#on second thought... maybe use `button.config(image=o_image_for_button)` insted

easy :)


问:
Pass Constant value in JPA query
I want to pass constant values as below : Please help

I am using EntityManager to Pass constant values ("Successful") in JPA Query.

For Example:-

```<code>Query query = em.createQuery("SELECT a.alertId ,a.vmdId,"Successful") from Alertstatus a where a.alertId = ? and a.vmdId = ?");
</code>```

答:
Try setting a parameter like that:   </p>

```<code>     Query query = em.createQuery("SELECT a.alertId ,a.vmdId, :parameter) from
     Alertstatus a where a.alertId = ? and a.vmdId = ?")
     .setParameter("parameter", "Successful");
</code>```

Title: Pass Constant value in JPA query

Body:
I want to pass constant values as below : Please help

I am using EntityManager to Pass constant values ("Successful") in JPA Query.

For Example:-

Query query = em.createQuery("SELECT a.alertId ,a.vmdId,"Successful") from Alertstatus a where a.alertId = ? and a.vmdId = ?");

Body:
Try setting a parameter like that:

     Query query = em.createQuery("SELECT a.alertId ,a.vmdId, :parameter) from
     Alertstatus a where a.alertId = ? and a.vmdId = ?")
     .setParameter("parameter", "Successful");


答:
```<code>savefig(fname, dpi=None, facecolor='w', edgecolor='w',
    orientation='portrait', papertype=None, format=None,
    transparent=False, bbox_inches=None, pad_inches=0.1,
    frameon=None)
</code>```

you can use dpi=300 or other values

Title: Saving plot with high resolution image

Body:
Since, i'm a newbie to python. I was trying to save a plot using matplotlib in python with the command plt.savefig().
The problem is that the image being save is low in resolution. Unable to read data points.

I was wondering if there is a way to save such figures in a very high resolution?

Body:
savefig(fname, dpi=None, facecolor='w', edgecolor='w',
    orientation='portrait', papertype=None, format=None,
    transparent=False, bbox_inches=None, pad_inches=0.1,
    frameon=None)

you can use dpi=300 or other values


问:
Adding multi-language option to a Qt app with hard-coded text
I'm a beginner in Qt. I have an app designed using Qt which has multiple windows with each consisting of several labels with hard coded text. What would be the easiest way to add multi language support for this app? Which built in Qt objects/functions I should use?

My current idea is to maybe create a separate xml file including the text for all labels for a language. Then once the user selects a language icon from the menu, load the relevant xml file. But I have no idea how to do this. Any help would be highly appreciated!

UPDATE:
I have tried to implement the example given here. But it throws the following error and I can't fix it. 'class Ui::MainWindow' has no member named 'menuLanguage'

QActionGroup* langGroup = new QActionGroup(ui->menuLanguage);

答:
Qt has built in functions for managing multiple languages:

see: https://wiki.qt.io/How_to_create_a_multi_language_application

Research lupdate lrelease and linguist


问:
PyQt - How can I re-initialise the whole code without restarting it?
I wrote a python GUI program consisting of two separate files; One is for logic code and the other for GUI using PyQt4. The behaviour of some objects (buttons, text fields ...) changes throughout the code and I need to reset everything to its original status by clicking on a QAction class menu item. How can I do that?

EDIT: the function that supposed to reset the GUI to the original status:

```<code>def newSession(self):
        self.ui.setupUi(self)
        self.filename = ""
        self.paramsSplitted = []
        self.timestep = None
        self.index = None
        self.selectedParam = None
        self.selectedMethod = None

        --Snip--
</code>```

答:
Like you requested in your comment here is a schematic way of utilizing a function to connect all signals and the method setupUi.

```<code>class MainWindow(QtGui.QMainWindow) :
    def __init__(self) :
        QtGui.QMainWindow.__init__(self)
        self.ui.setupUi(self)

        # Some code

        self.connectAllSignals()

    def connectAllSignals(self) :
        self.someWidget.clicked.connect(self.someFunction)
        self.someAction.triggered.connect(self.otherFunction)

        # All the other signals

    def disconnectAllSignals(self) :
        try :
            self.someWidget.clicked.disconnect()
            self.someAction.triggered.disconnect()

            # All the other signals

        except :
            print("Something went wrong. Check your code.")
            pass

    def newSession(self) :
        self.ui.setupUi(self)
        self.disconnectAllSignals()
        self.connectAllSignals()

        # Do whatever it takes
</code>```

By this you ensure you have only the initial settings for your signals and all dynamically added connections are broken. In the method disconnectAllSignals be sure all widgets exist and all signals have at least one connection by the time you call it. If you have new widgets invoked dynamically you should consider deleting them in th method newSession after calling connectAllSignals.

Body:
I wrote a python GUI program consisting of two separate files; One is for logic code and the other for GUI using PyQt4. The behaviour of some objects (buttons, text fields ...) changes throughout the code and I need to reset everything to its original status by clicking on a QAction class menu item. How can I do that?

EDIT: the function that supposed to reset the GUI to the original status:

def newSession(self):
        self.ui.setupUi(self)
        self.filename = ""
        self.paramsSplitted = []
        self.timestep = None
        self.index = None
        self.selectedParam = None
        self.selectedMethod = None

        --Snip--

Body:
Like you requested in your comment here is a schematic way of utilizing a function to connect all signals and the method setupUi.

class MainWindow(QtGui.QMainWindow) :
    def __init__(self) :
        QtGui.QMainWindow.__init__(self)
        self.ui.setupUi(self)

        # Some code

        self.connectAllSignals()

    def connectAllSignals(self) :
        self.someWidget.clicked.connect(self.someFunction)
        self.someAction.triggered.connect(self.otherFunction)

        # All the other signals

    def disconnectAllSignals(self) :
        try :
            self.someWidget.clicked.disconnect()
            self.someAction.triggered.disconnect()

            # All the other signals

        except :
            print("Something went wrong. Check your code.")
            pass

    def newSession(self) :
        self.ui.setupUi(self)
        self.disconnectAllSignals()
        self.connectAllSignals()

        # Do whatever it takes

By this you ensure you have only the initial settings for your signals and all dynamically added connections are broken. In the method disconnectAllSignals be sure all widgets exist and all signals have at least one connection by the time you call it. If you have new widgets invoked dynamically you should consider deleting them in th method newSession after calling connectAllSignals.


问:
How to get value from JSON array in Swift3
I'm new in Swift3 and I'm confused how to get value from this JSON array.

This is my coding:

```<code>let url = URL(string: apiServer)
URLSession.shared.dataTask(with: url!) {(data, response, error) in
    if error != nil {
       return
    }else{
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

            if let allEntry = json?[“allentry"] as? [NSArray] {
                 print("All Entry: \(allEntry)")
             }
        }catch{
            print(error.localizedDescription)
        }
    }
}.resume()
</code>```

This is JSON:

```<code>"allentry": [
              [
                "Month",
                "Entry"
              ],
              [
                "Jan",
                109.52380952380953
              ],
              [
                "Feb",
                105.26315789473684
              ],
              [
                "Mar",
                104.54545454545455
              ],
              [
                "Apr",
                100
              ],
              [
                "May",
                105
              ],
              [
                "Jun",
                106.66666666666667
              ],
              [
                "Jul",
                100
              ],
              [
                "Aug",
                100
              ],
              [
                "Sep",
                100
              ],
              [
                "Oct",
                72.727272727272734
              ],
              [
                "Nov",
                0
              ],
              [
                "Dec",
                0
              ]
            ]
</code>```

The output I got was this:

All Entry:

[<__NSArrayI 0x170029e60>( Month, Entry ) , <__NSArrayI 0x17002a0a0>(
Jan,
109.5238095238095 ) , <__NSArrayI 0x170029fc0>( Feb,
105.2631578947368 ) , <__NSArrayI 0x17002a100>( Mar,
104.5454545454545 ) , <__NSArrayI 0x17002a2e0>( Apr, 100 ) , <__NSArrayI 0x17002a3a0>( May, 105 ) , <__NSArrayI 0x17002a740>( Jun,
106.6666666666667 ) , <__NSArrayI 0x17002a920>( Jul, 100 ) , <__NSArrayI 0x17002a860>( Aug, 100 ) , <__NSArrayI 0x17002ade0>( Sep,
100 ) , <__NSArrayI 0x17002a8c0>( Oct,
72.72727272727273 ) , <__NSArrayI 0x17002a980>( Nov, 0 ) , <__NSArrayI 0x17002a9e0>( Dec, 0 ) ]

答:
This is a solution which maps the nested JSON arrays into a custom struct.

The first entry with the field names is being dropped.

```<code>struct Entry {
    let month : String
    let entry : Double
}
</code>```

```<code>let url = URL(string: apiServer)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
    if error != nil {
        print(error!)
        return
    } else {
        do {
            if let json = try JSONSerialization.jsonObject(with: data!) as? [String:Any],
                let entries = json["allentry"] as? [[Any]] {
                let items = entries.dropFirst().map{ Entry(month: $0[0] as! String, entry: $0[1] as! Double) }
                print(items)
            }
        } catch {
            print(error.localizedDescription)
        }
    }
}.resume()
</code>```

Body:
I'm new in Swift3 and I'm confused how to get value from this JSON array.

This is my coding:

let url = URL(string: apiServer)
URLSession.shared.dataTask(with: url!) {(data, response, error) in
    if error != nil {
       return
    }else{
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

            if let allEntry = json?[“allentry"] as? [NSArray] {
                 print("All Entry: \(allEntry)")
             }
        }catch{
            print(error.localizedDescription)
        }
    }
}.resume()

This is JSON:

"allentry": [
              [
                "Month",
                "Entry"
              ],
              [
                "Jan",
                109.52380952380953
              ],
              [
                "Feb",
                105.26315789473684
              ],
              [
                "Mar",
                104.54545454545455
              ],
              [
                "Apr",
                100
              ],
              [
                "May",
                105
              ],
              [
                "Jun",
                106.66666666666667
              ],
              [
                "Jul",
                100
              ],
              [
                "Aug",
                100
              ],
              [
                "Sep",
                100
              ],
              [
                "Oct",
                72.727272727272734
              ],
              [
                "Nov",
                0
              ],
              [
                "Dec",
                0
              ]
            ]

The output I got was this:

All Entry:

[<__NSArrayI 0x170029e60>( Month, Entry ) , <__NSArrayI 0x17002a0a0>(
Jan,
109.5238095238095 ) , <__NSArrayI 0x170029fc0>( Feb,
105.2631578947368 ) , <__NSArrayI 0x17002a100>( Mar,
104.5454545454545 ) , <__NSArrayI 0x17002a2e0>( Apr, 100 ) , <__NSArrayI 0x17002a3a0>( May, 105 ) , <__NSArrayI 0x17002a740>( Jun,
106.6666666666667 ) , <__NSArrayI 0x17002a920>( Jul, 100 ) , <__NSArrayI 0x17002a860>( Aug, 100 ) , <__NSArrayI 0x17002ade0>( Sep,
100 ) , <__NSArrayI 0x17002a8c0>( Oct,
72.72727272727273 ) , <__NSArrayI 0x17002a980>( Nov, 0 ) , <__NSArrayI 0x17002a9e0>( Dec, 0 ) ]

Body:
This is a solution which maps the nested JSON arrays into a custom struct.

The first entry with the field names is being dropped.

struct Entry {
    let month : String
    let entry : Double
}

let url = URL(string: apiServer)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
    if error != nil {
        print(error!)
        return
    } else {
        do {
            if let json = try JSONSerialization.jsonObject(with: data!) as? [String:Any],
                let entries = json["allentry"] as? [[Any]] {
                let items = entries.dropFirst().map{ Entry(month: $0[0] as! String, entry: $0[1] as! Double) }
                print(items)
            }
        } catch {
            print(error.localizedDescription)
        }
    }
}.resume()


问:
Changing the line style in d3js for every segment?
I'm trying to visualise the "additional work" resulting from change request in a burn chart. I managed to draw the chart, but I like to have the vertical lines that show the increase to have their own colour. Something like this:

My data is like this:

```<code>   var actualRaw = [{
        date: new Date(2017, 1, 1),
        added: 0,
        done: 50
    }, {
        date: new Date(2017, 1, 15),
        added: 10,
        done: 40
    }]
</code>```

which I transform like this:

```<code>    var actual = [];

    actualRaw.map(line => {
        actual.push({
            date: line.date,
            points: line.done,
            class: 'la'
        });
        actual.push({
            date: line.date,
            points: line.done + line.added,
            class: 'ln'
        });

    })
</code>```

and then try to apply formatting like this:

```<code>    chart.append("path")
        .datum(actual)
        .attr("class", function(d, i) {
            return 'line ' + d[i].class;
        })
        .attr("d", actualLine);
</code>```

However that function gets called only once. What do I miss?

My attempt so far complete.

答:
Simply put: you can't style different segments of a SVG <path> element like that.

There are alternatives, though. Here, for instance, I'm simply adding a key/value pair in actual...

```<code>actualRaw.map(line => {
    actual.push({
        date: line.date,
        points: line.done,
        class: 'la'
    });
    actual.push({
        date: line.date,
        points: line.done + line.added,
        class: 'ln',
        added: line.added//this one here...
    });
})
</code>```

... and using it to draw simple lines (that is, SVG <line> elements):

```<code>var redLines = chart.selectAll(null)
    .data(actual.filter(function(d) {
        return d.added
    }))
    .enter()
    .append("line")
    .attr("x1", function(d) {
        return x(d.date)
    })
    .attr("x2", function(d) {
        return x(d.date)
    })
    .attr("y1", function(d) {
        return y(d.points)
    })
    .attr("y2", function(d) {
        return y(d.points - d.added)
    })
    .style("stroke", "red");
</code>```

Here is the code with those changes:

  <title>Burn baby burn</title>

Burn Chart

```

Body:
I'm trying to visualise the "additional work" resulting from change request in a burn chart. I managed to draw the chart, but I like to have the vertical lines that show the increase to have their own colour. Something like this:

My data is like this:

   var actualRaw = [{
        date: new Date(2017, 1, 1),
        added: 0,
        done: 50
    }, {
        date: new Date(2017, 1, 15),
        added: 10,
        done: 40
    }]

which I transform like this:

    var actual = [];

    actualRaw.map(line => {
        actual.push({
            date: line.date,
            points: line.done,
            class: 'la'
        });
        actual.push({
            date: line.date,
            points: line.done + line.added,
            class: 'ln'
        });

    })

and then try to apply formatting like this:

    chart.append("path")
        .datum(actual)
        .attr("class", function(d, i) {
            return 'line ' + d[i].class;
        })
        .attr("d", actualLine);

However that function gets called only once. What do I miss?

My attempt so far complete.

Body:
Simply put: you can't style different segments of a SVG <path> element like that.

There are alternatives, though. Here, for instance, I'm simply adding a key/value pair in actual...

actualRaw.map(line => {
    actual.push({
        date: line.date,
        points: line.done,
        class: 'la'
    });
    actual.push({
        date: line.date,
        points: line.done + line.added,
        class: 'ln',
        added: line.added//this one here...
    });
})

... and using it to draw simple lines (that is, SVG <line> elements):

var redLines = chart.selectAll(null)
    .data(actual.filter(function(d) {
        return d.added
    }))
    .enter()
    .append("line")
    .attr("x1", function(d) {
        return x(d.date)
    })
    .attr("x2", function(d) {
        return x(d.date)
    })
    .attr("y1", function(d) {
        return y(d.points)
    })
    .attr("y2", function(d) {
        return y(d.points - d.added)
    })
    .style("stroke", "red");

Here is the code with those changes:

<head>
  <title>Burn baby burn</title>
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <style type="text/css">
    .chart {
      border: 1px solid black;
    }

    .chart div {
      font: 10px sans-serif;
      background-color: steelblue;
      text-align: right;
      padding: 3px;
      margin: 1px;
      color: white;
    }

    .chart rect {
      stroke: white;
      fill: steelblue;
    }

    .axis path,
    .axis line {
      fill: none;
      stroke: #000;
      shape-rendering: crispEdges;
    }

    .line {
      fill: none;
      stroke-width: 2px;
    }

    .line.ideal {
      stroke: steelblue;
    }

    .la {
      fill: none;
      stroke-width: 2px;
      stroke: green;
    }

    .ln {
      fill: none;
      stroke: red;
      stroke-width: 4px;
    }
  </style>
</head>

<body>
  <h1>Burn Chart</h1>
  <script type="text/javascript">
    var margin = {
        top: 20,
        right: 20,
        bottom: 30,
        left: 50
      },
      width = 960 - margin.left - margin.right,
      height = 500 - margin.top - margin.bottom;
    var x = d3.scaleTime()
      .range([0, width]);
    var y = d3.scaleLinear()
      .range([height, 0]);
    var ideal = [{
      date: new Date(2017, 1, 1),
      points: 50
    }, {
      date: new Date(2017, 12, 31),
      points: 0
    }];
    var actualRaw = [{
      date: new Date(2017, 1, 1),
      added: 0,
      done: 50
    }, {
      date: new Date(2017, 1, 15),
      added: 10,
      done: 40
    }, {
      date: new Date(2017, 2, 1),
      added: 0,
      done: 40
    }, {
      date: new Date(2017, 3, 1),
      added: 20,
      done: 30
    }, {
      date: new Date(2017, 4, 1),
      added: 10,
      done: 20
    }, {
      date: new Date(2017, 5, 1),
      added: 5,
      done: 10
    }, {
      date: new Date(2017, 6, 1),
      added: 0,
      done: 10
    }, {
      date: new Date(2017, 7, 1),
      added: 5,
      done: 10
    }, {
      date: new Date(2017, 8, 1),
      added: 0,
      done: 10
    }, {
      date: new Date(2017, 9, 1),
      added: 20,
      done: 20
    }, {
      date: new Date(2017, 10, 1),
      added: 0,
      done: 10
    }, {
      date: new Date(2017, 11, 1),
      added: 5,
      done: 10
    }, {
      date: new Date(2017, 12, 1),
      added: 0,
      done: 0
    }];
    var actual = [];
    actualRaw.map(line => {
      actual.push({
        date: line.date,
        points: line.done,
        class: 'la'
      });
      actual.push({
        date: line.date,
        points: line.done + line.added,
        class: 'ln',
        added: line.added
      });
    })
    var idealLine = d3.line()
      .x(function(d) {
        return x(d.date);
      })
      .y(function(d) {
        return y(d.points);
      });
    var actualLine = d3.line()
      .x(function(d) {
        return x(d.date);
      })
      .y(function(d) {
        return y(d.points);
      });
    x.domain(d3.extent(ideal, function(d) {
      return d.date;
    }));
    y.domain(d3.extent(actual, function(d) {
      return d.points;
    }));
    var xAxis = d3.axisBottom()
      .scale(x)
      .tickFormat(d3.timeFormat("%b %d"));
    var yAxis = d3.axisLeft()
      .scale(y);
    var chart = d3.select("body").append("svg")
      .attr("class", "chart")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
    // Create the x-axis
    chart.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);
    // Create the y-axis
    chart.append("g")
      .attr("class", "y axis")
      .call(yAxis)
      .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Points");
    // Paint the ideal line
    chart.append("path")
      .datum(ideal)
      .attr("class", "line ideal")
      .attr("d", idealLine);
    var counter = 0;
    // Paint the actual line
    chart.append("path")
      .datum(actual)
      .attr("class", function(d, i) {
        return 'line ' + d[i].class;
      })
      .attr("d", actualLine);

    var redLines = chart.selectAll(null)
      .data(actual.filter(function(d) {
        return d.added
      }))
      .enter()
      .append("line")
      .attr("x1", function(d) {
        return x(d.date)
      })
      .attr("x2", function(d) {
        return x(d.date)
      })
      .attr("y1", function(d) {
        return y(d.points)
      })
      .attr("y2", function(d) {
        return y(d.points - d.added)
      })
      .style("stroke", "red")
      .style("stroke-width", 4);
  </script>
</body>


问:
Change Parent layout from setOnItemClickListener()
I have an Activity a  with a ListView lv inside.

I have set the lv.setOnItemClickListener().

When the user clicks on a list item i want another list view (ListView lv_2) in the Activity a to be refreshed.

Problem is that i cannot access the Parent Activity a inside lv.setOnItemClickListener() am i right?

I studied some of custom event listeners but i don't understand how to use them in this particular case.

So how can i do this?

答:
```<code>lv1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        lv2Adapter.notifyDataSetChanged();
        lv2.setAdapter(lv2Adapter);
        lv2.notify();

    }
});
</code>```


问:
Can css class have class in it self and how would it be done?
My friend and I have had argument about CSS specifity and he was bringing up a class inside of a class:

```<code>.class{
    .subclass{
    }
}
</code>```

I have tried testing this in css but attributes from .subclass are not being applied.

My concern is are sub-classes done like this in css?

答:
CSS doesn't accept nesting classes but SASS and LESS do.

Nesting in Sass and Less

Body:
My friend and I have had argument about CSS specifity and he was bringing up a class inside of a class:

.class{
    .subclass{
    }
}

I have tried testing this in css but attributes from .subclass are not being applied.

My concern is are sub-classes done like this in css?


问:
Matlab: bar No public property CData exists
The Matlab example code cannot run in Matlab 2017a (Linux 64bits):
https://cn.mathworks.com/help/matlab/ref/bar.html

```<code>b = bar(rand(10,1));
b.FaceColor = 'flat';
b.CData(2,:) = [.5 0 .5];
</code>```

It can not color the specific bar and warns as:

No public property CData exists for class matlab.graphics.chart.primitive.Bar.

I don't know it is a specific feature merely for Matlab 2017b?

This code is only to color the specific bar. In Matlab 2012a, it can be easily done by:

```<code>bh=bar(MyStem); h=get(bh, 'children');
shading flat;  set(h,'FaceVertexCData',MyColor);
</code>```

I cannot understand why Matlab 2017 removes this feature.

答:
About the CData property, I wrote already in the comment.
Anyway, another workaround that I think can be more simple than those that been suggested, can be that:

```<code>x=rand(1,10);
b=bar([x;zeros(1,length(x))]);
xlim([0.5 1.5])
set(b,'FaceColor','r')
set(b(2),'FaceColor','b')
</code>```

If you want to number the bars as in a regular bar graph, you can add this:

```<code>set(gca,'XTick',0.5+[b.XOffset])
set(gca,'XTicklabels',1:length(x))
</code>```

Body:
The Matlab example code cannot run in Matlab 2017a (Linux 64bits):
https://cn.mathworks.com/help/matlab/ref/bar.html

b = bar(rand(10,1));
b.FaceColor = 'flat';
b.CData(2,:) = [.5 0 .5];

It can not color the specific bar and warns as:

No public property CData exists for class matlab.graphics.chart.primitive.Bar.

I don't know it is a specific feature merely for Matlab 2017b?

This code is only to color the specific bar. In Matlab 2012a, it can be easily done by:

bh=bar(MyStem); h=get(bh, 'children');
shading flat;  set(h,'FaceVertexCData',MyColor);

I cannot understand why Matlab 2017 removes this feature.

Body:
About the CData property, I wrote already in the comment.
Anyway, another workaround that I think can be more simple than those that been suggested, can be that:

x=rand(1,10);
b=bar([x;zeros(1,length(x))]);
xlim([0.5 1.5])
set(b,'FaceColor','r')
set(b(2),'FaceColor','b')

If you want to number the bars as in a regular bar graph, you can add this:

set(gca,'XTick',0.5+[b.XOffset])
set(gca,'XTicklabels',1:length(x))


问:
Weird problem with Android/Java method. Control seems to jump across if/else block
In the following Android sample, I have a set of JSON objects(referred to as templates) and I'm doing a sort of inheritance processing on them. If a JSON object has a key "extends", the corresponding value will refer to another JSON object. I just copy the mappings in the referred JSON object to the current one. Each property (referred to as component in the code) will have sub properties, so each sub property is copied individually.
All the JSON objects are stored in a HashMap.
EDIT: Posting sample code which demonstrates the issue.

```<code>package com.trial;

import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;

public class Trial extends Activity {

    HashMap<String, JSONObject> templates = new HashMap<String, JSONObject>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            templates.put("entity", new JSONObject("{\"Health\":{\"health\":50,\"maxHealth\":100}}"));
            templates.put("unit", new JSONObject("{\"Health\":{\"health\":70},\"extends\":\"entity\"}"));
            Iterator<String> templatesIterator = templates.keySet().iterator();
            while (templatesIterator.hasNext()) {
                String templateName = templatesIterator.next();
                JSONObject template = templates.get(templateName);
                if (template.has("extends"))
                    templates.put(templateName, processInheritance(template));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private JSONObject processInheritance(JSONObject template) throws JSONException {
        if (template.has("extends")) {
            //If current template extends from another template
            String parentTemplateName = template.getString("extends");
            template.remove("extends");
            JSONObject parentTemplate = processInheritance(templates.get(parentTemplateName));
            //Create a clone of the parent to which child properties/components can be added
            JSONObject processedTemplate = new JSONObject(parentTemplate.toString());
            Iterator<String> it = template.keys();
            while (it.hasNext()) {
                String componentName = it.next();
                if (processedTemplate.has(componentName)) {
                    //Component is already present. Loop through Component properties and make
                    //specific replacements
                    JSONObject componentData = template.getJSONObject(componentName);
                    Iterator<String> it2 = componentData.keys();
                    JSONObject processedComponentData = processedTemplate.getJSONObject(componentName);
                    while (it2.hasNext()) {
                        String propertyName = it2.next();
                        processedComponentData.put(propertyName, componentData.get(propertyName));
                    }
                    processedTemplate.put(componentName, processedComponentData);
                } else {
                    //Component is not already present. Simply copy
                    processedTemplate.put(componentName, template.get(componentName));
                }
            }
            return processedTemplate;
        } else {
            return template;
        }
    }
}
</code>```

On debugging I noticed that the code executes fine until after the while loop. Soon after the while loop, it jumps across the if/else and returns "template" instead of "processedTemplate". Even the resulting object indicates that "template" is being returned. I've tried clearing the binaries, recreating the emulator, and executing it on the actual device. The weird behavior persists. Could you someone tell me why this happens?

EDIT: The correct object IS being returned. My earlier comment that "template" was being returned was because of a bug where I was not saving the returned process object back into the HashMap.
I was simply doing

```<code>if (template.has("extends"))
    processInheritance(template));
</code>```

However the control still seems to jump across. An problem with Eclipse, I suppose.

答:
Changing the code as below seems to have fixed the issue, but the problem with the original code snippet still remains.</p>

```<code>private JSONObject processInheritance(JSONObject template) throws AssetLoadingException {
        try {
            if (!template.has("extends")) {
                return template;
            } else {
                //Everything else
            }
        } catch (JSONException ex) {
            throw new AssetLoadingException(ex);
        }
    }
</code>```

Body:
In the following Android sample, I have a set of JSON objects(referred to as templates) and I'm doing a sort of inheritance processing on them. If a JSON object has a key "extends", the corresponding value will refer to another JSON object. I just copy the mappings in the referred JSON object to the current one. Each property (referred to as component in the code) will have sub properties, so each sub property is copied individually.
All the JSON objects are stored in a HashMap.
EDIT: Posting sample code which demonstrates the issue.

package com.trial;

import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;

public class Trial extends Activity {

    HashMap<String, JSONObject> templates = new HashMap<String, JSONObject>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            templates.put("entity", new JSONObject("{\"Health\":{\"health\":50,\"maxHealth\":100}}"));
            templates.put("unit", new JSONObject("{\"Health\":{\"health\":70},\"extends\":\"entity\"}"));
            Iterator<String> templatesIterator = templates.keySet().iterator();
            while (templatesIterator.hasNext()) {
                String templateName = templatesIterator.next();
                JSONObject template = templates.get(templateName);
                if (template.has("extends"))
                    templates.put(templateName, processInheritance(template));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private JSONObject processInheritance(JSONObject template) throws JSONException {
        if (template.has("extends")) {
            //If current template extends from another template
            String parentTemplateName = template.getString("extends");
            template.remove("extends");
            JSONObject parentTemplate = processInheritance(templates.get(parentTemplateName));
            //Create a clone of the parent to which child properties/components can be added
            JSONObject processedTemplate = new JSONObject(parentTemplate.toString());
            Iterator<String> it = template.keys();
            while (it.hasNext()) {
                String componentName = it.next();
                if (processedTemplate.has(componentName)) {
                    //Component is already present. Loop through Component properties and make
                    //specific replacements
                    JSONObject componentData = template.getJSONObject(componentName);
                    Iterator<String> it2 = componentData.keys();
                    JSONObject processedComponentData = processedTemplate.getJSONObject(componentName);
                    while (it2.hasNext()) {
                        String propertyName = it2.next();
                        processedComponentData.put(propertyName, componentData.get(propertyName));
                    }
                    processedTemplate.put(componentName, processedComponentData);
                } else {
                    //Component is not already present. Simply copy
                    processedTemplate.put(componentName, template.get(componentName));
                }
            }
            return processedTemplate;
        } else {
            return template;
        }
    }
}

On debugging I noticed that the code executes fine until after the while loop. Soon after the while loop, it jumps across the if/else and returns "template" instead of "processedTemplate". Even the resulting object indicates that "template" is being returned. I've tried clearing the binaries, recreating the emulator, and executing it on the actual device. The weird behavior persists. Could you someone tell me why this happens?

EDIT: The correct object IS being returned. My earlier comment that "template" was being returned was because of a bug where I was not saving the returned process object back into the HashMap.
I was simply doing

if (template.has("extends"))
    processInheritance(template));

However the control still seems to jump across. An problem with Eclipse, I suppose.

Body:
Changing the code as below seems to have fixed the issue, but the problem with the original code snippet still remains.

private JSONObject processInheritance(JSONObject template) throws AssetLoadingException {
        try {
            if (!template.has("extends")) {
                return template;
            } else {
                //Everything else
            }
        } catch (JSONException ex) {
            throw new AssetLoadingException(ex);
        }
    }


问:
Populating 2d array zig zag with consecutive numbers C++
I'm stuck on this. Could you please help me?

Write   a   function    which   initialize  a   two-dimensional array.  The array   is  a square

matrix  (i.e.,  its width   and height  are identical.) The array   should  be  initialized in  the
zig-zag style.  Specifically,   we  start   at  the top-left    corner  and go  downward,   and put a

number  starting from   1.  Once    we  hit the bottom, we  go  to  the next    column  and fill    in

the numbers from    bottom  to  top.    We  fill    the numbers downward    in  the third

column, upward  in  the fourth  column, and so  on. The process ends when   all the
elements    in  the array   are filled.

```<code>However, How do I get my output like this?
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25

#include <iomanip>
#include <iostream>
using namespace std;
const int SIZE = 5; // Note SIZE can be anything between 1 to 9
void initGrid(int grid[SIZE][SIZE]);
void printGrid(int grid[SIZE][SIZE]);
int main() {
    int grid[SIZE][SIZE];
    initGrid(grid);
    printGrid(grid);
}
void initGrid(int grid[SIZE][SIZE]) {
    int inc = 1;
    for (int j = 0; j < SIZE; j++) {
        for (int i = 0; i < SIZE; i++) {
             grid[i][j] = inc;
             inc++;
        }
    }
}
void printGrid(int grid[SIZE][SIZE]) {
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            // setw() function handles the printing format.
            cout << setw(2) << grid[i][j] << " ";
        }
        cout << endl;
    }
}
</code>```

答:
Every two columns of the grid share the same filling pattern, the odd ones are filled in ascending order, the even ones in descending order. All you have to do is translate that into code:

```<code>template<size_t Rows, size_t Cols>
void initGrid(int (&grid)[Rows][Cols]) {
    int value = 1;
    for (size_t j = 0; j < Cols; ++j) {
        // first fill the odd column in descending order
        for (size_t i = 0; i < Rows; ++i, ++value) {
            grid[i][j] = value;
        }
        // then, if there is one, fill the even column
        ++j;
        if (j == Cols )
            break;
        for (size_t i = Rows; i > 0; ++value) {
            --i;   // size_t is unsigned, so I have to check i before decrementing
            grid[i][j] = value;
        }
    }
}
</code>```

I used the same data structure you used (but a different function signature) only to focus on the algorithm, but I'd use a class instead.

If you don't want to traverse the array column-wise (which, for big arrays, could result in performance drop due to cache misses) you can calculate the differences between values in every row:

```<code>template<size_t Rows, size_t Cols>
void zig_zag_fill(int (&grid)[Rows][Cols])
{
    int diff_up = 1;
    int diff_down = Rows * 2 - 1;
    for (size_t i = 0; i < Rows; ++i, diff_down -= 2, diff_up += 2)
    {
        int value = i + 1;
        size_t j = 0;
        while ( j < Cols )
        {
            grid[i][j] = value;
            value += diff_down;
            ++j;
            if ( j == Cols )
                break;
            grid[i][j] = value;
            value += diff_up;
            ++j;
        }
    }
}
</code>```

A complete test program like this:

```<code>#include <iostream>
#include <iomanip>

template<size_t Rows, size_t Cols>
void zig_zag_fill(int (&grid)[Rows][Cols]);

template<size_t Rows, size_t Cols>
void printGrid(int (&grid)[Rows][Cols]);

int main() {
    int grid[5][6];
    zig_zag_fill(grid);
    printGrid(grid);
    std::cout << '\n';
    int grid2[6][5];
    zig_zag_fill(grid2);
    printGrid(grid2);
    std::cout << '\n';
    int grid3[5][5];
    zig_zag_fill(grid3);
    printGrid(grid3);
    std::cout << '\n';
    int grid4[6][6];
    zig_zag_fill(grid4);
    printGrid(grid4);
    std::cout << '\n';
}

template<size_t Rows, size_t Cols>
void initGrid(int (&grid)[Rows][Cols]) {
    int value = 1;
    for (size_t j = 0; j < Cols; ++j) {
        for (size_t i = 0; i < Rows; ++i, ++value) {
            grid[i][j] = value;
        }
        ++j;
        if (j == Cols )
            break;
        for (size_t i = Rows; i > 0; ++value) {
            --i;
            grid[i][j] = value;
        }
    }
}

template<size_t Rows, size_t Cols>
void zig_zag_fill(int (&grid)[Rows][Cols])
{
    int diff_up = 1;
    int diff_down = Rows * 2 - 1;
    for (size_t i = 0; i < Rows; ++i, diff_down -= 2, diff_up += 2)
    {
        int value = i + 1;
        size_t j = 0;
        while ( j < Cols )
        {
            grid[i][j] = value;
            value += diff_down;
            ++j;
            if ( j == Cols )
                break;
            grid[i][j] = value;
            value += diff_up;
            ++j;
        }
    }
}

template<size_t Rows, size_t Cols>
void printGrid(int (&grid)[Rows][Cols]) {
    for (size_t i = 0; i < Rows; ++i) {
        for (size_t j = 0; j < Cols; ++j) {
            std::cout << std::setw(2) << grid[i][j] << " ";
        }
        std::cout << '\n';
    }
}
</code>```

Would output:

```
 1 10 11 20 21 30
 2  9 12 19 22 29
 3  8 13 18 23 28
 4  7 14 17 24 27
 5  6 15 16 25 26

 1 12 13 24 25
 2 11 14 23 26
 3 10 15 22 27
 4  9 16 21 28
 5  8 17 20 29
 6  7 18 19 30

 1 10 11 20 21
 2  9 12 19 22
 3  8 13 18 23
 4  7 14 17 24
 5  6 15 16 25

 1 12 13 24 25 36
 2 11 14 23 26 35
 3 10 15 22 27 34
 4  9 16 21 28 33
 5  8 17 20 29 32
 6  7 18 19 30 31
```

Body:
I'm stuck on this. Could you please help me?

Write   a   function    which   initialize  a   two-dimensional array.  The array   is  a square

matrix  (i.e.,  its width   and height  are identical.) The array   should  be  initialized in  the
zig-zag style.  Specifically,   we  start   at  the top-left    corner  and go  downward,   and put a

number  starting from   1.  Once    we  hit the bottom, we  go  to  the next    column  and fill    in

the numbers from    bottom  to  top.    We  fill    the numbers downward    in  the third

column, upward  in  the fourth  column, and so  on. The process ends when   all the
elements    in  the array   are filled.

However, How do I get my output like this?
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25

#include <iomanip>
#include <iostream>
using namespace std;
const int SIZE = 5; // Note SIZE can be anything between 1 to 9
void initGrid(int grid[SIZE][SIZE]);
void printGrid(int grid[SIZE][SIZE]);
int main() {
    int grid[SIZE][SIZE];
    initGrid(grid);
    printGrid(grid);
}
void initGrid(int grid[SIZE][SIZE]) {
    int inc = 1;
    for (int j = 0; j < SIZE; j++) {
        for (int i = 0; i < SIZE; i++) {
             grid[i][j] = inc;
             inc++;
        }
    }
}
void printGrid(int grid[SIZE][SIZE]) {
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            // setw() function handles the printing format.
            cout << setw(2) << grid[i][j] << " ";
        }
        cout << endl;
    }
}

Body:
Every two columns of the grid share the same filling pattern, the odd ones are filled in ascending order, the even ones in descending order. All you have to do is translate that into code:

template<size_t Rows, size_t Cols>
void initGrid(int (&grid)[Rows][Cols]) {
    int value = 1;
    for (size_t j = 0; j < Cols; ++j) {
        // first fill the odd column in descending order
        for (size_t i = 0; i < Rows; ++i, ++value) {
            grid[i][j] = value;
        }
        // then, if there is one, fill the even column
        ++j;
        if (j == Cols )
            break;
        for (size_t i = Rows; i > 0; ++value) {
            --i;   // size_t is unsigned, so I have to check i before decrementing
            grid[i][j] = value;
        }
    }
}

I used the same data structure you used (but a different function signature) only to focus on the algorithm, but I'd use a class instead.

If you don't want to traverse the array column-wise (which, for big arrays, could result in performance drop due to cache misses) you can calculate the differences between values in every row:

template<size_t Rows, size_t Cols>
void zig_zag_fill(int (&grid)[Rows][Cols])
{
    int diff_up = 1;
    int diff_down = Rows * 2 - 1;
    for (size_t i = 0; i < Rows; ++i, diff_down -= 2, diff_up += 2)
    {
        int value = i + 1;
        size_t j = 0;
        while ( j < Cols )
        {
            grid[i][j] = value;
            value += diff_down;
            ++j;
            if ( j == Cols )
                break;
            grid[i][j] = value;
            value += diff_up;
            ++j;
        }
    }
}

A complete test program like this:

#include <iostream>
#include <iomanip>

template<size_t Rows, size_t Cols>
void zig_zag_fill(int (&grid)[Rows][Cols]);

template<size_t Rows, size_t Cols>
void printGrid(int (&grid)[Rows][Cols]);

int main() {
    int grid[5][6];
    zig_zag_fill(grid);
    printGrid(grid);
    std::cout << '\n';
    int grid2[6][5];
    zig_zag_fill(grid2);
    printGrid(grid2);
    std::cout << '\n';
    int grid3[5][5];
    zig_zag_fill(grid3);
    printGrid(grid3);
    std::cout << '\n';
    int grid4[6][6];
    zig_zag_fill(grid4);
    printGrid(grid4);
    std::cout << '\n';
}

template<size_t Rows, size_t Cols>
void initGrid(int (&grid)[Rows][Cols]) {
    int value = 1;
    for (size_t j = 0; j < Cols; ++j) {
        for (size_t i = 0; i < Rows; ++i, ++value) {
            grid[i][j] = value;
        }
        ++j;
        if (j == Cols )
            break;
        for (size_t i = Rows; i > 0; ++value) {
            --i;
            grid[i][j] = value;
        }
    }
}

template<size_t Rows, size_t Cols>
void zig_zag_fill(int (&grid)[Rows][Cols])
{
    int diff_up = 1;
    int diff_down = Rows * 2 - 1;
    for (size_t i = 0; i < Rows; ++i, diff_down -= 2, diff_up += 2)
    {
        int value = i + 1;
        size_t j = 0;
        while ( j < Cols )
        {
            grid[i][j] = value;
            value += diff_down;
            ++j;
            if ( j == Cols )
                break;
            grid[i][j] = value;
            value += diff_up;
            ++j;
        }
    }
}

template<size_t Rows, size_t Cols>
void printGrid(int (&grid)[Rows][Cols]) {
    for (size_t i = 0; i < Rows; ++i) {
        for (size_t j = 0; j < Cols; ++j) {
            std::cout << std::setw(2) << grid[i][j] << " ";
        }
        std::cout << '\n';
    }
}

Would output:

 1 10 11 20 21 30
 2  9 12 19 22 29
 3  8 13 18 23 28
 4  7 14 17 24 27
 5  6 15 16 25 26

 1 12 13 24 25
 2 11 14 23 26
 3 10 15 22 27
 4  9 16 21 28
 5  8 17 20 29
 6  7 18 19 30

 1 10 11 20 21
 2  9 12 19 22
 3  8 13 18 23
 4  7 14 17 24
 5  6 15 16 25

 1 12 13 24 25 36
 2 11 14 23 26 35
 3 10 15 22 27 34
 4  9 16 21 28 33
 5  8 17 20 29 32
 6  7 18 19 30 31