问:
BigQuery async query job - the fetch_results() method returns wrong number of values
I am writing Python code with the BigQuery Client API, and attempting to use the async query code (written everywhere as a code sample), and it is failing at the fetch_data() method call.  Python errors out with the error:

ValueError: too many values to unpack

So, the 3 return values (rows, total_count, page_token) seem to be the incorrect number of return values.  But, I cannot find any documentation about what this method is supposed to return -- besides the numerous code examples that only show these 3 return results.

Here is a snippet of code that shows what I'm doing (not including the initialization of the 'client' variable or the imported libraries, which happen earlier in my code).

```<code>#---> Set up and start the async query job
job_id = str(uuid.uuid4())
job = client.run_async_query(job_id, query)
job.destination = temp_tbl
job.write_disposition = 'WRITE_TRUNCATE'
job.begin()
print 'job started...'

#---> Monitor the job for completion
retry_count = 360
while retry_count > 0 and job.state != 'DONE':
    print 'waiting for job to complete...'
    retry_count -= 1
    time.sleep(1)
    job.reload()

if job.state == 'DONE':
     print 'job DONE.'
     page_token = None
     total_count = None
     rownum = 0
     job_results = job.results()

     while True:

         # ---- Next line of code errors out...
         rows, total_count, page_token = job_results.fetch_data( max_results=10, page_token=page_token )

         for row in rows:
             rownum += 1
             print "Row number %d" % rownum

             if page_token is None:
                 print 'end of batch.'
                 break
</code>```

What are the specific return results I should expect from the job_results.fetch_data(...) method call on an async query job?

答:
Looks like you are right! The code no longer return these 3 parameters.

As you can see in this commit from the public repository, fetch_data now returns an instance of the HTTPIterator class (guess I didn't realize this before as I have a docker image with an older version of the bigquery client installed where it does return the 3 values).

The only way that I found to return the results was doing something like this:

```<code>iterator = job_results.fetch_data()
data = []
for page in iterator._page_iter(False):
    data.extend([page.next() for i in range(page.num_items)])
</code>```

Notice that now we don't have to manage pageTokens anymore, it's been automated for the most part.

[EDIT]:

I just realized you can get results by doing:

```<code>results = list(job_results.fetch_data())
</code>```

Got to admit it's way easier now then it was before!

Body:
I am writing Python code with the BigQuery Client API, and attempting to use the async query code (written everywhere as a code sample), and it is failing at the fetch_data() method call.  Python errors out with the error:

ValueError: too many values to unpack

So, the 3 return values (rows, total_count, page_token) seem to be the incorrect number of return values.  But, I cannot find any documentation about what this method is supposed to return -- besides the numerous code examples that only show these 3 return results.

Here is a snippet of code that shows what I'm doing (not including the initialization of the 'client' variable or the imported libraries, which happen earlier in my code).

#---> Set up and start the async query job
job_id = str(uuid.uuid4())
job = client.run_async_query(job_id, query)
job.destination = temp_tbl
job.write_disposition = 'WRITE_TRUNCATE'
job.begin()
print 'job started...'

#---> Monitor the job for completion
retry_count = 360
while retry_count > 0 and job.state != 'DONE':
    print 'waiting for job to complete...'
    retry_count -= 1
    time.sleep(1)
    job.reload()

if job.state == 'DONE':
     print 'job DONE.'
     page_token = None
     total_count = None
     rownum = 0
     job_results = job.results()

     while True:

         # ---- Next line of code errors out...
         rows, total_count, page_token = job_results.fetch_data( max_results=10, page_token=page_token )

         for row in rows:
             rownum += 1
             print "Row number %d" % rownum

             if page_token is None:
                 print 'end of batch.'
                 break

What are the specific return results I should expect from the job_results.fetch_data(...) method call on an async query job?

Body:
Looks like you are right! The code no longer return these 3 parameters.

As you can see in this commit from the public repository, fetch_data now returns an instance of the HTTPIterator class (guess I didn't realize this before as I have a docker image with an older version of the bigquery client installed where it does return the 3 values).

The only way that I found to return the results was doing something like this:

iterator = job_results.fetch_data()
data = []
for page in iterator._page_iter(False):
    data.extend([page.next() for i in range(page.num_items)])

Notice that now we don't have to manage pageTokens anymore, it's been automated for the most part.

[EDIT]:

I just realized you can get results by doing:

results = list(job_results.fetch_data())

Got to admit it's way easier now then it was before!


来源: stackexchange

问:
Xcode 9 (beta) refactoring: Rename broken
None of the refactor tools are working for me in XCode 9 beta. This is true even for new projects created with the beta (as with the test project, screenshot below). What gives?

I've found several demonstrations on YouTube showing the Xcode 9 rename refactor, but when I control-click on, say, a function name, the four refactoring options are all grayed out, including "Rename…".

Today I installed beta 2 in hopes that that would fix the issue, but still:

Is there some setting or something I need to change to enable refactoring?

If not, what's the best way to troubleshoot this?

答:
Was feeling too fed up to troubleshoot the issue carefully, but this managed to fix it, even if I can't say for sure whether the problem was a borked preference file or a corrupt Xcode bundle.

Moved all xcode-related preference files files out of ~/Library/Preferences into a temp dir

com.apple.dt.Instruments.plist

com.apple.dt.Xcode.Playground.plist

com.apple.dt.Xcode.plist

com.apple.dt.xcodebuild.plist

com.apple.preferences.extensions.XcodeSourceEditor.plist

Deleted /Applications/Xcode-beta.app and reinstalled from a fresh download

Both new and old projects seem to have refactoring working again instead of all grayed out. Even after dragging the moved preferences back in place, all's well!

ContentLicense: CC BY-SA 3.0


问:
How to use the priority queue STL for objects?
```<code>class Person
{
public:
    int age;
};
</code>```

I want to store objects of the class Person in a priority queue.

```<code>priority_queue< Person, vector<Person>, ??? >
</code>```

I think I need to define a class for the comparison thing, but I am not sure about it.

Also, when we write,

```<code>priority_queue< int, vector<int>, greater<int> >
</code>```

How does the greater work?

答:
We can define user defined comparator: .The code below can be helpful for you.

Code Snippet :

```<code>#include<bits/stdc++.h>
using namespace std;

struct man
{
  string name;
  int priority;
};

class comparator
{
 public:
   bool operator()(const man& a, const man& b)
   {
        return a.priority<b.priority;
   }
};

int main()
{
   man arr[5];
   priority_queue<man, vector<man>, comparator> pq;

   for(int i=0; i<3; i++)
   {
     cin>>arr[i].name>>arr[i].priority;
     pq.push(arr[i]);
   }

   while (!pq.empty())
   {
     cout<<pq.top().name<<" "<<pq.top().priority;
     pq.pop();
     cout<<endl;
   }
   return 0;
}
</code>```

input :

batman 2

  goku  9

  mario 4

Output

goku  9

  mario 4

  batman 2

Body:
class Person
{
public:
    int age;
};

I want to store objects of the class Person in a priority queue.

priority_queue< Person, vector<Person>, ??? >

I think I need to define a class for the comparison thing, but I am not sure about it.

Also, when we write,

priority_queue< int, vector<int>, greater<int> >

How does the greater work?

Body:
We can define user defined comparator: .The code below can be helpful for you.

Code Snippet :

#include<bits/stdc++.h>
using namespace std;

struct man
{
  string name;
  int priority;
};

class comparator
{
 public:
   bool operator()(const man& a, const man& b)
   {
        return a.priority<b.priority;
   }
};

int main()
{
   man arr[5];
   priority_queue<man, vector<man>, comparator> pq;

   for(int i=0; i<3; i++)
   {
     cin>>arr[i].name>>arr[i].priority;
     pq.push(arr[i]);
   }

   while (!pq.empty())
   {
     cout<<pq.top().name<<" "<<pq.top().priority;
     pq.pop();
     cout<<endl;
   }
   return 0;
}

input :

batman 2

  goku  9

  mario 4

Output

goku  9

  mario 4

  batman 2


问:
RemoteException(org.apache.hadoop.ipc.StandbyException): Operation category READ is not supported in state standby
If you want to know how I solved it, go here.

I have a oozie workflow. There is a shell action inside.

```<code>  <action name="start_fair_usage">
    <shell xmlns="uri:oozie:shell-action:0.1">
      <job-tracker>${JOB_TRACKER}</job-tracker>
      <name-node>${NAME_NODE}</name-node>
      <exec>${start_fair_usage}</exec>
      <argument>${today_without_dash}</argument>
      <argument>${yesterday_with_dash}</argument>
      <file>${start_fair_usage_path}#${start_fair_usage}</file>
      <capture-output/>
    </shell>
    <ok to="END"/>
    <error to="KILL"/>
  </action>
</code>```

This action starts a script. start_fair_usage.sh

```<code>echo "today_without_dash="$today_without_dash
echo "yeasterday_with_dash="$yeasterday_with_dash

echo "-----------RUN copy mta-------------"
bash copy_file.sh mta $today_without_dash
echo "-----------RUN copy rcr-------------"
bash copy_file.sh rcr $today_without_dash
echo "-----------RUN copy sub-------------"
bash copy_file.sh sub $today_without_dash
</code>```

Which in turn starts another script. copy_file.sh

```<code># directories in which where sub mtr rcr files are kept
echo "directories"
dirs=(
    /user/comverse/data/${2}_B
    )

# clear the hdfs directory of old files and copy new files
echo "remove old files "${1}

hadoop fs -rm -skipTrash /apps/hive/warehouse/amd.db/fair_usage/fct_evkuzmin/file_${1}/*

for i in $(hadoop fs -ls "${dirs[@]}" | egrep ${1}.gz | awk -F " " '{print $8}')
do
    hadoop fs -cp $i /apps/hive/warehouse/amd.db/fair_usage/fct_evkuzmin/file_${1}
    echo "copy file - "${i}
done

echo "end copy "${1}" files"
</code>```

How do I start the workflow so that it can copy files?

答:
I met the same problem ,below is the stack trace:

```<code>2017-07-03 18:07:24,208 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: reportBadBlock encountered RemoteException for block:  BP-455427998-10.120.117.100-1466433731629:blk_1140369410_67364810
org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.ipc.StandbyException): Operation category WRITE is not supported in state standby
        at org.apache.hadoop.hdfs.server.namenode.ha.StandbyState.checkOperation(StandbyState.java:87)
        at org.apache.hadoop.hdfs.server.namenode.NameNode$NameNodeHAContext.checkOperation(NameNode.java:1774)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.checkOperation(FSNamesystem.java:1313)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.reportBadBlocks(FSNamesystem.java:6263)
        at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.reportBadBlocks(NameNodeRpcServer.java:798)
        at org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolServerSideTranslatorPB.reportBadBlocks(DatanodeProtocolServerSideTranslatorPB.java:272)
        at org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos$DatanodeProtocolService$2.callBlockingMethod(DatanodeProtocolProtos.java:28766)
        at org.apache.hadoop.ipc.ProtobufRpcEngine$Server$ProtoBufRpcInvoker.call(ProtobufRpcEngine.java:616)
        at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:969)
        at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2049)
        at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2045)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:422)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
        at org.apache.hadoop.ipc.Server$Handler.run(Server.java:2045)

        at org.apache.hadoop.ipc.Client.call(Client.java:1475)
        at org.apache.hadoop.ipc.Client.call(Client.java:1412)
        at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:229)
        at com.sun.proxy.$Proxy14.reportBadBlocks(Unknown Source)
        at org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolClientSideTranslatorPB.reportBadBlocks(DatanodeProtocolClientSideTranslatorPB.java:290)
        at org.apache.hadoop.hdfs.server.datanode.ReportBadBlockAction.reportTo(ReportBadBlockAction.java:62)
        at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.processQueueMessages(BPServiceActor.java:988)
        at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.offerService(BPServiceActor.java:727)
        at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.run(BPServiceActor.java:824)
        at java.lang.Thread.run(Thread.java:745)
</code>```

If you are familiar with hadoop RPC, you will know that the above error log happends when RPC client(DataNode) trying to make a remote RPC call to the RPC Server(NameNode),NodeNode throw a exception because it is a standby one.So ,some of the above stacktrace was the server-side stack and some are the client-side stacktrace.

But the key is , does it has any bad influence to you HDFS system?
The answer is absolute no.

From BPOffsetService.java:

```<code>  void notifyNamenodeReceivingBlock(ExtendedBlock block, String storageUuid) {
checkBlock(block);
ReceivedDeletedBlockInfo bInfo = new ReceivedDeletedBlockInfo(
   block.getLocalBlock(), BlockStatus.RECEIVING_BLOCK, null);

for (BPServiceActor actor : bpServices) {
  actor.notifyNamenodeBlock(bInfo, storageUuid, false);
}
</code>```

}

The bpServices store the rpc list of both namenodes , including the active and the standby one.Obviously , a same request it send to both namenodes ,at least one request will report a 'category WRITE is not supported in state standby***'error and the other one will succeed.
So ,no worries about it.
In your hdfs HA configurtion ,if you configure like this:

```<code>       <property>
            <name>dfs.ha.namenodes.datahdfsmaster</name>
            <value>namenode1,namenode2</value>
    </property>
</code>```

And unfortunately ,if the namenode1 is the standby one , then you will receive much INFO-level log because namenode1 will be requested for some Operation and surely the NameNode-side checkOperation() will throw a INFO-level exception.

Body:
If you want to know how I solved it, go here.

I have a oozie workflow. There is a shell action inside.

  <action name="start_fair_usage">
    <shell xmlns="uri:oozie:shell-action:0.1">
      <job-tracker>${JOB_TRACKER}</job-tracker>
      <name-node>${NAME_NODE}</name-node>
      <exec>${start_fair_usage}</exec>
      <argument>${today_without_dash}</argument>
      <argument>${yesterday_with_dash}</argument>
      <file>${start_fair_usage_path}#${start_fair_usage}</file>
      <capture-output/>
    </shell>
    <ok to="END"/>
    <error to="KILL"/>
  </action>

This action starts a script. start_fair_usage.sh

echo "today_without_dash="$today_without_dash
echo "yeasterday_with_dash="$yeasterday_with_dash

echo "-----------RUN copy mta-------------"
bash copy_file.sh mta $today_without_dash
echo "-----------RUN copy rcr-------------"
bash copy_file.sh rcr $today_without_dash
echo "-----------RUN copy sub-------------"
bash copy_file.sh sub $today_without_dash

Which in turn starts another script. copy_file.sh

# directories in which where sub mtr rcr files are kept
echo "directories"
dirs=(
    /user/comverse/data/${2}_B
    )

# clear the hdfs directory of old files and copy new files
echo "remove old files "${1}

hadoop fs -rm -skipTrash /apps/hive/warehouse/amd.db/fair_usage/fct_evkuzmin/file_${1}/*

for i in $(hadoop fs -ls "${dirs[@]}" | egrep ${1}.gz | awk -F " " '{print $8}')
do
    hadoop fs -cp $i /apps/hive/warehouse/amd.db/fair_usage/fct_evkuzmin/file_${1}
    echo "copy file - "${i}
done

echo "end copy "${1}" files"

How do I start the workflow so that it can copy files?

Body:
I met the same problem ,below is the stack trace:

2017-07-03 18:07:24,208 INFO org.apache.hadoop.hdfs.server.datanode.DataNode: reportBadBlock encountered RemoteException for block:  BP-455427998-10.120.117.100-1466433731629:blk_1140369410_67364810
org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.ipc.StandbyException): Operation category WRITE is not supported in state standby
        at org.apache.hadoop.hdfs.server.namenode.ha.StandbyState.checkOperation(StandbyState.java:87)
        at org.apache.hadoop.hdfs.server.namenode.NameNode$NameNodeHAContext.checkOperation(NameNode.java:1774)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.checkOperation(FSNamesystem.java:1313)
        at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.reportBadBlocks(FSNamesystem.java:6263)
        at org.apache.hadoop.hdfs.server.namenode.NameNodeRpcServer.reportBadBlocks(NameNodeRpcServer.java:798)
        at org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolServerSideTranslatorPB.reportBadBlocks(DatanodeProtocolServerSideTranslatorPB.java:272)
        at org.apache.hadoop.hdfs.protocol.proto.DatanodeProtocolProtos$DatanodeProtocolService$2.callBlockingMethod(DatanodeProtocolProtos.java:28766)
        at org.apache.hadoop.ipc.ProtobufRpcEngine$Server$ProtoBufRpcInvoker.call(ProtobufRpcEngine.java:616)
        at org.apache.hadoop.ipc.RPC$Server.call(RPC.java:969)
        at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2049)
        at org.apache.hadoop.ipc.Server$Handler$1.run(Server.java:2045)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:422)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
        at org.apache.hadoop.ipc.Server$Handler.run(Server.java:2045)

        at org.apache.hadoop.ipc.Client.call(Client.java:1475)
        at org.apache.hadoop.ipc.Client.call(Client.java:1412)
        at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:229)
        at com.sun.proxy.$Proxy14.reportBadBlocks(Unknown Source)
        at org.apache.hadoop.hdfs.protocolPB.DatanodeProtocolClientSideTranslatorPB.reportBadBlocks(DatanodeProtocolClientSideTranslatorPB.java:290)
        at org.apache.hadoop.hdfs.server.datanode.ReportBadBlockAction.reportTo(ReportBadBlockAction.java:62)
        at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.processQueueMessages(BPServiceActor.java:988)
        at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.offerService(BPServiceActor.java:727)
        at org.apache.hadoop.hdfs.server.datanode.BPServiceActor.run(BPServiceActor.java:824)
        at java.lang.Thread.run(Thread.java:745)

If you are familiar with hadoop RPC, you will know that the above error log happends when RPC client(DataNode) trying to make a remote RPC call to the RPC Server(NameNode),NodeNode throw a exception because it is a standby one.So ,some of the above stacktrace was the server-side stack and some are the client-side stacktrace.

But the key is , does it has any bad influence to you HDFS system?
The answer is absolute no.

From BPOffsetService.java:

  void notifyNamenodeReceivingBlock(ExtendedBlock block, String storageUuid) {
checkBlock(block);
ReceivedDeletedBlockInfo bInfo = new ReceivedDeletedBlockInfo(
   block.getLocalBlock(), BlockStatus.RECEIVING_BLOCK, null);

for (BPServiceActor actor : bpServices) {
  actor.notifyNamenodeBlock(bInfo, storageUuid, false);
}

}

The bpServices store the rpc list of both namenodes , including the active and the standby one.Obviously , a same request it send to both namenodes ,at least one request will report a 'category WRITE is not supported in state standby***'error and the other one will succeed.
So ,no worries about it.
In your hdfs HA configurtion ,if you configure like this:

       <property>
            <name>dfs.ha.namenodes.datahdfsmaster</name>
            <value>namenode1,namenode2</value>
    </property>

And unfortunately ,if the namenode1 is the standby one , then you will receive much INFO-level log because namenode1 will be requested for some Operation and surely the NameNode-side checkOperation() will throw a INFO-level exception.


答:
This should work fine for you :         </p>

```<code>select sum(Connection) as Total_connection
        from Connection where ID in
( select ID from member where status = 1 );
</code>```

Title: sql select sum with condition 2 tables?

Body:
I have 2 table

Table Connection
----------------------------------------
|  ID       |  Member_ID  |  Connection|
----------------------------------------
|  1        |  100        |  22        |
----------------------------------------
|  2        |  101        |  15        |
----------------------------------------
|  3        |  102        |  19        |
----------------------------------------
|  4        |  103        |  21        |

Table Member
---------------------------
|  ID         |  Status     |
---------------------------
|  100        |  0          |
----------------------------
|  101        |  1          |
----------------------------
|  102        |  1          |
---------------------------
|  103        |  0          |

I want to get sum of Connection has status =1.
The result in example should be 15+19 = 34.

Body:
This should work fine for you :

select sum(Connection) as Total_connection
        from Connection where ID in
( select ID from member where status = 1 );


问:
Create VM with WMI in c#
I am trying to create a VM in Hyper-V with WMI.

```<code>        ManagementClass virtualSystemManagementService =
            new ManagementClass(@"root\virtualization\v2:Msvm_VirtualSystemManagementService");

        ManagementBaseObject inParams =
            virtualSystemManagementService
                .GetMethodParameters("DefineSystem");

        // Add the input parameters.
        ManagementClass virtualSystemSettingData =
            new ManagementClass(@"root\virtualization\v2:Msvm_VirtualSystemSettingData")
        {
            ["ElementName"] = "Test"
        };

        inParams["SystemSettings"] =
            virtualSystemSettingData.GetText(TextFormat.CimDtd20);

        // Execute the method and obtain the return values.
        ManagementBaseObject outParams =
            virtualSystemManagementService
                .InvokeMethod("DefineSystem", inParams, null);
</code>```

The call to InvokeMethod throws an System.Management.MangementException - "Invalid method Parameter(s).

I am basing this code on https://blogs.msdn.microsoft.com/virtual_pc_guy/2013/06/20/creating-a-virtual-machine-with-wmi-v2/

I do realize that this is really easy with powershell, but I am trying to understand how the WMI side of things works.

答:
You need to create an instance of msvm_VirtualSystemSettingData.</p>

```<code>   ManagementObject newInstance = new ManagementClass(scope, new ManagementPath("Msvm_VirtualSystemSettingData"), null).CreateInstance();
   newInstance["ElementName"] = vmName;
   inParameters["SystemSettings"] = newInstance.GetText(TextFormat.CimDtd20);
</code>```

Title: Create VM with WMI in c#

Body:
I am trying to create a VM in Hyper-V with WMI.

        ManagementClass virtualSystemManagementService =
            new ManagementClass(@"root\virtualization\v2:Msvm_VirtualSystemManagementService");

        ManagementBaseObject inParams =
            virtualSystemManagementService
                .GetMethodParameters("DefineSystem");

        // Add the input parameters.
        ManagementClass virtualSystemSettingData =
            new ManagementClass(@"root\virtualization\v2:Msvm_VirtualSystemSettingData")
        {
            ["ElementName"] = "Test"
        };

        inParams["SystemSettings"] =
            virtualSystemSettingData.GetText(TextFormat.CimDtd20);

        // Execute the method and obtain the return values.
        ManagementBaseObject outParams =
            virtualSystemManagementService
                .InvokeMethod("DefineSystem", inParams, null);

The call to InvokeMethod throws an System.Management.MangementException - "Invalid method Parameter(s).

I am basing this code on https://blogs.msdn.microsoft.com/virtual_pc_guy/2013/06/20/creating-a-virtual-machine-with-wmi-v2/

I do realize that this is really easy with powershell, but I am trying to understand how the WMI side of things works.

Body:
You need to create an instance of msvm_VirtualSystemSettingData.

   ManagementObject newInstance = new ManagementClass(scope, new ManagementPath("Msvm_VirtualSystemSettingData"), null).CreateInstance();
   newInstance["ElementName"] = vmName;
   inParameters["SystemSettings"] = newInstance.GetText(TextFormat.CimDtd20);


问:
Edit array of axis output from pandas plot method
I'm plotting from a pandas dataframe with subplots and as a result I get a np.array with a number of axis.

```<code>array([<matplotlib.axes._subplots.AxesSubplot object at blablabla>,
       <matplotlib.axes._subplots.AxesSubplot object at blablabla>,
       <matplotlib.axes._subplots.AxesSubplot object at blablabla>])
</code>```

I want to grab this output to edit the title, x label and save it as pdf. If it was only one axis I would first grab the output of the .plot in a variable, say ax and then set the title and get the figure with fig = ax.get_figure() to save it the way I want. How can I do the same here?

答:
Let's use ax = infront of df.plot to get a list of axes.  Then you can use list slicing to access each axes object and set_title, etc.. as below:

```<code>df = pd.DataFrame(np.random.randn(1000, 4), columns=list('ABCD'))
df = df.cumsum()

ax = df.plot(subplots=True)
ax[0].set_title('Series A')
ax[1].set_title('Series B')
ax[2].set_title('Series C')
ax[3].set_title('Series D')
fig = ax[0].get_figure()
fig.tight_layout()
</code>```

Body:
I'm plotting from a pandas dataframe with subplots and as a result I get a np.array with a number of axis.

array([<matplotlib.axes._subplots.AxesSubplot object at blablabla>,
       <matplotlib.axes._subplots.AxesSubplot object at blablabla>,
       <matplotlib.axes._subplots.AxesSubplot object at blablabla>])

I want to grab this output to edit the title, x label and save it as pdf. If it was only one axis I would first grab the output of the .plot in a variable, say ax and then set the title and get the figure with fig = ax.get_figure() to save it the way I want. How can I do the same here?

Body:
Let's use ax = infront of df.plot to get a list of axes.  Then you can use list slicing to access each axes object and set_title, etc.. as below:

df = pd.DataFrame(np.random.randn(1000, 4), columns=list('ABCD'))
df = df.cumsum()

ax = df.plot(subplots=True)
ax[0].set_title('Series A')
ax[1].set_title('Series B')
ax[2].set_title('Series C')
ax[3].set_title('Series D')
fig = ax[0].get_figure()
fig.tight_layout()


答:
Here is an example of how to write this query using generic SQL:</p>

```<code>SELECT
    SUM(Connection.Connection) AS ConnectionSum
FROM
    Connection
JOIN
    Member ON Connection.Member_ID = Member.ID
WHERE
    Member.Status = 1;
</code>```

Title: sql select sum with condition 2 tables?

Body:
Here is an example of how to write this query using generic SQL:

SELECT
    SUM(Connection.Connection) AS ConnectionSum
FROM
    Connection
JOIN
    Member ON Connection.Member_ID = Member.ID
WHERE
    Member.Status = 1;


问:
Boo vs. IronPython
After having looked at each of these two projects, it seems that both are VERY similar. Both run on top of the CLI, both have python style syntax, both use .NET instead of the standard python libraries.

So, what are the differences between them and advantages of each?

答:
Like Winston said, Boo is very extensible due to its open compiler architecture, take a look at these examples:

http://ayende.com/Blog/archive/2008/05/27/The-magic-of-boo--Flexible-syntax.aspx

http://www.infoq.com/articles/dsl-on-the-clr

http://ayende.com/Blog/archive/2007/12/21/Meta-Methods.aspx

http://ayende.com/Blog/archive/2007/11/24/Domain-Specific-Language-Losing-the-original-language.aspx

http://ayende.com/Blog/archive/2007/10/14/By-the-DSL-guess-what-I-am-reading.aspx

http://ayende.com/Blog/archive/2007/10/04/Redefining-If.aspx

http://ayende.com/Blog/archive/2007/09/21/Playing-with-Boos-DSLs.aspx

OwnerDisplayName: monoxide

ContentLicense: CC BY-SA 2.5

Title: Boo vs. IronPython

OwnerDisplayName: mausch


问:
Getting a HASP key with C/C++ (Problem)
I seem to be in need of some help (and by some, I mean a lot).

Im trying to make a C program (or c++ if I get it to work, the language is not really important) to connect to a HASP USB. HASP is basically a USB drive that has some unique codes. The purpose of the HASP is to basically just "secure" another program, so that it only runs while the HASP is connected to the computer.

First of all, let me say that I am actually trying to get it to work, not hacking another one. I am using the demo key for development, for now, although I have a master key.

This HASP program features a toolbox, that should generate the code in C ready to copy paste and get it to work. But, it doesent actually work, or at least, its not just copy paste.

(For more information about HASP, go http://www2.safenet-inc.com/google/SRM/dk-hasp.asp?CID=GooIntl-IND&HBX_PK=hasp&HBX_OU=50&CMP=KNC-GoogleAdd&wcw=google&_kk=hasp&_kt=e9b07d11-6db3-4153-a46b-5dc95204b6a3&gclid=CJfxibrp-qUCFRQv3wodBnwfpA )

Unfortunately, I do NOT have any kind of C or C++ coding experience, so I am having several problems trying to work this out. I only programmed the other part in Director (similar to Flash).

The code it gives me just for making a login (read, connection) to the HASP is the following:

```<code>const hasp_feature_t feature = HASP_DEFAULT_FID;

hasp_handle_t handle = HASP_INVALID_HANDLE_VALUE;
hasp_status_t status;

//This is a code needed to login, its just the demo code for now, but it matches
//the HASP i'm using

unsigned char vendor_code[] =

"AzIceaqfA1hX5wS+M8cGnYh5ceevUnOZIzJBbXFD6dgf3tBkb9cvUF/Tkd/iKu2fsg9wAysYKw7RMAsV"
"vIp4KcXle/v1RaXrLVnNBJ2H2DmrbUMOZbQUFXe698qmJsqNpLXRA367xpZ54i8kC5DTXwDhfxWTOZrB"
"rh5sRKHcoVLumztIQjgWh37AzmSd1bLOfUGI0xjAL9zJWO3fRaeB0NS2KlmoKaVT5Y04zZEc06waU2r6"
"AU2Dc4uipJqJmObqKM+tfNKAS0rZr5IudRiC7pUwnmtaHRe5fgSI8M7yvypvm+13Wm4Gwd4VnYiZvSxf"
"8ImN3ZOG9wEzfyMIlH2+rKPUVHI+igsqla0Wd9m7ZUR9vFotj1uYV0OzG7hX0+huN2E/IdgLDjbiapj1"
"e2fKHrMmGFaIvI6xzzJIQJF9GiRZ7+0jNFLKSyzX/K3JAyFrIPObfwM+y+zAgE1sWcZ1YnuBhICyRHBh"
"aJDKIZL8MywrEfB2yF+R3k9wFG1oN48gSLyfrfEKuB/qgNp+BeTruWUk0AwRE9XVMUuRbjpxa4YA67SK"
"unFEgFGgUfHBeHJTivvUl0u4Dki1UKAT973P+nXy2O0u239If/kRpNUVhMg8kpk7s8i6Arp7l/705/bL"
"Cx4kN5hHHSXIqkiG9tHdeNV8VYo5+72hgaCx3/uVoVLmtvxbOIvo120uTJbuLVTvT8KtsOlb3DxwUrwL"
"zaEMoAQAFk6Q9bNipHxfkRQER4kR7IYTMzSoW5mxh3H9O8Ge5BqVeYMEW36q9wnOYfxOLNw6yQMf8f9s"
"JN4KhZty02xm707S7VEfJJ1KNq7b5pP/3RjE0IKtB2gE6vAPRvRLzEohu0m7q1aUp8wAvSiqjZy7FLaT"
"tLEApXYvLvz6PEJdj4TegCZugj7c8bIOEqLXmloZ6EgVnjQ7/ttys7VFITB3mazzFiyQuKf4J6+b/a/Y";

status = hasp_login(feature, vendor_code, &handle);

/* check if operation was successful */
if (status != HASP_STATUS_OK)
{
    switch (status)
    {
        case HASP_FEATURE_NOT_FOUND:
            break;
        case HASP_HASP_NOT_FOUND:
            break;
        case HASP_OLD_DRIVER:
            break;
        case HASP_NO_DRIVER:
            break;
        case HASP_INV_VCODE:
            break;
        case HASP_FEATURE_TYPE_NOT_IMPL:
            break;
        case HASP_TMOF:
            break;
        case HASP_TS_DETECTED:
            break;
        default:
            break;
    }
}
</code>```

And the error:

```<code>hasp_demo.cpp|44|error: expected constructor, destructor, or type conversion before '=' token|
hasp_demo.cpp|47|error: expected unqualified-id before 'if'|
||=== Build finished: 2 errors, 0 warnings ===|
</code>```

I know this is a very specific help request, but I'm completely lost now and don't know what to do from now on. I tried playing around with the code, but it always gets me errors.

Also, im on windows, using GNU GCC Compiler in Codeblocks IDE.

答:
The code you pasted seems like an example how to use the API, not a working program by itself. It does not seem like it is intended to compile.

So I guess you need to learn C/C++, or find someone at your job who can help.

Title: Getting a HASP key with C/C++ (Problem)

Body:
I seem to be in need of some help (and by some, I mean a lot).

Im trying to make a C program (or c++ if I get it to work, the language is not really important) to connect to a HASP USB. HASP is basically a USB drive that has some unique codes. The purpose of the HASP is to basically just "secure" another program, so that it only runs while the HASP is connected to the computer.

First of all, let me say that I am actually trying to get it to work, not hacking another one. I am using the demo key for development, for now, although I have a master key.

This HASP program features a toolbox, that should generate the code in C ready to copy paste and get it to work. But, it doesent actually work, or at least, its not just copy paste.

(For more information about HASP, go http://www2.safenet-inc.com/google/SRM/dk-hasp.asp?CID=GooIntl-IND&HBX_PK=hasp&HBX_OU=50&CMP=KNC-GoogleAdd&wcw=google&_kk=hasp&_kt=e9b07d11-6db3-4153-a46b-5dc95204b6a3&gclid=CJfxibrp-qUCFRQv3wodBnwfpA )

Unfortunately, I do NOT have any kind of C or C++ coding experience, so I am having several problems trying to work this out. I only programmed the other part in Director (similar to Flash).

The code it gives me just for making a login (read, connection) to the HASP is the following:

const hasp_feature_t feature = HASP_DEFAULT_FID;

hasp_handle_t handle = HASP_INVALID_HANDLE_VALUE;
hasp_status_t status;

//This is a code needed to login, its just the demo code for now, but it matches
//the HASP i'm using

unsigned char vendor_code[] =

"AzIceaqfA1hX5wS+M8cGnYh5ceevUnOZIzJBbXFD6dgf3tBkb9cvUF/Tkd/iKu2fsg9wAysYKw7RMAsV"
"vIp4KcXle/v1RaXrLVnNBJ2H2DmrbUMOZbQUFXe698qmJsqNpLXRA367xpZ54i8kC5DTXwDhfxWTOZrB"
"rh5sRKHcoVLumztIQjgWh37AzmSd1bLOfUGI0xjAL9zJWO3fRaeB0NS2KlmoKaVT5Y04zZEc06waU2r6"
"AU2Dc4uipJqJmObqKM+tfNKAS0rZr5IudRiC7pUwnmtaHRe5fgSI8M7yvypvm+13Wm4Gwd4VnYiZvSxf"
"8ImN3ZOG9wEzfyMIlH2+rKPUVHI+igsqla0Wd9m7ZUR9vFotj1uYV0OzG7hX0+huN2E/IdgLDjbiapj1"
"e2fKHrMmGFaIvI6xzzJIQJF9GiRZ7+0jNFLKSyzX/K3JAyFrIPObfwM+y+zAgE1sWcZ1YnuBhICyRHBh"
"aJDKIZL8MywrEfB2yF+R3k9wFG1oN48gSLyfrfEKuB/qgNp+BeTruWUk0AwRE9XVMUuRbjpxa4YA67SK"
"unFEgFGgUfHBeHJTivvUl0u4Dki1UKAT973P+nXy2O0u239If/kRpNUVhMg8kpk7s8i6Arp7l/705/bL"
"Cx4kN5hHHSXIqkiG9tHdeNV8VYo5+72hgaCx3/uVoVLmtvxbOIvo120uTJbuLVTvT8KtsOlb3DxwUrwL"
"zaEMoAQAFk6Q9bNipHxfkRQER4kR7IYTMzSoW5mxh3H9O8Ge5BqVeYMEW36q9wnOYfxOLNw6yQMf8f9s"
"JN4KhZty02xm707S7VEfJJ1KNq7b5pP/3RjE0IKtB2gE6vAPRvRLzEohu0m7q1aUp8wAvSiqjZy7FLaT"
"tLEApXYvLvz6PEJdj4TegCZugj7c8bIOEqLXmloZ6EgVnjQ7/ttys7VFITB3mazzFiyQuKf4J6+b/a/Y";

status = hasp_login(feature, vendor_code, &handle);

/* check if operation was successful */
if (status != HASP_STATUS_OK)
{
    switch (status)
    {
        case HASP_FEATURE_NOT_FOUND:
            break;
        case HASP_HASP_NOT_FOUND:
            break;
        case HASP_OLD_DRIVER:
            break;
        case HASP_NO_DRIVER:
            break;
        case HASP_INV_VCODE:
            break;
        case HASP_FEATURE_TYPE_NOT_IMPL:
            break;
        case HASP_TMOF:
            break;
        case HASP_TS_DETECTED:
            break;
        default:
            break;
    }
}

And the error:

hasp_demo.cpp|44|error: expected constructor, destructor, or type conversion before '=' token|
hasp_demo.cpp|47|error: expected unqualified-id before 'if'|
||=== Build finished: 2 errors, 0 warnings ===|

I know this is a very specific help request, but I'm completely lost now and don't know what to do from now on. I tried playing around with the code, but it always gets me errors.

Also, im on windows, using GNU GCC Compiler in Codeblocks IDE.


问:
Display the emoji codes in a PHP variable
I have text in a php variable $sentence.  I want to display the actual emoji codes found in $sentence on my web page.  Not the emoji graphical icons but the actual emoji codes themselves which are embedded in the sentence.

I have been trying all day to do this by reverse engineering code that is usually used to "remove emojis".  No success.

Looking to display the actual codes to emojis embedded in text.  Example ...

[twitter.com/ProfitTradeRoom/status/880439582063566848][1]

As you can see the fire emoji is in this tweet.  The code for fire is 1F525. I want to see 1F525 on my screen when i echo out the php variable.  Basically "1F525 HOT 1F525 stocks today" on my screen instead of the graphical emojis.

String taken straight from my MySQL database (copied and pasted) ...

```<code>    HOTstocks today
</code>```

答:
I found the answer!  The issue was my mysql connection.  I was pulling from mysql into php.  None of my regular expressions were matching any emoji unicodes until I did this ...

```<code>mysql_set_charset('utf8mb4');
</code>```

I put mysql_set_charset immediately after I defined the connection string.  Now when I pull text with emojis it will match a preg_match / preg_replace.  For example detecting the fire emoji in a sentence ...

```<code>$theFireEmojiCode = '/[\x{1F525}]/u';
preg_match($theFireEmojiCode, $sentence, $matches);
</code>```

Or I can do a preg_replace like this ...

```<code>$theFireEmojiCode = '/[\x{1F525}]/u';
preg_replace($theFireEmojiCode, "1F525", $sentence);
</code>```

Hope this helps.

Body:
I have text in a php variable $sentence.  I want to display the actual emoji codes found in $sentence on my web page.  Not the emoji graphical icons but the actual emoji codes themselves which are embedded in the sentence.

I have been trying all day to do this by reverse engineering code that is usually used to "remove emojis".  No success.

Looking to display the actual codes to emojis embedded in text.  Example ...

[twitter.com/ProfitTradeRoom/status/880439582063566848][1]

As you can see the fire emoji is in this tweet.  The code for fire is 1F525. I want to see 1F525 on my screen when i echo out the php variable.  Basically "1F525 HOT 1F525 stocks today" on my screen instead of the graphical emojis.

String taken straight from my MySQL database (copied and pasted) ...

    HOTstocks today

Body:
I found the answer!  The issue was my mysql connection.  I was pulling from mysql into php.  None of my regular expressions were matching any emoji unicodes until I did this ...

mysql_set_charset('utf8mb4');

I put mysql_set_charset immediately after I defined the connection string.  Now when I pull text with emojis it will match a preg_match / preg_replace.  For example detecting the fire emoji in a sentence ...

$theFireEmojiCode = '/[\x{1F525}]/u';
preg_match($theFireEmojiCode, $sentence, $matches);

Or I can do a preg_replace like this ...

$theFireEmojiCode = '/[\x{1F525}]/u';
preg_replace($theFireEmojiCode, "1F525", $sentence);

Hope this helps.


问:
D3: Can I have an svg transition based on items in a list?
I would like to take a list...

```<code>var data = [100, 200, 300] // arbitrarily long
</code>```

... and transition an element across the screen based on each list item. For example, I would like to send a dot first to [100,100], [200,100], [300,100]. Is there a way to do this with data joining?

Right now, I have have a solution that works, but it works in what seems to be a very un-D3-ish way: using a counter to iterate through a list, and using no data-binding. Excluding the CSS, here's the code:

```<code><svg>
  <circle/>
</svg>

<script>

var data = [100,200,300]

var circle = d3.selectAll("circle")
    .attr("r",20)
    .attr("cy",100)
    .attr("cx",0)

var count = 0

repeat()

function repeat() {
  var run = circle
    .transition()
    .duration(1000)
    .attr("cx", function (d) {return data[count]});

    count++

  if (count < data.length){
    run
      .each("end", repeat);
  }
}

</script>
</code>```

Shouldn't there be a way to do this with data binding? I'd love to do this the right way, but for now this is all I can figure out just to make it work.

答:
Using this as a reference: https://bl.ocks.org/mbostock/1125997

I'm not convinced this is the best way to do it, because it still relies on an external variable count, which is not very D3.

Note the array structure of data.

https://jsfiddle.net/e51rzkth/4/

```<code>var data = [[[100,100],[200,100],[300,100]]]

var svg = d3.select("body")
    .append("svg")
  .attr("width", 400)
  .attr("height", 400)

var circle = svg.selectAll("circle")
  .data(data)
  .enter()
  .append("circle")
    .attr("r",20)
    .style("fill", "red")

var count = 0

circle
    .transition()
    .duration(1000)
    .delay(250)
    .on("start", function repeat() {
        d3.active(this)
          .transition()
          .attr('cx', d=>d[count][0])
          .attr('cy', d=>d[count][1])
          .transition()
            .on("start", repeat);
            count++;
      });
</code>```

For funsies, an example with multiple circles, each with their own path.

https://jsfiddle.net/e51rzkth/3/

Body:
I would like to take a list...

var data = [100, 200, 300] // arbitrarily long

... and transition an element across the screen based on each list item. For example, I would like to send a dot first to [100,100], [200,100], [300,100]. Is there a way to do this with data joining?

Right now, I have have a solution that works, but it works in what seems to be a very un-D3-ish way: using a counter to iterate through a list, and using no data-binding. Excluding the CSS, here's the code:

<svg>
  <circle/>
</svg>

Shouldn't there be a way to do this with data binding? I'd love to do this the right way, but for now this is all I can figure out just to make it work.

Body:
Using this as a reference: https://bl.ocks.org/mbostock/1125997

I'm not convinced this is the best way to do it, because it still relies on an external variable count, which is not very D3.

Note the array structure of data.

https://jsfiddle.net/e51rzkth/4/

var data = [[[100,100],[200,100],[300,100]]]

var svg = d3.select("body")
    .append("svg")
  .attr("width", 400)
  .attr("height", 400)

var circle = svg.selectAll("circle")
  .data(data)
  .enter()
  .append("circle")
    .attr("r",20)
    .style("fill", "red")

var count = 0

circle
    .transition()
    .duration(1000)
    .delay(250)
    .on("start", function repeat() {
        d3.active(this)
          .transition()
          .attr('cx', d=>d[count][0])
          .attr('cy', d=>d[count][1])
          .transition()
            .on("start", repeat);
            count++;
      });

For funsies, an example with multiple circles, each with their own path.

https://jsfiddle.net/e51rzkth/3/


问:
Error when inserting data to MySql
I have 1 tables and I need to insert two client details at once. However, there is error for me to insert the second client's data to MySql. Also, when both of the results are not able to key in when I insert in the second time.
MySql table:

This is Html table:

```<code>   <form name="creditAssessPage2" id="basicform" method="post" action="post.php" enctype="multipart/form-data">
         <tr>
             <td>Occupation</td>
             <td><input type="text"   id="occupationMain" name="occupationMain" class="form-control" autocomplete="off" ></td>
             <td><input type="text"   id="occupationJoint1" name="occupationJoint1" class="form-control" autocomplete="off" ></td>
        </tr>
        <tr>
            <td>Employment</td>
            <td contenteditable="true">
            <input list="employTypeList" name="employTypeMain" id="employTypeMain" class="form-control">
                 <datalist id="employTypeList">
                      <option value="">
                      <option value="Self-employed">
                      <option value="Employed">
                      <option value="Unemployed">
                      <option value="Retired">
                 </datalist>
            </td>
            <td contenteditable="true">
                <input list="employTypeList" name="employTypeJoint1" id="employTypeJoint1" class="form-control">
                <datalist id="employTypeList">
                     <option value="">
                     <option value="Self-employed">
                     <option value="Employed">
                     <option value="Unemployed">
                     <option value="Retired">
                </datalist>
            </td>
        </tr>
        <tr>
            <td>Company</td>
            <td><input type="text"   id="companyMain" name="companyMain" class="form-control" autocomplete="off" ></td>
            <td><input type="text"   id="companyJoint1" name="companyJoint1" class="form-control" autocomplete="off" ></td>
        </tr>
        <div class="form-group">
<button type="submit" name="submit" class="btn btn-default">Create</button><br/>
</div>
    </form>
</code>```

This is is my post.php code:

```<code><?php

require_once 'db/dbfunction.php';
require_once 'db/dbCreditAssessment.php';

session_start();
$con = open_connection();

$occupationMain = $_POST['occupationMain'];
$employTypeMain = $_POST['employTypeMain'];
$companyMain = $_POST['companyMain'];

$occupationJoint1 = $_POST['occupationJoint1'];
$employTypeJoint1 = $_POST['employTypeJoint1'];
$companyJoint1 = $_POST['companyJoint1'];

addemployementdetails($con,$occupationMain,$employTypeMain,$companyMain);
addemployementdetails2($con,$occupationJoint1,$employTypeJoint1,$companyJoint1);

close_connection($con);
?>
</code>```

This is the code for dbCreditAssessment.php:

```<code><?php

function addemployementdetails($con,$occupationMain,$employTypeMain,$companyMain){

    $query = "insert into employementdetails(Occupation,EmploymentStatus,NameOfBusiness)
            values('$occupationMain','$employTypeMain','$companyMain')";
                 //echo "{$sqlString}";

                 $insertResult = mysqli_query($con, $query);

                 if($insertResult){
                     echo " Applicant Detail Added !<br />";
                     echo "<a href='index.php'>Back to Home</a>";
                 }
                 else {
                     echo " Error !";
                     echo "{$query}";
                     //header('Location: post.php');
                 }

}

function addemployementdetails2($con,$occupationJoint1,$employTypeJoint1,$companyJoint1){
    $query2 = "insert into employementdetails(Occupation,EmploymentStatus,NameOfBusiness)
            values('$occupationJoint1','$employTypeJoint1','$companyJoint1')";

                 $insertResult2 = mysqli_query($con, $query2);

                 if($insertResult2){
                     echo " Applicant Detail Added !<br />";
                     echo "<a href='index.php'>Back to Home</a>";
                 }
                 else {
                     echo " Error !";
                     echo "{$query2}";
                     //header('Location: post.php');
                 }
}
</code>```

答:
Actually, your table has attribute EmploymentDetailsID as the Primary key which must have unique in each entry. But you are not inserting unique value in each entry. Now the solution for this problem is given below...

Alter table and make EmploymentDetailsID auto increment column. And for this purpose you can use code given below...

ALTER TABLE employementdetails MODIFY COLUMN EmploymentDetailsID varchar auto_increment

Title: Error when inserting data to MySql

Body:
I have 1 tables and I need to insert two client details at once. However, there is error for me to insert the second client's data to MySql. Also, when both of the results are not able to key in when I insert in the second time.
MySql table:

This is Html table:

   <form name="creditAssessPage2" id="basicform" method="post" action="post.php" enctype="multipart/form-data">

             Occupation
             <input type="text"   id="occupationMain" name="occupationMain" class="form-control" autocomplete="off" >
             <input type="text"   id="occupationJoint1" name="occupationJoint1" class="form-control" autocomplete="off" >

            Employment

            <input list="employTypeList" name="employTypeMain" id="employTypeMain" class="form-control">
                 <datalist id="employTypeList">
                      <option value="">
                      <option value="Self-employed">
                      <option value="Employed">
                      <option value="Unemployed">
                      <option value="Retired">
                 </datalist>

                <input list="employTypeList" name="employTypeJoint1" id="employTypeJoint1" class="form-control">
                <datalist id="employTypeList">
                     <option value="">
                     <option value="Self-employed">
                     <option value="Employed">
                     <option value="Unemployed">
                     <option value="Retired">
                </datalist>

            Company
            <input type="text"   id="companyMain" name="companyMain" class="form-control" autocomplete="off" >
            <input type="text"   id="companyJoint1" name="companyJoint1" class="form-control" autocomplete="off" >

<button type="submit" name="submit" class="btn btn-default">Create</button>

    </form>

This is is my post.php code:

<?php

require_once 'db/dbfunction.php';
require_once 'db/dbCreditAssessment.php';

session_start();
$con = open_connection();

$occupationMain = $_POST['occupationMain'];
$employTypeMain = $_POST['employTypeMain'];
$companyMain = $_POST['companyMain'];

$occupationJoint1 = $_POST['occupationJoint1'];
$employTypeJoint1 = $_POST['employTypeJoint1'];
$companyJoint1 = $_POST['companyJoint1'];

addemployementdetails($con,$occupationMain,$employTypeMain,$companyMain);
addemployementdetails2($con,$occupationJoint1,$employTypeJoint1,$companyJoint1);

close_connection($con);
?>

This is the code for dbCreditAssessment.php:

<?php

function addemployementdetails($con,$occupationMain,$employTypeMain,$companyMain){

    $query = "insert into employementdetails(Occupation,EmploymentStatus,NameOfBusiness)
            values('$occupationMain','$employTypeMain','$companyMain')";
                 //echo "{$sqlString}";

                 $insertResult = mysqli_query($con, $query);

                 if($insertResult){
                     echo " Applicant Detail Added !
";
                     echo "Back to Home";
                 }
                 else {
                     echo " Error !";
                     echo "{$query}";
                     //header('Location: post.php');
                 }

}

function addemployementdetails2($con,$occupationJoint1,$employTypeJoint1,$companyJoint1){
    $query2 = "insert into employementdetails(Occupation,EmploymentStatus,NameOfBusiness)
            values('$occupationJoint1','$employTypeJoint1','$companyJoint1')";

                 $insertResult2 = mysqli_query($con, $query2);

                 if($insertResult2){
                     echo " Applicant Detail Added !
";
                     echo "Back to Home";
                 }
                 else {
                     echo " Error !";
                     echo "{$query2}";
                     //header('Location: post.php');
                 }
}


问:
Addition of two arrays not working using pthread
Could you please some one help me to identify the issues in the following code.

Background: The test code adds two arrays, input1 & input2 and stores the results in output, using 4-threads.
The problem was one of the thread not able to do correctly, output buffer shows "0" randomly for one of the threads. Any help highly appreciated.

```<code>#include<iostream>
#include<pthread.h>
#include<unistd.h>
using namespace std;
int input1[1000], input2[1000], output[1000];

void* Addition(void* offset) {
    int *local_offset = (int*)offset;
    for(int i = ((*local_offset) * 250); i < ((*local_offset)+1)*250; ++i) {
            output[i] = input1[i] + input2[i];
    }
    pthread_exit(0);
}

int main() {
    pthread_t thread_id[4];
    void* status;
    fill_n(input1, 1000, 3); // input1, fill the buffer with 3
    fill_n(input2, 1000, 4); // input2, fill the buffer with 4
    fill_n(output, 1000, 0); // output, fill the buffer with 0

    // create 4 thread with load of 250items
    for(int i = 0; i < 4; ++i) {
            int result = pthread_create(&thread_id[i], NULL, Addition, &i);
            if(result) cout << "Thread creation failed" << endl;
    }

    // join the 4-threads
    for(int i = 0; i < 4; ++i) {
            int result = pthread_join(thread_id[i], &status);
            if(result) cout << "Join failed " << i << endl;
    }

    // print output buffer, the output buffer not updated properly,
    // noticed"0" for 1 & 2 thread randomly
    for(int i =0; i < 1000; ++i)
            cout << i << " " << output[i] << endl;

    pthread_exit(NULL);
}
</code>```

答:
I have found the root cause of the issue...
The "&i" gives unknown result because "i" memory will be overwritten by ++i and thread_id[0] get different value by the time the thread created... so you should have a dedicated memory so that no overwriting will happen by ++i;

&i is the problem...

```<code>int result = pthread_create(&thread_id[i], NULL, Addition, &i);
</code>```

To solve, replace with &shared_data[i] ....
  int result = pthread_create(&thread_id[i], NULL, Addition, &shared_data[i]);

The shared_data is an array of 4 elements.. like this

```<code>int shared_data[4] = {0,1,2,3};
</code>```

Body:
Could you please some one help me to identify the issues in the following code.

Background: The test code adds two arrays, input1 & input2 and stores the results in output, using 4-threads.
The problem was one of the thread not able to do correctly, output buffer shows "0" randomly for one of the threads. Any help highly appreciated.

#include<iostream>
#include<pthread.h>
#include<unistd.h>
using namespace std;
int input1[1000], input2[1000], output[1000];

void* Addition(void* offset) {
    int *local_offset = (int*)offset;
    for(int i = ((*local_offset) * 250); i < ((*local_offset)+1)*250; ++i) {
            output[i] = input1[i] + input2[i];
    }
    pthread_exit(0);
}

int main() {
    pthread_t thread_id[4];
    void* status;
    fill_n(input1, 1000, 3); // input1, fill the buffer with 3
    fill_n(input2, 1000, 4); // input2, fill the buffer with 4
    fill_n(output, 1000, 0); // output, fill the buffer with 0

    // create 4 thread with load of 250items
    for(int i = 0; i < 4; ++i) {
            int result = pthread_create(&thread_id[i], NULL, Addition, &i);
            if(result) cout << "Thread creation failed" << endl;
    }

    // join the 4-threads
    for(int i = 0; i < 4; ++i) {
            int result = pthread_join(thread_id[i], &status);
            if(result) cout << "Join failed " << i << endl;
    }

    // print output buffer, the output buffer not updated properly,
    // noticed"0" for 1 & 2 thread randomly
    for(int i =0; i < 1000; ++i)
            cout << i << " " << output[i] << endl;

    pthread_exit(NULL);
}

Body:
I have found the root cause of the issue...
The "&i" gives unknown result because "i" memory will be overwritten by ++i and thread_id[0] get different value by the time the thread created... so you should have a dedicated memory so that no overwriting will happen by ++i;

&i is the problem...

int result = pthread_create(&thread_id[i], NULL, Addition, &i);

To solve, replace with &shared_data[i] ....
  int result = pthread_create(&thread_id[i], NULL, Addition, &shared_data[i]);

The shared_data is an array of 4 elements.. like this

int shared_data[4] = {0,1,2,3};


问:
ASP.NET Core authenticating with Azure Active Directory and persisting custom Claims across requests
I have a default ASP.NET Core website created within Visual Studio 2017.  I have chosen to authenticate using an Azure Active Directory.
I run the site and can successfully login using an account in the Active Directory.

I can retrieve Claim information provided by Active Directory, e.g. by calling the following line I get the 'name'.

```<code>User.Claims.FirstOrDefault(c => c.Type == "name")?.Value;
</code>```

I want to add a custom claim - CompanyId = 123456 for the logged in user.
I'm able to add a custom claim however it is only available on the page where the claim is set.

```<code>Claim claim = new Claim("CompanyId", "123456", ClaimValueTypes.String);
((ClaimsIdentity)User.Identity).AddClaim(claim);
</code>```

My understanding is that I somehow need to update the token that has been issued by Active Directory or set the claim before the token is issued.  I'm unsure how to do this.

I suspect this needs to be done in the AccountController at SignIn()

```<code>// GET: /Account/SignIn
[HttpGet]
public IActionResult SignIn()
{
    return Challenge(
            new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectDefaults.AuthenticationScheme);
}
</code>```

I've read numerous articles and samples about this scenario (including https://github.com/ahelland/AADGuide-CodeSamples/tree/master/ClaimsWebApp) however have not managed to solve how to persist the Claim across requests.

I have successfully managed to persist custom Claims using ASP.NET Identity as the Authentication Provider, but this appears to be because the custom Claim is saved to the database..

答:
OnTokenValidated offers you the chance to modify the ClaimsIdentity obtained from the incoming token , code below is for your reference :

```<code>private Task TokenValidated(TokenValidatedContext context)
{
    Claim claim = new Claim("CompanyId", "123456", ClaimValueTypes.String);
    (context.Ticket.Principal.Identity as ClaimsIdentity).AddClaim(claim);

    return Task.FromResult(0);
}
</code>```

Setting the OpenIdConnectEvents:

```<code>Events = new OpenIdConnectEvents
{
    OnRemoteFailure = OnAuthenticationFailed,
    OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,

    OnTokenValidated = TokenValidated
}
</code>```

Then in controller using :

```<code>var companyId=  User.Claims.FirstOrDefault(c => c.Type == "CompanyId")?.Value;
</code>```

Body:
I have a default ASP.NET Core website created within Visual Studio 2017.  I have chosen to authenticate using an Azure Active Directory.
I run the site and can successfully login using an account in the Active Directory.

I can retrieve Claim information provided by Active Directory, e.g. by calling the following line I get the 'name'.

User.Claims.FirstOrDefault(c => c.Type == "name")?.Value;

I want to add a custom claim - CompanyId = 123456 for the logged in user.
I'm able to add a custom claim however it is only available on the page where the claim is set.

Claim claim = new Claim("CompanyId", "123456", ClaimValueTypes.String);
((ClaimsIdentity)User.Identity).AddClaim(claim);

My understanding is that I somehow need to update the token that has been issued by Active Directory or set the claim before the token is issued.  I'm unsure how to do this.

I suspect this needs to be done in the AccountController at SignIn()

// GET: /Account/SignIn
[HttpGet]
public IActionResult SignIn()
{
    return Challenge(
            new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectDefaults.AuthenticationScheme);
}

I've read numerous articles and samples about this scenario (including https://github.com/ahelland/AADGuide-CodeSamples/tree/master/ClaimsWebApp) however have not managed to solve how to persist the Claim across requests.

I have successfully managed to persist custom Claims using ASP.NET Identity as the Authentication Provider, but this appears to be because the custom Claim is saved to the database..

Body:
OnTokenValidated offers you the chance to modify the ClaimsIdentity obtained from the incoming token , code below is for your reference :

private Task TokenValidated(TokenValidatedContext context)
{
    Claim claim = new Claim("CompanyId", "123456", ClaimValueTypes.String);
    (context.Ticket.Principal.Identity as ClaimsIdentity).AddClaim(claim);

    return Task.FromResult(0);
}

Setting the OpenIdConnectEvents:

Events = new OpenIdConnectEvents
{
    OnRemoteFailure = OnAuthenticationFailed,
    OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,

    OnTokenValidated = TokenValidated
}

Then in controller using :

var companyId=  User.Claims.FirstOrDefault(c => c.Type == "CompanyId")?.Value;


问:
Getting the handler inside on() method

$( document ).ready(function() {

  $('#handler').on('click', '.selector', function(){
    alert( $(this).text());
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="handler">
  handler content
  selector content
</div></code>```

How do I get the #handler inside the on method without explicitly specifying it?

答:
In this specific case you can directly use the unique id you have

```<code>$("#handler").
</code>```

In case if that is a class, you have $(this).parent() to the top level.

you can chain it to nth level , till you reach the top. $(this).parent().parent()...

or since you know the selector, you can do $(this).parents("selector")

Title: Getting the handler inside on() method

Body:
$( document ).ready(function() {

  $('#handler').on('click', '.selector', function(){
    alert( $(this).text());
  });

});

  handler content
  selector content

How do I get the #handler inside the on method without explicitly specifying it?

Body:
In this specific case you can directly use the unique id you have

$("#handler").

In case if that is a class, you have $(this).parent() to the top level.

you can chain it to nth level , till you reach the top. $(this).parent().parent()...

or since you know the selector, you can do $(this).parents("selector")


答:
Use closest() if the parent has hierarchy,

```<code>$(this).closest('div')
</code>```

and use parent() if it is direct parent of target element,

```<code>$(this).parent('div');
</code>```

And the selector is unique and has id like handler then the best option is

```<code>$('#handler')
</code>```

Title: Getting the handler inside on() method

Body:
Use closest() if the parent has hierarchy,

$(this).closest('div')

and use parent() if it is direct parent of target element,

$(this).parent('div');

And the selector is unique and has id like handler then the best option is

$('#handler')


问:
Is declaring the same variable multiple times a good practice
Here is my javascript code:

```<code>(function(){
"use strict";
document.addEventListener("DOMContentLoaded",animations); /*on content loaded */

function animations() {

/*start of animation for the toggle navigation button in smaller view ports*/
(function () {

    var button = document.getElementById('nav-icon');
    button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            this.classList.remove('active');
        }
        else {
            this.classList.add('active');
        }
    })

})();  /*End of the toggle navigation animation*/

/*Start of  scrolling side navigation for smaller view ports*/

(function(){

        var button = document.getElementById('nav-icon');
        var body = document.querySelector('body');
        button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            body.classList.add('active-nav');
        }
        else {
            body.classList.remove('active-nav');
        }

    });

    })(); /*End of scrolling side navigation*/

(function () {
        // body...
        var media = window.matchMedia("(min-width: 992px)");
        var body = document.querySelector('body');
        var button = document.getElementById('nav-icon');
        window.addEventListener('resize',function(){

            if (media.matches) {

                    body.classList.remove('active-nav');

                    if (button.classList.contains('active')===true) {

                        button.classList.remove('active');
                    }

                }

        });

    })();

};

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

As you can see I have declared variables that have exactly the same value multiple times in my code, but they are in different functions. each iife is a seperate animation and has a different functionality although they might share  common elements. However, I wanted to know if this was a good practice. Should I declare common variables in the main function so they might be in the execution context of all the sub functions? Also, please highlight anything that doesnot look good or is not a good practice. Thank you

答:
In JavaScript, var is elevated to the function level, so it is scoped to the function. Since you are using the same variable names in different functions, you are fine, because then they exist in different scopes.

And as @theRemix and @Bergi have pointed out, beyond scoping, if you're variables are representing the same data within each anonymous function, consider refactoring to increase readability and code maintenance.

Body:
Here is my javascript code:

(function(){
"use strict";
document.addEventListener("DOMContentLoaded",animations); /*on content loaded */

function animations() {

/*start of animation for the toggle navigation button in smaller view ports*/
(function () {

    var button = document.getElementById('nav-icon');
    button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            this.classList.remove('active');
        }
        else {
            this.classList.add('active');
        }
    })

})();  /*End of the toggle navigation animation*/

/*Start of  scrolling side navigation for smaller view ports*/

(function(){

        var button = document.getElementById('nav-icon');
        var body = document.querySelector('body');
        button.addEventListener('click', function(){
        if (this.classList.contains('active')===true) {
            body.classList.add('active-nav');
        }
        else {
            body.classList.remove('active-nav');
        }

    });

    })(); /*End of scrolling side navigation*/

(function () {
        // body...
        var media = window.matchMedia("(min-width: 992px)");
        var body = document.querySelector('body');
        var button = document.getElementById('nav-icon');
        window.addEventListener('resize',function(){

            if (media.matches) {

                    body.classList.remove('active-nav');

                    if (button.classList.contains('active')===true) {

                        button.classList.remove('active');
                    }

                }

        });

    })();

};

})();

As you can see I have declared variables that have exactly the same value multiple times in my code, but they are in different functions. each iife is a seperate animation and has a different functionality although they might share  common elements. However, I wanted to know if this was a good practice. Should I declare common variables in the main function so they might be in the execution context of all the sub functions? Also, please highlight anything that doesnot look good or is not a good practice. Thank you


问:
How to add git to PATH (Bash on Windows)
I am using Bash on Ubuntu on Windows, and I installed git. How do I add git to my PATH?</p>

答:
The General command is (using setx):

```<code>setx PATH=%PATH%;C:\path\to\Git\bin
</code>```

On WSL (Windows Subsytem for Linux), you would type, after installation:

```<code>which git
</code>```

It should be already in your PATH (/usr/bin or /usr/local/bin)

If it is not, you can try and find it: find / -name "git", and add it to your ~/.profile with:

```<code>export PATH=$PATH:/path/to/git
</code>```

But be aware the WSL will install an old version of Git.

Fir the most recent one, use:

```<code>sudo add-apt-repository ppa:git-core/ppa
sudo apt-get update
sudo apt-get install git-core
</code>```

Where is /usr/local/bin on Windows?

As mentioned in BashOnWindows issue 402:

Under C:\Users\**user**\AppData\Local\lxss, You will find:

root folder

home folder

and a hidden rootfs folder (\bin, \boot, \dev, \etc...)

DON'T CHANGE ANYTHINK INSIDE! SERIOUSLY!

Access Windows files via /mnt/**letter**/

And:

Maybe I don't fully understand what Bash on Ubuntu on Windows is.

See Wikipedia WSL entry:

Windows Subsystem for Linux (WSL) is a compatibility layer for running Linux binary executables (in ELF format) natively on Windows 10.

  Windows Subsystem for Linux is only available on 64-bit editions of Windows 105 and can be activated on Windows 10 Anniversary Update and later.

  WSL uses fewer resources than a full virtualized machine, the most direct way to run Linux software on a Windows computer, while also allowing users to use Windows apps and Linux tools on the same set of files.5

The OP adds:

So if I install git and it's in /usr/bin/git, does that correspond to a particular folder such as C:\Program Files\etc...?

Yes, under C:\Users\**user**\AppData\Local\lxss\rootfs\usr\..., but you are not supposed to access it directly. You only use it through the WSL bash.

Is setting my PATH different by putting it in my ~/.profile vs. going into Control Panel --> System Properties --> Environment Variables

Yes, completely. If you want to set your Windows Environment Variables PATH, you need to use Git for Windows, as described in here.

Body:
The General command is (using setx):

setx PATH=%PATH%;C:\path\to\Git\bin

On WSL (Windows Subsytem for Linux), you would type, after installation:

which git

It should be already in your PATH (/usr/bin or /usr/local/bin)

If it is not, you can try and find it: find / -name "git", and add it to your ~/.profile with:

export PATH=$PATH:/path/to/git

But be aware the WSL will install an old version of Git.

Fir the most recent one, use:

sudo add-apt-repository ppa:git-core/ppa
sudo apt-get update
sudo apt-get install git-core

Where is /usr/local/bin on Windows?

As mentioned in BashOnWindows issue 402:

Under C:\Users\**user**\AppData\Local\lxss, You will find:

root folder

home folder

and a hidden rootfs folder (\bin, \boot, \dev, \etc...)

DON'T CHANGE ANYTHINK INSIDE! SERIOUSLY!

Access Windows files via /mnt/**letter**/

And:

Maybe I don't fully understand what Bash on Ubuntu on Windows is.

See Wikipedia WSL entry:

Windows Subsystem for Linux (WSL) is a compatibility layer for running Linux binary executables (in ELF format) natively on Windows 10.

  Windows Subsystem for Linux is only available on 64-bit editions of Windows 105 and can be activated on Windows 10 Anniversary Update and later.

  WSL uses fewer resources than a full virtualized machine, the most direct way to run Linux software on a Windows computer, while also allowing users to use Windows apps and Linux tools on the same set of files.5

The OP adds:

So if I install git and it's in /usr/bin/git, does that correspond to a particular folder such as C:\Program Files\etc...?

Yes, under C:\Users\**user**\AppData\Local\lxss\rootfs\usr\..., but you are not supposed to access it directly. You only use it through the WSL bash.

Is setting my PATH different by putting it in my ~/.profile vs. going into Control Panel --> System Properties --> Environment Variables

Yes, completely. If you want to set your Windows Environment Variables PATH, you need to use Git for Windows, as described in here.


问:
Swift - tableView Row height updates only after scrolling or toggle expand/collapse
I am using CollapsibleTableView from here and modified it as per my requirement to achieve collapsible sections. Here is how it looks now.

Since there is a border for my section as per the UI design, I had chosen the section header to be my UI element that holds data in both collapsed and expanded modes.

Reason: I tried but couldn't get it working in this model explained below -

** Have my header elements in section header and details of each item in its cell. By default, the section is in collapsed state. When user taps on the header, the cell is toggled to display. As I said, since there is a border that needs to be shown to the whole section (tapped header and its cell), I chose section header to be my UI element of operation. Here is my code for tableView -

```<code>func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections.count
    }

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        switch indexPath.row {
        case 0:
            return sections[indexPath.section].collapsed! ? 0 : (100.0 + heightOfLabel2!)
        case 1:
            return 0
        case 2:
            return 0
        default:
            return 0
        }
    }

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let header = self.tableView.dequeueReusableHeaderFooterViewWithIdentifier("header") as! CollapsibleTableViewHeader

        if sections.count == 0 {
            self.tableView.userInteractionEnabled = false
            header.cornerRadiusView.layer.borderWidth = 0.0
            header.benefitAlertImage.hidden = true
            header.benefitAlertText.hidden = true
            header.amountLabel.hidden = true
            header.titleLabel.text = "No_Vouchers".localized()
        }
        else {
            header.amountLabel.hidden = false
            header.cornerRadiusView.layer.borderWidth = 1.0
            self.tableView.userInteractionEnabled = true
            header.titleLabel.text = sections[section].name
            header.arrowImage.image = UIImage(named: "voucherDownArrow")
            header.setCollapsed(sections[section].collapsed)

            let stringRepresentation = sections[section].items.joinWithSeparator(", ")

            header.benefitDetailText1.text = stringRepresentation
            header.benefitDetailText2.text = sections[section].shortDesc
            header.benefitDetailText3.text = sections[section].untilDate

            header.section = section
            header.delegate = self

            if sections[section].collapsed == true {
                header.benefitAlertImage.hidden = true
                header.benefitAlertText.hidden = true
            }
            else {
                if sections[section].isNearExpiration == true {
                    header.benefitAlertImage.hidden = false
                    header.benefitAlertText.hidden = false
                }
                else {
                    header.benefitAlertImage.hidden = true
                    header.benefitAlertText.hidden = true
                }
            }

            if appLanguageDefault == "nl" {
                self.totalAmountLabel.text = "€ \(sections[section].totalAvailableBudget)"
            }
            else {
                self.totalAmountLabel.text = "\(sections[section].totalAvailableBudget) €"
            }
        }

        return header
    }
</code>```

Function to toggle collapse/expand -
I am using height values of the "dynamically changing" UILabels inside the section and then using those values to extend the border (using its layoutconstraint).

```<code>func toggleSection(header: CollapsibleTableViewHeader, section: Int) {
        let collapsed = !sections[section].collapsed

        header.benefitAlertImage.hidden = true
        header.benefitAlertText.hidden = true
        // Toggle collapse
        sections[section].collapsed = collapsed
        header.setCollapsed(collapsed)

        // Toggle Alert Labels show and hide
        if sections[section].collapsed == true {
            header.cornerRadiusViewBtmConstraint.constant = 0.0
            header.cornerRadiusViewTopConstraint.constant = 20.0
            header.benefitAlertImage.hidden = true
            header.benefitAlertText.hidden = true
        }
        else {

            heightOfLabel2 = header.benefitDetailText2.bounds.size.height

            if sections[section].isNearExpiration == true {
                header.benefitAlertImage.hidden = false
                header.benefitAlertText.hidden = false
                header.cornerRadiusViewBtmConstraint.constant = -100.0 - heightOfLabel2!
                header.cornerRadiusViewTopConstraint.constant = 10.0
                if let noOfDays = sections[section].daysUntilExpiration {
                    if appLanguageDefault == "nl" {

                        header.benefitAlertText.text = "(nog \(noOfDays) dagen geldig)"
                    }
                    else {
                        header.benefitAlertText.text = "(valable encore \(noOfDays) jour(s))"
                    }
                }
            }
            else {
                header.cornerRadiusViewBtmConstraint.constant = -80.0 - heightOfLabel2!
                header.cornerRadiusViewTopConstraint.constant = 20.0
                header.benefitAlertImage.hidden = true
                header.benefitAlertText.hidden = true
            }
        }

        // Adjust the height of the rows inside the section
        tableView.beginUpdates()
        for i in 0 ..< sections.count {
            tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: i, inSection: section)], withRowAnimation: .Automatic)
        }
        tableView.endUpdates()
    }
</code>```

The problem:
I need to have, few section headers in this table view to be expanded by default on the first launch of the view, based on some conditions. As I am calculating the height of the labels and using the heights to set for the border's top and bottom constraint, it has become difficult to show the expanded section header as per design.

The content comes out of the border since the height of my UILabel is being taken as 21 by default.

UPDATE: The row height changes only after I scroll through the view or when I toggle between collapse/expand

The Question:
How do I calculate the heights of the UILabels present in my Section header by the first time launch of the view? (That means, after my REST call is done, data is fetched and then I need to get the UIlabel height).

Currently, I am using heightOfLabel2 = header.benefitDetailText2.bounds.size.height

(Or)

Is there a better way to achieve this?

Thanks in advance!

答:
In this method,

```<code>func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        switch indexPath.row {
        case 0:
            return sections[indexPath.section].collapsed! ? 0 : (100.0 + heightOfLabel2!)
        case 1:
            return 0
        case 2:
            return 0
        default:
            return 0
        }
    }
</code>```

instead of using heightOfLabel2, try implementing the following method to calculate heights specific to each cell(since we know the text to be filled, its font and label width, we can calculate the height of label),

```<code>func getHeightForBenefitDetailText2ForIndexPath(indexPath: NSIndexPath)->CGFloat
</code>```

So your method should look like this,

```<code>func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        switch indexPath.row {
        case 0:
            return sections[indexPath.section].collapsed! ? 0 : (100.0 + getHeightForBenefitDetailText2ForIndexPath(indexPath))
        case 1:
            return 0
        case 2:
            return 0
        default:
            return 0
        }
    }
</code>```

And regarding your problem to expand few cells by for the very first time, make sure you set the collapsed property to true for those cells before reloading the table.

As a performance improvement, you can store the height value calculated for each expanded cell in a dictionary and return the value from the dictionary, to avoid the same calculation again and again.

Hope this helps you. If not, do share a sample project for more insight about your problem.

Body:
I am using CollapsibleTableView from here and modified it as per my requirement to achieve collapsible sections. Here is how it looks now.

Since there is a border for my section as per the UI design, I had chosen the section header to be my UI element that holds data in both collapsed and expanded modes.

Reason: I tried but couldn't get it working in this model explained below -

** Have my header elements in section header and details of each item in its cell. By default, the section is in collapsed state. When user taps on the header, the cell is toggled to display. As I said, since there is a border that needs to be shown to the whole section (tapped header and its cell), I chose section header to be my UI element of operation. Here is my code for tableView -

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections.count
    }

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        switch indexPath.row {
        case 0:
            return sections[indexPath.section].collapsed! ? 0 : (100.0 + heightOfLabel2!)
        case 1:
            return 0
        case 2:
            return 0
        default:
            return 0
        }
    }

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let header = self.tableView.dequeueReusableHeaderFooterViewWithIdentifier("header") as! CollapsibleTableViewHeader

        if sections.count == 0 {
            self.tableView.userInteractionEnabled = false
            header.cornerRadiusView.layer.borderWidth = 0.0
            header.benefitAlertImage.hidden = true
            header.benefitAlertText.hidden = true
            header.amountLabel.hidden = true
            header.titleLabel.text = "No_Vouchers".localized()
        }
        else {
            header.amountLabel.hidden = false
            header.cornerRadiusView.layer.borderWidth = 1.0
            self.tableView.userInteractionEnabled = true
            header.titleLabel.text = sections[section].name
            header.arrowImage.image = UIImage(named: "voucherDownArrow")
            header.setCollapsed(sections[section].collapsed)

            let stringRepresentation = sections[section].items.joinWithSeparator(", ")

            header.benefitDetailText1.text = stringRepresentation
            header.benefitDetailText2.text = sections[section].shortDesc
            header.benefitDetailText3.text = sections[section].untilDate

            header.section = section
            header.delegate = self

            if sections[section].collapsed == true {
                header.benefitAlertImage.hidden = true
                header.benefitAlertText.hidden = true
            }
            else {
                if sections[section].isNearExpiration == true {
                    header.benefitAlertImage.hidden = false
                    header.benefitAlertText.hidden = false
                }
                else {
                    header.benefitAlertImage.hidden = true
                    header.benefitAlertText.hidden = true
                }
            }

            if appLanguageDefault == "nl" {
                self.totalAmountLabel.text = "€ \(sections[section].totalAvailableBudget)"
            }
            else {
                self.totalAmountLabel.text = "\(sections[section].totalAvailableBudget) €"
            }
        }

        return header
    }

Function to toggle collapse/expand -
I am using height values of the "dynamically changing" UILabels inside the section and then using those values to extend the border (using its layoutconstraint).

func toggleSection(header: CollapsibleTableViewHeader, section: Int) {
        let collapsed = !sections[section].collapsed

        header.benefitAlertImage.hidden = true
        header.benefitAlertText.hidden = true
        // Toggle collapse
        sections[section].collapsed = collapsed
        header.setCollapsed(collapsed)

        // Toggle Alert Labels show and hide
        if sections[section].collapsed == true {
            header.cornerRadiusViewBtmConstraint.constant = 0.0
            header.cornerRadiusViewTopConstraint.constant = 20.0
            header.benefitAlertImage.hidden = true
            header.benefitAlertText.hidden = true
        }
        else {

            heightOfLabel2 = header.benefitDetailText2.bounds.size.height

            if sections[section].isNearExpiration == true {
                header.benefitAlertImage.hidden = false
                header.benefitAlertText.hidden = false
                header.cornerRadiusViewBtmConstraint.constant = -100.0 - heightOfLabel2!
                header.cornerRadiusViewTopConstraint.constant = 10.0
                if let noOfDays = sections[section].daysUntilExpiration {
                    if appLanguageDefault == "nl" {

                        header.benefitAlertText.text = "(nog \(noOfDays) dagen geldig)"
                    }
                    else {
                        header.benefitAlertText.text = "(valable encore \(noOfDays) jour(s))"
                    }
                }
            }
            else {
                header.cornerRadiusViewBtmConstraint.constant = -80.0 - heightOfLabel2!
                header.cornerRadiusViewTopConstraint.constant = 20.0
                header.benefitAlertImage.hidden = true
                header.benefitAlertText.hidden = true
            }
        }

        // Adjust the height of the rows inside the section
        tableView.beginUpdates()
        for i in 0 ..< sections.count {
            tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: i, inSection: section)], withRowAnimation: .Automatic)
        }
        tableView.endUpdates()
    }

The problem:
I need to have, few section headers in this table view to be expanded by default on the first launch of the view, based on some conditions. As I am calculating the height of the labels and using the heights to set for the border's top and bottom constraint, it has become difficult to show the expanded section header as per design.

The content comes out of the border since the height of my UILabel is being taken as 21 by default.

UPDATE: The row height changes only after I scroll through the view or when I toggle between collapse/expand

The Question:
How do I calculate the heights of the UILabels present in my Section header by the first time launch of the view? (That means, after my REST call is done, data is fetched and then I need to get the UIlabel height).

Currently, I am using heightOfLabel2 = header.benefitDetailText2.bounds.size.height

(Or)

Is there a better way to achieve this?

Thanks in advance!

Body:
In this method,

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        switch indexPath.row {
        case 0:
            return sections[indexPath.section].collapsed! ? 0 : (100.0 + heightOfLabel2!)
        case 1:
            return 0
        case 2:
            return 0
        default:
            return 0
        }
    }

instead of using heightOfLabel2, try implementing the following method to calculate heights specific to each cell(since we know the text to be filled, its font and label width, we can calculate the height of label),

func getHeightForBenefitDetailText2ForIndexPath(indexPath: NSIndexPath)->CGFloat

So your method should look like this,

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        switch indexPath.row {
        case 0:
            return sections[indexPath.section].collapsed! ? 0 : (100.0 + getHeightForBenefitDetailText2ForIndexPath(indexPath))
        case 1:
            return 0
        case 2:
            return 0
        default:
            return 0
        }
    }

And regarding your problem to expand few cells by for the very first time, make sure you set the collapsed property to true for those cells before reloading the table.

As a performance improvement, you can store the height value calculated for each expanded cell in a dictionary and return the value from the dictionary, to avoid the same calculation again and again.

Hope this helps you. If not, do share a sample project for more insight about your problem.


问:
Angular InjectionToken; what is 'app.config'?
I am following the docs on how to provide, then inject a non-class instance; specifically I want to provide application wide constants.  The docs use the InjectionToken for this, but the explanations are very bare; consider the first part:

app.config.ts

```<code>import { InjectionToken } from '@angular/core';

export let APP_CONFIG = new InjectionToken<AppConfig>('app.config');
</code>```

What's the point of the 'app.config' string? Every example of InjectorToken that I see here uses that, but none discusses what it means or refers to.

答:
It's a description as can be seen from the parameter name:

```<code>export class InjectionToken<T> extends OpaqueToken {
  constructor(desc: string) { super(desc); }
              ^^^^

  toString(): string { return `InjectionToken ${this._desc}`; }
}
</code>```

It can be used for debugging purposes as it's seen in the toString method.

It is probably modeled after Symbol which also receives description string in the constructor:

Parameters

description - Optional Optional, string. A description of the symbol
  which can be used for debugging but not to access the symbol itself.

Refer to the Angular 2 OpaqueToken vs Angular 4 InjectionToken to understand why the InjectionToken was introduced.

Body:
I am following the docs on how to provide, then inject a non-class instance; specifically I want to provide application wide constants.  The docs use the InjectionToken for this, but the explanations are very bare; consider the first part:

app.config.ts

import { InjectionToken } from '@angular/core';

export let APP_CONFIG = new InjectionToken<AppConfig>('app.config');

What's the point of the 'app.config' string? Every example of InjectorToken that I see here uses that, but none discusses what it means or refers to.

Body:
It's a description as can be seen from the parameter name:

export class InjectionToken<T> extends OpaqueToken {
  constructor(desc: string) { super(desc); }
              ^^^^

  toString(): string { return `InjectionToken ${this._desc}`; }
}

It can be used for debugging purposes as it's seen in the toString method.

It is probably modeled after Symbol which also receives description string in the constructor:

Parameters

description - Optional Optional, string. A description of the symbol
  which can be used for debugging but not to access the symbol itself.

Refer to the Angular 2 OpaqueToken vs Angular 4 InjectionToken to understand why the InjectionToken was introduced.


问:
open webpage in firefox
i am not sure..is there any chance to open my webpage in firefox. for example i am browsing mywebsite using IE. when ever i click link of the page then automatically it will open in firefox. this option is not for all pages only for specified page.

thanks.

答: What you ask for is not possible , but you could display a warning to your users that the page works best in the desired browser.</p>

Title: open webpage in firefox


答:
Change it to

```<code>$( document ).ready(function() {
  $('#handler').on('click', function(){
    //$(this) here will be #handler.
  });
});
</code>```

Or if you still want the function to fire when someone clicks on .selector then you can do the following

```<code>$( document ).ready(function() {
  $('#handler').on('click', '.selector', function(){
    var handler = $(this).parent();
  });
});
</code>```

Title: Getting the handler inside on() method

Body:
Change it to

$( document ).ready(function() {
  $('#handler').on('click', function(){
    //$(this) here will be #handler.
  });
});

Or if you still want the function to fire when someone clicks on .selector then you can do the following

$( document ).ready(function() {
  $('#handler').on('click', '.selector', function(){
    var handler = $(this).parent();
  });
});